text:
Q: IR Demodulator Design I am designing an IR demodulator circuit to replace the one shown in this question. Basically I want to demodulate a simple IR signal modulated at 32.678 kHz. I just need to know if the signal is present. No packets. Just IR present or not present.
Below is what I have so far...

I have tried simulating this in LTspice with no success so I am not sure if I've done something very wrong in spice or in my circuit. I am no pro with LTspice.
R1 N001 N006 2.49K tol=1 pwr=0.1
R2 Output N003 1Meg
R3 N006 N005 1Meg
C1 N005 N004 470pF
C2 N003 N001 220pF
C3 Output N001 220pF
V1 N006 0 2.5
V2 N002 0 5
V3 N004 0 PULSE(0 .05 0 0 0 0.0000152587890625 0.000030517578125 200)
XU1 N005 N003 N002 0 Output LT1722
.tran 12ms
.lib LTC.lib
.backanno
.end

I have a few questions:

*

*How best do I determine the value for R34? I have left it at 22k simply because the previous circuit used this value.

*C16 and R31 set the high pass knee point. What would be a wise choice for this value?

*The overall gain of the circuit is approximately 400 by my calculations. So, in choosing my op amp I would need a GBWP of 14 MHz or greater? Any other critical op amp specifications for this application? Note the amp showed is just a place holder until I choose the op amp.

*If I wanted to increase my gain beyond what is shown (~1000) would it be best to break this up into several stages?

A: Answer rewritten due to new information from Jason:
Some other answers talk about using a custom IR received IC - which is what I would tend to do except where price was utterly crucial and I could make a cheaper design wit acceptable performance discreetly.
But, this answer is aimed at making the existing circuit work as it should, as requested.
MCP601 op amp datasheet here
 This is single supply, rail to rail output, Vin = ground to Vdd-1.2V. So with Vdd = V5.0 = 5V Vin range = 0 - 3.8V.
 Set ideally set mid point at about range/2 = 1.9V or so but 2.5V used is OK.
R31 to Vground = Vdd/2 provides DC level for opamp input and output. With no signal Vout = V5.0/2 = 2.5V so output of D5 will be about  2.7-Vd = 2.5-0.5 =! 2.2V. You ideally want Vout ~+ 0 at 0 input - see below.
Filter looks to have potential for massive gain at some frequency ( ~~R17/R18 = 400:1 as noted) - whether this occurs anywhere depends on overall filter action. I'd be more comfortable if the basis for the design was described.
C16/R31 provide a high pass at << 1 kHz so well below IR frequency.
 You could increase this till it approaches IR frequency but far enough away for minimimal attenuatio bit that depends whether it was a formal part of your overall filter design - if it wasn't it should be. For best results te overall front end frequency response should be tailored to be a bandpass of designed characteristics.
Try this:
_
Aim: AC couple op-amp output so
Vout = positive signal peaks from op amp - V_D5

*

*Drive D5 with a capacitor = Cout = say 10 uF electrolytic so D5 is AC driven.

*Add D6 to ground with D6 cathode to Anode (D5 input) and D6 anode grounded.
This causes positive half cycles to be passed through D5 and to charge C15 and negative half cycles to be conducted through D6 to ground.
 This is potentially " a bit hard" on U1a and Cout = 1 uF may suffice.
 Cout > C15, to Cout >> C15 is desirable to stop the two dividing the output positive peaks by too much.

Report.

A: I agree with Tony, I would also use an integrated IR receiver. The only problem seemed to be the 32kHz, IR receiver modules are often narrow band around 38kHz to 56kHz. But when I checked my usual supplier Vishay they also seem to have non protocol specific modules covering 32kHz, like this one.
Main advantage of this kind of modules is that it does a lot more than your circuit:

The AGC (Automatic Gain Control) is important. It ensures that sensitivity is adjusted when a proper signal is received, so that noise (for example from HF fluorescent lighting ballasts) is suppressed.

A: In addition to what others have said, I would point-out that your filter arrangement is suspicious. At first glance, the portion of the circuit from U1 pin 3 to U1 pin 1 looks like a typical second-order bandpass filter but instead of driving the left hand side of R18 and grounding the non-inverting input of U1, you are doing the opposite, ie using it in a non-inverting configuration.
In this configuration it is acting as a second order high-pass filter with a high frequency gain of 1 will have both low and high frequency gains of 1 (consider very high frequencies at which C1 & C5 are effectively short circuits, or at dc with the capacitors removed, and you will see a unity gain amplifier).
By my calculations, you have a centre frequency of 14.5kHz and a Q of 10 (ie a gain of 10 at 14.5kHz) at which the maximum gain of around 200 will be reached. By 32kHz, the gain is nearly back to 1 around 10 (and a gain of 400 will never be reached).
The calculations I have used are ....
Putting :- \$R=R_{18}\$ = 2.49k
\$C=C_1=C_5\$ = 220pF
\$k=\dfrac{R_{17}}{R_{18}}=401.6\$
I get :-
\$f_0 = \dfrac{1}{2\pi RC\sqrt k}\$ = 14.5 kHz and
\$G_{max} = \dfrac{1+k}{2}\$ = 201.3

Edit
To answer your question about 'k', it is commonly used to indicate a constant or a factor - in this case I have used it for the ratio of R17/R18. As you increase the ratio, you will get more gain at the centre frequency, but the centre frequency will decrease at the same time.
But before you go any further, consider what Tony Stewart said about ambient noise levels. Do you even need such a filter?
I would in any case avoid high Q active filters - they are just too sensitive to component tolerances. I would also avoid filters with very high passband gain for the same reason. If you do need a lot of out-of-band rejection, consider cascading separate lowpass and highpass filters. You might also consider using a phase-locked-loop (PLL) or digital filtering but we don't know what your operational environment is like.
If this is a personal project, and you want to experiment a little without using an receiver IC as stevenvh suggests, I would do the following. Firstly you want to convert the current from the photodiode into a voltage so R34 needs to be as large as possible. But this comes with some trade-offs. If your ambient light level (eg sunlight) gives you more than 150uA or so of diode current, you will starve the diode of bias and it's sensitivity will be reduced (ie it will saturate). So place your receiver in the brightest conditions it is likely to experience and measure the voltage at the junction of the diode and R34. If it is more than 3V or so you might have problems (depending on the diode) and you might thave to reduce R34. If you can view the waveform here with an oscilloscope, what happens as you increase the background lighting with your 32kHz signal present? If the signal amplitude doesn't reduce, you might be able to increase R34 to 100k say. Much higher than this and you might not see any further increase in signal due to capacitance.
An oscilloscope will also tell you how much extra gain you will need and whether out-of-band interference from artificial lighting, TV remotes etc requires you to filter the signal further.

A: Before you design anything, you need specs guys.
Data rate
Signal range
Transmit pattern, duty cycle etc.
Design distance of sensitivity
Ambient noise factors ( sunlight , linear FL's etc)
Signal levels or gain neeeded.
V+ options?
Size , cost, qty to be made
etc etc
The previous design is OK. It uses "unbuffered" CMOS inverters which have a gain of 10. "buffered" inverters are 3 stages, hence gain =1000.  In that previous design the CMOS was being used as a linear amp with negative feedback. The Ceramic filter is a high Q BPF. The detector/discriminator gives a clean response.
Personally, I would use the TI or Sharp IR receiver device with daylight blocking filter , AGC , data detector and Rx Signal detector.

A: Any communication channel has to have a desired acceptable  non-zero error rate. There must be a know bandwidth or latency allowed for the signal and a well defined worst case environmental noise level, whether it is EMI, Flickering lights the sun, or stray IR remotes trying to jam your signal. Can you define these 1st? Then define the distance of the channel.
Once a spec is given, a design can commence, no sooner.
But if I were to guess a great solution.
Use a prudent design that also provides an aperture to block stray light for line of sight detection. Otherwise multi path distortion and stray movement between the path can affect error rate.
Then use this $1 chip.  http://www.vishay.com/docs/81764/tsop852.pdf
Beware of moisture ingress failures if improperly soldered. These devices use a  clear low temperature epoxy.
I just found a $0.75 solution http://media.digikey.com/pdf/Data%20Sheets/Vishay%20Semiconductors/TSOP392.pdf
Does that meet your budget?.. Make sure to filter and regulate your V+.


text:
Q: Python 3 and b'\x92'.decode('latin1') I'm getting results I didn't expect from decoding b'\x92' with the latin1 codec. See the session below:
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
>>> b'\xa3'.decode('latin1').encode('ascii', 'namereplace')
b'\\N{POUND SIGN}'
>>> b'\x92'.decode('latin1').encode('ascii', 'namereplace')
b'\\x92'
>>> ord(b'\x92'.decode('latin1'))
146

The result decoding b'\xa3' gave me exactly what I was expecting. But the two results for b'\x92' were not what I expected. I was expecting b'\x92'.decode('latin1') to result in U+2018, but it seems to be returning U+0092.
What am I missing?

A: The error I made was to expect that the character 0x92 decoded to "RIGHT SINGLE QUOTATION MARK" in latin-1, it doesn't. The confusion was caused because it was present in a file that was specified as being in latin1 encoding. It now appears that the file was actually encoded in windows-1252. This is apparently a common source of confusion:
http://www.i18nqa.com/debug/table-iso8859-1-vs-windows-1252.html
If the character is decoded with the correct encoding, then the expected result is obtained.
>>> b'\x92'.decode('windows-1252').encode('ascii', 'namereplace')
b'\\N{RIGHT SINGLE QUOTATION MARK}'

A:
I was expecting b'\x92'.decode('latin1') to result in U+2018

latin1 is an alias for ISO-8859-1. In that encoding, byte 0x92 maps to character U+0092, an unprintable control character.
The encoding you might have really meant is windows-1252, the Microsoft Western code page based on it. In that encoding, 0x92 is U+2019 which is close...
(Further befuddlement arises because for historical reasons web browsers are also confused between the two. When a web page is served as charset=iso-8859-1, web browsers actually use windows-1252.)

A: I just want to make clear that you're not encoding anything here.
xa3 has a ordinal value of 163 (0xa3 in hexadecimal). Since that ordinal is not seven bits, it can't be encoded into ascii. Your handler for errors just replaces the Unicode Character into the name of the character. The Unicode Character 163 maps to £.
'\x92' on the other hand, has an ordinal value of 146. According to this Wikipedia Article, the character isn't printable - it's a privately used control code in the C2 space. This explains why it's name is simply the literal '\\x92'.
As an aside, if you need the name of the character, it's much better to do it like this:
import unicodedata
print unicodedata.name(u'\xa3')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Evaluation of the double sum Is there a way to get a closed expression for the double sum:
$$\sum\limits_{n = 1}^\infty \sum\limits_{m = 1}^\infty \left( \frac{m}{(n^2 + m^2 - E_1)(n^2 + m^2 - E_2)} \right)^2$$
, where $E_1$ and $E_2$ are some complex parameters, which is not equal to $n^2 + m^2$ for any $n, m \ge 1$?
While struggling to evaluate this sum I tried evaluating a simpler sum by setting $E_1 = 0, E_2 = 0$:
$$\sum\limits_{n = 1}^\infty \sum\limits_{m = 1}^\infty \frac{m^2}{(n^2 + m^2)^4}$$
I noticed that:
$$\sum\limits_{n = 1}^\infty \sum\limits_{m = 1}^\infty \frac{m^2}{(n^2 + m^2)^4} = \sum\limits_{n = 1}^\infty \sum\limits_{m = 1}^\infty \frac{n^2}{(n^2 + m^2)^4}$$, so
$$2 \sum\limits_{n = 1}^\infty \sum\limits_{m = 1}^\infty \frac{m^2}{(n^2 + m^2)^4} = \sum\limits_{n = 1}^\infty \sum\limits_{m = 1}^\infty \frac{m^2}{(n^2 + m^2)^4} + \sum\limits_{n = 1}^\infty \sum\limits_{m = 1}^\infty \frac{n^2}{(n^2 + m^2)^4} = \sum\limits_{n = 1}^\infty \sum\limits_{m = 1}^\infty \frac{n^2 + m^2}{(n^2 + m^2)^4} = \sum\limits_{n = 1}^\infty \sum\limits_{m = 1}^\infty \frac{1}{(n^2 + m^2)^3}$$
But I still have no idea how to evaluate even $\sum\limits_{n = 1}^\infty \sum\limits_{m = 1}^\infty \frac{1}{(n^2 + m^2)^3}$. I tried using Wolfram Mathematica, and it just didn't give anything after 10 minutes of computation.
It is known we can evaluate infinite sums (indexed by one variable) of rational functions and get closed expressions in terms of the polygamma function. Is there any similar result for double sums? Is there some general method of evaluating double sums? It seems not, since evaluating even simpler sum $\frac{1}{(n^2 + m^2)^2}$ involves combinatorics, but I still hope to find something.
UPD: I was not very careful while reading this and seems the sum $\frac{1}{(n^2 + m^2)^3}$ can be evaluated the same way as for $\frac{1}{(n^2 + m^2)^2}$. However, this still leaves the question of evaluating the original sum.


text:
Q: Laravel 5 - Blob doesn't retrive an image right I'm using Laravel to store an image (generated from a canvas) but when I retrieve the value from the column and I pass it to the "src" attribute of an  block it doesn't load and into the browser console I see the error

"Failed to load resource: net::ERR_INVALID_URL"

migration
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTblTaccuinoTable extends Migration
{
/**
 * Schema table name to migrate
 * @var string
 */
public $set_schema_table = 'tbl_taccuino';

/**
 * Run the migrations.
 * @table tbl_taccuino
 *
 * @return void
 */
public function up()
{
    if (Schema::hasTable($this->set_schema_table)) return;
    Schema::create($this->set_schema_table, function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id_taccuino');
        $table->integer('id_paziente')->unsigned();
        $table->string('taccuino_descrizione', 45);
        $table->date('taccuino_data');
        $table->binary('taccuino_report_anteriore');
        $table->binary('taccuino_report_posteriore');

        $table->index(["id_paziente"], 'fk_tbl_taccuino_tbl_pazienti1_idx');

        $table->foreign('id_paziente', 'fk_tbl_taccuino_tbl_pazienti1_idx')
            ->references('id_paziente')->on('tbl_pazienti')
            ->onDelete('no action')
            ->onUpdate('no action');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
 public function down()
 {
   Schema::dropIfExists($this->set_schema_table);
 }
}

Model
<?php

/**
* Created by Reliese Model.
* Date: Mon, 25 Dec 2017 12:47:05 +0000.
*/

namespace App\Models\Patient;

use Reliese\Database\Eloquent\Model as Eloquent;

/**
 * Class Taccuino
 *
 * @property int $id_taccuino
 * @property int $id_paziente
 * @property string $taccuino_descrizione
 * @property \Carbon\Carbon $taccuino_data
 * @property boolean $taccuino_report_anteriore
 * @property boolean $taccuino_report_posteriore
 *
 * @property \App\Models\Pazienti $tbl_pazienti
 *
 * @package App\Models
 */
class Taccuino extends Eloquent
{
protected $table = 'tbl_taccuino';
protected $primaryKey = 'id_taccuino';
public $incrementing = false;
public $timestamps = false;

protected $casts = [
    'id_taccuino' => 'int',
    'id_paziente' => 'int',
];

protected $dates = [
    'taccuino_data'
];

protected $fillable = [
    'id_paziente',
    'taccuino_descrizione',
    'taccuino_data',
    'taccuino_report_anteriore',
    'taccuino_report_posteriore'
];

public function tbl_pazienti()
{
    return $this->belongsTo(\App\Models\Patient\Pazienti::class, 'id_paziente');
}
}

Inside my blade view

taccuino_report_anteriore }}">

PS: The blob string value starts with
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA..."

A: You might try outputting unescaped src values for the image:


text:
Q: Are generic types coupled to the type of their generic type parameters? Given class A
public class A<T> where T : B{
  ...
}

Is A coupled to B? Or is is more useful to think of this as a type restriction?
I was making a class diagram and was wondering how to represent this type of relationship when planning out a system's architecture.

A: I'm not sure what you mean by coupled, but where T : B is a generic type constraint. So T must implement B.

A: "Coupling" is a fairly abstract concept. In this case A would have at least some coupling to B, since a change in B could require a change in A.
A "type restriction" would be a more specific, but should probably called "generic type constraint" since that is the term commonly used in the documentation. But all constraints imply some amount of coupling, if A did not use any methods or properties of B there should be no reason for the constraint to exist.
If the goal is to write a class diagram the important thing is that whoever reads it understand the idea. If in doubt, add some comment or text to make it clearer. But in my experience, class diagrams are not commonly used in professional environments, since they tend to get obsolete fairly quickly. Source code is usually a better source of truth about how things work.


text:
Q: What happens if up quarks are replaced by down quarks and down quarks are replaced by up quarks? I believe the quarks would flip the proton's internal charge, reverse the spin of the proton, transform into another flavor, and then become unconfined and free.

A: The proton ($uud$) turns into a neutron ($ddu$). Up and down quarks don't have equal charges; the up is $+\frac{2}{3}e$ and the down is $-\frac{1}{3}e$.
By the way, such an operation has a name - isospin symmetry transformation - corresponding to an approximate SU(2) symmetry that makes the proton and neutron have almost similar masses.

A: Um... no, there's no reason to think any of that stuff would happen. The transformation of up quarks into down quarks and vice versa is called an isospin transformation, and it's been quite well studied. For example, the proton and neutron are members of an isospin doublet, which means that making this transformation would convert each one into the other.


text:
Q: Need to filter dimension where two attributes are the same I've obfuscated the scenario but the general idea still applies, so if the schema seems retarded, it probably is in this example...
Let's say I have a Student dimension, and in it are two attributes - Major and Minor (subjects).
I want to be able to create a Named Set in SSAS that gives me Students who have somehow been recorded as having the same subject for Major and Minor...
Dimension looks a little like this:
Student
  - Major
  - Minor

The underlying table looks something like this:
StudentID  |  MajorKey  | MinorKey
1             50          51
2             45          101
3             58          56
4             45          45

So, in effect, I want an MDX expression like this:
FILTER (
  [Student].allmembers,
  [Student].[Major] = [Student].[Minor]
)

... but I can't quite figure out the syntax. Any ideas?
UPDATE:
If I use this syntax...
FILTER (
  [Student].allmembers,
  [Student].[Major].Properties("Key") = [Student].[Minor].Properties("Key")
)

Then it slows down the ENTIRE cube for some reason. Every Measure (natural or calculated) takes several minutes as opposed to 1-2 seconds pre-cache.

A: I got it!
Basically the filter expression was correct, but I needed to Crossjoin the set what I wanted to filter against...
FILTER (
  CROSSJOIN([Student].[Major].[Major], [Student].[Minor].[Minor]),
  [Student].[Major].Properties("Key") = [Student].[Minor].Properties("Key")
)

I know I answered this quick but I've spent the best part of 10 hours on this today :P


text:
Q: Unix socket connection to MySql with Java to avoid JDBC's TCP/IP overhead? Is it possible to make a Unix socket connection to MySql with Java to avoid JDBC's TCP/IP overhead?
Does anyone know a library (or a few libraries, perhaps) that makes this possible?

A: Also the mySQL JDBC driver has been polished over a long period and has several optimization tweaks , like caching of metadata. I would be surprised that the JDBC developers would have left a lot of TCP/IP overhead in the driver.
Going over JNI to the C based implementation would probably cost more in jumping to native code than can be gained from reduced TCP/IP overhead.
If you really want to cut out the TCP/IP overhead you might consider using an embedded database like sqlite, derby or hypersonic.

A: JDBC is only an interface specification. It does not add any TCP/IP overhead. If there is overhead it is caused by the JDBC driver. There are also JDBC drivers for in memory or file databases and don't use TCP/IP at all.
The MYSQL JDBC driver is a JDBC Type 4 driver. That means it does not use any native code to access the database. If Java has no method to access unix sockets, the driver can not use them either.[1]
If you really want to use a unix socket maybe it is possible to use MySQL's ODBC driver which seems to supports unix sockets and then use a JDBC-ODBC bridge to access it from Java.

A: You could always take the C library and wrap it yourself. I think it supports UNIX sockets.
Can I ask how you've determined the TCP/IP overhead to be an issue? How did you narrow the problem (that I assume you're having) down to that?
Is the problem just the connection overhead as opposed to the packet overhead? If establishing connections is taking too long a connection pooling library (such as the one in Apache commons) would handle that for you.

A: Just use junixsocket, https://github.com/kohlschutter/junixsocket
It's a JNI-powered library that provides access to AF_UNIX sockets using the standard Java Socket API, and also comes with a MySQL connection factory.


text:
Q: Building With Docker Returns HashSum Errors Whenever I try to build with Docker, I'm encountering HashSum errors:

E: Failed to fetch
  http://apt.postgresql.org/pub/repos/apt/pool/main/p/postgis/postgis-doc_2.5.2+dfsg-1~exp1.pgdg90+1_all.deb
  Hash Sum mismatch    Hashes of expected file:
      - SHA256:8b04987f50d0a76c1bf8a830ea7f184e9a562892b9f835ab01cad576135fcc21
      - SHA1:68dcdd364b906882659a6dfd03f0db4bc7f2f385 [weak]
      - MD5Sum:f13452c5f91078db1df409fa531ac888 [weak]
      - Filesize:3742202 [weak]

This occurs for several Postgres files and one of the Postgis files.
I've tried running apt-clean/apt-update, removing lists and adding a file to handle a bad-proxy from this issue.
Has anyone encountered/found a solution to this? Dockerfile in question is below.
FROM postgres:9.4

RUN sed -i 's|http://httpredir.debian.org/debian|http://ftp.ie.debian.org/debian/|g' /etc/apt/sources.list

ADD /99fixbadproxy ./badproxy
RUN apt-get install apt && apt-get update && apt-get install -y \
    postgis \
    postgresql-9.4-postgis-scripts \
    postgresql-9.4-postgis-2.2 \
    && apt-get clean && rm -rf /var/lib/apt/lists/*


text:
Q: init.d script getting error First of all sorry for my bad english
Ok, i wrote a init.d script and i don't know its true or false (i am new at this things)
#!/bin/sh
. /etc/init.d/someserver

start () {
    echo -n $"Starting someserver.jar: "

    java -jar /home/someserver/someserver.jar &
    echo $! > /home/someserver/someserver.pid
}

stop () {
    echo -n $"Stopping someserver.jar: "

    PID=$(/home/someserver/someserver.pid)
    kill -9 $PID
}

restart() {
    stop
    start
}

case $1 in
    start)
        start
    ;;
    stop)
        stop
    ;;
    *)

    echo $"Usage: someserver {start|stop}"
    exit 1
esac

after that i use this commands;
$ sudo chmod 755 /etc/init.d/someserver

$ sudo update-rc.d someserver defaults

i am getting this info;
insserv: warning: script 'someserver' missing LSB tags and overrides

/etc/init.d/someserver: 6: .: 3: Too many open files

I search the errors and info's but i can't understand so what does it mean and what should i do?
Note:os debian, and i writing this for mmonit

A: Have you looked at other init scripts for reference?
Let's go through this section by section. First let's name a shell to be executed. Ok.
#!/bin/sh

Now please put LSB tags there as the init system suggests (tells the init system the dependencies)
### BEGIN INIT INFO
# Provides:          someserver
# Required-Start:    $syslog $network $remote_fs
# Required-Stop:     $syslog $remote_fs
# Should-Start:      $local_fs $named
# Should-Stop:       $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: someserver
# Description:       Some Server
### END INIT INFO

Then you sourced the init script itself, why? That's probably why the error you mentioned occurs, as this way it's called recursively, which is probably not what was intended.
Usually you source some script to get a config or so:
# source some config (can be omitted)
[ -f /etc/configs/someserver ] && source /etc/configs/someserver

Why do you have the dollar signs in every echo statement? (Ok, localization, I believe)
(Note: By looking at some other init script you see that debian uses the start-stop-daemon to manage daemons, so you may implement that. I don't do that here.)
start () {
    echo -n "Starting someserver.jar: "

    java -jar /home/someserver/someserver.jar &
    echo $! > /home/someserver/someserver.pid
}

You forgot a cat in stop().
Also I would not necessarily kill -9 but first only kill. You can put in a check if it really disappears and then kill -9. Again, maybe you should use start-stop-daemon.
stop () {
    echo -n "Stopping someserver.jar: "

    PID=$(cat /home/someserver/someserver.pid)
    kill $PID
}

You generally want to wait a little bit before restarting
restart() {
    stop
    sleep 10
    start
}

Finally you should also implement restart.
case "$1" in
    start)
      start
      ;;

    stop)
      stop
      ;;

    restart)
      restart
      ;;

    *)
      echo "Usage: someserver {start|stop|restart}"
      exit 1
      ;;
esac

Wasn't that bad. But you missed some details.


text:
Q: Laravel IoC Multiple Subclasses Bindings: how to make sure it'll be resolved correctly The title would be vague due to my English. Hope someone can improve it.
Here is the thing:
I have one abstract class Validator.
Currently, I have two subclasses, LoginValidator and SignupValidator , which extend from Validator.
I have two services: LoginService and SignupService and they have the same
function __construct(Validator $validator)
I wrote two ServiceProviders to bind the Validator.
LoginServiceProvider.php
$this->app->bind('Validators\Validator','Validators\LoginValidator');
SignupServiceProvider.php
$this->app->bind('Validators\Validator','Validators\SignupValidator');
Therefore, the $validator in __construct(Validator $validator) is actually always resolved to SignupValidator. I know the reason.
I wonder if there is any way to make sure that:
class LoginService {
  //$validator will be LoginValidator
  function __construct(Validator $validator){}

}

class SignupService {
  //$validator will be SignupValidator
  function __construct(Validator $validator){}
}

OR
I'm simply wrong, I should do __construct(LoginValidator $validator) ?

A: The question was answered by someone here at Laravel.io
I found it useful so I am posting the link here
-Thanks


text:
Q: How to get string length without counting newline characters as 2 chars in Java? So I need the length of a string, but I want newline characters to be counter as 1 character in a string. Is there an elegant way to do this?

A: Count the number of characters in a string using string.length(). Then subtract the number of times your 2-character newline occurs in the string. Have a look at Occurrences of substring in a string for nice ways of doing this.
There is no special method for doing this, because counting characters is much more complicated than it looks at first. For example, sometimes, the newline is not represented as \r\n, but just as \n - or just as \r. In fact, you actually have no guarantee that something you think is a single character actually has a length of 1.
System.out.println("é".length());

This prints 2, because I used an e followed by a character called a combining acute accent.


text:
Q: PHP if item is empty in XML I'm trying to remove a node if the child attritbutes are empty.
XML is a http request with simpleXML, which i cannot paste here.
Therefor im pasting some of the XML document from the url:
THE XML
<game id="1421692" status="Pre-Game" summary="1:00 PM" PreRegPost="Regular Season" PreRegPostID="2" GameDate="11/2/2014 1:00:00 PM">
<HomeTeam HomeTeam="Vikings" HomeTeamAbr="Min" HomeTeamID="16" HomeScore="0" Home_Outcome="undecided">HomeTeam</HomeTeam>
<AwayTeam AwayTeam="Redskins" AwayTeamAbr="Was" AwayTeamID="28" AwayScore="0" Away_Outcome="undecided">AwayTeam</AwayTeam>
game
</game>
<game id="" status="" summary="" PreRegPost="" PreRegPostID="2" GameDate="">
<HomeTeam HomeTeam="" HomeTeamAbr="" HomeTeamID="16" HomeScore="" Home_Outcome="">HomeTeam</HomeTeam>
<AwayTeam AwayTeam="" AwayTeamAbr="" AwayTeamID="" AwayScore="" Away_Outcome="">AwayTeam</AwayTeam>
game
</game>
<game id="1421668" status="Pre-Game" summary="1:00 PM" PreRegPost="Regular Season" PreRegPostID="2" GameDate="11/16/2014 1:00:00 PM">
<HomeTeam HomeTeam="Bears" HomeTeamAbr="Chi" HomeTeamID="3" HomeScore="0" Home_Outcome="undecided">HomeTeam</HomeTeam>
<AwayTeam AwayTeam="Vikings" AwayTeamAbr="Min" AwayTeamID="16" AwayScore="0" Away_Outcome="undecided">AwayTeam</AwayTeam>
game
</game>

THE PHP
  foreach ($game->{'info-schedule'}[0]->game as $games) {
    //Get the Date and Time for the game
    $time = $games->attributes()->GameDate;
    //Get the HomeTeam Data
    $hometeam = $games->HomeTeam->attributes()->HomeTeamAbr;
    $hometeamscore = $games->HomeTeam->attributes()->HomeTeamScore;
    //Get the AwayTeam Data
    $awayteam = $games->AwayTeam->attributes()->AwayTeamAbr;
    $awayteamscore = $games->AwayTeam->attributes()->AwayTeamScore;
    //Change TimeZone
    $playtime = new DateTime($time, new DateTimeZone('America/Los_Angeles'));
    $playtime->setTimezone(new DateTimeZone('Europe/Copenhagen'));

        $playtimes .= "
".$playtime->format('d/m - H:i')."
";
        $versus .= "
".$hometeam."".$hometeamscore."".$awayteamscore."".$awayteam."
";

  }

THE HTML

<?php echo $playtimes; ?>

<?php echo $versus; ?>

My output current looks like this:
02/11 - 22:00 / MinWas
16/06 - 00:37 /         //This is supposed to come out all empty
16/11 - 22:00 / ChiMin

The problem is that, in the empty node it automatically output my local time even tho its empty.
How do i convert or remove that empty node?
PS. This is my second foreach loop - So don't judge it :)

A: Skip an iteration with the continue keyword if the awayteam does not exist.
foreach ($game->{'info-schedule'}[0]->game as $games) {
    //Get the Date and Time for the game
    $time = $games->attributes()->GameDate;
    //Get the HomeTeam Data
    $hometeam = $games->HomeTeam->attributes()->HomeTeamAbr;
    $hometeamscore = $games->HomeTeam->attributes()->HomeTeamScore;

    if (empty($games->AwayTeam->attributes()->AwayTeamAbr)) {
        continue;
    }

    //Get the AwayTeam Data
    $awayteam = $games->AwayTeam->attributes()->AwayTeamAbr;

    $awayteamscore = $games->AwayTeam->attributes()->AwayTeamScore;
    //Change TimeZone
    $playtime = new DateTime($time, new DateTimeZone('America/Los_Angeles'));
    $playtime->setTimezone(new DateTimeZone('Europe/Copenhagen'));

    $playtimes .= "
".$playtime->format('d/m - H:i')."
";
    $versus .= "
".$hometeam."".$hometeamscore."".$awayteamscore."".$awayteam."
";
}

A: You just need a simple validation check to determine whether to process your foreach iteration. From what I understand, you can check that $hometeam is not empty (unset, blank, empty, zero, false, etc) before adding the results. This will skip the iteration completely if it is blank using continue():
foreach ($game->{'info-schedule'}[0]->game as $games) {
    if(empty($hometeam))
        continue;

    // rest of your code
}

Something you should keep in mind is that large concatenations like that are fine but are a little messy, and you should consider using an array like this:
$play_time = array();
$versus = array();

foreach ($game->{'info-schedule'}[0]->game as $games) {
    if(empty($hometeam))
        continue;

    // rest of your code
    $play_time[] = "
".$playtime->format('d/m - H:i')."
";
    $versus[] = "
".$hometeam."".$hometeamscore."".$awayteamscore."".$awayteam."
";

}

Then you output like this (using implode()) (note: you could use a \n or PHP_EOL separator to have your output a little cleaner in the source code):

        <?php echo implode($play_time); ?>

        <?php echo implode($versus) ?>

And another side note too, blocks of HTML like that might be easier expressed using an sprintf() call to insert formatted content into a string:
$pt_format = '
%s
';
$vs_format = '
%s%s$s$s
';

foreach ($game->{'info-schedule'}[0]->game as $games) {
    if(empty($hometeam))
        continue;

    // rest of your code
    $play_time[] = sprintf($pt_format, $playtime->format('d/m - H:i'));
    $versus[] = sprintf($vs_format, $hometeam, $hometeamscore, $awayteamscore, $awayteam);
}

Just a thought :) It's a bit easier to read like that.


text:
Q: Why does a Teams Tab based on a SharePoint Framework-WebPart open a Webbrowser? A SharePoint Framework-WebPart, that is added to a Microsoft Teams-Team as a Tab, works fine for most users- but for a few users a Webbrowser opens when they try to open that Tab in their mobile Teams, trying to load the SharePoint Website that is linked to the Microsoft Teams-Team - but that Website does not open either.
The users that report the issue are using a current version of the Microsoft Teams-mobile app.
How can this issue be prevented?


text:
Q: For loop to download and extract zip files from url Does anyone have some suggestions for why I can't get this code to do what I want it to do? I'm trying to write a script that will save me several hours each week. I need to download 83 zip files, extract them, import them into ArcGIS Pro, and then run the files through a series of geoprocessing tools, and then compile the results. Right now I'm doing this manually, and I'd love to automate this process as much as possible.
I can use the following snippet of code to download and extract one file. I can't seem to get it to work with a for loop though.
import requests, zipfile
from io import BytesIO

url = 'https://www.deq.state.mi.us/gis-data/downloads/waterwells/Alcona_WaterWells.zip'

filename = url.split('/')[-1]

req = requests.get(url)

zipfile = zipfile.ZipFile(BytesIO(req.content))
zipfile.extractall(r'C:\Users\UserName\Downloads\Water_Wells')

I have created a url list of all 83 urls. These don't change, and content is updated regularly. This for loop only returns the first county, just like the above snippet of code. I'm only including a few of the files here.
url_list = ['https://www.deq.state.mi.us/gis-data/downloads/waterwells/Alcona_WaterWells.zip',
           'https://www.deq.state.mi.us/gis-data/downloads/waterwells/Alger_WaterWells.zip',
           'https://www.deq.state.mi.us/gis-data/downloads/waterwells/Allegan_WaterWells.zip']

for link in url_list:
    filename = url.split('/')[-1]

    req = requests.get(url)

zipfile = zipfile.ZipFile(BytesIO(req.content))
zipfile.extractall(r'C:\Users\UserName\Downloads\Water_Wells')


text:
Q: Swap multiple images from javascript array I am coding a website with multiple pages of thumbnail image galleries. I want to populate the thumbnail images on each page from an array, so that I won't have to change the path of multiple images on each page. The folder path is defined in a var statement - which I would like to be the only unique element on each gallery page - and the images in each gallery's folder will have the same names (t1.jpg, t2.jpg, etc.).
I have the main image swap working, and tried to use a similar function for the thumbnails, but it doesn't work because the image ID is the same for all the thumbnail images. I could give each image a unique ID, but then would have to call a separate function for each thumbnail swap (15 per page).
I am a javascript novice and despite much searching I can't figure out how to work around this or find any similar examples. Any help or advice would be appreciated.
Javascript:

HTML:

A: Each ID attribute on the page should be unique. Remove them and rewrite your code as:
function loadThumb(thumbID, obj) {
     var newThumb = imgThumbs[thumbID];
     obj.src = imgPath + newThumb;
}

And the corresponding HTML part will look like

ps: Actually I do not see the purpose of that script - onload function could be triggered before the image is loaded in a preloadImages() function.
pps: try this code http://jsfiddle.net/4cKvs/  and jQuery variant http://jsfiddle.net/zSBNR/

A: If you are a Javascript novice I recommend you to search in google about
jQuery it is can help you a lot (Google also using it).


text:
Q: Are IE7 and 8 modes in IE9 the real thing? I just want to know if IE7 and IE8 modes in the F12 toolbar menus are actually using IE7 and IE8 to render pages and if there are any differences between them and their standalone counterparts?

A: There are differences. From my understanding, you really can't rely on them for JavaScript because IE9 will still use its IE9 JS engine, rather than the true ones from IE7 and IE8. And I'm sure even the rendering engines aren't 100% accurate.
In all my searching for the holy grail of IE testing, there only one thing that you can truly depend on: testing actually on a Windows OS running that browser. Microsoft offers a program called Virtual PC and provides downloads for virtual discs that contain different versions of Windows & IE.
If you really want accuracy, this is the only way to go.


text:
Q: Getting rid of scaffold.css in rails I want to get rid of the default css stylesheet app/assets/stylesheets/scaffold.css.scss but when I delete it and run the server the styles still seem to be there.

A: Check out your public ( or public/assets ) folder.  You may be serving a 'precompiled' version from public/stylesheets ( or public/assets ).  I think you can rake assets:precompile to update your file.  Vaguely remember having to do something like this when I was working with some code that someone else had configured the project.

A: Clean up your precompiled assets using:
rake assets:clean


text:
Q: InvalidValueError: not an instance of HTMLInputElement Angular 5 I'm trying to do autocomplete for an address using the google mapsAPI in my app, but I keep getting the "InvalidValueError: not an instance of HTMLInputElement" error. Below are the things I have tried
html input inside of a form. As you can see I tried the focus trick and it didn't work either.
 <input id="address" type="text" name="address" #address="ngModel" [(ngModel)]="markersService.selectedMarker.address" placeholder="Address"
    autocorrect="off"
    autocapitalize="off"
    spellcheck="off"
    class="inputFields"
    required
    (focus)="autocompleteSearch()"/>

.ts file
 //I implemented this in an app with Angular 4 and it worked, now with Angular5 it' doesn't
 ngAfterViewInit() {
    this.autocompleteSearch();
 }

  autocompleteSearch() {
    /*
    I tried this trick based on some answers I saw in different places, but it didn't work
    var addressInput = document.getElementById('address').getElementsByTagName('input')[0];
    of course I was passing this in the code below instead of the addressElement
    */
    this.mapsAPILoader.load().then(
      ()=>{
        let autocomplete = new google.maps.places.Autocomplete(this.addressElement.nativeElement, { types:["address"]});
        autocomplete.addListener('places_changed', ()=> {
          this.ngZone.run(()=> {
            let place: google.maps.places.PlaceResult = autocomplete.getPlace();

            if(place.geometry === undefined || place.geometry === null) {
              return;
            }
          });
        })
      }
    )
  }

I tried 4 different things, no luck to get this to work

A: The template reference variable #address is tied to ngModel. You could define another one, like #address1:
<input #address1 #address="ngModel" ... >

and use it to access the element in code:
@ViewChild('address1') public addressElement: ElementRef;

...

let inputElement = this.addressElement.nativeElement as HTMLInputElement;


text:
Q: Using a subquery in a dynamic where clause I'm trying to do the following:
SELECT *
FROM myTable
WHERE workplace IN
    (CASE @param
        WHEN 'a' THEN (SELECT workplace
                      FROM workPlaceTable
                      WHERE condition1)
        WHEN 'b' THEN (SELECT workplace
                      FROM workPlaceTable
                      WHERE condition2)
    END)

This will always return:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Has anybody an idea how I can realize this without an if and repeating the query?

A: I don't think you need the subquery at all, just use a JOIN with a WHERE clause:
SELECT T1.*
FROM myTable T1
INNER JOIN workPlaceTable T2 ON T1.workplace = T2.workplace
WHERE (@param = 'a' AND condition1) OR (@param = 'b' AND condition2)

If @param = 'a' then condition1 will be evaluated, otherwise condition2 will be evaluated.

A:
Has anybody an idea how I can realize this without an if and repeating
  the query?

Something like this could work for you.
select *
from myTable
where @Param = 'a' and workplace in (
                                    select workplace
                                    from workPlaceTable
                                    where condition1
                                    ) or
      @Param = 'b' and workplace in (
                                    select workplace
                                    from workPlaceTable
                                    where condition2
                                    );

A: To elaborate on @Allan's answer, a join would look something like this:
SELECT myTable.*
FROM myTable
INNER JOIN workPlaceTable ON myTable.workplace = workPlaceTable.workplace AND
(
    (@param = 'a' AND <<condition1>>) OR (@param = 'b' AND <<condition2>>)
)

By the way, this question has nothing to do with dynamic-sql.

A: You can try this;

SELECT *
  FROM myTable
 WHERE (@param = 'a' and
       workplace in
       (SELECT workplace FROM workPlaceTable WHERE condition1))
    OR (@param = 'b' and
       workplace in
       (SELECT workplace FROM workPlaceTable WHERE condition2))


text:
Q: Need to access NSArray object that contains CLLocation information I am new to objective-c and have been trying to work on this problem for the past 2 and a half hours. So far I was able to have some success and my app can start searching for the user's location as soon as the app is launched.
I then setup a delegate for CLLocationManager based off of this advice:
"Add the syntax to declare that this class (the ViewController.h/m) is adopting this particular protocol. By default, any other classes that create an instance of this class will also automatically adopt the protocol.
@interface ViewController : UIViewController <CLLocationManagerDelegate>

The line of code listed above shows the syntax used to show ViewController adopts the CLLocationManagerDelegate protocol. We simply add it between angled brackets <> in the @interface line in the header."
So I successfully added the above line inside my ViewController.m and ViewController.h file, and then I also followed that same tutorials advice of:
"The full method is:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

and when implemented it tells the delegate that new location data is available. We have two arguments on this method. The first lets you know which CLLocationManager provided the update and the last provides the CLLocation information which is stored in an NSArray."
Below is all of my ViewController.h code and then next wll be my ViewController.m code:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController <CLLocationManagerDelegate>

@property (nonatomic, strong) IBOutlet UILabel *gpsLabel;

-(IBAction)gpsButton;

@end

Here is my ViewController.m code:
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager * gpsLM;

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;

@end

@implementation ViewController

- (void)viewDidLoad
{

[super viewDidLoad];

self.gpsLM = [[CLLocationManager alloc]init];

[self.gpsLM startUpdatingLocation];

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

-(IBAction)gpsButton{

}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

}

@end

I am confused on where to go from here. Assuming I am even doing everything correctly so far(am I?), then how do I access the location data that has been stored in the NSArray object called locations?
Thank you for the help.

A: Welcome to the iOS community!
First, you'll probably find it helpful to look at the CLLocationManagerDelegate reference, under the heading for the locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations method.  The important bit here is:

locations: An array of CLLocation objects containing the location data.
  This array always contains at least one object representing the
  current location. If updates were deferred or if multiple locations
  arrived before they could be delivered, the array may contain
  additional entries. The objects in the array are organized in the
  order in which they occurred. Therefore, the most recent location
  update is at the end of the array.

The important thing to get is that this method is called by the system when the user's location changes.
So, for instance, you could print out a message to your console when the location updates by changing your implementation to something like:
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *currentLocation = [locations lastObject];
    NSLog(@"Location is: %.5f %.5f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
}

If you instead want to do something in response to user activity, you could use manager.location, which is automatically updated every time the CLLocationManager detects a new location.  (If this didn't exist, you would need to add another instance variable to your class to store the most recent location, and update that in locationManager:didUpdateLocations:.)
So, for instance, if you wanted to update your label with the current location whenever the button was pressed, you could add something like:
-(IBAction)gpsButton {
    CLLocation *currentLocation = self.gpsLM.location;
    self.gpsLabel.text = [NSString stringWithFormat:@"Location is: %.5f, %.5f"];
}

(Note: this assumes that the gpsButton action and the gpsLabel outlet are hooked up to something graphically in Interface Builder.)
If you're familiar with other programming languages, this is a push versus pull distinction.  CLLocationManager provides a push model (it calls your locationManager:didUpdateLocations: method to inform you immediately of changes), and also a pull model (you can ask it for the most current location through .location at any time).  Which one you use will depend on what you want to do.


text:
Q: How to use wizard assemblies attached in VsixMainfest in project templates? I have a vsixmanifest file that has an assembly attribute. The file looks like:
<Content>
<ProjectTemplate>Solution</ProjectTemplate>
<Assembly AssemblyName="SolutionNameWizard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1c39bfcc-223f-4c12-a5dc-55eeca7c61f7">
    Assemblies\SolutionNameWizard.dll
</Assembly>

I know that the assembly name and public key are correct.
Now, I am trying to use this assembly in one of my templates. Right now I have:
<WizardExtension>
      <Assembly>SolutionNameWizard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1c39bfcc-223f-4c12-a5dc-55eeca7c61f7</Assembly>
      <FullClassName>SolutionNameWizard.IWizardImplementation</FullClassName>
</WizardExtension>

Is there something that I am missing? When I run the vsix I get the following error:
A problem was encountered creating the sub project 'test.Web' Error: this template
attemtped to load component assembly 'SolutionNameWizard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1c39bfcc-223f-4c12-a5dc-55eeca7c61f7'.

I know that templates require the assembly to be in the GAC, is that also the case when I am using vsix? I was hoping to avoid the GAC and still use my wizard.
EDIT: I changed the public key to the proper string as suggested in the answers, but am still having the issue.
Edit 2: in addition to the helpful answer below, here is a blog that I wrote after I finished this process. It links to a bunch of articles that I found to be very helpful: https://thebhwgroup.com/blog/2013/10/visual-studio-templates

A: If your assembly is being provided via your VSIX, it does not need to be in the GAC.
Your PublicKeyToken is definitely not correct. You're using a Guid when it should be a 16-character hex string (8 bytes). See the following example:
MyAssembly, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
You can find the PublicKeyToken value for your assembly by running sn.exe -T MyAssembly.dll from a VS command prompt.

A: If anyone else happens to stumble upon this question, I ended up following this guide: http://blog.tonysneed.com/2011/09/14/build-a-multi-project-visual-studio-template/
It made the process (mostly) very easy. If anyone happens to run into similar issues, feel free to contact me and I can try to share what I learned.
Edit: here is short blog article I wrote after completing this process. It might be helpful for someone who stumbles upon this: http://www.thebhwgroup.com/blog/2013/10/visual-studio-templates/


text:
Q: Quick Search with autocorrect (GIN INDEX and PG_TRGM extension) I am testing a simple search mechanism to handle SMALL typos/misspellings. Similar to a autocorrect mechanism.
I am struggling a lot with this. So I am creating a function (pl/pgsql) to handle this, and I am running it on SUPABASE.IO, PostgreSQL 13.3 (similar to RDS).
I would like to:

*

*LIMIT the returned results to only the highly similar email addresses, say similarity > 0.7;

*Use an INDEX as the actual list of emails will be in the order of tens of millions, so it has to return in under a second.

DROP TABLE IF EXISTS email;
CREATE TABLE email (
  email_address TEXT NOT NULL UNIQUE,
  person_id UUID NOT NULL,
  CONSTRAINT email_pk PRIMARY KEY (email_address)
);

DROP INDEX IF EXISTS email_address_trigram_idx;
CREATE INDEX email_address_trigram_idx ON email USING gin(email_address gin_trgm_ops);

INSERT INTO email(email_address, person_id) VALUES
  ('test100@gmail.com', uuid_generate_v4())
, ('100test@gmail.com', uuid_generate_v4())
, ('testoo1000@gmail.com', uuid_generate_v4())
, ('test1001@gmail.com', uuid_generate_v4())
, ('test100@gmial.com', uuid_generate_v4())
, ('test200@gmail.com', uuid_generate_v4())
, ('200test@gmail.com', uuid_generate_v4())
, ('testoo2000@gmail.com', uuid_generate_v4())
, ('test2002@gmail.com', uuid_generate_v4())
, ('test200@gmial.com', uuid_generate_v4())
, ('test300@gmail.com', uuid_generate_v4())
, ('300test@gmail.com', uuid_generate_v4())
, ('testoo3000@gmail.com', uuid_generate_v4())
, ('test3003@gmail.com', uuid_generate_v4())
, ('test300@gmial.com', uuid_generate_v4())
, ('test400@gmail.com', uuid_generate_v4())
, ('400test@gmail.com', uuid_generate_v4())
, ('testoo4000@gmail.com', uuid_generate_v4())
, ('test4004@gmail.com', uuid_generate_v4())
, ('test400@gmial.com', uuid_generate_v4())
, ('tset100@gmail.com', uuid_generate_v4())
, ('100tset@gmail.com', uuid_generate_v4())
, ('tsetoo1000@gmail.com', uuid_generate_v4())
, ('tset1001@gmail.com', uuid_generate_v4())
, ('tset100@gmial.com', uuid_generate_v4())
, ('tset200@gmail.com', uuid_generate_v4())
, ('200tset@gmail.com', uuid_generate_v4())
, ('tsetoo2000@gmail.com', uuid_generate_v4())
, ('tset2002@gmail.com', uuid_generate_v4())
, ('tset200@gmial.com', uuid_generate_v4())
, ('tset300@gmail.com', uuid_generate_v4())
, ('300tset@gmail.com', uuid_generate_v4())
, ('tsetoo3000@gmail.com', uuid_generate_v4())
, ('tset3003@gmail.com', uuid_generate_v4())
, ('tset300@gmial.com', uuid_generate_v4())
, ('tset400@gmail.com', uuid_generate_v4())
, ('400tset@gmail.com', uuid_generate_v4())
, ('tsetoo4000@gmail.com', uuid_generate_v4())
, ('tset4004@gmail.com', uuid_generate_v4())
, ('tset400@gmial.com', uuid_generate_v4())
, ('different_email@yahoo.com', uuid_generate_v4());

SET pg_trgm.similarity_threshold = 0.8; -- This doesn't seem to affect my queries

SELECT *, similarity('tesd100@gmail.com', email_address)
FROM email
WHERE email_address % 'tesd100@gmail.com';

I want a way of searching quickly and still tolerate some minor typos in the search.

A: First off, your table definition creates two unique indices on (email_address). Don't. Drop the UNIQUE constraint, keep the PK:
CREATE TABLE email (
  email_address text PRIMARY KEY
, person_id uuid NOT NULL  -- bigint?
);

(Also not sure why you would need uuid for person_id. There aren't nearly enough people in the world to justify more than a bigint.)
Next, since you want to ...

LIMIT the returned results to only the highly similar email addresses,

I suggest a nearest neighbor search. Create a GiST index for this purpose instead of the GIN:
CREATE INDEX email_address_trigram_gist_idx ON email USING gist (email_address gist_trgm_ops);

And use a query like this:
SELECT *, similarity('tesd100@gmail.com', email_address)
FROM   email
WHERE  email_address % 'tesd100@gmail.com'
ORDER  BY email_address <-> 'tesd100@gmail.com'  -- note the use of the operator <->
LIMIT  10;

Quoting the manual:

This can be implemented quite efficiently by GiST indexes, but not by
GIN indexes. It will usually beat the first formulation when only a
small number of the closest matches is wanted.

While working with a small LIMIT, there is probably no need to set pg_trgm.similarity_threshold very high because this query gives you the best matches first.
Related:

*

*Search in 300 million addresses with pg_trgm

*Finding similar strings with PostgreSQL quickly

*PostgreSQL GIN index slower than GIST for pg_trgm?


text:
Q: Bounding the expectation of the difference between empirical vs generalization error Let the (defect) difference between empirical and generalization error be:
$$D[f_S] = I_S[f_S] - I[f_S]$$
where the empirical risk is:
$$I_S[f_S] = \frac{1}{n}\sum^n_{i=1} V(f_S,z_i)$$
where $V(f,z)$ is some loss function and $z_i = (x_i, y_i)$ is some training point (with its label) sampled from its distribution.
Let $f_S$ be the function that was chosen based on looking at the training set $S$.
The generalization error of the $f_S$:
$$I[f_S] = \int_z V(f_S,z)p_z(z) dz$$
We are also assuming that the learning algorithm $\mathcal{A}$ that maps training sets to predictor functions $f \in \mathcal{H}$ is beta-stable (uniform stable). i.e.
$$\forall(S,z) \in \mathcal{Z}^{n+1}, \forall i, \sup_{z' \in \mathcal{Z}} |V(f_S, z') - V(f_{S^{i,z}, z'})| \leq \beta $$
where $S^{i,z}$ is the "old"/original training with the ith training point replaced with new sample/training point $z$. Thus, $f_{S^{i,z}}$ is the predictor trained with this new training data (but the same training algorithm).
I was looking at the lecture slides on this page and was confused about slide 20 (titled Bounding the expectation of the Defect).
In it it has the following equation:
$$\mathbb{E}_S[D[f_S]] = \mathbb{E}_S[I_S[f_S] - I[f_S]]$$
$$ = \mathbb{E}_{(S,z)}[\frac{1}{n} \sum^n_{i=1}[ V(f_S, z_i) - V(f_S,z) ]$$
That equality on that slide does not make sense to me nor does the following equality. Does someone understand why they are true?
The slides do have the following explanation for it (which does not make sense to me):

The second equality follows by the "symmetry" of the expectation: the expected value of a training set on a training point doesn't
  change when we "rename" the points.

After that it continues and writes:
$$ = \mathbb{E}_{(S,z)}[\frac{1}{n} \sum^n_{i=1}[ V(f_S^{i,z}, z) - V(f_S,z) ]$$
Which I am not 100% sure if I understand why thats valid and the last one must be some argument related to the stability of the learning algorithm...
$$\leq \beta $$

Anyway, this is what I have tried to make sense of the slide so far:
First I expanded the RHS of the first equality:
$$ \mathbb{E}_S[D[f_S]] = \mathbb{E}_S[I_S[f_S] - I[f_S]] = \mathbb{E}_{S}[\frac{1}{n} \sum^{n}_{i=1}V(f_S, z_i) - \mathbb{E}_z[V(f_S,z)] ]$$
Then it seems that its just ok to "pull out" the expectation wrt (with respect to) to a single training point wrt to all values the training point could take but I can't see why thats ok. i.e.
$$\mathbb{E}_{S}[ \mathbb{E}_z [ \sum^{n}_{i=1} V(f_S, z_i)] - \mathbb{E}_z[V(f_S,z)] ] = \mathbb{E}_{S}[ \mathbb{E}_z [ \sum^{n}_{i=1} V(f_S, z_i) - V(f_S,z) ] $$
I do understand that $z_i$ is a specific value that we sampled. So its a random variable. However, how does that not break the previous equality that we had already established? Btw, before someone says that its ok because of linearity of expectation, my question would be why is $\mathbb{E}_z$ a valid operator in the first place when taken over $\mathbb{E}_S[I_S[f_S]]$, i.e. shouldn't it change the value of $\mathbb{E}_S[I_S[f_S]]$
I do understand that when we have a sample say $s_i$, then $\mathbb{E}_s[s_i]=\mathbb{E}_s[s]$ because $s_i$ is just the random variable s. However, I cannot see why its the same in this case...or how that kind of argument applies here...

Thinking about it some more, this is the only justification I have (which I won't lie, I am not satisfied with it because I am not sure of its correctness).
$$\mathbb{E}_{S}[I_S[f_S]]$$
Is just a "constant". i.e. its the value we expect of the empirical risk using $f_S$ as the predictor function. Thus taking the expectation wrt to a single training point does/changes nothing.
$$\mathbb{E}_{S}[I_S[f_S]] = \mathbb{E}_z\mathbb{E}_{S}[I_S[f_S]]$$
which kind of resolves part of the issue.


text:
Q: Why Does the FormClosed Event Handler Get Called Twice? StackOverflow may not be the correct place to as a why question, but I am looking for a because answer rather than a how to answer. I have already worked around the problem by disabling the handler in the hander.
The application has a DataGridView that displays inventory information during incoming inspection. The data grid is too wide for the screen and requires horizontal scrolling. To make the data easier to see and edit a modal editor has been added. There are 2 buttons to close the modal editor, either Save or Cancel. Using the close button at the top right corner of the modal editor form should perform the same action as the cancel button.
When the cancel button is clicked everything works fine. When the close button is clicked the modal editor FormClosed event fire twice. Why is the modal editor FormClosed event firing twice? Do I have a bug in my code?
    private bool CancelModalEditor()
    {
        bool cancelled = false;

        string cancelMsg = (_cancelClicked) ? "Canceling" : "Closing";
        cancelMsg += " the editor will delete the Record with Serial Number: " + SerialNumber + " from the Audit Session. Is this what you want to do?";

        DialogResult dlg = MessageBox.Show(cancelMsg, "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
        if (dlg == DialogResult.Yes)
        {
            SaveClicked = false;
        }
        else
        {
            cancelled = true;
        }

        return cancelled;
    }

    private void AEMEBtn_Cancel_Click(object sender, EventArgs e)
    {
        _cancelClicked = true;
        if (!CancelModalEditor())
        {
            Close();
        }
        else
        {
            _cancelClicked = false;
        }
    }

    private void AEModalEditor_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        if (!_cancelClicked && !SaveClicked)
        {
            if (CancelModalEditor())
            {
                e.Cancel = true;
            }
            else
            {
                _cancelClicked = true;      // Prevent Infite Loop
                Close();
            }
        }
    }

File where modal editor is invoked.
    private void ModalEditorForm_Closed(object sender, FormClosedEventArgs e)
    {
        AEModalEditor modalEditor = (AEModalEditor)sender;
        int currentRow = modalEditor.RowID - 1;

        if (modalEditor.SaveClicked)
        {
            UpdateDataGridRowWithModalEditorValues(dgAssetDetails, currentRow, modalEditor.AssetControlsValues);
            updateAuditDetailsDataGridRow(currentRow, modalEditor.AuditControlsValues);
            UpdateAuditTextFields(modalEditor);
            SelectAllCellsInRow(currentRow);
        }
        else
        {
            DeleteRowFromAllDataGridViews(modalEditor.SerialNumber, currentRow);
            _previouslySelectedRow = -1;
        }

        // Save all records in either case so that session data isn't lost.
        save(false);

        _currentlySelectedDataGrid = DataGrids.None;
        _modalEditorOpen = false;
        txtSerialNumber.Focus();
    }

A: Don't call close in the closing-event again. The form is already closing and don't need to be closed a second time.
private void AEModalEditor_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
    if (!_cancelClicked && !SaveClicked)
    {
        if (CancelModalEditor())
        {
            e.Cancel = true;
        }
        else
        {
            _cancelClicked = true;
            // You called Close here again
            Close();
        }
    }
}


text:
Q: jQuery validate different field depending on a checkbox I'm trying to use jQuery validation plugin to validate a form I have on one of my applications.
The form (simplified) is as follow :
<form id="my_form" action="#" method="post" novalidate="novalidate">
    <input id="my_hidden_input" type="text" style="display:none;">
    <input id="my_select_checkbox" class="checkbox" type="checkbox" value="1">
    <select id="my_select_1" class="select valid" type="select">
    <select id="my_select_2" class="select valid" type="select">
</form>

What I'm trying to do is to validate the following : if the checkbox is checked, I check that a value is selected in my first select, and if the checkbox isn't checked, I check the selected value of my second list.
I tried something like :
$('#my_form').validate({ // initialize the plugin
    rules: {
        my_hidden_input:{
            "checkboxSelect": true,
        },
    },
    submitHandler: function (form) { // for demo
        console.log($("#monitors_start").value);
        return false;
    }
});

jQuery.validator.addMethod(
    "checkboxSelect",
    function() {
        if ($("#my_select_checkbox").attr('checked'))
            return $("#my_select_1").val();
        else
        return $("#my_select_2").val();
    }, "test addMethod"
);

But it seems i'm not getting it properly... If anybody could help it'd be greatly appreciated !
Thanks !

A: You can use the depends option like
var validator = $('#form').validate({
    rules: {
        my_select_1: {
            required: {
                depends: function () {
                    return $('#my_select_checkbox').is(':checked')
                }
            }
        },
        my_select_2: {
            required: {
                depends: function () {
                    return !$('#my_select_checkbox').is(':checked')
                }
            }
        }
    },
    messages: {}
});

Demo: Fiddle


text:
Q: Value object encapsulating domain logic We use DDD in our project in financial domain.
I have a value object:
final class VatRate extends DecimalNumber {

}

abstract class DecimalNumber
{
    public static function fromString(string $number): static
    {
        return new static(\Brick\Math\BigDecimal:of($number));
    }
}

I need to create zero vat rate in domain aggregate.
Both aggregate and VatRate exists in domain layer.
This is the way I am doing it:
$zeroVat = VatRate::fromString('0.0');

I was told it is not right. I should doing it this way:
final class VatRate extends DecimalNumber {
    public static function zero(): self
    {
        return self::fromString('0.0');
    }
}

$zeroVat = VatRate::zero();

What is the point to encapsulate domain logic in this case?
The only response I had is that it is more "Domain" way of doing things.
When I need to create VAT rate 0.20 then should I similarly create static method VatRate::zeroPointTwenty()?
What are the pros and cons of both solutions?

A:
What is the point to encapsulate domain logic in this case?

"Information hiding" -- see Parnas 1971.
Basic idea, by creating a seam between the code that knows how to use a zero and the code that knows how to create a zero, we reduce the amount of code directly impacted if we need to change the underlying data structure or initialization routine.
In addition, by introducing a seam, you create the opportunity to introduce an intention revealing name.
If your development environment has a decent indexer, you'll easily be able to find usages of zero without getting your results cluttered with a bunch of other calls to fromString with different arguments.
Another way of thinking about this: strings are not "of the financial domain", they are the general purpose data structure that this implementation just happens to use.  Therefore, they don't "belong" in the domain specific language we are creating to describe to programmers how this code does something useful to the business.
There are lots of ways we can tell the computer to do the right thing.  The goal is to use that freedom to better communicate with the next programmer to come along.

What are the cons?  It's trade offs all the way down, right?
The main downsides are this: that it's another piece of code to keep track of.  You've got to find a good place to put it, and make sure that everybody who needs it can find it.  If you've got a bunch of "unit" test zealots around, then maybe they are going to insist on a bunch of testing ceremony to go with this new one-line-function.

It's not "free" - especially if it isn't your current habit.  It's extra work we do today, while all of the context is fresh in our minds, so that the people who have to work in this code later have an easier time of it.


text:
Q: ssh through java I am using java ssh tools to make an ssh connection to my school account and look for a file and then delete it.  However I am creating three functions to do the same thing but with different files,  I am looking for a way to do that at the same thing instead of doing one after the other.  Here is some code.  Basically I want to know if there is a way to do this all on one ssh connection or some kind of fork or multithreading.
public void updateinterval() {
    try {
        JSch jsch = new JSch();

        String user = "***********";
        String host = "********";
        Session session = jsch.getSession(user, host, 22);

        session.setPassword("*********");

        // username and password will be given via UserInfo interface.
        UserInfo userInfo = new SftpUserInfo();

        session.setUserInfo(userInfo);

        session.connect();

        // look for a file named feedinterval

        String checkfortimeupdate =
                "cd public_html/final;grep '-send' feedinterval";

        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(checkfortimeupdate);

        // X Forwarding
        // channel.setXForwarding(true);

        // channel.setInputStream(System.in);
        channel.setInputStream(null);

        // channel.setOutputStream(System.out);

        // FileOutputStream fos=new FileOutputStream("/tmp/stderr");
        // ((ChannelExec)channel).setErrStream(fos);
        ((ChannelExec) channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        channel.connect();

        byte[] tmp = new byte[1024];

        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                String returned = new String(tmp, 0, i);

                String argument = returned.substring(6);

                if (returned.contains("-send")) {

                    // if its there its calls the removeinterval function
                    // which removes the file it found
                    // by doing the same thing this function does but with a
                    // different ssh command

                    arduinoupdate hey = new arduinoupdate();

                    hey.removeinterval();

                    try {
                        Runtime rt = Runtime.getRuntime();

                        String[] commands = {
                                "system.exe", "-send", argument };

                        Process proc = rt.exec(commands);
                    }

                    catch (IOException e) {
                    }
                }
            }

            if (channel.isClosed()) {
                System.out.println("UpdateInterval Closed exit-status: "
                        + channel.getExitStatus());
                break;
            }
            try {
                /* Thread.sleep(1000); */
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
    } catch (Exception e) {
        System.out.println(e);
    }
}

A: If you want to run multiple tasks perhaps ExpectJ would work better for you. ExpectJ uses JSCH under the covers, so this may make your life easier.
final ExpectJ expectJ = new ExpectJ();
final Spawn spawn = expectJ.spawn("host", 22, "user", "pass");
spawn.send("cd public_html/final\n");
spawn.expect("someReturn");
...
spawn.send("exit\n");
spawn.expectClose();

A: As said by the commenters, better factor it out in separate functions.
Then is gets more clear how to reuse the same connection (i.e. Session) for several commands.
public void updateInterval(Session s, String filename) {
    String checkfortimeupdate = "fgrep '-send' \"public_html/final/" + filename + "\"";

    ChannelExec channel = (ChannelExec)session.openChannel("exec");
    channel.setCommand(checkfortimeupdate);

    channel.setInputStream(null);
    channel.setErrStream(System.err);
    BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream(), encoding));

    channel.connect();

    eatOutput(in);

    if (channel.isClosed()) {
        System.out.println("UpdateInterval Closed exit-status: "
                           + channel.getExitStatus());
        break;
    }
    channel.disconnect();
}

Then put the reading from the BufferedReader (it has a readLine method) in the method eatOutput, and have another method which opens the session and calls three times the method shown here (with different file names), and closes the session again.

A: In respect to the usage of ExpectJ,
which is the best library to use in machine critical production application for expect based functionality?
ExpectJ or Expect4J library? Though, both library uses the JSch underneath!
Or Apache SSHD - Client:
SshClient client = SshClient.setUpDefaultClient(); PipedOutputStream PipedIn...?


text:
Q: C++-Python Interop: Marshalling data faster I'm working on an app that has a C++ and Python API, and am implementing an API call that needs to be used in both languages. Part of the data this API sends back is an array of structs representing color information:
struct {
    float r;
    float g;
    float b;
    float a;
} Foo_Pixel;

In my interop code, I marshal the data thusly:
Foo_Pixel color;

PyObject* tileValues = PyList_New( numValues );

for (int pixelIndex = 0; pixelIndex < numValues; pixelIndex++)
{
  color = value[pixelIndex];
  PyObject* newColourItem = Py_BuildValue("ffff", color.r, color.g, color.b, color.a);
  PyList_SetItem(tileValues, pixelIndex, newColourItem);
}

Essentially, I'm looping over the provided data and am building a list of tuples for the user to consume. However, this seems a little inefficient to me. Is there a faster way to create a PyObject out of an array of float structs?

A: Before Py_BuildValue can build the tuple you want, it needs to parse the format string you give it to determine the type and number of its arguments as well as what the returned PyObject will be.  If you know all this ahead of time, you can skip these steps and build the tuple directly:
PyObject* newColourItem = PyTuple_New(4);
PyTuple_SET_ITEM(newColourItem, 0, PyFloat_FromDouble(color.r));
PyTuple_SET_ITEM(newColourItem, 1, PyFloat_FromDouble(color.g));
PyTuple_SET_ITEM(newColourItem, 2, PyFloat_FromDouble(color.b));
PyTuple_SET_ITEM(newColourItem, 3, PyFloat_FromDouble(color.a));

You'll notice too that I used PyTuple_SET_ITEM instead of PyTuple_SetItem.  The two functions are the same except that the first does not perform any error checking.  Thus, it is more efficient, but also dangerous if you give it a bad index.  However, this is not a problem here since we know exactly what indexes we are filling.
On the same note, you could replace PyList_SetItem with PyList_SET_ITEM.  Since you already know the indexes that you are using are valid, checking for errors is unnecessary here.
That is about all you can do however.  There are no API functions for what you are doing and the code you posted was already pretty efficient to being with.  If you are trying to improve the overall speed of your application, I would look elsewhere for optimizations.


text:
Q: Detect if event listener is attached to directive in Angular In my directive, I have the following event defined:
function wizard() {
    return {
        scope: {
            raiseCancel: '&onCancel'
        },

And then further down, I attempt to check if a listener is attached. If one is not, I want to execute some default behavior.
if (scope.raiseCancel) scope.raiseCancel();
else $window.history.back();

But apparently scope.raiseCancel will always be truthy because Angular assigns an anonymous function that calls angular.noop when no event listener is attached. How can I detect if there is a listener for my event?

A: You should handle your raiseCancel as an event handler, returning false to prevent the default behaviour.
Of course that mean code change in the raiseCancel handler(s) passed
if (scope.raiseCancel == null || scope.raiseCancel() !== false) {
    $window.history.back();
}


text:
Q: How to create a modal that shows blog-posts in blogger homepage? I have a blogger website; in the homepage (index page) there are blog-posts (thumbnail, title, snippets and "view" button). I need to create a modal that pops-up when the "view" button is clicked. It should show blog-post title, image thumbnail and some other post details.
How to achieve that please ?
I tried java script but the modal shows only one blog-post when click on each "view" button.

<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css' rel='stylesheet'/>


text:
Q: The norm of $f_n : \ell^2 \to \mathbb{R}$, where $f_n(x) = \sum_{k=1}^{n} a_kx_k$ Let $ \ f_n :\ell^2 \to \mathbb{R} $ such  that $ \ell^2 = \{ x = (x_n)_n,  \sum_{k=0}^\infty |x_k|\lt \infty \}$, $f_n(x) = \sum_{k=1}^{n} a_kx_k$ and $a=(a_n)_{n\geq1}$ is a sequence of real numbers.
Proof that for every $n\geq 1$, $f_n$ is a continuous and find its norm.
My attempt:
$$|f_n(x)|=\left| \sum_{k=1}^{n} a_kx_k\right| \leq \sum_{k=1}^{n}|a_k||x_k|\leq M||x||_{\ell^2}$$ Where
$M= \sup_n\sum_{k=1}^{n}|a_k|$
Hence $f_n$ is bounded implies continuous.
To find the norm  we have that
$$|f_n(x)|\leq M||x||_{\ell^2}$$
then  $||f_n||\leq M$
but i dont know how to show $||f_n||\geq M$.
Anyway is what I did right?

A: Hint:
From $|f_n(x)|=\left| \sum_{k=1}^{n} a_kx_k\right| \leq \sum_{k=1}^{n}|a_k||x_k|,$ apply Cauchy-Schwarz inequality on the finite sum up to $n$. Then use the fact that $\left( \sum_{k=1}^nx_k^2\right)^{1/2}\leq \|x\|_2$. This will allow you to establish an $M_n$ such that $|f_n(x)|\leq M_n \|x\|_2$.
To establish that this $M_n$ is also the norm of the operator $f_n$, consider the sequence
$$
x_k=
\begin{cases}
a_k,& k\leq n \\
0,&k>n
\end{cases}
$$


text:
Q: Cron jobs output on console I have written a shell script (myscript.sh):
#!/bin/sh
ls
pwd

I want to schedule this job for every minute and it should display on the console. In order to do that I have done crontab -e:
*/1 * * * * /root/myscript.sh

Here, it's display the output in the file /var/mail/root rather than printing on the console.
What changes I have to make inorder to print the output on console?

A: The easiest way I can think of is to log the output to disk and have a console window constantly checking to see if the logfile has been altered and printing the changes.
crontab:
*/1 * * * * /root/myscript.sh | tee -a /path/to/logfile.log

in console:
tail -F /path/to/logfile.log

The problem with this is that you will get an ever growing log file which will need to be periodically deleted.
To avoid this you would have to do something more complicated whereby you identify the console pid that you wish to write to and store this in a predefined place.
console script:
#!/usr/bin/env bash

# register.sh script
# prints parent pid to special file

echo $PPID > /path/to/predfined_location.txt

wrapper script for crontab
#!/usr/bin/env bash

cmd=$1
remote_pid_location=$2

# Read the contents of the file into $remote_pid.
# Hopefully the contents will be the pid of the process that wants the output
# of the command to be run.
read remote_pid < $remote_pid_location

# if the process still exists and has an open stdin file descriptor
if stat /proc/$remote_pid/fd/0 &>/dev/null
then
    # then run the command echoing it's output to stdout and to the
    # stdin of the remote process
    $cmd | tee /proc/$remote_pid/fd/0
else
    # otherwise just run the command as normal
    $cmd
fi

crontab usage:
*/1 * * * * /root/wrapper_script.sh /root/myscript.sh /path/to/predefined_location.txt

Now all you have to do is run register.sh in the console you want the program to print to.

A: I tried to achieve the output of a cron job to a gnome terminal , and managed it by this
*/1 * * * * /root/myscript.sh > /dev/pts/0

I suppose if you do not have a GUI and you only have CLI you might use
*/1 * * * * /root/myscript.sh > /dev/tty1

to achieve the output of a crontab job to be redirected to your console. But first be sure to find the name of your terminal. if it is /dev/tty1 or something else. I am not sure how this can be done for all cases, probably with something like
env | grep -i tty

A: One option would be to use "wall" in your script to display a message to all terminals. E.G.
wall -n Display this message to all terminals.


text:
Q: `ngAnimate` - integration issue I have installed my angular using bower. here is my bower.json
{
  "name": "TCP",
  "version": "1.0.0",
  "dependencies": {
    "jquery": "~2.1.4",
    "angular": "~1.4.1",
    "angular-animate": "~1.4.1"
  },
  "resolutions": {
    "angular": "~1.4.1"
  }
}

And I am initiating the angular-animate in the app.js like this:
(function () {

    "user strict";

    angular.module("tcpApp", ["ngRoute","ngResource", "ngAnimate"])

    .config(function ($routeProvider, $locationProvider) {

        $routeProvider
            .when ("/", {
                templateUrl : "views/login/login.html",
                controller  : "loginController",
                className   : "login"
        });

        $routeProvider
            .when ("/home", {
                templateUrl : "views/home/home.html",
                controller  : "homeController",
                className   : "home"
        });

        $routeProvider
            .otherwise ({
                redirectTo:'/'
        });
    })

})();

Now I want to fade-in my login page while the page loads. I have applied a class name as .loginAnimate and keeping the style in the index page, as like this:

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <base href="/">
    <title>TCP App</title>
    <link rel="stylesheet" href="css/lib/fonts.css">
    <link rel="stylesheet" href="css/lib/reset.css">
    <link rel="stylesheet" href="css/tcp.css">
    <link rel="stylesheet" href="css/config.css">
    <link rel="stylesheet" media="screen and (min-width: 768px)"  href="css/mobile768.css">
    <link rel="stylesheet" media="screen and (max-width: 320px)"  href="css/mobile320.css">

But the animation is not working at all. and i am not getting ng-active class name in the ng-view. any one help me to solve this issue please?

A: I removed the  from adjust of the ng-view and added to login.html page. now this is works for me.
Should not we add any adjacent to ng-view ?
before:

         //removed

Now my wrapper is look like this:


text:
Q: Как упросить конструкцию Дано задание упросить конструкцию до 1 строки кода
with open('text.txt', 'a') as f:
    i = ' '
    while True:
        i = input()
        f.write(i + '\n')
        if i == '':
            break

У меня вышло упростить лишь до 2 строк кода
i = ' '
while bool(i): i = input(); open('text.txt', 'a').write(f'{i}\n')

A: while s := input():print(s, file=open('test.txt', 'a'))

либо так:
print(*iter(input, ''), sep='\n', file=open('test.txt', 'a'))

Если в iter передать два аргумента, то он будет вызывать первый аргумент (input), до тех пор, пока результат не будет равен второму аргументу ('')

A: спасибо @Danis, что напомнил про возможности функции iter
open('text.txt', 'a').write('\n'.join(iter(input, '')))


text:
Q: How to get the long 'less' prompt with sudo? I have added the following to my user's .bashrc file to get a longer prompt in less:
export LESS="-M"

This is added to the root user's .bashrc file as well, so when I sudo bash to get a root shell, it works just as well.
But when using sudo less …, it doesn't apply. There's only the simple colon prompt giving me no information at all where I am in the file. How can I change that?

A: You should keep this environmental variable when running sudo. Edit the file /etc/sudoers and add
Defaults        env_keep += "LESS"

A: You need to be using aliases in your .bashrc file not export. You need to be editing your /etc/bash.bashrc file to inclide,
  alias less="sudo less -m"
more info from this POST


text:
Q: What is the proper way to extract XMLElement values? I have seen and tried many different versions of XML data parsing here on this forum, and even some in the documentation. Is there a tried and true "Best Practice" way to extract all the XMLElement values or is each new file type a hack a thon to extract the correct data and fields? Here's the code I'm using now, but it's not efficient and does not grab all the values needed. Is there a better way?
a=thePartIreallyneeded;
elements = Column@Cases[dat,
XMLElement[tag : _, _, value : _] :> (tag -> value), Infinity];
pairsE = List @@ elements;
gatheredE = GatherBy[pairsE, #[[1]] &];
propertiesE = Part[#, 1, 1] & /@ gatheredE;
targetPositionsE = gatheredE[[a]];

Here is a very small snippet of the section of values I'd like to extract.  What I need to get are the Color Names, the Target Id values and the values for each color name. Thank you!
XMLElement[{"http://colorexchangeformat.com/CxF3-core", "Resources"}, {}, \
{XMLElement[{"http://colorexchangeformat.com/CxF3-core",
"ObjectCollection"}, {}, \
{XMLElement[{"http://colorexchangeformat.com/CxF3-core",
  "Object"}, {"ObjectType" -> "Target", "Name" -> "Target1",
  "Id" -> "c1"}, \
{XMLElement[{"http://colorexchangeformat.com/CxF3-core",
    "CreationDate"}, {}, {"2013-05-17T11:59:45-06:00"}],
  XMLElement[{"http://colorexchangeformat.com/CxF3-core",
    "DeviceColorValues"}, {}, \
{XMLElement[{"http://colorexchangeformat.com/CxF3-core",
      "ColorCMYK"}, {"ColorSpecification" ->
       "Unknown"}, \
{XMLElement[{"http://colorexchangeformat.com/CxF3-core",
        "Cyan"}, {}, {"0"}],
      XMLElement[{"http://colorexchangeformat.com/CxF3-core",
        "Magenta"}, {}, {"0"}],
      XMLElement[{"http://colorexchangeformat.com/CxF3-core",
        "Yellow"}, {}, {"0"}],
      XMLElement[{"http://colorexchangeformat.com/CxF3-core",
        "Black"}, {}, {"0"}]}]}]}],
 XMLElement[{"http://colorexchangeformat.com/CxF3-core", "Object"}, {"ObjectType" ->   "Target", "Name" -> "Target11", "Id" -> "c11"}, \
{XMLElement[{"http://colorexchangeformat.com/CxF3-core",
"CreationDate"}, {}, {"2013-05-17T11:59:45-06:00"}],
 XMLElement[{"http://colorexchangeformat.com/CxF3-core",
"DeviceColorValues"}, {}, \
{XMLElement[{"http://colorexchangeformat.com/CxF3-core",
  "ColorCMYK"}, {"ColorSpecification" ->
   "Unknown"}, \
{XMLElement[{"http://colorexchangeformat.com/CxF3-core",
    "Cyan"}, {}, {"11.596052607559"}],
  XMLElement[{"http://colorexchangeformat.com/CxF3-core",
    "Magenta"}, {}, {"25.435485248175"}],
  XMLElement[{"http://colorexchangeformat.com/CxF3-core",
    "Yellow"}, {}, {"0"}],
  XMLElement[{"http://colorexchangeformat.com/CxF3-core",
    "Black"}, {}, {"0"}]}]}]}]}]}]

A: This is one way. Using data=xmlInfo
nodes=Cases[data,XMLElement[{_,"Object"},{"ObjectType"->"Target","Name"->target_,"Id"->id_},{x__}]:> {target,id,{x}} ,\[Infinity]];
getColors=Cases[#,XMLElement[{_,color_/;MemberQ[{"Cyan","Yellow","Black","Magenta"},color]},{},{value_}]-> {color,value},\[Infinity]]&;
nodes[[All,3]]=getColors/@nodes[[All,3]];
nodes

{{Target1,c1,{{Cyan,0},{Magenta,0},{Yellow,0},{Black,0}}},{Target11,c11,{{Cyan,11.596052607559},{Magenta,25.435485248175},{Yellow,0},{Black,0}}}}

I really I'm not confortable in parsing XML like this. I fell it's clumsy, but it's they the only way I know until now.


text:
Q: WHERE and AND clause not return values I have this PostgreSQL SQL query for selection few values from 4 tables joined by INNER JOIN, and I have problem with returning a value.
Select u.id,u.name,u.image,u.created_at as member_from,
       p.referral, p.note,
       CASE WHEN count(l.selfy_id)=NULL THEN '0' ELSE count(l.selfy_id) END as likes_total,
       CASE WHEN count(s.id)=NULL THEN '0' ELSE count(s.id) END as selfies_total
from users as u
inner join profiles  p on p.user_id = u.id
inner join selfies  s on s.user_id = u.id
inner join likes  l on l.selfy_id = s.id
where (u.active = true and s.active = true and u.id= 2 )
group by u.id,u.name,u.image,member_from,p.referral,p.note;

If I exclude in where block s.active = true  I am getting some result but when included its not returns anything.
In tables selfies I have 4 rows with active true and one with active false values.
Solution was left join on likes table.

A: This is too long for a comment and not relevant to the question being asked (which apparently was solved using left join).
COUNT() never returns NULL values.  And a CASE expression only returns a single value with a single type.  And, basically all comparisons to NULL return NULL, which is treated as FALSE.  Given these facts, can you name three things wrong with this expression?
   CASE WHEN count(l.selfy_id)=NULL THEN '0' ELSE count(l.selfy_id) END as likes_total,

You can formulate the SELECT as:
Select u.id, u.name, u.image, u.created_at as member_from,
       p.referral, p.note,
       count(l.selfy_id) as likes_total, count(s.id) as selfies_total

Now, these are going to return exactly the same values, because COUNT() counts non-NULL values and both of the argument to COUNT() are used in JOIN conditions -- so are never NULL.
I speculate that you really intend:
Select u.id, u.name, u.image, u.created_at as member_from,
       p.referral, p.note,
       count(distinct l.selfy_id) as likes_total,
       count(distinct s.id) as selfies_total

although I am not 100% sure those ids are the right ones to be counting.


text:
Q: Microsoft graph: ICalUid is returned null when loading selected fields in calendarView We are using the CalendarView endpoint to get the list of meetings from the calendar.
If we specify $select to get limited fields the iCalUid is returned null, even though we specify iCalUid in $select.
Following is the sample request that returns null iCalUid
https://graph.microsoft.com/v1.0/me/calendar/calendarView?startDateTime=2020-04-09T04:00:00.000Z&endDateTime=2020-05-01T04:00:00.000Z&$top=100&$orderby=start/dateTime%20asc&$select=id,subject,iCalUId

If we do the same call without $select filter it works fine and returns proper iCalUid.
This problem only happens with one particular tenant the above scenario is working fine for hundreds of other tenants.
Following are some details to debug the session
client-request-id: 9faa4f1a-4cbc-4467-8e1c-15ac34e6a2ae

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36

Request time: 1 April 2020

A: I tried repro the issue with the above Graph API request, but it works for me. I can get the iCalUid.
You can give a try with Microsoft Graph Explorer/POSTMAN for the given tenant and see if you can still repro the issue or also you can limit the smaller number of items. If you can repro the issue, i would suggest you to check these items using tools like MFCMAPI/EWSEditor or use Microsoft CalCheck utility to see they're in good shape and fix the issue.


text:
Q: Java data structures, a map that uses an object inside the value as the key I'm still unsure on how to explain this properly but I will give it my best shot:
I have a set of objects that have values inside that I would like to use as the key for a map.
In order to get the object I'm looking for, I could simply iterate over the set comparing the inner values as I go; this seems inefficient considering one of these values inside the object could be used as a key.
Now the issue is this: were I to change the value inside the object, I also have to update the key to the map, is there not a data structure that would facilitate this task?
In essence; I would like an auto-updating map with keys changing as the value inside changes... I would rather not have to store the map inside the value so, surely there's a more efficient way of thinking than my closed mind?
I hope I've explained myself well enough to get my thinking across.

A: If I'm getting you right, consider this code:
    public class Main{
        public static void main(String[] args) {
            Test test = new Test(5);
            Map<Test, String> map = new HashMap<Test, String>();
            map.put(test, "I'm here");
            test.value = 10;
            System.out.print(map.get(test));
        }

    }

    class Test{
        public int value;
        Test(int value){
            this.value = value;
        }
    }

As the object you pass into the map as a key is passed by reference, any changes on the object will be reflected in the key set as well. This way you can use entire object as a key, not just the field it contains. You will need to be careful with providing proper equals() and hashCode() methods, though.

A:
I would like an auto-updating map with keys changing as the value inside changes..

Well, you interesting to change parent a.e. storage (Map) on any child change (Value). I don't know if its good design.
If you change the key to Value, map doesn't change
So I would write custom Map like:
 public class MyMap extends LinkedHashMap<String, Value> {/**/}

and there I would override put method and implement onValueChange() method by using Interface.
Each child will store instance of Map through interface.
So here we go ....:
RegisterItf
public interface RegisterItf {
   public void onValueChange(String newKey, String oldKey, Value newValue);
}

MyMap
public class MyMap extends LinkedHashMap<String, Value> implements RegisterItf{

    private static final long serialVersionUID = 1L;

    @Override
    public Value put(String key, Value value) {
        value.setReg(this); // send map instance to each child who registered
        return super.put(key, value);
    }

    @Override
    public void onValueChange(String newKey, String oldKey, Value newValue) {
        //here you remove old key and add new one
    }
}

Value
public class Value {
    private String mSomeData;
    private String mKey;

    private RegisterItf reg;

    public void setmKey(String key) {

        if(reg != null){
            reg.onValueChange(key, mKey, this);
        }

        this.mKey = key;
    }

   public void setReg(RegisterItf reg) {
        this.reg = reg;
    }
}

main
       MyMap map = new MyMap();

        Value val = new Value();
        val.setmKey("aa");
        val.setmSomeData("blabla");

        map.put(val.getmKey(), val);
...


text:
Q: Accessing an element of an array through negative indexes I want to access contents of an array by arbitrary indexes. Lets say we have an array with three elements in it. The modulo comes in handy here and solves the problem for any positive integer perfectly:
var arr = array['foo', 'bar', 'foobar'];
var someInteger = 3;
var element = array[ someInteger%arr.length ]; // returns the first element 'foo'

Now I would like to have the same result for negative integers but I do not know how =(
var arr = array['foo', 'bar', 'foobar'];
var someInteger = -1; // I need this negative integer to return the last element which it doesn´t
var someInteger = -2; // I need this negative integer to return 'bar'
var someInteger = -3; // I need this negative integer to return 'foo'
var someInteger = -4; // I need this negative integer to return 'foobar'
var someInteger = -5; // I need this negative integer to return 'bar'

I really hope my problem is clear enough =)

A: You can use

*

*n integer

*n % l integer in (-l, l)

*n % l + l integer in (0, 2*l)

*(n % l + l) % l integer in [0, l)
In JavaScript,
arr[(someInteger % arr.length + arr.length) % arr.length]

Alternatively, you can play with flooring, ceiling and truncating:
n - Math.floor(n / l) * l; // in [ 0,l)
n - Math.ceil (n / l) * l; // in (-l,0]
n - Math.trunc(n / l) * l; // in (-l,l)

A: If the number is negative:
while(someInteger < 0)
    someInteger += arr.length;

and then use array[ someInteger%arr.length ] as you did earlier.


text:
Q: LDAP Syntax/Semantics: Filter vs. Base DN? This is probably pretty stupid, but I'm still green to LDAP. So I hope someone can lend me a hand.
I am using Apache Directory Studio to do my searches and I am confused about when I should be using a filter or when I should be breaking up my filter into two, using one part as the filter and the other as my search base.
Here's an example where I'm trying filter out a group.
Filter: CN=JohnTestGroup,OU=TECH,DC=lab,DC=ing
Base:   DC=lab,DC=ing

This yielded zero results. I realized that perhaps I am being redundant as part of the base is in the filter, so I got rid of that part in the filter.
Filter: CN=JohnTestGroup,OU=TECH
Base:   DC=lab,DC=ing

This still did not yield anything. So I tried this:
Filter: CN=JohnTestGroup
Base:   OU=TECH,DC=lab,DC=ing

I moved the OU parameter into the Base. This worked, but I don't understand why the first or second attempts didn't. Someone care to drop some knowledge on me?
This is probably a matter of syntax/semantics, so if anyone could point me to a resource, I'd be more than willing to read more about it.

A: Read about Scopes there: http://www.idevelopment.info/data/LDAP/LDAP_Resources/SEARCH_Setting_the_SCOPE_Parameter.shtml
If you set you search scope to SUBTREE both (2 and 3), possible 1 variants start work, but searching by subtree works slower

A: I think you are misunderstanding how the filter works.  It is meant to be key=value pairings.
So (objectClass=iNetOrgPerson) as an example.
If you wish a filter to find a DN, then you pick an identifying chracteristic like CN, and filter (CN=JohnTestGroup) or perhaps (mail=John@mail.net).
The base tells the LDAP server where to start looking, as seriyPS notes in his/her answer, the SCOPE is the next question.  How deep should the server search, as that adds overhead and performance issues. Subtree is simplist conceptually.  Just keep looking from here down, till you run out of tree to look through.
That is why your last one works.
Now, if you want to find a specific object and you know its DN, you do an ENTRY scope query for the base of the specific DN.


text:
Q: PHP mysql_result error My SESSION username is Hassan
This is my PHP code:
$user = $_SESSION['username'];
echo $user;
$sql = mysql_query('SELECT `full_name` FROM `users` WHERE username="$user"');
$full_name = mysql_result($sql,0);
echo $full_name;

To make sure there is a $_SESSION['username'] I echo the $user and the result I get is perfect, this is what I get when I goto home.php:

Hassan
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 5 in C:\xampp\htdocs\PHP\Projects\UserSys\home.php on line 15

I have now ticked the correct answer, question solved close post.

A: You are trying to stick your $user variable in a single-quote string. It won't be evaluated.
Simply change your query to use double quotes:
$sql = mysql_query("SELECT `full_name` FROM `users` WHERE username='$user'");

Though while this should fix your immediate issue, please realize you are using deprecated mysql_* functions, and potentially opening yourself to SQL injection. You should be escaping your query params at least, ideally using prepared statements.