text:
Q: To change the citation/Reference style I want to change the citation/Reference style in my article. So far I follow the following style:
\begin{thebibliography}{10}
    \bibitem{ii} Andrew, B., \textit{An introduction to p-adic numbers and p-adic analysis}, URL:https://www.maths.gla.ac.uk/ $\sim$ajb.
    \bibitem{kj} Bachman, G., \textit{Introduction to p-adic numbers and valuation theory}, Academic Press, \textbf{1964}.
    \bibitem{hj}Conrad, K., \textit{Infinite series in p- adic fields},\\
    URL:https://www.math.uconn.edu/$ \sim$kconrad/blurbs/gradnumthy/infseriespadic.pdf
    \bibitem{citekey} Dragovich, B., Khrennikov, A.Y., Kozyrev, S.V. et al. P-Adic Num Ultrametr Anal Appl (2009) 1: 1. https://doi.org/10.1134/S2070046609010014
    \bibitem{brancho-1} Dragovich, B., Power series everywhere convergent on $\mathbb{R}$ and all $\mathbb{Q}_p$, J. Math. Phys., \textbf{1993}.
    \bibitem{brancho-2} Dragovich, B., \textit{On some p-adic series with factorials}, arXiv preprint math-ph/0402050, \textbf{2004}.
    \bibitem{jgh} Gouvea, F. Q., p-adic numbers : An introduction, 2nd Edition, Springer-Verlag, \textbf{1997}.
    \bibitem{j}Katok, S., \textit{p-adic analysis compared with real}, American Mathematical Society, \textbf{2007}.
    \bibitem{abc} Koblitz, N., \text{p-adic Numbers, p-adic Analysis, and Zeta-functions}, Springer, \textbf{1984}.
    \bibitem{jhg} Robert, A. M., \textit{A course in p-adic analysis}, Springer-Verlag, \textbf{2000}.
     \bibitem{schi-1}   W. H. Schikhof, \textit{Ultrametric Calculus} Cambridge U.P., Cambridge, \textbf{1984}..
\end{thebibliography}

This produces the following style both in text part (citation part) (see the highlighted parts) :

And in the Reference part, it looks like (see the highlighted parts):

But I want the following style both in citation part and in Reference part:

That is I want to display few letter of Authors name rather than numerical numbers $1,2,3,...$
Any help doing such Reference as in the last image.
Edit:
How to display the following style (where not only the paper but also the proposition or theorem will be mentioned):

A: Since your are generating your bibliography manually, you really have to do everything in the bibliography manually. This includes giving the desired citation labels if they are not numeric.
The citation label can be given in the optional argument to \bibitem: \bibitem[<citation label>]{<cite key>}. You should then give the longes citation label in the mandatory argument of thebibliography (in the example below the longest label is Dr~3)
\documentclass{article}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{hyperref}
\begin{document}
\cite{brancho-1}

\cite[Prop.~1.5.8]{ii}

\begin{thebibliography}{Dr~3}
  \bibitem[An]{ii} Andrew, B., \textit{An introduction to p-adic numbers and p-adic analysis},
    URL: \url{https://www.maths.gla.ac.uk/~ajb}.
  \bibitem[Ba]{kj} Bachman, G., \textit{Introduction to p-adic numbers and valuation theory},
    Academic Press, \textbf{1964}.
  \bibitem[Co]{hj}Conrad, K., \textit{Infinite series in p-adic fields},
    URL: \url{https://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/infseriespadic.pdf}
  \bibitem[Dr~1]{citekey} Dragovich, B., Khrennikov, A.Y., Kozyrev, S.V. et al.
    P-Adic Num Ultrametr Anal Appl (2009) 1: 1. \url{https://doi.org/10.1134/S2070046609010014}
  \bibitem[Dr~2]{brancho-1} Dragovich, B., Power series everywhere convergent
    on~$\mathbb{R}$ and all~$\mathbb{Q}_p$, J. Math. Phys., \textbf{1993}.
  \bibitem[Dr~3]{brancho-2} Dragovich, B., \textit{On some p-adic series with factorials},
    arXiv preprint math-ph/0402050, \textbf{2004}.
  \bibitem[Go]{jgh} Gouvea, F. Q., p-adic numbers: An introduction,
    2nd Edition, Springer-Verlag, \textbf{1997}.
  \bibitem[Ka]{j}Katok, S., \textit{p-adic analysis compared with real},
    American Mathematical Society, \textbf{2007}.
  \bibitem[Ko]{abc} Koblitz, N., \textit{p-adic Numbers, p-adic Analysis, and Zeta-functions},
    Springer, \textbf{1984}.
  \bibitem[Ro]{jhg} Robert, A. M., \textit{A course in p-adic analysis},
    Springer-Verlag, \textbf{2000}.
  \bibitem[Sc]{schi-1} Schikhof, W. H. , \textit{Ultrametric Calculus},
    Cambridge U.P., Cambridge, \textbf{1984}.
\end{thebibliography}
\end{document}

Specific references to theorems, propositions, lemmas etc. can be given via the optional argument of \cite: \cite[<pinpoint reference>]{<cite key>}


text:
Q: ORM Doctrine ManyToOne on update CASCADE (Symfony) I have two entities
class Promotor
{

/**
 * @ORM\ManyToOne(targetEntity="Ciudad", inversedBy="promotor")
 * @ORM\JoinColumn(name="ciudad_id", referencedColumnName="id", nullable=false)
 */
protected $ciudad;

and
class Ciudad
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="nombre", type="string", length=50)
 */
private $nombre;

A "Promotor" can live in one "Ciudad" (City). And in a "Ciudad" (City) can live many "Promotores".
If i add onDelete="CASCADE" in JoinColumn
/**
 * @ORM\ManyToOne(targetEntity="Ciudad", inversedBy="promotor")
 * @ORM\JoinColumn(name="ciudad_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
 */
protected $ciudad;

it generate the next code
ALTER TABLE promotor DROP FOREIGN KEY FK_BF20A37FE8608214;
ALTER TABLE promotor ADD CONSTRAINT FK_BF20A37FE8608214 FOREIGN KEY (ciudad_id)
REFERENCES Ciudad (id) ON DELETE CASCADE

but also i like do CASCADE on update. I try with onUpdate="CASCADE" but it doesn' work
[Doctrine\Common\Annotations\AnnotationException]
[Creation Error] The annotation @ORM\JoinColumn declared on property     Web\PromotorBundle\Entity\Promotor::$ciudad does not have a property named
"onUpdate". Available properties: name, referencedColumnName, unique, nulla
ble, onDelete, columnDefinition, fieldName

By the error I understand that the property onUpdate does not exist, but.. Is there any way to do cascade on update?

A: The onDelete="CASCADE" is used on the database level. As you already said there is no onUpdate. Another downside is that ON DELETE CASCADE only works on InnoDB. It doesn't work on MyISAM.
But you can use Doctrine in-memory cascade operations:
class Promotor
{

/**
* @ORM\ManyToOne(targetEntity="Ciudad", inversedBy="promotor", cascade={"persist", "remove"})
* @ORM\JoinColumn(name="ciudad_id", referencedColumnName="id", nullable=false)
*/
protected $ciudad;

It's all described in the documentation: https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#transitive-persistence-cascade-operations
Plus you can skip the JoinColumn annotation, because the way you have it written, is the default configuration and it's generated implicitly.
So you can just write:
class Promotor
{

/**
* @ORM\ManyToOne(targetEntity="Ciudad", inversedBy="promotor", cascade={"persist", "remove"})
*/
protected $ciudad;

redpajama_set_name: RedPajamaStackExchange


text:
Q: adding rows and columns together using flutter i am trying to add two-row and 4 columns, I added rows but couldn't add columns, I want them to take the same size so I used expanded()
here is a picture
here is what iam lokking for
i am done with rows but couldn't adds columns
 Widget build(BuildContext context) {
return MaterialApp(
  home: Scaffold(
    appBar: AppBar(
      backgroundColor: Colors.black,
      title: Text("homepage"),
    ),
    backgroundColor: Colors.yellowAccent[700],
    body: SafeArea(
      child: Row(
        children: [
          Expanded(
            child: Container(
              color: Colors.yellowAccent[700],
              child: ClipRRect(
                borderRadius: BorderRadius.circular(20), // Image border
                child: SizedBox.fromSize(
                  size: Size.fromRadius(75), // Image radius
                  child: Image.network('https://picsum.photos/250?image=9',
                      fit: BoxFit.cover),
                ),
              ),
              margin: EdgeInsets.all(15),
            ),
          ),
          Expanded(
            child: Container(
              color: Colors.yellowAccent[700],
              child: ClipRRect(
                borderRadius: BorderRadius.circular(20), // Image border
                child: SizedBox.fromSize(
                  size: Size.fromRadius(75), // Image radius
                  child: Image.network('https://picsum.photos/250?image=9',
                      fit: BoxFit.cover),
                ),
              ),
              margin: EdgeInsets.all(15),
            ),
          ),
        ],
      ),

    ),
  ),
);

A: Use GridView.
 GridView.count(
  crossAxisCount: 2,
  crossAxisSpacing: 10,
  mainAxisSpacing: 10,
  children: [
    ...List.generate(
      6,
      (index) => ClipRRect(
        borderRadius: BorderRadius.circular(20), // Image border
        child: Container(
          color: Colors.yellowAccent[700],
          child: SizedBox.fromSize(
            size: Size.fromRadius(75), // Image radius
            child: Image.network(
                'https://picsum.photos/250?image=9',
                fit: BoxFit.cover),
          ),
        ),
      ),
    )
  ],
),

Using Row and Column, you need to provide fixed height for each Row.
    body: SafeArea(
          child: LayoutBuilder(
            builder: (context, constraints) => Column(
              children: [
                SizedBox(
                  height: constraints.maxHeight * .3,
                  child: Row(
                    children: [
                      ...List.generate(
                        2,
                        (index) => Expanded(
                          child: Container(
                            color: Colors.yellowAccent[700],
                            padding: EdgeInsets.all(12),
                            child: ClipRRect(
                              borderRadius:
                                  BorderRadius.circular(20), // Image border
                              child: Image.network(
                                  'https://picsum.photos/250?image=9',
                                  fit: BoxFit.cover),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(
                  height: constraints.maxHeight * .3,
                  child: Row(
                    children: [
                      ...List.generate(
                        2,
                        (index) => Expanded(
                          child: Container(
                            color: Colors.yellowAccent[700],
                            padding: EdgeInsets.all(12),
                            child: ClipRRect(
                              borderRadius:
                                  BorderRadius.circular(20), // Image border
                              child: Image.network(
                                  'https://picsum.photos/250?image=9',
                                  fit: BoxFit.cover),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),

A: return MaterialApp(
  home: Scaffold(
    appBar: AppBar(
      backgroundColor: Colors.black,
      title: Text("homepage"),
    ),
    backgroundColor: Colors.yellowAccent[700],
    body: SafeArea(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            children: [
              Expanded(
                child: Container(
                  color: Colors.yellowAccent[700],
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20), // Image border
                    child: SizedBox.fromSize(
                      size: Size.fromRadius(size), // Image radius
                      child: Image.network(
                          'https://picsum.photos/250?image=9' ,
                          fit: BoxFit.cover),
                    ),
                  ),
                  margin: EdgeInsets.all(margin),
                ),
              ),
Expanded(
                child: Container(
                  color: Colors.yellowAccent[700],
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20), // Image border
                    child: SizedBox.fromSize(
                      size: Size.fromRadius(size), // Image radius
                      child: Image.network(
                          'https://picsum.photos/250?image=9',
                          fit: BoxFit.cover),
                    ),
                  ),
                  margin: EdgeInsets.all(margin),
                ),
              ),
              Expanded(
                child: Container(
                  color: Colors.yellowAccent[700],
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20), // Image border
                    child: SizedBox.fromSize(
                      size: Size.fromRadius(size), // Image radius
                      child: Image.network(
                          'https://picsum.photos/250?image=9',
                          fit: BoxFit.cover),
                    ),
                  ),
                  margin: EdgeInsets.all(margin),
                ),
              ),
              Expanded(
                child: Container(
                  color: Colors.yellowAccent[700],
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20), // Image border
                    child: SizedBox.fromSize(
                      size: Size.fromRadius(size), // Image radius
                      child: Image.network(
                          'https://picsum.photos/250?image=9',
                          fit: BoxFit.cover),
                    ),
                  ),
                  margin: EdgeInsets.all(margin),
                ),
              ),
            ],
          ),
Column(
            children: [
              Expanded(
                child: Container(
                  color: Colors.yellowAccent[700],
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20), // Image border
                    child: SizedBox.fromSize(
                      size: Size.fromRadius(size), // Image radius
                      child: Image.network(
                          'https://picsum.photos/250?image=9',
                          fit: BoxFit.cover),
                    ),
                  ),
                  margin: EdgeInsets.all(margin),
                ),
              ),
              Expanded(
                child: Container(
                  color: Colors.yellowAccent[700],
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20), // Image border
                    child: SizedBox.fromSize(
                      size: Size.fromRadius(size), // Image radius
                      child: Image.network(
                          'https://picsum.photos/250?image=9',
                          fit: BoxFit.cover),
                    ),
                  ),
                  margin: EdgeInsets.all(margin),
                ),
              ),
Expanded(
                child: Container(
                  color: Colors.yellowAccent[700],
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20), // Image border
                    child: SizedBox.fromSize(
                      size: Size.fromRadius(size), // Image radius
                      child: Image.network(
                          'https://picsum.photos/250?image=9',
                          fit: BoxFit.cover),
                    ),
                  ),
                  margin: EdgeInsets.all(margin),
                ),
              ),
              Expanded(
                child: Container(
                  color: Colors.yellowAccent[700],
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20), // Image border
                    child: SizedBox.fromSize(
                      size: Size.fromRadius(size), // Image radius
                      child: Image.network(
                          'https://t3.ftcdn.net/jpg/04/33/08/02/360_F_433080252_BWd42il6gVUmQaXIkASbUrHfKMV3fnqg.jpg',
                          fit: BoxFit.cover),
                    ),
                  ),
                  margin: EdgeInsets.all(margin),
                ),
              ),
            ],
          ),
        ],
      ),
    ),
  ),
);

}
}

this is the answer
I just added a column inside a row with expanded so it take the same size


text:
Q: How to get RGB values of two separate lines in an image in two variables using opencv python I have detected two lines in an image using cv2. now I want to get the RGB values of both lines in separate variables like left_line_veriable = ['rgb values'], right_line_rgb_values = ['rgb values']
Here is my code:
import cv2
import numpy as np

image = cv2.imread('tape.png')
image = cv2.cvtCOLOR(image, cv2.COLOR_BGR2GRAY)

# Apply adaptive threshold
image_thr = cv2.adaptiveThreshold(image, 255, cv2.THRESH_BINARY_INV, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, 81, 2)

# Apply morphological opening with vertical line kernel
kernel = np.ones((image.shape[0], 1), dtype=np.uint8) * 255
image_mop = cv2.morphologyEx(image_thr, cv2.MORPH_OPEN, kernel)

color_detected_img = cv2.bitwise_and(image, image, mask=image_mop)

cv2.imshow('image', color_detected_img)

cv2.waitKey(0)
cv2.destroyAllWindows()

This is the image from which I want to get both line's RGB values in two variables as described above:

A: Maybe is not the most optimal way, but it is not hard to do. As I said in my comments, you can label the image to kind of segment the lines, then get the mean of the rgb values in it and the average position to get to know which one is left and right. Here is a small script to demonstrate what I am saying. The last part is just to show the results.
import cv2
import numpy as np

# load img and get the greyscale
img = cv2.imread("x.png")
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# label the image
ret, thres = cv2.threshold(grey, 1, 255, cv2.THRESH_BINARY)
labelAmount, labels = cv2.connectedComponents(thres)

# get the mean of the color and position
values = []
# first label (0) is background
for i in range(1, labelAmount):
  mask = np.zeros(labels.shape, dtype=np.uint8)
  mask[labels == i] = 255
  mean = cv2.mean(img, mask)[:-1]
  meanPos = np.mean(cv2.findNonZero(mask), axis=0)[0]
  values.append((mean, meanPos))

# sort them by x value (left to right)
values = sorted(values, key = lambda v : v[1][0])

left_line_color = values[0][0]
right_line_color = values[1][0]

# just to show the results
left_only = np.zeros(img.shape, dtype=np.uint8)
right_only = np.zeros(img.shape, dtype=np.uint8)
left_only = cv2.line (left_only, (int(values[0][1][0]), 0), (int(values[0][1][0]), img.shape[0]), left_line_color,5 )
right_only = cv2.line (right_only, (int(values[1][1][0]), 0), (int(values[1][1][0]), img.shape[0]), right_line_color,5 )
cv2.imshow("left_line", left_only)
cv2.imshow("right_line", right_only)
cv2.imshow("original", img)
cv2.waitKey(0)


text:
Q: How to calculate the polygon area and create a column of results in R I'm working with shapefile in R and I need to calculate the polygons' area that I created by Gdiference function, So ,now I need to create a column with the size of  freshly  polygons created, because after that I need take out the small polygons which are not important to my academic research
I didn't use any function yet.

A: Use sf::st_area
Pro tip: dplyr::mutate allows you to do multiple computations at once. For example, if your shapefile units are in meters, you can easily compute the area in acres or hectares as well.
library(sf); library(tidyverse)
p <- st_read("polygon.shp")

p %>%
  dplyr::mutate(area_meters = st_area(p),
                # 1 m2 = 0.0.000247105 acres
                area_acres = area_meters * 0.0.000247105,
                # 1m2 = 0.0001 hectares
                area_hectares = area_meters * 0.0001)

A: Can you provide data for an example? Anyways, try this:
library(sf)
f <- st_read("shapefile.shp")
f$area <- st_area(f) #Take care of units

Best


text:
Q: test of correlation among binary variables prior to running logistic regression analysis I am running a logistic regression analysis with binary variables on SPSS:
dependent variable:

*

*preterm birth (Y/N)

independent variables:

*

*hypertension (Y/N), diabetes (Y/N), C section (Y/N), younger than 20 (Y/N), older than 35 (Y/N)

3 questions:

*

*Is it necessary to test the correlation between the independent variables first prior to running the logistic regression model?

*If so, how do I test it? Pearson's chi-square?

*What are the implications on the logistic regression model?

A: This should be a comment but as I can't comment yet so I leave as an answer....
"younger than 20 (Y/N), older than 35 (Y/N)"
If you have the actual age, I think using age is better, 20 and 35 sounds like a random cutoff to me.

A: Why do you think you need to test correlation of independent variables (covariables) prior to logistic regression? No, there is no such need. If the covariables are highly correlated, there might be problems with colinearity, just as in linear regression.  But there is no need to "test" for this prior to modelling.


text:
Q: What are XML Plugins for Intellij IDEA similar to XML Tools for Notepad++? Currently, we have XMLTools plugin for Notepad++ which basically does some kind of prettifying the XML within Notepad++.
Do we have a similar plugin for Intellij, which does the prettifying?

A: IntelliJ IDEA has built-in functionality for XML reformatting (Code | Reformat Code). You can configure formatting options in Settings | Editor | Code Style | XML.

A: IntelliJ supports reformatting XML out of the box without the need for plugins.
From the official help at https://www.jetbrains.com/help/idea/2016.2/reformatting-source-code.html#d1711579e29 :

Reformatting code for the current file
To reformat code for the current file, follow these steps:
In the editor of the currently opened file, press Ctrl+Shift+Alt+L.
  Note that if you select Code | Reformat Code from the main menu or
  press Ctrl+Alt+L, IntelliJ IDEA will try to reformat the source code
  automatically without opening the Reformat File dialog. In the
  Reformat File dialog, specify options for the reformatting and click
  Run.


text:
Q: Can't be applied to bigint, varchar in Athena Select Id, sr_no from table_a a
Left join table_b b
On a.id=b.sr_no

#Note id is bigint and sr_no is string in Athena.
I am getting error like cannot be applied to bigint, varchar while querying the data.
I have also tried cast but it is still not working.
Any suggestion/help is highly appreciated.

A: You should cast either the bigint to varchar or the other way around. For example:
Select Id, sr_no from table_a a
Left join table_b b
On a.id=cast(b.sr_no as bigint)
-- or alternatively:
-- on cast(a.id as varchar) = b.sr_no


text:
Q: Raspberry Pi GPIO doesn't Hold Its State I have been working on WiFi controlled robot car using Raspberry Pi-3.
Here I am using TCP server to send commands to raspberry pi.I was trying to place LEDs, but when I send command from client the Leds are in On state only for 20-30 sec. Here is the Led Program code i was working on, please help
import RPi.GPIO as GPIO
from time import sleep

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(07, GPIO.IN)
def default():
    GPIO.setup(07, GPIO.OUT)
    GPIO.output(07, GPIO.HIGH)

def fled():
    GPIO.setup(07, GPIO.IN)
    state = GPIO.input(07)
    if(state is True):
            GPIO.setup(07, GPIO.OUT)
            GPIO.output(07, GPIO.LOW)

    else:
            GPIO.setup(07, GPIO.OUT)
            GPIO.output(07, GPIO.HIGH)


text:
Q: getJSON not returning value I am trying to fetch some data from my localhost url (/data) to another localhost url (/) but I'm not getting any data
...var x = (new Date()).getTime(),
        y = 2.0;
        $.getJSON('/data', {}, function(data){
             value = data.tem_min;
        })
        series.addPoint([x, value], true, true);

A: getJSON is an async function so when you execute:
series.addPoint([x, value], true, true);

value is null because the function you passed to getJSON is not being executed until the http request is done.
So you just need to use the value after it's set:
$.getJSON('/data', {}, function(data){
    value = data.tem_min;
    series.addPoint([x, value], true, true);
})


text:
Q: Encrypting file in Node via Crypto and Stream I want to read from a stream then encrypt it and finally write it to another file.
This is my code:
var fs = require('fs');
var crypto = require('crypto');
var infile = fs.createReadStream('a.dmg');
var outfile = fs.createWriteStream('b.dmg');
var encrypt = crypto.createCipher('aes192', 'behdad');
var size = fs.statSync('a.dmg').size;
console.log(size);
infile.on('data',function(data) {
    var percentage = parseInt(infile.bytesRead) / parseInt(size);
    console.log(percentage * 100);
    var encrypted = encrypt.read(data);
    console.log(encrypted);
    if(encrypted){
        console.log(encrypted);
        outfile.write(encrypted);
    }

});
infile.on('close', function() {
    encrypt.end();
     outfile.close();

});

But it returns an empty file, and encrypted is null. What is the problem? I don't want to use pipe .

A: You really want to use Cipher#update and Cipher#final instead of Stream#read, because the function signature is read([size]) and data is not a size.
var fs = require('fs');
var crypto = require('crypto');
var infile = fs.createReadStream('a.dmg');
var outfile = fs.createWriteStream('b.dmg');
var encrypt = crypto.createCipher('aes192', 'behdad');
var size = fs.statSync('a.dmg').size;
console.log(size);
infile.on('data',function(data) {
    var percentage = parseInt(infile.bytesRead) / parseInt(size);
    console.log(percentage * 100);
    var encrypted = encrypt.update(data);
    console.log(encrypted);
    if(encrypted){
        console.log(encrypted);
        outfile.write(encrypted);
    }
});
infile.on('close', function() {
    outfile.write(encrypt.final());
    outfile.close();

});
Since crypto.createCipher is deprecated now. You should use crypto.createCipheriv where you provide a key and IV. That means that you should stretch the password that you use with PBKDF2 or similar to get a key and generate a random IV to get semantic security. Since the salt for PBKDF2 and the IV are not supposed to be secret, they can be written in front of the ciphertext. Since they have always the same length (salt is usually 8-16 bytes and IV always 16 bytes for AES-CBC), you know how many bytes you have to read in order to get those values back. Keep in mind that the decryption code has to have proper error handling.


text:
Q: Trying to write Grok pattern for specific log files I am trying to write a Grok pattern for the app generated log files. I am unable to filter out few fields.
Input Log File
2019-05-02 05:32:41,017 INFO [some_class_name] Property: MatchResult(id=null, symbol=BTC_ETH, a=13172871, b=11372687136, c=1111, d=2222, e=139128979137, f=138713871, number=1.00000000000000000000, price=0.0423000, g=1, h=1, i=0.000100000000000000000000, j=0.000004525972500000000000000000000000000000000, createTime=Thu May 02 05:32:41 UTC 2019)
2019-05-02 11:06:46,356 INFO [Some_class_name] property:  User uid:2 Login ip:127.0.0.1

Both of these lines will be in the same log file. I need to filter out every field in it. Ex:
%{DATESTAMP:date} %{LOGLEVEL:log} \[%{DATA:class}\] %{NOTSPACE:Property}\: %{SPACE} %{NOTSPACE:user} %{WORD:uid}

I have tried with this pattern, after uid (for the 2nd line on the log file, I cant get the number i.e. uid:2)
Similarly, for the first line, I did till Property: MatchResult, after '(', I cannot get separate fields.
I am doing this for the first time. Please let me know if needed more info.
Thanks

A: Try this:
%{DATESTAMP:date} %{LOGLEVEL:log} \[%{DATA:class}\] [P|p]roperty\: (%{NOTSPACE:property}\(%{GREEDYDATA:arguments}\))?( User%{SPACE}(%{NOTSPACE:user})?%{SPACE}uid\:%{WORD:uid} Login ip\:%{IP:ip})?

Tested in Elasticsearch 6.7


text:
Q: Kotlin: heapsort неправильно работает На маленьких массивах все ОК, на средних и больших неверно работает. Что я делаю не так?
UPDATE:
Переписал старый код, но все равное не работает правильно.
 fun sort(arr: Array< Int>) {

    var k: Int = Math.floor((arr.size() - 1) / 2.0).toInt()
    var heapSize: Int = arr.size() - 1

    while ( heapSize != 1) {

        builtHeap(arr, heapSize, k)
        swap(arr, 0, heapSize)
        heapSize--
        k = Math.floor((heapSize-1 ) / 2.0).toInt()
    }
 }

 fun builtHeap(arr:Array< Int>, hs:Int,  k: Int): Array< Int> {
    var i=0

    while (i != k) {
       heapify(arr, i, hs)
       arr.printArray()
       i++
    }
    return arr
 }

 fun heapify( arr:Array< Int>, ind: Int, heapSize: Int) {
    var left: Int = ind*2+1
    var right: Int = ind*2+2

    if((left < heapSize)&&(arr[left] > arr[ind]))
       swap(arr, left, ind)

    if((right < heapSize)&&(arr[right] > arr[ind]))
       swap(arr, right, ind)
  }

  fun swap(arr: Array< Int>, ind1: Int, ind2: Int): Array< Int> {

    var tmp: Int = arr[ind1]
    arr[ind1] = arr[ind2]
    arr[ind2] = tmp
    return arr
  }

  fun Array<out Any>.printArray() {
     this.forEach {
        print("$it ")
     }
     println()
  }

  fun main(args: Array<String>) {

     val array = arrayOf(4,1,3,2,43,12,78 )
     array.printArray()

     sort(array)
     array.printArray()
  }


text:
Q: Join MySQL Tables to Display Count Firstly, I'm a beginner to MySQL and I'm still learning. I'm trying to join 2 tables to display a count. Primarily, I use 2 codes. One code to display names -
SELECT tag_logs.timestamp, People.Name FROM `tag_logs` INNER JOIN People  WHERE tag_logs.tag_no = People.nametag

Another code to display count of names -
SELECT tag_logs.tag_no, COUNT(tag_logs.tag_no) FROM tag_logs GROUP BY tag_no HAVING COUNT(tag_no) >= 1

I want to display Name and a count number, instead of a tag number and count. I attempted to join both tables by using the following code, however, I've had little luck -
SELECT People.Name FROM `tag_logs` INNER JOIN People  WHERE tag_logs.tag_no = People.nametag AND COUNT(tag_logs.tag_no) FROM tag_logs GROUP BY tag_no HAVING COUNT(tag_no) >= 1

I'm given an error when I try to call 'FROM tag_logs' a second time. Is there a way to work around this?
I aim to make this my final result, except I should be able to see names instead of numbers.

A: It should be
SELECT People.Name FROM `tag_logs`
INNER JOIN People on tag_logs.tag_no = People.nametag
GROUP BY tag_no HAVING COUNT(tag_no) >= 1

EDIT
SELECT People.Name, COUNT(tag_no)  FROM `tag_logs`
INNER JOIN People on tag_logs.tag_no = People.nametag
GROUP BY tag_no HAVING COUNT(tag_no) >= 1

A: Two tables are joined using ON clause. You should learn joins.
SELECT  People.Name ,COUNT(tag_logs.tag_no)
FROM `tag_logs`
INNER JOIN People  ON tag_logs.tag_no = People.nametag
GROUP BY tag_logs.tag_no
HAVING COUNT(tag_no) >= 1

A: I believe the query that you want looks like this:
SELECT p.Name, COUNT(*)
FROM tag_logs tl INNER JOIN
     People p
     ON tl.tag_no = p.nametag
GROUP BY p.Name;

Notes:

*

*COUNT(*) is shorter than COUNT(tl.tag_no) and they do the same thing.

*GROUP BY clause now matches the SELECT.  If you could have people with the same names, then add p.nametag to the GROUP BY.  A version use only GROUP BY tl.tag_no is invalid SQL and should fail in most databases, because of the non-matching p.Name in the SELECT.

*The HAVING clause (HAVING COUNT(tag_no) >= 1) is unnecessary, because the INNER JOIN requires at least one match and tag_no is never NULL (because it is used for the JOIN).

*I introduced table aliases, so the query is easier to write and to read.


text:
Q: When using Radius Networks Android IBeacon library in android.app.Service, it didn't work I am using Radius Networks Android IBeacon library. But when I try to use it in service ,it didn't work, just like the problem in this page: https://stackoverflow.com/questions/22439299/ranging-ibeacons-in-service-thread#. I can get a good performance in Activity, but when I used it in Service, it didn't work. If you want to see my code, please see the above link, my code is same as his.
At the same time, I can see a log err:
Class not found when unmarshalling: com.radiusnetworks.ibeacon.service.StartRMData.
I really need your help!

A: If you look at the comments at the bottom of the referenced question, you will see that the problem was that the code could not successfully send toast messages from the service during the ranging callback.  Using Lod.d to log messages about the iBeacon detections showed detections worked fine.
Did you try this?  If your code is exactly the same, presumably this will solve your problem, too.  If not, you will need to post your code so we can figure out what is wrong.


text:
Q: How to call getSupportFragmentManager() from a fragment? I want to use a custom date and time picker in my code for that  i created a seperate package and put all the date and time picker classes there.
The code is running smoothly if i'm running it from main activity but when i want to call from a fragment it's not recognizing getSupportFragmentManager() method
the call which i'm making from my fragment is :
SimpleDateTimePicker simpleDateTimePicker = SimpleDateTimePicker.make(
            "Set Date & Time Title",
            new Date(),
            this,
            getSupportFragmentManager()
    );

    simpleDateTimePicker.show();

Please help, thank you guys.

A: You don't.
You need to call getChildFragmentManager() from the Fragment. Attempting to call getActivity().getSupportFragmentManager() will throw an error.

A: looks like SimpleDateTimePicker class is your own class, which accepts only android.app.FragmentManager, not  android.support.v4.app.FragmentManager. So you can use that class only with API11 or higher. If you want to use android.support.v4.app.FragmentManager, you need to edit your SimpleDateTimePicker to accept that android.support.v4.app.FragmentManager in constructor
EDIT:
ok, there are 2 different classes: android.app.FragmentManager and android.support.v4.app.FragmentManager. The second one is a compatibility implementation of the first one. Most apps use the second, as it allowed to be used before API 11. And the class from your link uses the first one. There are two ways to fix it:
1st - you start using android.app.FragmentManager instead of android.support.v4.app.FragmentManager. It will cause app work only above api 11.
2nd way is changing code of SimpleDateTimePicker to use android.support.v4.app.FragmentManager. It is more correct way I think.

A: Firstly check your frgaments extends from android.support.v4.app.Fragment or android.app.Fragment .If it is android.app.Fragment then call getActivity().getFragmentManager(); or if it extends from support frgament then call getActivity().getSupportFragmentManager();

A: This is working for me
getBaseActivity().getFragmentManager()

Try it.

A: This worked for me:
getChildFragmentManager()


text:
Q: bootstrap layout - left margin issue when deploy multiple spans I use Bootstrap for my css layout.
How come the following html code produces different margin-left for the side elements ?
Like the screen shot shows.
Thanks a lot for the help.

       header

nav 1

nav 2

nav 3

nav 4

nav 5

nav 6

side 1

side 2

side 3

              body

foot 1

foot 2

foot3

A: You have nested rows in the side bar. Try this for that section

side 1

side 2

side 3

For full details, see the fluid nested section at http://twitter.github.io/bootstrap/scaffolding.html#fluidGridSystem
Good luck!


text:
Q: Mongo kafka connector, deserializer question I am using kafka connect in order to read data from mongo and write them to kafka topic. I am using the mongo kafka source connector. The message coming to my listener throws following exception when i am trying to deserializer.
(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value
why is the above error?

A: my connectors had org.apache.kafka.connect.json.JsonConverter instead of
org.apache.kafka.connect.storage.StringConverter This solved the problem.
Also in the spring when initializing the JsonDeserializer pass in the custom objectMapper for example like below
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.registerModule(new JavaTimeModule());
hope this helps someone


text:
Q: Log two model runs with Keras wandb I am training multiple models in the same Colab notebook to compare some results. I've written a function to avoid repeating code, and I've added WandbCallback() in the list of callbacks for model_name.fit().
def generic_FE_trainer(model_name, checkpoint_filename, min_lr=1e-7):
    earlystop = callbacks.EarlyStopping(monitor="val_loss",
                                    patience=11,
                                    verbose=1)
    lr_reduction = callbacks.ReduceLROnPlateau(monitor='val_accuracy',
                                           patience=5,
                                           verbose=1,
                                           factor=0.8,
                                           min_lr=min_lr)
    checkpoint_dir = os.path.join(save_dir, checkpoint_filename)
    if not os.path.exists(checkpoint_dir):
        os.makedirs(checkpoint_dir)
    checkpoint = callbacks.ModelCheckpoint(filepath=os.path.join(checkpoint_dir, checkpoint_filename+'.h5'),
                                           monitor="val_loss",
                                           verbose=1,
                                           save_best_only=True,
                                           save_weights_only=False)
    return model_name.fit(train_gen,
                          epochs=40,
                          batch_size=4,
                          verbose=1,
                          callbacks=[earlystop, checkpoint, lr_reduction, WandbCallback()],
                          validation_data=val_gen)

I call them with something like the code below, but then my project dashboard puts the data for both on the same graphs, where I've attached a graph for epochs (although it's not particularly useful) to show as an example.
history1 = generic_FE_trainer(model1, 'model1')
history2 = generic_FE_trainer(model2, 'model2')

This is the same for all my metrics, so how can I have wandb plot these graphs separately? I would like them to be in different runs, if that's possible.

A: Use w = wandb.init() again to spawn a new process, and make sure to pass in reinit=True. The epochs are connected here because the first run never ends. To end a run, use w.finish().
So here, different runs would spawn with
w = wandb.init(reinit=True)
history1 = generic_FE_trainer(model1, 'model1')
w.finish()
wandb.init()
history2 = generic_FE_trainer(model2, 'model2')


text:
Q: Html outline format I need to break down a project into a outline  - I saw some "section" tabs for html5 but I could not get them to work. Is there another accepted format for statdardized outlines ?  I just came up with this html on my own - there might be a better way to do it.

p.envelope {
  border: 1px solid black;
  padding: 5px 5px;
  background-color: lightblue;
  display: inline-block;
  width: 700px;
  /*display: inline ; */
}

  blah blah

Point One

Point One a

Point Two b

Point Three c

A: The proper way to nest lists within other lists, is to put the nested list within a parent list item.

Main Point One:

Point One a

Point Two b

Point Three c

Main Point Two


text:
Q: Execute method not blocked in qgis plugin I am developing a QGIS Plugins, complex plugin with various classes and methods that call other methods.
My plugin works fine, but I'm loking to run some class method in the background (something like jobs in JAVA) to avoid frozen GUI. I mean, I have a class, this class has a method and this method I would like run in background
I tried with QThread,QTask, threading, QProcess, etc, but I did not find what I want to do.
Some idea could help me? Some plugin does works with background process? Some plugin example?
Thanks

A: I have been using QTask in order to run heavy processes in the background.
The useful ressources I am using are these ones :

*

*https://gis.stackexchange.com/questions/94477/how-to-use-threads-in-pyqgis-mainly-to-keep-ui-active

*https://github.com/qgis/QGIS/pull/3004
You have to specifically create a new Class that inherits from QgsTask and call it in the run() method of your GUI Plugin.
In my case this is what I have :
class MyPlugin:
"""QGIS Plugin Implementation.
    ... __init__ method, tr method, initGui method, ...
"""
    def run(self):
        """Run method that performs the work after clicking 'OK' in the Plugin GUI"""
        task = MyTask('UserFriendlyTaskName', **props)
        QgsApplication.taskManager().addTask( task )

class MyTask(QgsTask):
    def __init__(self, task_name, **props):
        QgsTask.__init__(self, desc)
        # do w/e with the props
    def run(self):
        # call your heavy processes

See this .gif below for the UI rendering in QGIS3, there is no freezing and I can still move on the map and edit data while the plugin is running.
QGIS GUI Launch Background Process GIF
Hope this answer finds you in time !

A: If i understand correctly, you want to refresh the UI to avoid QGIS freezing.
This is what worked for me:
from PyQt5.QtWidgets import QApplication

QApplication.processEvents()

This will refresh the UI of QGIS.
You probably have to call it multiple time, for example after every iteration in a for loop.

A: thanks you for your answer
what I would to do is run a method in background without freezing QGIS GUI
a example of my code
class Example:
  def __init__(self):
      code
      self.createBotton()

  def createButton(self):
      Here I create my button
      self.okbutton.clicked.connect(self.pressOkButton)

  def pressOkButton(self):
      here I call other methods
      self.methodA()
      self.methodB()

  def methodA(self):
      code
  def methodB(self):
      code

my question is--> how can i run 'pressOkButton' method in background? When i executed this method i can not ineract with QGIS GUI until finish method
NOTE:consider that it is a class that belongs to my plugin so this class is instantiated when starting the plugin


text:
Q: On SBS 2003, can I use SBSMONITORING MSSQL instance for installing a production database? At new customer I ound on an  2003 install the situation described in the title.  A production database is installed in the instance used by SBS for monitoring the system.
Is it recommended to keep things in such a situation, or am I supposed to use an ad hoc SQLServer instance?
Is there some official recommendation about the case?

A: A SQL Instance is just an instance of the MSSQL Engine.  Obviously you can create multiple instances on a server to segregate things.  In this case I think the concern you have is really over the name of the instance as the OS uses this instance for other internal processes.
If you take the Single Responsibility Principle into account it makes a lot of sense to either spin up another instance to store production databases so they are segregated from internal utility databases.  Or better yet spin up a different server all together to store production data.
There aren't any overall best practices when it comes to instances and combining roles and responsibilities, often just preferences.  Microsoft would probably advise you not to use that instance for other data.
Personally, I would recommend the same, spin up another instance and keep your data there.  Use the internal utility instances for just those purposes.


text:
Q: Proof outline of limit of recursive sequence (using $\epsilon-N$ definition) Consider the sequence $\{x_n\}$ defined as $x_1:=2, x_{n+1} = \sqrt{1+x_n}$. It can be shown fairly easily that $\lim\limits_{n\to\infty} x_n = \frac{1+\sqrt{5}}{2}$ by first showing that $x_n$ is a bounded, monotonically decreasing sequence, then passing to the limit of $x_n$. However, I have to demonstrate this using the $\epsilon-N$ definition. By using this thread as a reference, I have attempted a proof. Brief outline of my steps so far:

*

*Show $\{x_n\}$ is bounded and monotone decreasing via induction. Hence, $\{x_n\}$ converges to a limit $L \in \mathbb{R}$.

*Note that $\lim\limits_{n\to\infty} x_{n+1} = \lim\limits_{n\to\infty} x_n = L$.

*Fix $\epsilon>0$. Then for $n>N_0, N_0 \in \mathbb{N}$ we have $\left| x_{n+1} - L \right| < \epsilon$.

*Rewrite as $\left|\frac{\sqrt{1+x_n}-L}{x_n-L}\right|\cdot\left|x_n-L\right|<\epsilon$.

*Show that $\left|\frac{\sqrt{1+x_n}-L}{x_n-L}\right| \leq 1 \forall n\in\mathbb{N}$.

Then this is where I'm stuck. I know I should claim that $L:=\frac{1+\sqrt{5}}{2}$, but I'm not sure where to go from there. Any help is appreciated. Thanks.

A: $$\left|x_{n+1}-\frac{1+\sqrt5}{2}\right|=\left|\sqrt{1+x_n}-\frac{1+\sqrt5}{2}\right|=\frac{\left|1+x_n-\frac{3+\sqrt5}{2}\right|}{\sqrt{1+x_n}+\frac{1+\sqrt5}{2}}=$$
$$=\frac{\left|x_n-\frac{1+\sqrt5}{2}\right|}{\sqrt{1+x_n}+\frac{1+\sqrt5}{2}}\leq \frac{\left|x_n-\frac{1+\sqrt5}{2}\right|}{1+\frac{1+\sqrt5}{2}}\leq\frac{\left|x_n-\frac{1+\sqrt5}{2}\right|}{2}\leq$$
$$\leq\frac{1}{2^2}\left|x_{n-1}-\frac{1+\sqrt5}{2}\right|\leq...\leq\frac{1}{2^n}\left|x_1-\frac{1+\sqrt5}{2}\right|\rightarrow0.$$
Now easy to use the $\varepsilon-N$ language.

A: The missing part from your argument is $$ |x_{n+1}-L|=|\sqrt {1+x_n} -    \sqrt {1+L}|=\frac {|x_n-L|}{|\sqrt {1+x_n} +\sqrt    {1+L} |} $$ Note that$$ |\sqrt {1+x_n} +\sqrt    {1+L} |> 1+      \sqrt    {1+L}>2                         $$ Therefore $$|x_{n+1}-L|< \frac {|x_{n}-L|}{2}     $$The rest of the proof follows easily.


text:
Q: tables and matrices are misaligned in Rstudio When I create data frames and matrices, the values are not neatly aligned by their columns.
Any ideas on how to solve this? Probably something is off in my R formats, but can't figure out which one.


text:
Q: How to create a gif image with C# I want to create a gif file with several frames.
I want to use the Method which Microsoft support--Image.SaveAdd
But I don't know how to set the EncoderParameters Paramater to make up a gif file.
I can't find documents to refer. So how to create a gif file with Image.SaveAdd

A: Probably, too late to be useful for the original poster, but I managed to create a proper gif using just System.Drawing. The code below is based on jschroedl's answer, but also sets the frame delays and number of animation loops.
// Gdi+ constants absent from System.Drawing.
const int PropertyTagFrameDelay = 0x5100;
const int PropertyTagLoopCount = 0x5101;
const short PropertyTagTypeLong = 4;
const short PropertyTagTypeShort = 3;

const inr UintBytes = 4;

//...

var gifEncoder = GetEncoder(ImageFormat.Gif);
// Params of the first frame.
var encoderParams1 = new EncoderParameters(1);
encoderParams1.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
// Params of other frames.
var encoderParamsN = new EncoderParameters(1);
encoderParamsN.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.FrameDimensionTime);
// Params for the finalizing call.
var encoderParamsFlush = new EncoderParameters(1);
encoderParamsFlush.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.Flush);

// PropertyItem for the frame delay (apparently, no other way to create a fresh instance).
var frameDelay = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));
frameDelay.Id = PropertyTagFrameDelay;
frameDelay.Type = PropertyTagTypeLong;
// Length of the value in bytes.
frameDelay.Len = Bitmaps.Count * UintBytes;
// The value is an array of 4-byte entries: one per frame.
// Every entry is the frame delay in 1/100-s of a second, in little endian.
frameDelay.Value = new byte[Bitmaps.Count * UintBytes];
// E.g., here, we're setting the delay of every frame to 1 second.
var frameDelayBytes = BitConverter.GetBytes((uint)100);
for (int j = 0; j < Bitmaps.Count; ++j)
    Array.Copy(frameDelayBytes, 0, frameDelay.Value, j * UintBytes, UintBytes);

// PropertyItem for the number of animation loops.
var loopPropertyItem = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));
loopPropertyItem.Id = PropertyTagLoopCount;
loopPropertyItem.Type = PropertyTagTypeShort;
loopPropertyItem.Len = 1;
// 0 means to animate forever.
loopPropertyItem.Value = BitConverter.GetBytes((ushort)0);

using (var stream = new FileStream("animation.gif", FileMode.Create))
{
    bool first = true;
    Bitmap firstBitmap = null;
    // Bitmaps is a collection of Bitmap instances that'll become gif frames.
    foreach (var bitmap in Bitmaps)
    {
        if (first)
        {
            firstBitmap = bitmap;
            firstBitmap.SetPropertyItem(frameDelay);
            firstBitmap.SetPropertyItem(loopPropertyItem);
            firstBitmap.Save(stream, gifEncoder, encoderParams1);
            first = false;
        }
        else
        {
            firstBitmap.SaveAdd(bitmap, encoderParamsN);
        }
    }
    firstBitmap.SaveAdd(encoderParamsFlush);
}

// ...

private ImageCodecInfo GetEncoder(ImageFormat format)
{
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    foreach (ImageCodecInfo codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }
    return null;
}

A: I had success with these parameters. img1,2,3,4... are the images I want to combine.
ULONG parameterValue;

EncoderParameters encoderParameters;
encoderParameters.Count = 1;

encoderParameters.Parameter[0].Guid = EncoderSaveFlag;
encoderParameters.Parameter[0].Type = EncoderParameterValueTypeLong;
encoderParameters.Parameter[0].NumberOfValues = 1;
encoderParameters.Parameter[0].Value = &parameterValue;

// Save the first frame
parameterValue = EncoderValueMultiFrame;
rc = img1->Save(L"Output.gif", &encoderClsid, &encoderParameters);
assert(rc == Ok);

// Add the second frame
parameterValue = EncoderValueFrameDimensionTime;
rc = img1->SaveAdd(img2, &encoderParameters);
assert(rc == Ok);

// etc...adding frames  img3,4,5...

// Done...
parameterValue = EncoderValueFlush;
rc = img1->SaveAdd(&encoderParameters);
assert(rc == Ok);

Edit: I just realized that you asked for C# and I have C++ code. Hopefully the parameters still apply.

A: If you want create gif with many picture you can use ngif. see this
//you should replace filepath
String [] imageFilePaths = new String[]{"c:\\01.png","c:\\02.png","c:\\03.png"};
String outputFilePath = "c:\\test.gif";
AnimatedGifEncoder e = new AnimatedGifEncoder();
e.Start( outputFilePath );
e.SetDelay(500);
//-1:no repeat,0:always repeat
e.SetRepeat(0);
for (int i = 0, count = imageFilePaths.Length; i < count; i++ )
{
 e.AddFrame( Image.FromFile( imageFilePaths[i] ) );
}
e.Finish();
/* extract Gif */
string outputPath = "c:\\";
GifDecoder gifDecoder = new GifDecoder();
gifDecoder.Read( "c:\\test.gif" );
for ( int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++ )
{
 Image frame = gifDecoder.GetFrame( i ); // frame i
 frame.Save( outputPath + Guid.NewGuid().ToString()
                       + ".png", ImageFormat.Png );
}


text:
Q: Having issue with ng-bind and datepicker Data field is StartDate. Data is retrieved from server via ajax call in Json format. StartDate comes as JSON date /Date(1453356000000)/.
A textbox is bound using ng-bind as seen below:
<input type="text" ng-model="di.StartDate | JSONdate | date: 'dd-MMM-yyyy'" required placeholder="dd-MMM-yyyy" data-dateformat="dd-M-yy" datepicker />

Date is displayed as 21-Jan-2016 as expected.
When I click the textbox to change the date, datepicker pops up and I select a new date.
Now the problem is in the JSON object (di) an new attribute/property is created along with the original StartDate attribute/property.
StartDate : /Date(1453356000000)/
StartDate | JSONdate | date: 'dd-MMM-yyyy' : '12-Jan-2016'

Screenshot#1


text:
Q: Using my laptop as a USB power supply I've been using my laptop as a USB charger for my media player (usually an iPod Touch).  Each night, I play an audio-book from my media player (usually iPod Touch), which needs to be charging (via USB).
Is there an alternate OS (to Windows) or an extremely low power setting for that would allow me to use my laptop only as a power supply for my devices?

A: In Windows 7 there is a setting to permit USB charging during sleep and standby/hibernate: In control panel Power Options > Advanced Settings > (choose from dropdown) > USB Settings, check the box USB selective suspend setting.
Info found at: getting devices in usb port to charge at Microsoft Answers, Windows; Re: HP USB power during standby and hibernate at HP Support Forum.

A: If @minopret's answer to have to laptop charge the device when in a low power state doesn't work, then I would suggest leaving the computer at the BIOS screen. The USB ports are probably powered so keyboards would work in BIOS mode, and the hard drive will probably spin down because it is idle. I assume everything else would be minimally powered. Some laptops can heat up because the temporary sensors don't ramp up the fans when in BIOS, but if your laptop doesn't have that problem, then the BIOS screen may be the minimal power needed to power the USB ports with the computer on.


text:
Q: How can I access the GOV header contents of a MPEG4 file? I would like to know how to access the contents of the GOV headers of a mp4 video file.
I am using an Axis camera to stream video over RTSP, which is stored in the hard disk in mp4 format. According to the documentation, the camera inserts specific trigger data in the MPEG4 GOV header, but I don't know how this information can be accessed or retrieved.
I am developing a C++ application, but for now I don't need to process the data programmatically, so a solution that allows the visualization of the GOV header contents would be enough for me.

A: The supplementary data is typically embedded right into stream and is supposedly written into video payload data of the MP4 file. The intention is to retain the entire stream MPEG-4 compliant, still have the additional data inside. Decoders would typically just ignore it.
You typically need to stream that data back from the file and parse the stream to extract the portions of data with trigger information. You would need specific APIs for video streaming (file format/demultiplexer etc - what is your OS and environment after all?) and you would need Axis technical information to see what exactly they are embedding and how exactly you need to parse that out.

A: If you are streaming over RTSP, the MPEG4 header will not be transmitted - instead the "SDP" (session description protocol) information is exchanged via a DESCRIBE request from the client.  This sdp file contains an encoded version of the frame rate etc. that is actually taken from the MDAT atom in the mpeg4 header.
If you specifically need to access the gov atom to determine the p-frame i-frame differential, you could try parsing the MPEG4 header on the server and transmitting it via a separate channel.
The way an MPEG4 header looks is basically a plaintext atom name, and then a length that is usually 4 bytes (you'll need to byte swap depending on your platform), and then data.
Here is some debugging code I have in my mpeg4 header parser:
public boolean valid_atom(byte[] word, int offset) {
    for (int i = 0; i < 4; i++)
        if (!(word[i + offset] >= 'a' && word[i + offset] <= 'z') && !(word[i + offset] >= 'A' && word[i + offset] <= 'Z'))
            return false;
    return true;
}

...
public int parse_atom(byte[] b, int offset, int depth) {
    int len;
    len = ifba(b, offset);
    Log.d(TAG, String.format("atom: %c%c%c%c depth %d @ %d len %d", b[offset + 4], b[offset + 5], b[offset + 6], b[offset + 7], depth, offset, len));
    return len;
}

...
private int ifba(byte[] buffer, int offset) {
    int retval = (buffer[offset] & 0xFF) << 24;
    retval += (buffer[offset + 1] & 0xFF) << 16;
    retval += (buffer[offset + 2] & 0XFF) << 8;
    retval += (buffer[offset + 3] & 0XFF);
    return retval;
}


text:
Q: Page isn't working when insert data to mysql with PHP Good day. I have a simple html file with 2 button, when button clicked, it will input some data to database. Unfortunately, when the button is clicked, chrome displays 192.168.0.168 is currently unable to handle this request.HTTP ERROR 500
The following is my html code snippet
<form action="mode.php" method="POST">
<input style="background-color: green;" id="home" name="home" type="submit" value="HOME"></br>
<input style="background-color: red;" id="away" name="away" type="submit" value="AWAY">
</form>

and this is the mode.php coding:
<?php

   $dbhost = 'localhost:3036';
   $dbuser = 'xxx';
   $dbpass = 'abc1234';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
if (isset($_POST['home'])) {
$sql= insert into home_mode (id, status) value (null, "HOME");

mysql_select_db('home_mode');

$retval = mysql_query( $sql, $conn );
   if(! $retval ) {
      die('Could not enter data: ' . mysql_error());
   }

echo "Mode changed to HOME";}
?>

*I have tested the connection to MySQL with a test script and it's successful.
Please assist, thank you!

A: You're trying to insert NULL on auto increment column. Remove NULL from INSERT query and try like this:
$sql= insert into home_mode (status) value ("HOME");

Also you really should consider and change old, deprecated mysql_* to mysqli_* or PDO.
Update: Selecting last inserted row
$select_last_row = SELECT MAX( status ) FROM  home_mode


text:
Q: array/list index out of range python the error I get is:
IndexError: list index out of range
and I don't know why, any help?
for x in range(0,9):
    print("Enter user: ",x)
    y = []
    y.append(input())
for z in range(0,9):
    print(y[z])

A: You are resetting y on every iteration of your first loop by calling y = [].
Change it to:
y = []
for x in range(0,9):
    print("Enter user: ",x)
    y.append(input())
for z in range(0,9):
    print(y[z])

A: You are creating y in every iteration, do this instead:
y = []
for x in range(9):
    print("Enter user: ",x)
    y.append(input())
for z in range(9):
    print(y[z])

Plus, you can change the last loop to this
print('\n'.join(y))


text:
Q: Best way to deploy node api on linux server for production By the past, I always used the Heroku platform to host and run any API I develop.
I recently decided to transfer the last one I am developping, on my Linux (Debian) dedicated server.
As it is more powerfull than any of my Heroku instances, I think I will increase the performances of my app.
Now I am looking for tools, or scripts,  to deploy and run my app in background, without having to manually restart-it in case of crash or any problem.
This is basically what heroku does.
I am aware of the /etc/init.d service thing, and also the screen method.
I am more looking for a "ready-to-use" and configurable solution, that would save my time.
So, what is the best way to deploy an app, and make sure it will always be running properly ?

A: First you need to have a persistent background service that will keep NodeJS processes (server instances) running, across crashes and reboots.
Pm2 is a popular node process manager. It's mostly operates via CLI:
npm -g install pm2
pm2 start --name my_server ./server.js
pm2 list
pm2 stop my_server
pm2 restart my_server
pm2 logs my_server

You can have it auto install init.d or upstart etc scripts with:
pm2 startup

So, it can restart across reboots of host machine.
Process management is one part of automation. The other is getting latest code on server host and restarting the server.
One way is to clone the code repository on server. Then every time you need to deploy, you'll need to do on host machine:
pm2 stop my_server
git pull
pm2 restart my_server

The other, more automated way is to setup a git server on host machine (GitLab), and automate restarts when code is pushed to project repository (Git Hooks : Post Receive). You can place pm2 restart script in post receive hook of hosted project repository.
With this, the deploy will be as simple as:
git push server branch

There are also more powerful solutions available, for eaxmple: Docker.


text:
Q: multiple where statement mongodb Ok so i'm having a hard time with mongodb, coming from MySQL i'm having trouble
writing the queries to get my data. My Database looks like this:
opened: [
            {day: "Monday", from: 64800, till: 79200},
            {day: "Thuesday", from: 64800, till: 79200},
            {day: "Wednesday", from: 64800, till: 79200},
            {day: "Thursday", from: 64800, till: 79200},
            {day: "Friday", from: 64800, till: 79200},
            {day: "Saturday", from: 64800, till: 79200},
            {day: "Sunday", from: 64800, till: 79200}
        ]

What i'm trying to accomplish is the following:
I have a variable named: currendTime and I have a variable where I have the currentDay as a full name. So the variable currentDay contains "Friday".
What I want to achieve is to search for the day where currentDay is equal to Friday and where current time is higher than "from" and currentTime is lower than "till"
Could somebody help me?
Update
this is what i have so far:
db.collection('test', function(err, collection) {
    collection.find(
        {
            opened: {$and: [{$elemMatch: {day: weekDay}},
                            {from: {$lt: currentTime}},
                            {till: {$gt: currentTime}}]}
            }).toArray(function(err,items) {
            res.send(items);
        });

A: You need to combine all the array element fields to match against into the $elemMatch object:
db.collection('test', function(err, collection) {
    collection.find({
        opened: {
            $elemMatch: {
                day: weekDay,
                from: {$lt: currentTime},
                till: {$gt: currentTime}
            }
        }
    }).toArray(function(err,items) {
        res.send(items);
    });

If you just want that matched element, include the following field projection parameter to your find call:
{ 'opened.$': 1 }


text:
Q: Differential Equation Setup for an RLC Circuit I'm getting confused on how to setup the following differential equation problem:
You have a series circuit with a capacitor of $0.25*10^{-6}$ F, a resistor of $5*10^{3}$ ohms, and an inductor of 1H.
A 12 volt battery is connected and is closed at $t=0$. I need to find the equation for the charge of the capacitor at time $t$.
Based on the information given in the book I am using, I would think to setup the equation as follows:
$LQ''+RQ'+\frac1cQ=E(t)$
$L$, the inductance, would be $1$
$R$ is resistance and is $5*10^3$
Finally, capitance is $C=0.25*10^{-6}$
$Q(t)$ would represent the charge of the capacitor at time $t$, which is the solution to my problem.
The issue I am having is with the 12 volt battery that is connected. Normally, I would think to set $E(t)$ to 0 because $E(t)$ is the impressed voltage, but obviously with the battery, the impressed voltage would be 12 volts and not 0.
I'm guessing that my equation for $E(t)$ is wrong (and should be a function of time), but could someone point me in the right direction to complete the setup of the problem?

A: Using KVL, we would have ($V_S$ is your $E(t)$ = Voltage Source = constant DC $12 V$ source):
$$\tag 1 V_R + V_L + V_C = V_S \Rightarrow iR + L\frac{di}{dt} + \frac{1}{C}\int idt = V_S$$
Differentiating $(1)$ wrt $t$, we get:
$$R \frac{di}{dt} + L\frac{d^{2}i}{dt^2} + \frac{1}{C} i = 0$$
That is:
$$\frac{d^{2}i}{dt^2} + \frac{R}{L} \frac{di}{dt} + \frac{1}{LC} i = 0$$
This a 2nd-order ODE with constant coefficients.
You would of course solve the homogeneous and non-homogeneous case.
Maybe these notes will also be helpful.
Make sense?


text:
Q: Domain routes in laravel I have a laravel appplication running with apache on azure app services and everything is all right, but press click in any link its redirects me to the app service domain for example:

myapp.azurewebsites.net

but me domain is for example:

myapp.com

I dont know if i should change the .htaccess file, or the webconfig file, or some laravel configuration?

A:
I dont know if i should change the .htaccess file, or the webconfig file, or some laravel configuration?

*

*In your site's web.config file, you need to add a redirect rule from your wwwroot folder or if you don't have a web.config file, then you can create one and just paste the below text by changing host names:

<configuration>
  <system.webServer>
    <rewrite>
        <rules>
          <rule name="Redirect requests to default azure websites domain" stopProcessing="true">
            <match url="(.*)" />
            <conditions logicalGrouping="MatchAny">
              <add input="{HTTP_HOST}" pattern="^yoursite\.azurewebsites\.net$" />
            </conditions>
            <action type="Redirect" url="http://www.yoursite.com/{R:0}" />
          </rule>
        </rules>
    </rewrite>
  </system.webServer>
</configuration>

*

*Please refer  REDIRECT TO SITE USING A .HTACCESS FILE? in order to make changes in redirect URLs of .htaccess file.

*To make changes in the routing of laravel configuration, please refer HTTP Routing.


text:
Q: Query ignores index resulting full table scan I have two tables from django in mysql 5.7, auth_user and account_account:
CREATE TABLE `auth_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(150) NOT NULL,
  `first_name` varchar(30) NOT NULL,
  `last_name` varchar(30) NOT NULL,
  `email` varchar(75) NOT NULL,
  `password` varchar(128) NOT NULL,
  `is_staff` tinyint(1) NOT NULL,
  `is_active` tinyint(1) NOT NULL,
  `is_superuser` tinyint(1) NOT NULL,
  `last_login` datetime DEFAULT NULL,
  `date_joined` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  KEY `is_staff` (`is_staff`)
) ENGINE=InnoDB AUTO_INCREMENT=4438 DEFAULT CHARSET=utf8;

CREATE TABLE `account_account` (
  `user_ptr_id` int(11) NOT NULL,
  `org_form` smallint(5) unsigned DEFAULT NULL,
  `org_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `contact_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `balance` decimal(15,2) NOT NULL,
  `total_debt` decimal(15,2) NOT NULL,
  `contact_email` varchar(255) NOT NULL,
  `phone` varchar(255) NOT NULL,
  `mob_phone` varchar(255) NOT NULL,
  `other_phone` varchar(255) NOT NULL,
  `delivery_methods` smallint(5) unsigned NOT NULL,
  `delivery_address` longtext NOT NULL,
  `payment_method` smallint(5) unsigned NOT NULL,
  `person_type` smallint(5) unsigned NOT NULL,
  `client_type` smallint(5) unsigned NOT NULL,
  `city` smallint(5) unsigned NOT NULL DEFAULT '1',
  `patronymic` varchar(255) NOT NULL,
  `can_delay` tinyint(1) NOT NULL,
  `status` smallint(5) unsigned NOT NULL,
  `block_reason` varchar(255) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `manager_id` int(11) DEFAULT NULL,
  `wholesale_level_id` int(11) DEFAULT NULL,
  `markup_type` smallint(5) unsigned NOT NULL,
  `org_markup_level_id` int(11) DEFAULT NULL,
  `use_vat` tinyint(1) NOT NULL,
  `last_order_date` datetime NOT NULL,
  `group_id` int(11) DEFAULT NULL,
  `is_partner` tinyint(1) NOT NULL,
  `partner_markup` decimal(15,2) DEFAULT NULL,
  `call_markup` decimal(15,2) DEFAULT NULL,
  `delivery_price` decimal(15,2) DEFAULT NULL,
  `city_id` int(11) NOT NULL,
  `unloading_at` time NOT NULL,
  `site` varchar(200),
  `ip_address_id` varchar(20) DEFAULT NULL,
  `ip_restriction` tinyint(1) NOT NULL,
  `visualisation_id` int(11),
  `_express_delivery_price` int(10) unsigned DEFAULT NULL,
  `is_express_delivery` tinyint(1) NOT NULL,
  `payment_type` smallint(5) unsigned NOT NULL,
  PRIMARY KEY (`user_ptr_id`),
  KEY `account_account_501a2222` (`manager_id`),
  KEY `account_account_7c811b3c` (`wholesale_level_id`),
  KEY `group_id_refs_id_35dd1116` (`group_id`),
  KEY `city_id_refs_id_96652cf` (`city_id`),
  KEY `account_account_ip_address_id_e42ae8c3_uniq` (`ip_address_id`),
  KEY `account_ac_visualisation_id_cd5729f6_fk_account_visualisation_id` (`visualisation_id`),
  CONSTRAINT `account_ac_visualisation_id_cd5729f6_fk_account_visualisation_id` FOREIGN KEY (`visualisation_id`) REFERENCES `account_visualisation` (`id`),
  CONSTRAINT `account_accou_ip_address_id_e42ae8c3_fk_account_ipadress_address` FOREIGN KEY (`ip_address_id`) REFERENCES `account_ipadress` (`address`),
  CONSTRAINT `account_account_city_id_2ab1a62f_fk_classifiers_city_id` FOREIGN KEY (`city_id`) REFERENCES `classifiers_city` (`id`),
  CONSTRAINT `group_id_refs_id_35dd1116` FOREIGN KEY (`group_id`) REFERENCES `account_clientgroup` (`id`),
  CONSTRAINT `user_ptr_id_refs_id_17b5ed9e` FOREIGN KEY (`user_ptr_id`) REFERENCES `auth_user` (`id`),
  CONSTRAINT `wholesale_level_id_refs_id_369bcb86` FOREIGN KEY (`wholesale_level_id`) REFERENCES `classifiers_wholesalelevel` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I'm trying to do query:
explain     SELECT  `auth_user`.`id`, `account_account`.`contact_name`, `account_account`.`contact_email`,
            `account_account`.`phone`
        FROM  `account_account`
        INNER JOIN  `auth_user`  ON (`account_account`.`user_ptr_id` = `auth_user`.`id`)
        WHERE  (`auth_user`.`is_staff` = 0)
        LIMIT  16;

+----+-------------+-----------------+------------+--------+------------------+---------+---------+-----------------------------------+------+----------+-------------+
| id | select_type | table           | partitions | type   | possible_keys    | key     | key_len | ref                               | rows | filtered | Extra       |
+----+-------------+-----------------+------------+--------+------------------+---------+---------+-----------------------------------+------+----------+-------------+
|  1 | SIMPLE      | account_account | NULL       | ALL    | PRIMARY          | NULL    | NULL    | NULL                              | 3741 |   100.00 | NULL        |
|  1 | SIMPLE      | auth_user       | NULL       | eq_ref | PRIMARY,is_staff | PRIMARY | 4       | raros.account_account.user_ptr_id |    1 |   100.00 | Using where |
+----+-------------+-----------------+------------+--------+------------------+---------+---------+-----------------------------------+------+----------+-------------+

It shows that account_account does full scan even if we do not do any filtering on account, only join. Can you explain to me two things:

*

*why mysql does not take is_staff index for initial filtering? we have two indexes on auth_user: primary and is_staff

*why mysql does full scan on account_account, even if we do not do any filtering for account_account table?

Thanks in advance!

A: It may be that it is quite optimal the way you have it.
First note that the ALL and 3741 Rows in EXPLAIN are not necessarily meaningful.  This is because EXPLAIN rarely notices LIMIT when listing such data.
Let's suppose it does do ALL:

*

*Scan the entire table of about 3741 rows.  Do it in any order, since there is nothing to constrain the scan (such as an ORDER BY).

*For each of those rows, reach into the other table.

*Reaching into auth_user via the PRIMARY KEY is quite efficient.

*Check is_staff.  If it is usually 0, then all is well.  If it is rarely 0, then there is a lot of wasted effort.

*Stop after 16 rows.  So, depending on is_staff, this required looking at between 16 and 3741 rows.

Add an ORDER BY; then let's re-Explain it.


text:
Q: Change appearance of turtle I am programming in python 3.2.2 turtle. I am able to make the turtle follow my cursor when I clack but now I have trouble changing the appearance of the turtle. In my code you will see a tank, and I want the image of the tank to be my turtle.
Here is my code:
#importing modules
from turtle import Turtle
from turtle import *

#Setting up variables
unVar1 = 25
unVar2 = 100
unVar3 = 90
unVar4 = 150
unVar5 = -30
unVar6 = 75
unVar7 = 50
screen = Screen() # create the screen

#first part in making the turtle move
turtle = Turtle()
t = Turtle() # create the first turtle
t2 = Turtle() # create the second turtle
screen.onscreenclick(turtle.goto) # set up the callback for moving the first turtle

#defining shapes and objects
def drawSquare(t , xPrime, yPrime, sideLength):
    t.up()
    t.hideturtle()
    t.goto(xPrime, yPrime)
    t.setheading(270)
    t.down()
    for count in range(4):
        t.forward(sideLength)
        t.left(90)
    t.end_fill()
def drawRectangle(t, x2, y2, sideLength1, sideLength2):
    t.up()
    t.hideturtle()
    t.goto(x2, y2)
    t.setheading(270)
    t.down()
    for count in range(2):
        t.forward(sideLength1)
        t.left(90)
        t.forward(sideLength2)
        t.left(90)
    t.end_fill()
def drawTank():
    t.pencolor("black")
    t.fillcolor("gray")
    t.begin_fill()
    tire1 = drawRectangle(t, int("10"), unVar1, unVar6, int("30")) #Tire
    t.begin_fill()
    tire2 = drawRectangle(t, int("110"), unVar1, unVar6, int("30"))    #Tire
    t.begin_fill()
    tire3 = drawRectangle(t, int("110"), unVar2, unVar6, int("30"))  #Tire
    t.begin_fill()
    tire4 = drawRectangle(t, int("10"), unVar2, unVar6, int("30"))   #Tire
    t.pencolor("gray")
    t.fillcolor("black")
    t.begin_fill()
    bodyTank = drawRectangle(t, int("20"), unVar3, int("130"), int("110"))
    t.begin_fill()
    gunTank = drawRectangle(t, int("65"), unVar4, int("100"), int("20"))   #Gun
    t.begin_fill()
    exhaustTank = drawRectangle(t, int("50"), unVar5, int("20"), int("10"))
    t.fillcolor("red")
    t.begin_fill()
    turretTank = drawSquare(t, int("50"), unVar7, int("50"))  #Turret
    t.end_fill()
drawTank()
screen.mainloop() # start everything running

A: You can create a tank cursor with the code you have, you just need to rearrange it.  The drawing functions need to create polygons rather than draw directly to the screen.  The following will create your tank cursor and drive it around the screen a bit.  See the comments on tankCursor() about how you can also used fixed polygons instead -- you don't have to make a bitmap image to do this:
import turtle

unVar1 = 25
unVar2 = 100
unVar3 = 90
unVar4 = 150
unVar5 = -30
unVar6 = 75
unVar7 = 50

def polySquare(t, x, y, length):
    t.goto(x, y)
    t.setheading(270)

    t.begin_poly()

    for count in range(4):
        t.forward(length)
        t.left(90)

    t.end_poly()

    return t.get_poly()

def polyRectangle(t, x, y, length1, length2):
    t.goto(x, y)
    t.setheading(270)

    t.begin_poly()

    for count in range(2):
        t.forward(length1)
        t.left(90)
        t.forward(length2)
        t.left(90)

    t.end_poly()

    return t.get_poly()

def tankCursor():

    """
    Create the tank cursor.  An alternate solution is to toss the temporary turtle
    and use the commented out polygon assignments instead of the poly* function calls
    """

    temporary = turtle.Turtle()

    screen = turtle.getscreen()

    delay = screen.delay()

    screen.delay(0)

    temporary.hideturtle()
    temporary.penup()

    tank = turtle.Shape("compound")

    # tire1 = ((10, unVar1), (10, unVar1 - unVar6), (10 + 30, unVar1 - unVar6), (10 + 30, unVar1))
    tire1 = polyRectangle(temporary, 10, unVar1, unVar6, 30)  # Tire #1
    tank.addcomponent(tire1, "gray", "black")

    # tire2 = ((110, unVar1), (110, unVar1 - unVar6), (110 + 30, unVar1 - unVar6), (110 + 30, unVar1))
    tire2 = polyRectangle(temporary, 110, unVar1, unVar6, 30)  # Tire #2
    tank.addcomponent(tire2, "gray", "black")

    # tire3 = ((110, unVar2), (110, unVar2 - unVar6), (110 + 30, unVar2 - unVar6), (110 + 30, unVar2))
    tire3 = polyRectangle(temporary, 110, unVar2, unVar6, 30)  # Tire #3
    tank.addcomponent(tire3, "gray", "black")

    # tire4 = ((10, unVar2), (10, unVar2 - unVar6), (10 + 30, unVar2 - unVar6), (10 + 30, unVar2))
    tire4 = polyRectangle(temporary, 10, unVar2, unVar6, 30)  # Tire #4
    tank.addcomponent(tire4, "gray", "black")

    # bodyTank = ((20, unVar3), (20, unVar3 - 130), (20 + 110, unVar3 - 130), (20 + 110, unVar3))
    bodyTank = polyRectangle(temporary, 20, unVar3, 130, 110)
    tank.addcomponent(bodyTank, "black", "gray")

    # gunTank = ((65, unVar4), (65, unVar4 - 100), (65 + 20, unVar4 - 100), (65 + 20, unVar4))
    gunTank = polyRectangle(temporary, 65, unVar4, 100, 20)   # Gun
    tank.addcomponent(gunTank, "black", "gray")

    # exhaustTank = ((50, unVar5), (50, unVar5 - 20), (50 + 10, unVar5 - 20), (50 + 10, unVar5))
    exhaustTank = polyRectangle(temporary, 50, unVar5, 20, 10)
    tank.addcomponent(exhaustTank, "black", "gray")

    # turretTank = ((50, unVar7), (50, unVar7 - 50), (50 + 50, unVar7 - 50), (50 + 50, unVar7))
    turretTank = polySquare(temporary, 50, unVar7, 50)  # Turret
    tank.addcomponent(turretTank, "red", "gray")

    turtle.addshape("tank", shape=tank)

    del temporary

    screen.delay(delay)

tankCursor()  # creates and registers the "tank" cursor shape

turtle.shape("tank")

turtle.up()  # get rid of the ink

# show our tank in motion

turtle.setheading(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(45)
turtle.forward(100)

turtle.done()

A: Since the tank is a shape you created using turtle, you can always simply take a screenshot of your tank and set that screenshot as the shape of the turtle using the turtle module's register_shape and shape functions like so:
turtle.register_shape("INSERT PATH OF SCREENSHOT HERE")
t.shape("INSERT PATH OF SCREENSHOT HERE")

However, if you want to do something harder, you can use the turtle.register_shape() method shown above, but instead of supplying the path of some image, you will instead have to supply a name, and then some coordinates to create the shape. In short, the syntax for that would be:
turtle.register_shape(name, (coordinates))
t.shape(name)

However, that would be very tedious seeing as how complex your tank already is, so I would recommend going on with the method above, where you just take a screenshot of the tank and use that screenshot as a shape for the turtle.
Also, some issues I see with your code:

*

*The following:
from turtle import Turtle
from turtle import *

You are importing the turtle module twice. There is no need for that! from turtle import * already imports the Turtle() function, so the first import command is not needed. Therefore, change the import command to just:
from turtle import *
# The rest of your code...

*When the user clicks on the screen to go somewhere, your turtle creates a line wherever it goes. There is a way to avoid this. However, I don't know if you want this, but if you do and decide to keep it, it does result in a lot of the lines going to places they were not supposed to and could eventually start hogging up a lot of memory until your program crashes. So I do recommend taking this step, but whether or not you do is up to you. However, if you do decide to take this step, then to start, define the following function after t2 = Turtle():
def Go(x, y):
    # Turn the animation completely off
    screen.tracer(0, 0)
    # Pick the pen up so no lines are created as the turtle moves
    turtle.penup()
    # Go to the clicked position on the canvas
    turtle.goto(x, y)
    # Put the pen back down
    turtle.pendown()
    # Turn animation back on
    screen.tracer(1, 1)

And then change:
screen.onscreenclick(turtle.goto)

To:
screen.onscreenclick(Go)

And that's it! I hope this helps! :)


text:
Q: Empty body using express post I can't seem to get the data from this post call. The body shows as an empty object {}.
I've tried several versions including these posts with no luck: Express.js req.body undefined
I've also tried different content-types, but that also hasn't worked.
Thoughts? Thanks in advance.
index.js:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./queries.js')

const port = 7000

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.get('/', (req, res) => {
    res.json({
        info: 'Node.js, Express, and Postgres API'
    })
})

app.post('/jothook/', jsonParser, db.jothook)

app.listen(port, () => {
    console.log(`App running on port ${port}.`)
})

queries.js:
const Pool = require('pg').Pool
const { req } = require('express');
const pool = new Pool({
    user: 'testuser',
    host: '167.XX.XX.XX',
    database: 'testdb',
    password: 'testpwd',
    port: 5432,
})

const jothook = (req, res) => {
  var qy = JSON.stringify(req.body);
  var qy = 'INSERT INTO data_test VALUES ' + qy;
    pool.query(qy, (error, results) => {
        if (error) {
            throw error
        }
        res.status(201).send(`Data Inserted`)
    })
};

module.exports = {
    jothook
};

post call:
{headers={Content-Type=application/json}, body="'test_data', 'joe', 'smith'", method=POST, mode=cors}


text:
Q: .net Ajax calendarExtender cuts of saturday's in IE7 (works fine in firefox) I was having this problem in IE7 where the saturdays appear to be missing from the calendar. It displays fine in Firefox and a few people have suggested that it could be my other stylesheets messing it up so i am now using a custom calendar CSS theme and i'm still having the same problem.
Any ideas? is there a known bug with the ajax toolkit pack that is used?

A: here's a solution:
.cal_Theme1 .ajax__calendar_days td { padding:0px; }

A: Great answer from SocialAddict, but it didn't work for me...
My problem was the body/container size.
So here is what cured me:
<style>
    div.ajax__calendar_days table tr td{padding-right: 0px;}
    div.ajax__calendar_body{width: 205px;}
    div.ajax__calendar_container{width: 205px;}
</style>

I also changed my calendar style, (like SocialAddict did), but this style works out of the box.

A: Asp code:
            <asp:TextBox ID="F1_I2" runat="server" CssClass="bigInput">
            </asp:TextBox>
            <cc1:CalendarExtender ID="F1_I2_CalendarExtender" CssClass="cal_Theme1" runat="server"
                TargetControlID="F1_I2" Format="dd/MM/yyyy">
            </cc1:CalendarExtender>
            <div class="magiPad" />

I have a custom CSS applied to the calendar which i dont think will display well on here, but this is it:
/* Calendar css */
.cal_Theme1 .ajax__calendar_container {background-color: #e2e2e2;width:182px;border:solid 1px #cccccc;}
.cal_Theme1 .ajax__calendar_header{background-color: #ffffff; margin-bottom: 4px;}
.cal_Theme1 .ajax__calendar_title,.cal_Theme1 .ajax__calendar_next,.cal_Theme1 .ajax__calendar_prev{color: #004080; padding-top: 3px;}
.cal_Theme1 .ajax__calendar_body{background-color: #e9e9e9; border: solid 1px #cccccc;}
.cal_Theme1 .ajax__calendar_dayname{text-align:center; font-weight:bold; margin-bottom: 4px; margin-top: 2px;}
.cal_Theme1 .ajax__calendar_day{text-align:center;}
.cal_Theme1 .ajax__calendar_hover .ajax__calendar_day,.cal_Theme1 .ajax__calendar_hover .ajax__calendar_month,.cal_Theme1 .ajax__calendar_hover .ajax__calendar_year,.cal_Theme1 .ajax__calendar_active{color: #004080; font-weight:bold; background-color: #ffffff;}
.cal_Theme1 .ajax__calendar_today{font-weight:bold;}
.cal_Theme1 .ajax__calendar_other,.cal_Theme1 .ajax__calendar_hover .ajax__calendar_today,.cal_Theme1 .ajax__calendar_hover .ajax__calendar_title{color: #bbbbbb;}

A: If anyone else has this problem then i recommend setting a wildcard css element at the beginning of your style to blank out all posible padding and margin issues.
This fixes the problem in IE6.IE7 and firefox works fine too.
.yourCalendarTheme * {padding:0px;margin:0px;}

A: I had a similar problem and the solution marked as best (by SocialAddict) did not work for me. The core of my problem is that a css class set in a table was causing my calender extender to cut off Saturdays. The solution that worked involved modifying the calender extender's css. Here it is:

.ajax__calendar_body tr td {
 padding: 0px;
 margin: 0px;}


text:
Q: sql on double select without join statement i want to select all the productreview item and productimage.productimage, how to select? if i do not use double select it may show the bright entity quantity. pls help me to select the productimg and select a the item on productreview

the way i do it cant get the result i want
select distinct `productreview.userid,
    productreview.productid,
    productreview.producttitle,
    productreview.productreview,
    productreview.recommend,
    productreview.reviewdate,
    productreview.posted,
    productimage.productimg
from productreview,product,productstock,productimage
where productreview.productid=product.productid AND
    product.productid=productstock.productid and
    productstock.productid=productimage.productid and
    productstock.productcolortype = productimage.productcolortype and
    productimage.productcolortype='type1'`

A: you can join ProductReview table with ProdutImage table on basis of productID column. Here is SQL Query
SELECT PR.*,PI.ProductImg FROM ProdcutReview AS PR INNER JOIN ProdcutImg AS PI
ON PR.ProductID = PI.ProductID


text:
Q: How to break a word into characters in swift How can i do the same thing in swift 2 :
String a = "danial";
  for (int i= 0 ; i < a.length() ; i++) {
    System.out.println(a.charAt(i));
  }
}

A: Try this :
let myString = "danial"
let characters = Array(myString.characters)
print(characters) //OP : ["d","a","n","i","a","l"]
print(characters[0]) //OP : ["d"]

A: Try this:
It was initial created.
let string : String = "danial"
let characters = Array(string)
println(characters)
//["d","a","n","i","a","l"]

String conforms to the SequenceType protocol, and its sequence generator enumerates the characters.
Swift 2, String does no longer conform to SequenceType, but the characters property provides a sequence of the Unicode characters:
let string = "danial"
let characters = Array(string.characters)
print(characters)
//["d","a","n","i","a","l"]

A: As of Swift 4.*,
let stringArray = Array(wordString)

A: Let a = array("danial")  // a = ["d", "a", "n", "i", "a", "l"]

i.e. array of Character


text:
Q: Switching to pages dynamically in Inno Setup I have a requirement to switch to pages dynamically in the Inno setup. Lemme just explain what needs to be done and what I tried so far.
Here is a sample logic mentioned below:
Page1 --> Page2 --> Page3 --> Page4 --> Page5
I will get a single value from a series of radio button from Page3 from the User at runtime and based on that value I need to switch to different pages for Page4 and Page5.
Here is what I tried... :
a.) I wrote all the logic in the InitializeWizard() but I could not create Page4 and Page5 since it was created based on the value selected from Page3 and during initialization it is empty.
b.) I tried to write all the logic in the CurPageChanged(CurPageID: Integer) procedure, and same thing happened and I could not get the Page.ID for any pages in NextButtonClick(CurPageID: Integer) (including Page1 and Page2).
Please help me how can I proceed in this situation.
Thanks in Advance,
DeeJay


text:
Q: .NET MVC Best practices as far as keeping the controller from being very unreadable I have been developing my first large (for me) MVC project for a couple of months now and things are getting exceedingly difficult to navigate.
I have been slacking off on refactoring and am seeking modern examples of 'best practices' as far as keeping your controller thin and moving all of that data to your models.
I read this article that discusses things in detail, but does not provide an example project.
Most 'best practices' threads posted here tend to link to MVC Music Store or the Nerd Dinner project, but at the same time the comments tend to say they are more 'beginner's guides' rather than examples of 'best practices.'
Does anyone know of any up-to-date open-source MVC projects that demonstrate proper development structure?
note:  A typical problem that I'd like to learn to resolve:  My controllers are very long and full of code that drives the website - I need to move this code off into methods that are merely referenced by the controller.  Where do I throw all of these methods?
Here is a an sample of my code from a controller as suggested by a comment on one of the replies.  How would I move some of this information over to my ViewModel?  (I have included the ViewModel below):
Controller:
public ActionResult AttendanceView(int id)
{
    //
    // Generates list of Attendances specifically for current Course
    var attendanceItems = db.Attendance.Where(s => s.CourseID == id);
    List<Attendance> attendanceItemsList = attendanceItems.ToList();
    // End of generating list of Attendances

    //
    // Generates list of Students in alphabetical order sorted by LastName
    var student = attendanceItemsList.Select(a => a.Student).Distinct().OrderBy(s => s.LastName);
    List<Student> StudentList = student.ToList();
    // End of generating list of Students

    //
    // Generates list of AttendingDays specifically for current Course
    Course course = db.Courses.FirstOrDefault(p => p.CourseID == id);
    List<int> attDayList = new List<int>();
    for (int i = 0; i < course.AttendingDays; i++)
    {
        attDayList.Add(i + 1);
    };
    // End of generating list of AttendingDays

    AttendanceReportViewModel model = new AttendanceReportViewModel
    {
        AttendanceDays = attDayList,
        Students = StudentList,
        Attendances = attendanceItemsList,
        courseId = id
    };
    return View(model);
}

ViewModel:
namespace MyApp.ViewModels
{
    public class AttendanceReportViewModel
    {
        public List<int> AttendanceDays { get; set; }

        public List<Student> Students { get; set; }

        public List<Attendance> Attendances { get; set; }

        public int courseId { get; set; }

        public string IsPresent(Student student, int attendanceDay)
        {
            return Attendances.Single(a => a.StudentID == student.StudentID && a.AttendanceDay == attendanceDay).Present ? MyAppResource.Present_Text : MyAppResource.Absent_Text;
        }
    }
}

A: What you're basically looking for is a layered architecture. For example the Service Layer pattern requires you to define a lot of the logic in the service layer instead of in your controllers.
There are examples of this, one of them being Silk from the Pattern & Practices team at Microsoft: http://silk.codeplex.com/

A: When you say your controllers are "long and full of code," does this mean ALL of your code is in the controller?  If that is the case, you need to break out most of the logic into supporting ViewModel classes.
I usually put most (if not all) of my code in ViewModel classes, one per View/Controller.  All logic is surfaced from the ViewModel, such that each Controller action runs one, maybe two lines of code (within reason.)
UPDATE:
I would take all the logic out of your Action and move it into a ViewModel method that takes an int for the ID.  Now your Controller action method is one line:
return View(MyViewModel.AttendanceView(id));

This is a simplistic example, there are more advanced ideas out there.

A: Does anyone know of any up-to-date open-source MVC projects that demonstrate proper development structure?
Unfortunately no. All projects I've seen so far aren't very suitable for a beginner to start learning with. Not because they contain a poor code, but because of their complexity.
A typical problem that I'd like to learn to resolve: My controllers are very long and full of code that drives the website - I need to move this code off into methods that are merely referenced by the controller. Where do I throw all of these methods?
If your controllers contain many lines, then you're doing it wrong. You need to learn about the separation of concerns and how to write a clean code (and what does it mean). For instance, never write a code to retrieve something from a database in your controller. Such action belongs to a database access layer, logically further divided into multiple classes. Learn about the principles like "Don't repeat yourself" etc.
There's much to discuss on how to write a good code and I'm not sure whether it can be done here. There are whole books discussing this matter, but I hope I gave you at least some useful pointers to start with.


text:
Q: does intel 82579lm gigabit network connection support wol? I have an on-Board intel 82579LM Gigabit Network Connection on my HPz420 PC which runs Win 10 Pro x64bit. In the Networkadapter settings there isn't the "Active Magic Packets" option, in order to be able to activate Wake on Lan. Even though I could activate WOL in BIOS, if the network adapter itself hadn't the option to activate wol, it would not work. Does anyone know, if this network adapter support wol or not ?

A: Yes, 82579LM has WOL, I have not seen any NIC that does not have it since NE2000 nics.
When I think about WOL I think about power on from power off mode. (not really wake from sleep)
Not all features that a NIC has can be changed in all versions of the Windows driver, and some features can not be changed at all.
Sure, NICs have registers that can be modified to change features, but few (if any) store these, so the only time any options in a windows driver would have any effect is after windows boots, so potentially when a machine goes to sleep. but on system reset, and power off, they would be irrelevant.
Consider for a moment that you turn of the machine by pulling the plug, this resets the NIC entirely, now plug in the power, and use WOL to start the machine, note that no Windows driver would have had the chance to modify the registers on the NIC to modify WOL settings.
When you enable WOL in BIOS:

*

*Super IO is configured in NVRAM to react to WOL signal from NIC

*Enables SB power to NIC, other settings are irrelevant.

Now let's look on the drivers in Wired_driver_26.4_x64.exe\PRO1000\Winx64\NDIS63\ there is e1c63x64.inf here we can find 82579LM and in turn Powermgmt.reg - Note that these settings are in regards to "wake from sleep" (this is driver ver 03/29/2016,12.15.31.4) So if you want' these settings, make sure to install a driver that has them.
A quick search found this that especially mentions the NIC in question.

A: In addition to @NiKiZe's answer: some drivers (especially those included in Windows) explicitly deactivate WoL on shutdown, even if there's no option to activate it.
To verify, remove power from the PC, replug after a few seconds. You should see the link come up when still powered down. If WoL works now but not after a shutdown, you need to replace/update the driver. If not, there might be a missing BIOS option (look for PME). All vendor-provided drivers I've seen do support WoL.


text:
Q: How to specify the key format (i.e. camelcase) for an ActiveModel::Serializer :has_many association as a one-off option (not global config)? I have a serializer like this:
class FooSerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :foo_bars, serializer: BarSerializer
end

class BarSerializer < ActiveModel::Serializer
  attributes :id, :acronym
end

My issue is that when instantiating the serializer and calling as_json on it, I get the following:
$ foo = Foo.first
$ s = FooSerializer.new(foo)
$ s.as_json

$ => {
    :foo => {
        :id => 1,
        :name => "Foo",
        :foo_bars => [
            {
              :id => 1,
              :acronym => "F1",
            },
            {
              :id => 2,
              :acronym => "F2",
            },
        ]
    }
}

But my front end API expects to receive camelcase fooBars rather than snake case foo_bars. How can I configure the serializer to output the foo_bars association with the key fooBars

A: (posted this because I figured this out myself, but couldn't find the answer anywhere and hope this helps someone else, or even myself when I inevitably google this again someday...)
Pretty easy to do. Just add the key option to your serializer's has_many
class FooSerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :foo_bars, serializer: BarSerializer, key: :fooBars
end

Done. Now your serializer will output the has_many with fooBars instead of foo_bars


text:
Q: Should I always use "this" in Dart? Is it a good practice to use always 'this' in a method.
Even if there is no usage of the same variable name as input to this method.
String getStory(number) {
   return this.storyData[number];
}

By doing this there won't have any conflicts with any input variable name (never).
Thank you in advance for your feedback.

A: Generally this. is only supposed to be used when there is ambiguity about what variable is being used.
class Test{
  final int x;

  Test(this.x);
}


text:
Q: Which port and protocol does Google Cloud Messaging (GCM) use? Which port and protocol does Google Cloud Messaging (GCM) use?
We experience some times that messages doesnt get through, and have noticed that it depends on which network we sitting on.

A: The device accesses the GCM servers on ports 5228-5230.

Note: If your organization has a firewall that restricts the traffic
  to or from the Internet, you'll need to configure it to allow
  connectivity with GCM. The ports to open are: 5228, 5229, and 5230.
  GCM typically only uses 5228, but it sometimes uses 5229 and 5230. GCM
  doesn't provide specific IPs. It changes IPs frequently. We recommend
  against using ACLs but if you must use them,  take a broad approach
  such as the method suggested in this support link.

This is relevant if your device is connected to the internet via WiFi.
Here is the link to the relevant GCM documentation: https://developers.google.com/cloud-messaging/http


text:
Q: Azure D Series VM configuration for WebRole hosted on Cloud Service I'd like to move my WebRole on azure to use one of the new D-Series VM's to take advantage of the faster CPU's and SSD's.
Is there any IIS configurations that would optimize running on an SSD or can I assume that just moving to an SSD will increase performance?
I'm running a single website inside IIS on IIS 8.5.

A: Just moving to SSD will increase performance on disk io intensive tasks.  To be taking advantage of the SSD's, you application has to be performing disk intensive tasks on the web role.  Typically web roles use very little actual disk unless there is a database hosted on the same server.  As I am assuming you are using Azure Cloud Services, I doubt this is the case.  Therefor, I think the SSD's will likely not increase your performance significantly due to the use case.
That said the bigger better faster CPUs most definitely will help out a web role.  The sheer CPU speed will help, as will the ability to use all CPU's.  To really drive performance make sure you kick off longer tasks on background threads, which will get allocated accordingly.
Hopefully that helps.