text:
Q: Comparação de BigDecimal retorna resultado inesperado Em um dos meus métodos realizo a seguinte comparação, como no exemplo abaixo:
public static void main(String[] args) {

    BigDecimal valor = new BigDecimal("100");
    exemplo(valor);

}

public static void exemplo(BigDecimal valor) {
    if (valor.compareTo(new BigDecimal("50.000")) == 1 || valor.compareTo(new BigDecimal("50.000")) == 0) {
        System.out.println("número maior");
    }
}

Passando como parâmetro o valor "100", o problema é que a class BigDecimal acaba considerando o valor "100" maior que o valor "50.000", tentei passar o valor como: "50.000.00" para tentar solucionar o problema, mas a classe não me permite fazer isso, alguma solução?

A: O ponto é o separador decimal, então você está comparando 100 com 50 (50.000 lido "em português" é 50,000, ou simplesmente 50). Não use pontos para fazer separação de milhar. Na verdade isto não existe em programação. Veja:
public static void exemplo(BigDecimal valor) {
    if (valor.compareTo(new BigDecimal("50000")) == 1 || valor.compareTo(new BigDecimal("50000")) == 0) System.out.println("número maior");
}

Funciona perfeitamente.
O motivo de não aceitar 50.000.00 é porque ele tem dois separadores decimais, ou para o que nós usamos aqui no Brasil, é como se tivesse duas vírgulas, o que um número não pode ter.
Eu imagino que no seu problema real está recebendo um valor como string e ele tem casas decimais. Aí você deve converter o valor para BigDecimal de acordo com o padrão que receber. É outra coisa completamente diferente.
public static void exemplo(BigDecimal valor) {
    try {
        DecimalFormat df = new DecimalFormat("###,##0", new DecimalFormatSymbols (new Locale ("pt", "BR")));
        df.setParseBigDecimal(true);
        BigDecimal decimal = (BigDecimal)df.parse("50.000");
        if (valor.compareTo(decimal) == 1 || valor.compareTo(decimal) == 0) System.out.println("número maior");
        else System.out.println("número menor");
    } catch (ParseException e) { //só para facilitar, não faça isto
        e.printStackTrace();
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

A: Você está, na verdade, comparando 100 com 50. Em inglês, o ponto separa a parte inteira da parte fracionária de um número em vez da vírgula.
Como indicado na documentação oficial, o BigDecimal aceita números fracionários representados dessa forma em seu construtor. É o que você está fazendo sem ver.
Para fazer o que você pretende, compare com "50000".


text:
Q: grep-like function in R I'm trying to write a program in R which would take in a .pdb file and give out a .xyz-file.
I'm having problems with erasing some rows that contain useless data. There are around 30-40 thousand rows, from which I would only need about 3000. The rows that contain the useful information start with the word "ATOM".
In unix terminal I would just use the command
grep ATOM < filename.pdb > newfile.xyz

but I have no idea how to achieve the same result with R.
Thank you for your help!

A: You should be able to use grep, and depending on your specific situation, perhaps substr.
For example
#Random string variable
stringVar <- c("abcdefg", "defg", "eff", "abc")

#find the location of variables starting with "abc"
abcLoc <- grep("abc", substr(stringVar, 1, 3))

#Extract "abc" instances
out <- stringVar[abcLoc]
out

Note that the substr part limits the search to only the first three characters of each element of stringVar (e.g., "abc", "def", etc.). This may not be strictly necessary but I've found it to be very useful at times. For example, if you had an element like "defabc" that you didn't want to include, using substr would ensure it wouldn't be "found" by grep.
Hope it's helpful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ggplot list value changes based on printing Here is a simplified version of an issue I encountered:
grob.list <- vector("list", length = 2)
for (i in 1:2) {
  grob.list[[i]] <- qplot(1:5, 1:5 * (-1)^i)
}

grid.arrange(grobs = grob.list)

We get two of the same graph (grob.list[[1]] is wrong).
If we print (even invisibly) the grobs turn out correctly.
grob.list <- vector("list", length = 2)
for (i in 1:2) {
  grob.list[[i]] <- qplot(1:5, 1:5 * (-1)^i)
  invisible(print(grob.list[[i]]))
}

grid.arrange(grobs = grob.list)

So does printing forces a ggplot object to "settle"? What does printing a ggplot object actually change to it?
Seems related to Grid of multiple ggplot2 plots which have been made in a for loop but doesn't address what printing does.

A: Printing forces the evaluation of the argument i, otherwise R's lazy evaluation delays looking up a value for it until plot rendering time, at which point it's just 2.
One option is to use force() in a function:
plot.g <- function(i) {
    force(i)
    qplot(1:5, 1:5 * (-1)^i)
}

grob.list <- vector("list", length = 2)
for (i in 1:2) {
    grob.list[[i]] <- plot.g(i)
}

grid.arrange(grobs = grob.list)

...or use lapply which in modern versions of R will force the evaluation of the argument i:
l <- lapply(1:2,function(i) qplot(1:5, 1:5 * (-1)^i))

grid.arrange(grobs = l)


text:
Q: codeigniter MVC inserting sensitive data in mysql table I am using codeigniter to build a page where users can like the post of another user.
I have three pages in this example, view_page.php , model_page.php and controller_page.php.
My view_page.php looks like this
<?php foreach($members as $value): ?>

        <?php echo $value['post_id']; ?>
        <?php echo $value['post_title']; ?>
        <a href="like/<?php echo $value['post_id']; ?>">Like

<?php endforeach; ?>

Controller_page.php
function like($post_id) {
    $this->load->model('model_page');
    $this->model_page->like_user($post_id);
    redirect('controller_page/viewdata');
}

My question is,
If a user with user_id = 1, posts something on the view_page.php (as shown in the image below), his post_id, post_title, and like button will show.
If another user with User_id = 22, likes that post, how do I add user_id=22 in the mysql table, to know which user liked the post?
I was thinking of passing the user_id=22 in the url of the like button, but then people can just manipulate the likes but changing user_id in the address bar.
How do I do it correctly?
Thanks in advance

A: You can make a table where you store all likes
For Example.
id post_id user_id
1  1       22
2  1       44

A: The Whole code for your questions would ask many aspects , As of now the solution provided by Tanseer UL Hassan is the best DB design ,now since your question is how to implement it , you can code in the following manner:
1) Create the variable which is to be passed to the controller :
<input type="hidden" name="hidUserIdFromSession" id="hidUserIdFromSession" value="<?php echo $someUserIdFromSession;?>">

2) Use ajax to Insert data in the above-mentioned table, like this :
$('#yourButton').click(function() {
//Modify this according to your button name
var postId = "Get your post id here";
var userId = $("#hidUserIdFromSession").val();
     $.ajax({
     type: 'POST',
     url: '<?php echo base_url("your/url/comes/here")?>',
     data: "postId="+postId+"&userId="+userId,
     success:function(response){
         //Your succes functions code comes here(Alert or any other processing).
     }
  });
});

3) Get the values inside controller function like this:
public function functionName(){
  //This is the same function which is called inside ajax call
  $arrReturn = array();
  $postId = $this->input->post('postId');
  $userId = $this->input->post('userId');
  $inserted = $this->model->insertLikeData($postId,$userId);
  //this is a call to model function in which you will actually make the Query to insert the data.
  if($inserted){
   $arrReturn['status'] = "Success";
   $arrReturn['data'] = array();//In case if you want to send some data.
  }else{
   $arrReturn['status'] = "Error";
   $arrReturn['data'] = array();//In case if you want to send some data.
  }
  $arrReturn = json_encode($arrReturn);
  echo $arrReturn;
}


text:
Q: I want to make a table audit/shadow table only when the email column of my table is updated when i update one row (email) the trigger sends all of the data to the shadow table I only want the one row that was updated what am i doing wrong in mt trigger code below?
CREATE TRIGGER AspNetUsersEmail_trigger
ON AspNetUsers
AFTER INSERT, UPDATE
AS
IF ( UPDATE (Email) )
BEGIN
INSERT INTO [dbo].[AspNetUserEmailAudit]([UserId],[UserName],[Email],[NormalizedEmail],[FirstName],[LastName])
SELECT Id,[UserName],[Email],[NormalizedEmail],[FirstName],[LastName] FROM AspNetUsers
END;

UPDATE [Elearn2].[dbo].[AspNetUsers]
SET Email = 'isaac@gmail.com'
WHERE [Id] = 'A1785377-E3BA-483A-8600-024CA5885951'

A: you should use inserted table:
CREATE TRIGGER AspNetUsersEmail_trigger
ON AspNetUsers
AFTER INSERT, UPDATE
AS
IF ( UPDATE (Email) )
BEGIN
INSERT INTO [dbo].[AspNetUserEmailAudit]([UserId],[UserName],[Email],[NormalizedEmail],[FirstName],[LastName])
SELECT Id,[UserName],[Email],[NormalizedEmail],[FirstName],[LastName]
FROM INSERTED
END;

read more about these special tables here

A: In MS SQL you have to select the data from the table inserted.
The tables deleted and inserted exists in triggers and contains the deleted and updated / inserted rows.


text:
Q: Xamaria.form InitializeComponent does not exist in this context Mainpage.xaml.cs

Mainpage.xaml

Anytime i run the application i got error code
  The name 'InitializeComponent' does not exist in the current context


text:
Q: iMacros - change URL and save screen shot So, I'm trying to get iMacros to go to an URL and take a screen shot:
url~place/something/something/########.jpg
It works, of course, but now I want it to loop and go through tons of numbers.
I'm starting at 900000000 and want it to loop through 900100000 while saving a screen shot of the web page only if it loads successfully.
I have searched around for hours and found some scripts some people have used, but I haven't been able to get anything to work. I don't even know where to start really.
Thanks!

A: If by ######## you mean a number that is changable then you can use this.
URL GOTO=url~place/something/something/{{!loop}}.jpg

This is an example for link. The key part is {{!loop}} . When you set number of loops and press play on iMacros the {{!loop}} will change from 1 to the number of loops you placed.


text:
Q: gnuplot: time course plot of a matrix of data I have Matrix Data like:
gnuplot: 3D plot of a matrix of data
How can I plot a 2D time course of parts of the data. E.g. in the example the time course for the value 0.6 would be: -6.35, -6.52, -6.48, -5.91.
Thanks in advance

A: Basically you have column data and you want to plot the values on one of them, column 3 in the example you give. In gnuplot this is achieved with using:
plot "data" using 0:3 every ::1

using 0:3 means "plot the values in column 0 as the x value and those in column 3 as the y value". Column 0 in gnuplot gives the order in which the data element appears (that is, 1, 2, 3, 4, ...).
every ::1 means start by plotting item number 1 (the first item would be number 0 in gnuplot). In your example this prevents 0.6 to be plotted together with the other elements in the column, -6.35, -6.52, -6.48, -5.91.
Typing help using and help every within gnuplot will give you more detailed info.


text:
Q: pexpect.interact(): TypeError: write() argument must be str, not bytes My pexpect script is quite simple, but I hit "TypeError: write() argument must be str, not bytes" after child.interact()
child = pexpect.spawn('npm login', timeout=40, encoding='utf-8')
child.logfile_read = sys.stdout
child.expect('Username:')
child.sendline('qiulang2000')
child.expect('Password:')
child.sendline('xxxx')
...
child.interact()

The error message:
File "/Users/qiulang/PycharmProjects/pexpect-test/./main.py", line 63, in <module>
    main()
  File "/Users/qiulang/PycharmProjects/pexpect-test/./main.py", line 59, in main
    npm_login()
  File "/Users/qiulang/PycharmProjects/pexpect-test/./main.py", line 54, in npm_login
    child.interact()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pexpect/pty_spawn.py", line 793, in interact
    self.__interact_copy(escape_character, input_filter, output_filter)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pexpect/pty_spawn.py", line 838, in __interact_copy
    self._log(data, 'read')
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pexpect/spawnbase.py", line 133, in _log
    second_log.write(s)
TypeError: write() argument must be str, not bytes

I know what that error meant, e.g. as TypeError: write() argument must be str, not bytes (Python 3 vs Python 2 ) explained, but how do I fix that for child.interact() ?
I change my codes to
child = pexpect.spawn('npm login', timeout=40)
child.logfile_read = sys.stdout.buffer
...

BUT then pexpect echo twice for every message after interact()! How do I fix that then ?

A: The comment I got solved my two problems. I listed what I experienced but all credits go to him.
So after add child.logfile_read = None  it solved the "TypeError: write() argument must be str, not bytes" error with using child.logfile_read = sys.stdout.
It also solved the duplicated echo problem when using child.logfile_read = sys.stdout.buffer
To quote from pexpect.interact doc, "If a logfile is specified, then the data sent and received from the child process in interact mode is duplicated to the given log" and "Even with encoding='utf-8' support, meth:interact will always pass input_filter and output_filter bytes.", which probably explained the TypeError I got.
BTW, for a simple pexpect script like ssh login I actually don't need to set child.logfile_read = sys.stdout at all because I just need to send my ssh password. But for npm login because it needs several steps, without child.logfile_read = sys.stdout the script will fail.


text:
Q: Merging & restructuring XML files using XSLT I am new to XSLT and XPath, and am struggling to write a stylesheet to merge two files.
For this question I'm just going to use a simple example of the concept I am struggling with, instead of my actual data.  Let's say I have two xml files that contain separate, but related data.  authors.xml and books.xml.  authors.xml contains a collection of authors, with some basic information about them, while books.xml contains a collection of books, with information (including the author, importantly) about them.
I want a resulting XML file that contains a collection of authors - but inside each author element, also a collection of books that belong to that author.
The best I have managed so far is to just duplicate the list of books inside each author, and I have a feeling that I may even be taking a completely strange/wrong approach to the problem.  I am only beginning to wrap my head around how the stylesheet is processed.
Sample authors.xml:
<authors>
    <author>
        <name>Jane Doe</name>
        <age>25</age>
    </author>
    <author>
        <name>John Smith</name>
        <age>53</age>
    </author>
</authors>

Sample books.xml:
<books>
    <book>
        <title>Flying Kites</title>
        <author>Jane Doe</author>
    </book>
    <book>
        <title>XSLT For Dummies</title>
        <author>John Smith</author>
    </book>
    <book>
        <title>Running Fast</title>
        <author>Jane Doe</author>
    </book>
</books>

Sample output.xml:
<authors>
    <author>
        <name>Jane Doe</name>
        <age>25</age>
        <books>
            <book>
                <title>Flying Kites</title>
            </book>
            <book>
                <title>Running Fast</title>
            </book>
        </books>
    </author>
    <author>
        <name>John Smith</name>
        <age>53</age>
        <books>
            <book>
                <title>XSLT For Dummies</title>
            </book>
        </books>
    </author>
</authors>

I'll also provide my current stylesheet, though I fear it may be on the wrong track:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output encoding="ISO-8859-1" indent="yes" method="xml"/>
<xsl:variable name="books" select="document('books.xml')"/>

<xsl:template match="/">
    <authors>
        <xsl:apply-templates select="/authors/author"/>
    </authors>
</xsl:template>

<xsl:template match="author">
    <author>
        <name><xsl:value-of select="./name"/></name>
        <age><xsl:value-of select="./age"/></age>
        <books>
            <xsl:apply-templates select="$books/books/book"/>
        </books>
    </author>
</xsl:template>

<xsl:template match="book">
    <!-- How to only copy if correct author? -->
    <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

I've spent a few hours searching around, but nothing I have found has solved my problem - although what I've found has helped me understand how both XSLT and XPath work a little better.
The question here was helpful, but was mostly about 'tacking on' updated data to an existing file.  The more relevant part to me was updating the date, which the supplied answer didn't actually do - and  was unable to do it myself.
I also posed my question on /r/learnprogramming, but the only responses I got were basically "XSLT is awful.  Run away now."
I seldom ask for help, but I've been stumped on this for a while without even an idea of what approach I should be taking.  Any help or advice would be greatly appreciated.
If it is relevant, I am using Saxon 9 to process the xslt.

A: You're almost there. To select the books per author, use a predicate in the author template.
<xsl:template match="author">
    <author>
        <xsl:copy-of select="name"/>
        <xsl:copy-of select="age"/>
        <books>
            <xsl:apply-templates select="$books/books/book[author=current()/name]"/>
        </books>
    </author>
</xsl:template>

You can also use copy-of (as shown above) instead of value-of.
If you want to copy the entire node, you don't need to change anything in the book template, but copy-of will also include the author child, so you might want to do it differently:
<xsl:template match="book">
    <xsl:copy>
        <xsl:copy-of select="title"/>
    </xsl:copy>
</xsl:template>


text:
Q: How to test the APNS p12 certificate environments ruby? I'm developing a service for sending push notifications, but I can't tell if the uploaded apns certificate p12 is from sandbox or production. I would like to test this in order to avoid human error when uploading the certificate.

A: The common name of the issued certificate tells you if it's from sandbox or production.
Example for production: Apple Production IOS Push Services: your.app.identifier
My ruby skills are a bit rusty but this should do it:
require 'openssl'
raw_cert = OpenSSL::PKCS12.new(File.read(path_to_your_cert), your_pwd) # If you want to read a .p12 cert

cert = OpenSSL::X509::Certificate.new(raw_cert)
cert.subject.start_with?("Apple Production IOS")

See also here: http://ruby-doc.org/stdlib-2.0.0/libdoc/openssl/rdoc/OpenSSL/X509/Certificate.html

A: I've made a few changes to the code suggested by muenzpraeger.
require 'openssl'

# If you want to read a .p12 cert

raw_cert = OpenSSL::PKCS12.new(File.read(path_to_your_cert), your_pwd)

OpenSSL::X509::Certificate.new(raw_cert).subject.to_s.include? "Apple Production"


text:
Q: SSRS 2016 visibility toggle not appearing I have a report with a hidden group. This group can be expanded with a toggle on  a text box within the parent group.

In SSRS2012, this toggle happily appears in the red circle.
However, in SSRS 2016, this is not appearing when viewed via the web portal. Can anyone help me out with this?


text:
Q: Get all XMLs from raw text file? I have log file and i need to write programm which get all xml's from this file.
File looks like
text
text
xml
text
xml
text
etc

Can you give me advice what is better to use regexp or something else?
Maybe it's possible to do it with dom4j?
If i'll try to use regexp i see next problem that text parts have <> tags.
Update 1:
XML example
  SOAP message:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
 here is body part of valid xml
</soapenv:Body>
</soapenv:Envelope>
text,text,text,text
symbols etc
  SOAP message:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
 here is body part of valid xml
</soapenv:Body>
</soapenv:Envelope>
text,text,text,text
symbols etc

Thanks.

A: if your XMl is always on one line then you can just iterate over lines checking if it starts with <. If so try to parse the whole line as DOM.
String xml = "hello\n" + //
        "this is some text\n" + //
        "<foo>I am XML</foo>\n" + //
        "<bar>me too!</bar>\n" + //
        "foo is bar\n" + //
        "<this is not valid XML\n" + //
        "<foo><bar>so am I</bar></foo>\n";
List<Document> docs = new ArrayList<Document>(); // the documents we can find
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
for (String line : xml.split("\n")) {
    if (line.startsWith("<")) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(line.getBytes());
            Document doc = docBuilder.parse(bis);
            docs.add(doc);
        } catch (Exception e) {
            System.out.println("Problem parsing line: `" + line + "` as XML");
        }
    } else {
        System.out.println("Discarding line: `" + line + "`");
    }
}
System.out.println("\nFound " + docs.size() + " XML documents.");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
for (Document doc : docs) {
    StringWriter sw = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(sw));
    String docAsXml = sw.getBuffer().toString().replaceAll("</?description>", "");
    System.out.println(docAsXml);
}

Output:
Discarding line: `hello`
Discarding line: `this is some text`
Discarding line: `foo is bar`
Problem parsing line: `<this is not valid XML` as XML

Found 3 XML documents.
<foo>I am XML</foo>
<bar>me too!</bar>
<foo><bar>so am I</bar></foo>

A: If each such part is in separate line, then it should be pretty simple:
s = s.replaceAll("(?m)^\\s*[^<].*\\n?", "");


text:
Q: calling to functions with polymorphic pointers #include <iostream>
class A{};
class AA:public A{};

struct X {
    void f(A *) {
        std::cout << "X::f(A*)\n";
    }
};

struct Y:public X {
    void f(A *) {
        std::cout << "Y::f(A*)\n";
    }
};

int main() {
    Y *y = new Y();
    X *x = new Y();
    const X *cx = new Y();

    y->X::f(new AA);
    x->f(new AA);
}

Print:

X::f(A*)
X::f(A*)

I don't understand why y->X::f(new AA) and x->f(new AA) wont raise compilation error. I get that X::f(A *) is called in both of the cases. But what is the principle whereby the compiler chooses to use this method? Function overload with polymorphism? Any thumb rules?

A: Your question implies you expected the behavior you would have gotten if f had been declared virtual in X.  In some languages, that is the only possible behavior.  In C++ you have a choice.
As you declared f, it uses the compile time type so x-f(new AA) calls X::f  because x is an X*
If you had declared f virtual in X the x-f(new AA) would call Y::f because x points to a Y
For the other aspect of your question (why there is no error involved in calling X::f for a object of type Y), X is a base class of Y, so there should be a valid object of type X buried inside each object of type Y and that X object should be usable with any X method.
Until seeing above comments, I missed the third aspect of your question, that the compiler deduces the need for an implicit cast from AA* to A* when you pass an AA* to a method that needs an A* and A is a base class of AA.  That deduction is largely separate from the compile time or run time choice between X::f and Y::f

A: The way your code currently is, if you do this:
y->X::f(new AA);
y->f(new AA);
x->f(new AA);

You'll get this:
X::f(A*)
Y::f(A*)
X::f(A*)

But, if you declare X::f as virtual, you'll instead get this:
X::f(A*)
Y::f(A*)
Y::f(A*)

Also, because AA is a child class of A, you can pass a pointer to AA where a pointer to A would be expected.

A: If you want x->f(new AA) to call Y::f(), then you need to declare X::f() as virtual.
If X::f() is not declared as virtual, then (as x is a X pointer) x->f(new AA) calls X::f().
See C++ standard section 10.3 "Virtual functions" (N3242):

*

*Virtual functions support dynamic binding and object-oriented programming. A class that declares or
  inherits a virtual function is called a polymorphic class.

*If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly
  from Base, a member function vf with the same name, parameter-type-list, cv-qualification, and refqualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.


text:
Q: An exception has been thrown during the rendering of a template ("The "yml~" translation loader is not registered.") I have this problem, when I try to load page after installed LexikTranslationBundle

An exception has been thrown during the rendering of a template ("The
  "yml~" translation loader is not registered.") in
  backendLayoutBundle:Layout:empty.html.twig at line 8.

empty.html.twig at line 8:

{% trans %}Reporting application{% endtrans %}

config:
lexik_translation:
    fallback_locale: en      # (required) default locale to use
    managed_locales: [en]    # (required) locales that the bundle have to manage
    base_layout:     "LexikTranslationBundle::layout.html.twig" # layout used with the translation edition template
    use_yml_tree:    false    # if "true" we will print a nice tree in the yml source files. It is a little slower.
    grid_input_type: text     # define field type used in the grid (text|textarea)
    storage:
        type: orm                    # where to store translations: "orm", "mongodb" or "propel"
        object_manager: default    # The name of the entity / document manager which uses different connection (see: http://symfony.com/doc/current/cookbook/doctrine/multiple_entity_managers.html)
                                     # When using propel, this can be used to specify the propel connection name
    resources_registration:
        type:                 all     # resources type to register: "all", "files" or "database"
        managed_locales_only: true    # will only load resources for managed locales


text:
Q: pyqt4 crosshair does not follow mouse movement in GraphicsLayoutWidget. How do I effectively debug this? I have tried to reverse engineer the MouseInteraction example to add a crosshair to a GraphicsLayoutWidget of an already functioning app. Please consider reading my last paragraph as this is a problem I have stumbled upon before, yet I have yet to get the broadly actionable feedback I need.
Horizontal and vertical lines for the crosshair to be displayed is initialized as follows
class MultiRoiViewBox(pg.ViewBox):
    def __init__(self,parent=None,border=None,lockAspect=False,enableMouse=True,invertY=False,enableMenu=True,name=None):
        pg.ViewBox.__init__(self,parent,border,lockAspect,enableMouse,invertY,enableMenu,name)

        self.vLine = pg.InfiniteLine(angle=90, movable=False)
        self.hLine = pg.InfiniteLine(angle=0, movable=False)
        #Other initializations...

The cross-hair is only displayed after an image is loaded and displayed via the GraphicsLayoutWidget. When the following executes the image and crosshair are displayed, however the SignalProxy doesn't seem to establish the right connection since the crosshair does not follow the mouse.
def showImage(self,arr):
    if arr==None:
        self.img = None
        return
    if self.img==None:
        self.img = pg.ImageItem(arr,autoRange=False,autoLevels=False)
        self.addItem(self.img)
    self.addItem(self.vLine, ignoreBounds=True)
    self.addItem(self.hLine, ignoreBounds=True)
    proxy = pg.SignalProxy(self.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
    self.img.setImage(arr,autoLevels=False)
    self.updateView()

Here is the function that is supposed to be called upon mouse movement.
def mouseMoved(self, ev):
    pos = ev[0]  ## using signal proxy turns original arguments into a tuple
    if self.sceneBoundingRect().contains(pos):
        mousePoint = self.vb.mapSceneToView(pos)
        index = int(mousePoint.x())
        self.vLine.setPos(mousePoint.x())
        self.hLine.setPos(mousePoint.y())

I have a breakpoint in the mouseMoved function and it is never triggered so the problem must lie in this single line in showImage:
proxy = pg.SignalProxy(self.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)

This even though there are no errors and I don't know what I should be looking for in the debugger since all the variables in this line of code seem to be in order. I can see that the scene is a GraphicsScene, but since GraphicsLayoutWidget consists of a GraphicsView I assume all is in order
>>> pg
<module 'pyqtgraph' from '/usr/lib/python2.7/dist-packages/pyqtgraph/__init__.pyc'>
>>> self.scene()
<pyqtgraph.GraphicsScene.GraphicsScene.GraphicsScene object at 0x7f8aeb4ee640>
>>> self.scene().sigMouseMoved
<bound signal sigMouseMoved of GraphicsScene object at 0x7f8aeb4ee640>
>>> self.mouseMoved
<bound method MultiRoiViewBox.mouseMoved of <ViewBoxCustom.MultiRoiViewBox object at 0x7f8aeb4ee770>>

If you see the answer, I humbly request insight into how you arrived at it for my own improvement. It is unclear to me what the proper debugging steps should be in this case. I've identified the line that I'm sure must be causing the issue, with a breakpoint here I find everything seems to be in order so what am I, generally speaking, supposed to do in such a predicament?
I'm a pycharm pro user if that helps makes explanations easier.

A: You were right with your assumption in what line the problem is. You simply forgot that your SignalProxy has to be an instance object. In your code it is a local variable of showImage.
So adding a self. to the line with your definition of the SignalProxy should make your code work:
self.proxy = pg.SignalProxy(self.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)

Don't be ashamed. I once made the same mistake and needed a long time to see it. :D
To be clear because I read the suggestion from barny in the comments. Just adding self.scene().sigMouseMoved.connect(self.mouseMoved) is wrong! It will work because that is not using the SignalProxy at all. If you added this, you can remove the SignalProxy line and it will still work. If you correct your SignalProxy line you have to remove the line saying that again.
I recommend using the SignalProxy, because there you can use the option rateLimit. That is especially important in cases like yours when using MouseMoved or MouseDrag events. Otherwise dependend on how much code/how much calculation is done it can result in non-fluent movement like in your case the crosshair.
Hope that will help you or someone else.


text:
Q: Microsoft accounts I have a Microsoft account (@outlook.com) and an Orgainizational account (@mycompany.com)
I find that Office 365 and SharePoint routinely get confused between them.
I'm currently trying to login to a SharePoint site with my Organizational account, and it keeps going to 'You need permission to access this site' page.
I've logout out of SharePoint many times and shut the browser, but every time I go back to the site it thinks I'm trying to use my Microsoft account.
What gives??

A: If your organization has a single sign-on app, reinstall it. I have seen this behavior before for SSO. Also make sure in your 365 top right corner that your organization account is selected, not your Microsoft account. Any Office product in 365, I normally change it in word.


text:
Q: How can I make the bot join on the channel? Somebody can check this code and tell me what's wrong with this?
@client.command()
async def join(ctx):
  if (ctx.author.voice):
    channel = ctx.message.author.voice.channel
    await channel.connect()
  else:
    await ctx.send("NO")

Error:


text:
Q: Vich upload bundle remove image Hi guys i have implemented vichuploadbundle to upload images but i want in the admin the user to remove the image.
<?php

namespace George\PageBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use George\UserBundle\Entity\User;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * Page
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="George\PageBundle\Entity\PageRepository")
 * @Vich\Uploadable
 */
class Page
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

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

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

/**
 * @var boolean
 *
 * @ORM\Column(name="visible", type="boolean")
 */
private $visible;

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

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

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

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

/**
 * @ORM\ManyToOne(targetEntity="George\UserBundle\Entity\User",  inversedBy="pages")
 * @ORM\JoinColumn(onDelete="CASCADE")
 */
private $owner;

//@ORM\Column(length=128, unique=true)
/**
 * @Gedmo\Slug(fields={"title"})
 * @ORM\Column(length=128, unique=true)
 */
private $slug;

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set title
 *
 * @param string $title
 *
 * @return Page
 */
public function setTitle($title)
{
    $this->title = $title;

    return $this;
}

/**
 * Get title
 *
 * @return string
 */
public function getTitle()
{
    return $this->title;
}

/**
 * Set content
 *
 * @param string $content
 *
 * @return Page
 */
public function setContent($content)
{
    $this->content = $content;

    return $this;
}

/**
 * Get content
 *
 * @return string
 */
public function getContent()
{
    return $this->content;
}

/**
 * Set visible
 *
 * @param boolean $visible
 *
 * @return Page
 */
public function setVisible($visible)
{
    $this->visible = $visible;

    return $this;
}

/**
 * Get visible
 *
 * @return boolean
 */
public function getVisible()
{
    return $this->visible;
}

/**
 * Set created
 *
 * @param \DateTime $created
 *
 * @return Page
 */
public function setCreated($created)
{
    $this->created = $created;

    return $this;
}

/**
 * Get created
 *
 * @return \DateTime
 */
public function getCreated()
{
    return $this->created;
}

/**
 * Set modefied
 *
 * @param \DateTime $modefied
 *
 * @return Page
 */
public function setModefied($modefied)
{
    $this->modefied = $modefied;

    return $this;
}

/**
 * Get modefied
 *
 * @return \DateTime
 */
public function getModefied()
{
    return $this->modefied;
}

/**
 * Set description
 *
 * @param string $description
 *
 * @return Page
 */
public function setDescription($description)
{
    $this->description = $description;

    return $this;
}

/**
 * Get description
 *
 * @return string
 */
public function getDescription()
{
    return $this->description;
}

/**
 * Set keywords
 *
 * @param string $keywords
 *
 * @return Page
 */
public function setKeywords($keywords)
{
    $this->keywords = $keywords;

    return $this;
}

/**
 * Get keywords
 *
 * @return string
 */
public function getKeywords()
{
    return $this->keywords;
}

/**
 * @return mixed
 */
public function getOwner()
{
    return $this->owner;
}

/**
 * @param mixed $owner
 */
public function setOwner(User $owner)
{
    $this->owner = $owner;
}

public function getSlug()
{
    return $this->slug;
}

// ..... other fields

/**
 * NOTE: This is not a mapped field of entity metadata, just a simple property.
 *
 * @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
 *
 * @var File
 */
private $imageFile;

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

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

/**
 * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
 * of 'UploadedFile' is injected into this setter to trigger the  update. If this
 * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
 * must be able to accept an instance of 'File' as the bundle will inject one here
 * during Doctrine hydration.
 *
 * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
 */
public function setImageFile(File $image = null)
{
    $this->imageFile = $image;

    if ($image) {
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        $this->updatedAt = new \DateTime('now');
    }
}

/**
 * @return File
 */
public function getImageFile()
{
    return $this->imageFile;
}

/**
 * @param string $imageName
 */
public function setImageName($imageName)
{
    $this->imageName = $imageName;
}

/**
 * @return string
 */
public function getImageName()
{
    return $this->imageName;
}
}

Can you advice me what is the best solution to this. I think it will be best if i have a method remove image and in the method try to use bundles build in function for removal the image (which i don't find anywhere) and update it in the database. In the front end this can be don trough ajax or on submit... Is there a build in function for the removal of file in the vichuploadbundle?

A: I have found how to remove the image. The bundle provides a custom form type in order to ease the upload, deletion and download of images.
When you build the form you specifies the widget:
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...

$builder->add('image', 'vich_image', array(
    'required'      => false,
    'allow_delete'  => true, // not mandatory, default is true
    'download_link' => true, // not mandatory, default is true
));
}

This add a twig template for deleting the img :)


text:
Q: Emberjs: Best Practice Partials & Includes I am new to Ember, but I have extensive Angular experience.
I am trying to create a single page web application with ember.
My app will be pretty extensive and large, so I would like to separate the page into multiple views.
Every Ember demo and tutorial creates an application only using the index.html page.
In Angular, we have a view attribute (ng-view) and use includes with partials. (ng-include)
Does ember have an equivalent? If so, can you direct me to any documentation or demo that uses it?
PS - I know I can dynamically build an HTML file with GRUNT by taking smaller HTML files and concat/uglifying them together, but is that the best practice or does ember have a view and include system equivalent.


text:
Q: Twitter Bootstrap does not resize(well) on mobiles I am using Twitter Bootstrap on two project, one is a static HTML website and other is a Rails application. When I test the website on desktop browser,resize works. But when I test it on mobile [Nokia E72], it just does not fit the width. Interesting thing is when I test the bootstrap homepage (http://twitter.github.com/bootstrap/) - it also has same problem.. Is this only me? I searched on stackoverflow and Google and everyone else seems to pretty happy with Bootstrap on their mobiles.
I have also tested alternative framework: Foundation - which seems to work better and there is at least no horizontal scroll.
Update: This seems to be a problem on my nokia E72.

A: Twitter's bootstrap only supports desktop browsers it seems.
https://github.com/twitter/bootstrap/wiki/Browser-Compatibility
Ok, I just found out there's something you need to add for android resizing:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">

From http://twitter.github.com/bootstrap/scaffolding.html#responsive

A: I'm not familiar with your phone (or it's screen size), but you might find the following site very helpful in testing your website... http://www.responsinator.com/ - you will probably find your screen size and that may help resolve the issue.

A: The more popular the browser, the better it will work with bootstrap. Quoting bootstrap documentation

Originally built with only modern browsers in mind, Bootstrap has evolved to include support for all major browsers (even IE7!) and, with Bootstrap 2, tablets and smartphones, too.

The Nokia E72 native browser is probably not supported and not standards compliant. You could try testing with Opera Mini. According to http://en.wikipedia.org/wiki/Usage_share_of_web_browsers the Nokia browser has a usage share of anywhere between 0.3% and 12% in 2011, and the trend appears to be that it's loosing marker share. So you should really test with Safari, Opera and Android.


text:
Q: How do i render a control to a string I've seen it time and time again the typical answer being something like this:
public string RenderControlToHtml(Control ControlToRender)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
    System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
    ControlToRender.RenderControl(htmlWriter);
    return sb.ToString();
}

... This is fine if you have simple html tags but when I have a textbox or some other asp control in my control it throws a wobbly about the control not being on a form (which in fact it is because im trying to render a portion of the page to a string that i can then send as an email)
So ...
I'm pretty sure this has been asked and answered before but i'm at a loss for finding a real answer that actually works ...
How do i render the html output of both server and client side controls to a html string in .Net 4.0 because seemingly the above is not good enough?
Note:
I have found examples that talk about doing this at page level ...
public override void VerifyRenderingInServerForm(Control control)
{
    //Do nothing (we dont care if theres a form or not)
}

... and disabling event validation but apparently that's not working for me either.
Is there a way to do this without a "hack" thats clean?
Also:
I even tried creating a new page, adding a form to it, added my control to that then calling renderControl on that page to which i got more errors.
EDIT:
I've been digging around and I think the problem might be related to postbacks or something because i found this:
http://forums.asp.net/t/1325559.aspx
Another thing that might be putting a bit of a spanner in the works is my use of the ajax toolkit, I essentially need only the visible portion of the control which seems to give a bit of a headache for updatepanels for some reason.
I'm guessing the above sample works only on basic .net controls that are not ajax toolkit related.
What further complicates the issue is that I would like to get the control in its current state when a button is clicked at the bottom of it ...
Essentially the control represents a form for booking an MOT and I would like to render the form filled in to an email that is then sent to the garage if that makes sense.
I'm thinking i may have to admit defeat here and simply get the markup from the client and manually build an email pulling out the control values as this seems to be a compatability issue between ajax controls and the renderControl method from what i can tell (maybe you cant render a partial postback compatible control in this fashion).
Unless someone smarter than me can prove it can be done ???

A: Create an ajax control extender and get the html markup on the client side then post that back to the server for processing, it's a bit of hack but it seems that anything involving ajax controls will cause the default recommended mechanism to break.


text:
Q: How do I add code to my Web Browser in PyQt5 to make changes to the internet? I'm using PyQt5 for a browser in python and I want to know how I can write code that makes changes to the internet (the web) in PyQt5. I want to be able to connect to the web and for example change where a website goes to. If someone searches google.com in their url bar I want the internet to go to my website.com.
My code is:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *

class MyWebBrowser(QMainWindow):
    def __init__(self,):
        super(MyWebBrowser, self).__init__()

        self.window=QWidget()
        self.window.setWindowTitle("Brave")

        self.layout=QVBoxLayout()
        self.horizontal = QHBoxLayout()

        self.url_bar = QTextEdit()
        self.url_bar.setMaximumHeight(30)

        self.go_btn=QPushButton("Go")
        self.go_btn.setMinimumHeight(30)

        self.back_btn = QPushButton("<")
        self.back_btn.setMinimumHeight(30)

        self.forward_btn = QPushButton(">")
        self.forward_btn.setMinimumHeight(30)

        self.horizontal.addWidget(self.url_bar)
        self.horizontal.addWidget(self.go_btn)
        self.horizontal.addWidget(self.back_btn)
        self.horizontal.addWidget(self.forward_btn)

        self.browser=QWebEngineView()

        self.go_btn.clicked.connect(lambda: self.navigate(self.url_bar.toPlainText()))
        self.back_btn.clicked.connect(self.browser.back)
        self.forward_btn.clicked.connect(self.browser.forward)
        self.layout.addLayout(self.horizontal)
        self.layout.addWidget(self.browser)

        self.browser.setUrl(QUrl("http://www.google.com"))

        self.window.setLayout(self.layout)
        self.window.show()

    def navigate(self,url):
        if not url.startswith("http"):
            url = "http://" + url
            self.url_bar.setText(url)
        self.browser.setUrl(QUrl(url))
app=QApplication([])
window=MyWebBrowser()
app.exec_()

A: In your code, the navigate function is what gets called when the Go button in the browser is clicked. You can make the navigate function modify the URL when the URL contains the string google.com:
def navigate(self, url):
    if not url.startswith("http"):
        url = "http://" + url
        self.url_bar.setText(url)

    # redirect to your website
    if "google.com" in url:
        url = "http://stackoverflow.com"

    self.browser.setUrl(QUrl(url))

This way, when you try to visit google.com, the address bar will still say http://google.com, but the browser will actually be sent to http://stackoverflow.com.


text:
Q: Add padding to object in 4-channel image I have a 4-channel image (.png, .tif) like this one:

I am using OpenCV, and I would like to add padding of type BORDER_REFLECT around the flower. copyMakeBorder is not useful, since it adds padding to the edges of the image.
I can add certain padding if I split the image in bgr + alpha and apply dilate with BORDER_REFLECT option on the bgr image, but that solution spoils all the pixels of the flower.
Is there any way to perform a selective BORDER_REFLECT padding addition on a ROI defined by a binary mask?
EDIT:
The result I expect is something like (sorry I painted it very quickly with GIMP) :

I painted two black lines to delimit the old & new contour of the flower after the padding, but of course those lines should not appear in the final result. The padding region (inside the two black lines) must be composed by mirrored pixels from the flower (I painted it yellow to make it understandable).

A: A simple python script to resize the image and copy the original over the enlarged one will do the trick.
import cv2

img = cv2.imread('border_reflect.png', cv2.IMREAD_UNCHANGED)

pad = 20
sh = img.shape
sh_pad = (sh[0]+pad, sh[1]+pad)
imgpad = cv2.resize(img, sh_pad)

imgpad[20:20+sh[0], 20:20+sh[1], :][img[:,:,3]==255] = img[img[:,:,3]==255]
cv2.imwrite("padded_image.png", imgpad)

Here is the result

But that doesn't look very 'centered'. So I modified the code to detect and account for the offsets while copying.
import cv2

img = cv2.imread('border_reflect.png', cv2.IMREAD_UNCHANGED)

pad = 20
sh = img.shape
sh_pad = (sh[0]+pad, sh[1]+pad)
imgpad = cv2.resize(img, sh_pad)

def get_roi(img):
    cimg = img[:,:,3].copy()

    contours,hierarchy = cv2.findContours(cimg,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

    #Remove the tiny pixel noises that get detected as contours
    contours = [cnt for cnt in contours if cv2.contourArea(cnt) > 10]

    x,y,w,h = cv2.boundingRect(cnt)
    roi=img[y:y+h,x:x+w]
    return roi

roi = get_roi(img)
roi2 = get_roi(imgpad)

sh = roi.shape
sh2 = roi2.shape

o = ((sh2[0]-sh[0])/2, (sh2[1]-sh[1])/2)

roi2[o[0]:o[0]+sh[0], o[1]:o[1]+sh[1], :][roi[:,:,3]==255] = roi[roi[:,:,3]==255]
cv2.imwrite("padded_image.png", imgpad)

Looks much better now

A: The issue has been already addressed and solved here:
http://answers.opencv.org/question/90229/add-padding-to-object-in-4-channel-image/


text:
Q: SOAP request from WSDL in .net I would like to get a sample SOAP Request for a given action from the WSDL just like SOAP UI. I would like to avoid using svcutil to generate an assembly and reflect over it, but is still acceptable. But, I am not sure how to generate SOAP Reqest from the method info.
Any info on this would be of great help.
Story behind what I need....
I am looking at a web application, which can test web services (just like wcfTestClient and SOAP UI but its web based) and user can save the SOAP Request in their account and execute them when ever they would like to as well as do it periodically.

A: If I get it right you can use WCFTestClient also have a loot at Web Service Studio.
EDIT Based on your comments seems you need dynamic client proxy. Actually there are very few cases when you really need it. Can you please let us know why exactly you need it ?
Although if you are sure that there is no other way and you have one of those very rare cases so that dynamic client proxy must be used, have a look HERE and HERE.

A: Finally, I stumbled upon a codeproject app available at http://www.codeproject.com/KB/cpp/wsdlparser.aspx
This meets my requirements to parse and construct SOAP Request from the wsdl just like SOAP UI. I have to make some modifications to the code, to make it work with WCF services, which I soon hope will be posting in github.

A: If you don't want to use SoapUI (don't see why you wouldn't) you could use the built-in WcfTestClient.exe. It's primitive compared to SoapUI but could get the job done.


text:
Q: Use edge detection to segment images I have an RGB from which I detected the edges and I'm curious if I can use it to optimize a segmentation or as a mask to improve the segmentation to identify cultivated fields.
Could you do that? If yes, how?
import cv2
image = cv2.imread('path_to_RGB.tif')

canny = cv2.Canny(image, 100, 200, 1)

cnts = cv2.findContours(canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

for c in cnts:
    cv2.drawContours(image,[c], 0, (36,255,12), 2)

cv2.imwrite('C:\\canny.tif', canny)
cv2.waitKey(0)


text:
Q: Can't send traffic both ways through Azure VPN Gateway? Probably a really rookie mistake, but here goes. I have a Juniper SRX and an Azure VPN Gateway, and they are connected. My on-prem VMs can connect to the Azure VMs via Vnet IP, but the reverse is not working. Neither ping nor TCP connections seem to be working. I've created a route in Windows on-prem to go to the subnet in Azure, but I can't find the VPN Gateway IP in this Vnet at all. The Gateway Subnet just shows the route as associated device, but no IP. Does anyone have an idea?

A: Did you configure a Local network gateway to communicate back to on prem?
Scroll to about halfway down this step-by-step to see how to configure your local network gateway.
https://blogs.technet.microsoft.com/canitpro/2017/06/28/step-by-step-configuring-a-site-to-site-vpn-gateway-between-azure-and-on-premise/
PowerShell Steps (if needed):
https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-create-site-to-site-rm-powershell#2-create-the-local-network-gateway


text:
Q: Make a p have the same width/height as an image that is placed in another div I am trying to make a p always have the same width and height as an image that is placed next to it.
I set specific dimensions to both of the divs containing those elements, and then set the img width and height to 100% (as mentioned here). Unfortunately that led to images getting distorted even if I used the dimensions of the actual images being provided. Forgot to mention that I use Picturefill by the way, perhaps it has something to do with that..
I should mention that it is possible to somewhat control the amount of distortion, by adjusting the values in the sizes attribute of the picturefill HTML. However it turned out that I would have to add thousands of different values to that attribute to actually make it work this way. It just didn't really feel like the correct approach to something like this.
HTML
<div>
  <img
     sizes="(min-width: ...px) ...vw, (min-width: ...px) ...vw etc"
     srcset="/images/img1.jpg 280w,
             /images/img2.jpg 350w"
     alt="...">
</div>

<div>
 <p> ... </p>
</div>

A: Set the image width to 100% and height to auto. That way, the image will preserve its aspect ratio while still being resized.


text:
Q: How do I set the URL for a SitePrism::Page that might have a subdomain? The infrastructure I'm working with originally handled the URLs the way the Site Prism documentation suggested: the domain was handled by setting Capybara.app_host, and the pages themselves called set_url with a relative path.
It turns out that some pages on the production site have a subdomain, like members.mycompany.com rather than www.mycompany.com. The tests also need to be able to run on test environments with different domains entirely, and in the test environments there are no subdomains at all, even for those pages that do have the subdomain in the production site. So putting the full URL into each SitePrism::Page is not an option.
I believed that the best option was to stop using Capybara.app_host entirely, and create a URL builder that would use the state of the environment (i.e. :test or :production), the relative path to the page, and a flag indicating whether or not the page was part of the production subdomain. Something like:
def get_url(relative_path, subdomain_flag=false)
   case Environment.get_environment
   when :test
      domain = "https://testmachine.localenvironment.com"
   when :production
      if subdomain_flag
         domain = "https://members.mycompany.com"
      else
         domain = "https://www.mycompany.com"
      end
   end
   return "#{domain}" + "#{relative_path}"
end

I had hoped that I could use get_url in each of my SitePrism::Page objects to generate the full URL without the need for Capybara.app_host, like so:
class LoginPage < SitePrism::Page
   set_url get_url("/login")
   ...
end

class MemberPage < SitePrism::Page
   set_url get_url("/mypage", true)
   ...
end

If the Environment were :test, I'd expect the LoginPage to load https://testmachine.localenvironment.com/login and MemberPage to load https://testmachine.localenvironment.com/mypage. If the Environment were :production, I'd expect LoginPage to load https://www.mycompany.com/login and MemberPage to load https://members.mycompany.com/mypage.
I believe the code in my get_url method does what I think it should do, and I also believe that the Environment object I created is having its state set to the proper environment prior to the pages' #load method being called in the test. Sadly, when I try to load my SitePrism::Page objects, the environment value that gets picked up by get_url is always the default value from the Environment object (which is :test). As a result, it ends up loading the test environment URL even if I'm trying to execute against production.
It feels like the set_url part of each SitePrism::Page object is evaluated before the SitePrism::Page objects are instantiated, and I can't seem to find a way to get my initialization of the Environment to happen prior to it. I'm new to Ruby so I'm hoping I'm just misunderstanding the order or hierarchy that these things are loading in, and that it's not difficult to correct. Can anyone identify what's wrong with my attempt, or, if there is a better way to handle this situation, point me to what that better way is?

A: Yes, those set_url calls are being evaluated when the class is being defined, in other words, when your file is first required.
The simple solution is to make sure that your Environment configuration is initialised before the page objects are required.
Note that the SitePrism docs say that set_url is only needed when navigating directly to a page:

Note that setting a URL is optional - you only need to set a url if
  you want to be able to navigate directly to that page. It makes sense
  to set the URL for a page model of a home page or a login page, but
  probably not a search results page.

For verifying that you're on a page, you can use a regular expression instead. See https://github.com/natritmeyer/site_prism#verifying-that-a-particular-page-is-displayed for an example of running in multiple environments.


text:
Q: Question about hyperbolic PDE I am reading the book 1 (Par 2.2 pag. 31) about the computational fluid dynamics. Unfortunately  I don't understand the scheme of the characteristics of the wave equations.
This scheme starts from the example of hyperbolic PDE:
$\frac{\partial^2 u}{\partial t^2}-\frac{\partial^2 u}{\partial x^2}=0$  (1)
The settled intial condition is:
$u(x,0)=sin(\pi x)$ , $\frac{\partial u}{\partial t }(x,0)=0$ (2)
The boundary condition is:
$u(0,t)=u(1,t)=0$  (3)
Here are my questions:

*

*How can I calculate the characteristic directions from (1)? Why the characteristics direction is $\pm\frac{d x}{dt }$?

*As far as I understood, the characteristic directions are the angular coefficients of the lines. why do they intercept the x-axis in $x_{i}-t_{i}$ and $x_{i}+t_{i}$? or maybe I am misunderstanding the Figure.

*Why the lower triangle is called "Domain of dependence" and the upper "Domain of Influence"?
I have tried to search other resources, but it is difficult to understand for me.
1 Fletcher, Clive A. J. (1998). Computational Techniques for Fluid Dynamics 1 . , 10.1007/978-3-642-58229-5()

A: (1) Different fields have different strategies for solving hyperbolic PDEs. You can check that the equation is solved by the sum of one wave traveling left at constant speed and another traveling right at constant speed.
(2) Those are the characteristics for just a single point.
(3) The domain of dependence indicates the region of the initial condition that impacts the solution at (x_1,t_1). It turns out with hyperbolic PDEs the propagation speed of information is finite. This matches the intuition that any events on the opposite side of the world have literally no impact on me until about .01 seconds later. Hence "domain of dependence". Domain of influence reflects the opposite phenomenon. Starting at (x_1,t_1), what regions of space/time are influenced by the function value, which once again reflects the idea that propagation is finite. I am only included in the domain of influence on events on the other side of the world about .01 seconds after they occur.
Here's a good video I'd recommend, short and to the point.
https://www.youtube.com/watch?v=Av1VJ5fJcKo


text:
Q: Delete Solidworks drawing Detail view I need to delete unnecessary detail views in specified Solidworks drawing, but I need to use late binding. First I try to delete Detail view from feature tree, but then it delete only Detail view leaving sketched circle. Then I delete Detail view in drawing, same result. Then Detail view circle, same result. Last I try delete sketched circle, but it doesn't select certain circle. When this code is compile in Solidworks API, all is working correctly, but when this is compile in Excel VBA, then it does this weird thing. I have suspicion that this is connected with late binding. Any suggestions?
Dim SwApp
On Error Resume Next
Set SwApp = GetObject(, "SldWorks.Application")
'If Solidworks is not started then start it
If Err.Number <> 0 Then
Set SwApp = CreateObject("SldWorks.Application")
End If
SwApp.Visible = True
Dim InitialDrawing2 As Object
Set InitialDrawing2 = SwApp.Opendoc(FormatSketchTemplateFolder & "FormatSketch+Tray.SLDDRW", 3)
Dim Status As Boolean
Status = InitialDrawing2.Extension.SelectByID2("Detail Circle2", "DETAILCIRCLE", 0, 0, 0, False, 0, Nothing, 0)
         InitialDrawing2.EditDelete
Status = InitialDrawing2.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, 0)
         InitialDrawing2.EditDelete

A: After several hours I found an error.
Before selecting circles needs to select certain drawing view
Dim SwApp
On Error Resume Next
Set SwApp = GetObject(, "SldWorks.Application")
'If Solidworks is not started then start it
If Err.Number <> 0 Then
Set SwApp = CreateObject("SldWorks.Application")
End If
SwApp.Visible = True
Dim InitialDrawing2 As Object
Set InitialDrawing2 = SwApp.Opendoc(FormatSketchTemplateFolder & "FormatSketch+Tray.SLDDRW", 3)
Dim Status As Boolean
InitialDrawing2.ActivateView ("Drawing View9")
Status = InitialDrawing2.Extension.SelectByID2("Detail Circle2", "DETAILCIRCLE", 0, 0, 0, False, 0, Nothing, 0)
         InitialDrawing2.EditDelete
Status = InitialDrawing2.Extension.SelectByID2("Arc1", "SKETCHSEGMENT", 0, 0, 0, False, 0, Nothing, 0)
         InitialDrawing2.EditDelete


text:
Q: What is the best way to set the required attribute based on a state in React? I'd like to set the required attribute on input based on a state, I tried something like the following:
const [required, setRequired] = useState(false)

return(
  <form onSubmit={submitHandler}>
    <input id='name' type='text' required={required} onChange={changeHandler} />
  </form>
)

At the moment, I can't submit the form as the input is still required 'even if my state is false'. What am I missing?
Thanks in advance!

A: This ended up being weirder than I imagined.
required is a weird one in HTML. It doesn't need to be set to a boolean value, if it is passed to an input element then that input is required.
To programmatically set attributes to your JSX elements, you can use the spread operator on an object that contains required as a key.
The way I managed to do this was with a component that looked like this:
const Component = () => {
    const [required, setRequired] = useState({ required: true });

    return (
        <form>
            <input id="name" type="text" {...required} onChange={() => { //handleChange }} />
        </form>
    )
}

Here's another interesting stackOverflow discussion about the required attribute.
EDIT:
If you want to remove the required attribute later, you can set the state variable to an empty object.
setRequired({});

A:
The required attribute only works with default form actions. You'll need to do your own validation in the handler. You should also explicitly define the button type attribute as well since buttons by default are type="submit".
Create a validation function and pass your state values to it. Return true if input is valid, false otherwise.

This might be the answer you are looking for:
https://stackoverflow.com/a/64962453/8044582


text:
Q: Warning: Attempt to present ViewController on ViewController which is already presenting ViewController I have a view controller with a toolbar with 3 UIButtons that open a new view controller as a popover. I created the segues in Storyboard and selected "Present as Popover". The popovers work but when the user taps on another button while a popover is currently open, I get this error:
Warning: Attempt to present <Fingerpainter.OpacityViewController: 0x79095110>  on <Fingerpainter.DrawingViewController: 0x7b278000> which is already presenting <Fingerpainter.BrushSizeViewController: 0x79573770>

Is there a way to like make sure all popovers are closed before opening a new one? Here's my prepareForSegue method in the main ViewController (containing the toolbar):
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let identifier = segue.identifier ?? ""
    let popoverPresentationController = segue.destinationViewController.popoverPresentationController
    popoverPresentationController!.delegate = self
switch identifier {
    case Storyboard.BrushSizeSegueIdentifier:
        if let brushSizeViewController = popoverPresentationController?.presentedViewController as? BrushSizeViewController {

            // set properties in brushSizeViewController
        }
    case Storyboard.OpacitySegueIdentifier:
        if let opacityViewController = popoverPresentationController?.presentedViewController as? OpacityViewController {
            //set properties in opacityViewController
        }
    case Storyboard.ColorSegueIdentity:
        if let colorViewController = popoverPresentationController?.presentedViewController as? ColorViewController {
            //set properties in colorViewController
        }
    default:
        break
    }

}

A:
Is there a way to like make sure all popovers are closed before opening a new one

It's the other way around. It's your job to make sure that while the popover is present, a button that summons another popover is not tappable. You can do this by disabling the button, but more commonly, in order to coordinate the disabling of the button with the presence of the popover, it's done by adjusting the popover presentation controller's passthroughViews.
Unfortunately there's a massive and long-standing bug where even setting the passthroughViews to nil doesn't prevent toolbar buttons from being tappable. The workaround is to do it with a delay. A lot of my popover code adds this sort of thing:
if let pop = popoverPresentationController {
    delay(0.1) {
        pop.passthroughViews = nil
    }
}

(where delay is described here: https://stackoverflow.com/a/24318861/341994).


text:
Q: How to Loop table creation I have the following code which works fine for one table but I am trying to figure out how to make it loop.
DECLARE @sql NVARCHAR(2000)
DECLARE @table VARCHAR(100)
DECLARE @command NVARCHAR(1000)

SELECT @table = ( VV.SRC_CD )
FROM   VV

SET @sql = 'SELECT [CD],[SRC_CD],[SRC_CD_DESC],[DSC],[REFRESH_DT],[GEN_DSC] = CAST(null as VARCHAR(50))      INTO dbo.vv_' + @table
           +
' FROM [vv] A WHERE A.SRC_CD <> ''GEN''      AND A.DSC <> ''NO DATA'' AND A.DSC <> ''(BLANK) NO'' AND A.src_cd = '''
           + @table + ''''

EXEC Sp_executesql
  @stmt = @sql

The code that populates the @table variable returns one row.  What I am trying to do is get this procedure to loop one time for each distinct value in the table for that row.  The distinct clause doesn't work here and I have tried a basic table array with no luck.
Do I need to modify this to use a cursor?

A: It sounds like you're in need of a cursor, something like:
DECLARE @Iterator NVARCHAR(100)
       ,@sql NVARCHAR(MAX)
DECLARE xyz CURSOR
FOR
--Select stuff to iterate over
SELECT DISTINCT SRC_CD
FROM w

OPEN xyz
FETCH NEXT FROM xyz
INTO @Iterator

WHILE @@FETCH_STATUS = 0
BEGIN

--Do stuff
SET @sql = 'SELECT [CD],[SRC_CD],[SRC_CD_DESC],[DSC],[REFRESH_DT],[GEN_DSC] = CAST(null as VARCHAR(50))
            INTO dbo.vv_' + @Iterator +'
            FROM [vv] A
            WHERE A.SRC_CD <> ''GEN''
                 AND A.DSC <> ''NO DATA''
                 AND A.DSC <> ''(BLANK) NO''
                 AND A.src_cd = ''' + @Iterator + ''''
PRINT (@sql)

    FETCH NEXT FROM xyz
    INTO @Iterator
END

CLOSE xyz
DEALLOCATE xyz
GO

I left PRINT in there so you can ensure the output is as desired before executing.


text:
Q: How to join Pandas Dataframes with keeping the left column multiple times? I want to do the following join:
    A   B
0   a   z
1   b   y
2   c   x

    A   C   D
0   a   1   xy
1   b   1   xc
2   a   2   xv
3   c   2   xb

to
    A   B   C   D
0   a   z   1   xy
1   b   y   1   xc
2   c   x   1   NaN
3   a   z   2   xv
4   b   y   2   NaN
5   c   x   2   xb

So for every value in 'C' I want to join the whole first Dataframe to the second one without losing any rows of the first Frame. Is that possible?

A: join and reindex
d = d2.set_index(['A', 'C'])
d = d.reindex(pd.MultiIndex.from_product(d.index.levels, names=d.index.names))
d.join(d1.set_index('A')).reset_index().sort_index(1)

   A  B  C    D
0  a  z  1   xy
1  a  z  2   xv
2  b  y  1   xc
3  b  y  2  NaN
4  c  x  1  NaN
5  c  x  2   xb

Rearrange some things to match OP exactly
d = d2.set_index(['C', 'A'])
d = d.reindex(pd.MultiIndex.from_product(d.index.levels, names=d.index.names))
d.join(d1.set_index('A')).sort_index().reset_index().sort_index(1)

   A  B  C    D
0  a  z  1   xy
1  b  y  1   xc
2  c  x  1  NaN
3  a  z  2   xv
4  b  y  2  NaN
5  c  x  2   xb

Clever use of pd.concat
pd.concat(d.merge(d1.assign(C=i), 'outer') for i, d in d2.groupby('C'))

   A  B  C    D
0  a  z  1   xy
1  b  y  1   xc
4  c  x  1  NaN
2  a  z  2   xv
5  b  y  2  NaN
3  c  x  2   xb

A: This will involve groupby + merge , I cannot guarantee the speed
df2.groupby('C').apply(lambda x : x.merge(df1,on='A',how='outer').assign(C=lambda d: d['C'].ffill())).reset_index(drop=True)
Out[954]:
   A    C    D  B
0  a  1.0   xy  z
1  b  1.0   xc  y
2  c  1.0  NaN  x
3  a  2.0   xv  z
4  c  2.0   xb  x
5  b  2.0  NaN  y


text:
Q: Linked Lists: How to remove odd numbers? I am currently taking an online computer science introductory course and have just learned the concept of a linked list. Though I understand the concept of linked lists, I still am unsure as how to deal with linked lists.
As such, I seek out help in solving the following problem, which will be of significant help for my understanding of linked lists:
Write a function (not in LinkedList class definition) that given a linked list, will change that linked list to filter out odd numbers. Immediately after the function returns, the linked list will only have even numbers.
I am unsure as to how to access the nodes in the list and check whether they are odd or even and remove or keep them accordingly.
I apologize if this seems like a trivial question, but I would appreciate any help that might help me learn.
The code for the linked list and node classes (as provided by the online course):
class Node:
    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next = next_node

    def __str__(self):
        return str(self.data)

class LinkedList:
    def __init__(self):
        self.length = 0
        self.head = None

    def print_list(self):
        node = self.head
        while node is not None:
            print(node, end=' ')
            node = node.next
        print('')

    def add_at_head(self, node):
        node.next = self.head
        self.head = node
        self.length += 1

    def remove_node_after(self, node):
        if node.next is not None:
            temp = node.next
            node.next = node.next.next
            temp.next = None
            self.length -= 1

    def remove_first_node(self):
        if self.head is None:
            return
        temp = self.head
        self.head = self.head.next
        temp.next = None
        self.length -= 1

    def print_backward(self):
        def print_nodes_backward(node):
            if node.next is not None:
                print_nodes_backward(node.next)
            if node is not None:
                print(node, end=' ')

        if self.head is not None:
            print_nodes_backward(self.head)

        print('')

A: Let's say you have a bare-bones simple linked list that looks like this:
class LinkedList:
    class ListNode:
        def __init__(self, data):
            self.data = data
            self.next = None
    def __init__(self):
        self.head = None
    def add(self, data):
        if self.head is None:
            self.head = LinkedList.ListNode(data)
        else:
            current_node = self.head
            while current_node.next is not None:
                current_node = current_node.next
            current_node.next = LinkedList.ListNode(data)
    def __str__(self):
        ret = "["
        current_node = self.head
        while current_node is not None:
            ret = ret + str(current_node.data)
            if current_node.next is not None:
                ret = ret + ", "
            current_node = current_node.next
        ret = ret + "]"
        return ret

In other words, the LinkedList contains a single head, which is a ListNode. Every element in the Linked List is contained in a ListNode, and each ListNode points towards the next element in the list.
As you can see, for adding an element to the list, we either create a node at the head if the list is empty (i.e. self.head is None), or we traverse to the end of the list by continuously jumping to the .next element for each ListNode, starting from the head. We also use this paradigm for printing a string representation of our list.
So, to remove any node from the linked list, we can simply change the node that references it, so that the node we want to remove gets skipped. At which point it will disappear.
To remove all list nodes containing odd-numbered data, we might do something like this:
    def remove_odds(self):
        # special case: head node
        # remove odd head elements by simply setting head to the next element after
        while (self.head is not None) and (self.head.data % 2 == 1):
            self.head = self.head.next
        # regular case: the rest of the nodes
        current_node = self.head
        while (current_node is not None) and (current_node.next is not None):
            # if the next node's data is odd, then
            if current_node.next.data % 2 == 1:
                # skip that node by pointing this node's .next to the next node's .next
                current_node.next = current_node.next.next
            # otherwise, move forwards in the list
            else:
                current_node = current_node.next

Proof of concept:
>>> lst = LinkedList()
>>> lst.add(2)
>>> lst.add(5)
>>> lst.add(6)
>>> lst.add(3)
>>> lst.add(7)
>>> lst.add(8)
>>> lst.add(10)
>>> lst.add(1)
>>> lst.add(4)
>>> print(lst)
[2, 5, 6, 3, 7, 8, 10, 1, 4]
>>> lst.remove_odds()
>>> print(lst)
[2, 6, 8, 10, 4]

A: Copied from comment: The idea is to iterate through the list head-to-tail while remembering the previous node; when you find a garbage node, apply remove_node_after to the remembered node, or move the head to the current node if we haven't had time to remember anything yet.
The code would be something like this (untested):
class LinkedList:
    # ...
    def delete_if(self, pred):
        prev = None
        curr = self.head
        while curr:
            if pred(curr.data):
                if prev:
                    self.remove_node_after(prev)
                else:
                    self.head = curr
            prev = curr
            curr = curr.next

llist.delete_if(lambda x: x % 2 == 1) # delete if odd

A: # Mahmoud AL-Mokdad
# this course on Udemy By SEfactoru right
# use my code
def filter_even(ll):
    first_node = ll.head
    while (first_node is not None) and (first_node.data % 2 != 0):
        ll.remove_first_node()
        first_node = ll.head
    node = first_node
    while node is not None and node.next is not None:
        if node.next.data % 2 != 0:
            ll.remove_node_after(node)
        else:
            node = node.next


text:
Q: Getting the mouse coordinates in the WM_LBUTTONDOWN message the structure of MSG as followed:
typedef struct tagMSG {
  HWND   hwnd;
  UINT   message;
  WPARAM wParam;
  LPARAM lParam;
  DWORD  time;
  POINT  pt;
} MSG, *PMSG;

the message procedure as followed:
long WINAPI WndProc(HWND hWnd, UINT iMessage, UINT wParam, LONG lParam)

My Question: In the message procedure, why it doesn't pass the POINT variable to window procedure, and how to find mouse's POINT ? By GetCursorPos() ? I find some example get it by LOWORD(lParam), HIWORD(lParam) directly.. can you tell me the information about it ? thank you...
i had see someone write this, is it right ? i not sure:
RECT rect1;
long WINAPI WndProc(HWND hWnd,UINT iMessage,UINT wParam,LONG lParam)
{
    HDC hDC;
    WORD x,y;
    PAINTSTRUCT ps;

    x = LOWORD(lParam);
    y = HIWORD(lParam);

    switch(iMessage)
    {
    case WM_LBUTTONDOWN:
        if(wParam&MK_CONTROL)
        {
            rect1.left = x;
            rect1.top = y;
        }
        else if(wParam&MK_SHIFT)
        {
            rect1.left = x;
            rect1.top = y;
        }
        break;

    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    default:
        return(DefWindowProc(hWnd,iMessage,wParam,lParam));
    }
    return 0;
}

A:
In the process function, why it doesn't pass the POINT variable to process function, and how to find mouse's POINT ?

There are separate functions to retrieve that information if you really want it.  Most message handlers don't deal with mouse input, and there's no point in passing around extra arguments for message handlers that will almost never use them. (Arguably WndProc could have been defined to take a MSG*; I don't know the reason for its design, but I'd guess that members were added to the MSG structure over time.)

By GetCursorPos() ?

No. GetCursorPos will return the current position of the cursor, which might be different from the position when the message was generated.  You instead want GetMessagePos. (This is analogous to GetAsyncKeyState versus GetKeyState.)
Similarly, a message handler can obtain the message time through GetMessageTime.

A: The coordinates do not disappear. They are in lParam. See WM_MOUSEMOVE message on MSDN:
A window receives this message through its WindowProc function.
...
lParam

    The low-order word specifies the x-coordinate of the cursor.
The coordinate is relative to the upper-left corner of the client area.

    The high-order word specifies the y-coordinate of the cursor.
The coordinate is relative to the upper-left corner of the client area.
...
Use the following code to obtain the horizontal and vertical position:

xPos = GET_X_LPARAM(lParam);
yPos = GET_Y_LPARAM(lParam);


text:
Q: Programming a "t command" into a serial object So I have a grouping of "t commands", which is a string.  These commands are supposed to be sent to a serial port, which will then run the command.  I am using something similar to this in order to change the string into byte form which can then be read by the serial port:
(I'm using pySerial)
import serial
s=serial.Serial('COM')
str=('t command')
str=bytearray(str,"utf-8")
s.write.(str)

there are no errors, but the command is not working.  Anybody have any ideas?


text:
Q: How to find a AWS SageMaker Pipeline execution from inside one of its steps? In code that is running inside a processing step I would like to find details about pipeline execution that the step is part of.
From the step (processing step) I have access to:

*

*Job name

*Job ARN

How to find pipeline execution (or it's ARN) based on that?
I explored following things:
One can using boto3 SageMaker client:

*

*List all pipelines

*For each pipeline list all executions

*For each execution list all steps

*Filter the steps to find the execution
However, I think there should be a better way?

I tried to explore Lineage API, but it seems that you can't use job ARN as a starting ARN.


text:
Q: I am trying to troubleshoot why my api are not working In the Google console, my credentials are showing as 100% error. I don't understand why or how to troubleshoot.
I have enabled, regenerated, created new ones, added payment method, restricted, unrestricted, they just don't seem to work and I have no idea why.
NO code, just api keys
This is just to add into a wordpress site, should be simple. All I need are the keys to work.


text:
Q: ServerSocket send message to client public class Server extends AsyncTask<Void, Intent, Void> {

    private final Context context;

    public Server(Context context) {
        this.context = context;
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            ServerSocket server = new ServerSocket(12345);
            while (true) {
                Socket client = server.accept();

                // send message
                OutputStream outputStream = client.getOutputStream();
                String message = "Hello Android! - Send from Server.";
                outputStream.write(message.getBytes());

                // THIS DONT WORK FOR SOME REASONS read message
                String response = "";
//              InputStream inputStream = client.getInputStream();
//              response = Utils.inputStreamToString(inputStream);

                // notify ServerService
                Intent intent = new Intent(Messenger.ACTION);
                intent.putExtra("action", Messenger.SERVER_NEW_CLIENT_CONNECTED);
                intent.putExtra("message", "Message: " + response);
                publishProgress(intent);

                client.close();
            }
            server.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Intent... value) {
        if (value.length == 0)
            return;
        Intent data = value[0];
        context.sendBroadcast(data);
    }

}

The block where I read the message from the socket is commented out. If I dont comment it out, the client socket cannot establish a connection to the server.
What can be the problem?

A: is there any error printed to the console ?
I'm also a newbie but maybe the following thing could work :
DataIntputStream input = new DataInputStream(client.getInputStream()) ;
byte[] b  =  new byte[1024]
input.read(b) ;
String inputString  = new String(b) ;


text:
Q: document.cookie.match inconsistent, sometimes extracting wrong cookie value I have the following script (used in Google Tag Manager)
function() {
  try {
    var cml = document.cookie.match("comagic_visitor.+=.+%7C%7C.+(\\d{6})\;")[1];
    if (cml !== undefined) {
    return cml;
    }
  } catch(e) {}
  return 'false';
}

It has to get the cookie value. Name of the cookie may change, but the first part of it always remain unchanged "_comagic_visitor".
For some reason when I use the code to get cookie value in console I get correct value:
PHPSESSID=3reongfce35dl150rbdkkllto0; region=2; region2=2; _gat_UA-XXXXXX-2=1; _ym_visorc_263098=w; _ga=GA1.3.26804606X.X431002649; _comagic_visitorTH17k=cASNWQ3N9mRZT8tSmUtTGs5IG9LaD7BPHtCCiEpq_fpSnSKGMcCsEG0kPVur16gH%7C%7C124972212; _comagic_sessionTH17k=203937260

VALUE: 972212
But using it with Tag Manager I get 937260 (which as you can see is from "_comagic_session" (last 6 digits).
Unfortunately I'm not good at debugging and my js skill is very bad to figure out how to fix this. Any ideas on what I have to fix?

A:
Any ideas on what I have to fix?

You need to fix the regular expression used for matching.  The argument in parenthesis in document.cookie.match() is a regular expression.
From MDN, document.cookie is a string of all the cookies, separated by ;.  Since document.cookie is simply a String document.cookie.match() is simply calling String.match().  String.match(regexp) finds an Array of matches using the regular expression parameter regexp.
The regexp you are using is:
comagic_visitor.+=.+%7C%7C.+(\\d{6})\;

This regexp means a match must satisfy all of the following conditions:

*

*comagic_visitor begin with comagic_visitor

*.+ followed by one or more other characters (any chars except newline and a couple others).  This can be dangerous

*= followed by =

*.+ followed by one or more other characters Again, can be dangerous

*%7C is a little dangerous depending on where you use it, and might be a literal %7C or could be translated into | which means "or"

*.+ one or more other characters

*(\\d{6}) the parenthesis extract this as the result of the match, and \d{6} is exactly 6 digits.  It seems to be escaped by an extra \ which would be unnecessary if you used /regexp/ instead of "regexp"

*\; is an escaped ;, which requires the final ;
Primary Issue: This regexp is much too loose and matches much more than desirable.  .+ is greedy, in practice it matches as much as it can, and allows the regexp to match the beginning of the desired cookie, all the other cookies in the string, and the digits in some other cookie.  Since the individual cookies in document.cookie are probably not guaranteed to be in any particular order, a greedy match can behave inconsistently. When the desired cookie is at the end of the string, you will get the correct result.  At other times, you won't, when the .+ matches too much and there are 6 digits at some other cookie at the end that can be matched.
Alternative #1:  Write a short function to split your cookie string on ; which will split into an array of strings and then feed each string into match separately and return the first match.  This prevents the regexp from making a bad match in the full cookie string.
Alternative #2:  Fix the regexp to match only what you want. You can use http://refiddle.com/ or a console window to test regular expressions.  Possibly you can change the .+ to [^;]+ which changes any char except newline to any char except ; and that might fix it, because to match across multiple cookies in the full cookie string it has to be allowed to match a ; and if we deny that those false matches should be impossible.
Like this:
var cml = document.cookie.match(/comagic_visitor[^;]+(\d{6})\;/)[1];

This works for me in nodejs.
d = "PHPSESSID=3reongfce35dl150rbdkkllto0; region=2; region2=2; _gat_UA-XXXXXX-2=1; _ym_visorc_263098=w; _ga=GA1.3.26804606X.X431002649; _comagic_visitorTH17k=cASNWQ3N9mRZT8tSmUtTGs5IG9LaD7BPHtCCiEpq_fpSnSKGMcCsEG0kPVur16gH%7C%7C124972212; _comagic_sessionTH17k=203937260";
r = /comagic_visitor[^;]+(\d{6})\;/
d.match(r)[1]
---> '972212'


text:
Q: How to display quiz questions with logic in prompt? I have an array of questions that I need to display in the prompt in order. But the quiz has a logic, questions should be substituted depending on the user's answers. Each question has an ID, and each answer has a question ID that should be next. How can I do that?
Right now my code prints them out one by one. How can I make logic in providing questions?

const questions = [{
    id: "1",
    question: "q1",
    answer_1: {
      text: "a1",
      next_question: "2",
    },
    answer_2: {
      text: "a2",
      next_question: "3",
    },
  },
  {
    id: "2",
    question: "q2",
    answer_1: {
      text: "a1",
      next_question: "",
    },
    answer_2: {
      text: "a2",
      next_question: "",
    },
  },
  {
    id: "3",
    question: "q3",
    answer_1: {
      text: "a1",
      next_question: "",
    },
    answer_2: {
      text: "a2",
      next_question: "4",
    },
  },
  {
    id: "4",
    question: "q4",
    answer_1: {
      text: "a1",
      next_question: "",
    },
    answer_2: {
      text: "a2",
      next_question: "",
    },
  },
];

function quiz(questionList) {
  questionList.forEach((question) => {
    prompt(
      `${question.question}`,
      `${question.answer_1.text} / ${question.answer_2.text}`
    );
  });
}

quiz(questions);

A: You can change the function to ask the question based on the question object passed as a parameter, then check the answer to the question and call itself with the next question.

const questions=[{id:"1",question:"q1",answer_1:{text:"a1",next_question:"2"},answer_2:{text:"a2",next_question:"3"}},{id:"2",question:"q2",answer_1:{text:"a1",next_question:""},answer_2:{text:"a2",next_question:""}},{id:"3",question:"q3",answer_1:{text:"a1",next_question:""},answer_2:{text:"a2",next_question:"4"}},{id:"4",question:"q4",answer_1:{text:"a1",next_question:""},answer_2:{text:"a2",next_question:""}}];

function quizQuestion({ question, answer_1, answer_2 }) {
    const answer = prompt(
      `${question}`,
      `${answer_1.text} / ${answer_2.text}`
    );

    let nextQuestion;
    if(answer == answer_1.text){
      nextQuestion = answer_1.next_question;
    } else if (answer == answer_2.text){
      nextQuestion = answer_2.next_question;
    } else {
      alert('Invalid answer')
    }

    if(nextQuestion){
      quizQuestion(questions.find(q => q.id == nextQuestion))
    }
}

quizQuestion(questions[0]);


text:
Q: is it possible put image in input type="check box"? i want to put an image on the background of check box & radio box in my html code but it's not work but it's work on other form property.

A: I write my own code to fix this issue. This will work like this. I didn't have this code now but I write same way here on SO.

<input type="checkbox" name="value"/>

In css we will hide this checkbox by make it's Z-index less then the image that I put inside this wrapper code. Eventwise when someone click on image it's look like checkbox and in real checkbox will be clicked. instead of display:none using opacity:0 will be better. This will break in IE6 but we didn't care about that because I am not supporting IE6 anymore.
In Javascript You can write event if you want a different (but similar to mine) implementation. You can replace native Html Checkbox,Radio and select (select2 is better if you stick with Twitter bootstrap) with your own themes based controls.

A: I found the way how give image to checkbox & radio button with pure css.
HTML
<input type='checkbox' name='thing' value='valuable' id="thing"/>

CSS
input[type=checkbox] {
    display:none;
}

input[type=checkbox] + label {
    background: #999;
    height: 16px;
    width: 16px;
    display:inline-block;
    padding: 0 0 0 0px;
}

input[type=checkbox]:checked + label {
    background: #0080FF;
    height: 16px;
    width: 16px;
    display:inline-block;
    padding: 0 0 0 0px;
}

Check this for more http://css-tricks.com/the-checkbox-hack/ ,
https://gist.github.com/592332

A:
I made an example of "Use Images Like Checkboxes and Radios Pure Css"
Link to Stackblitz

* {
  font-family: Lato;
  margin: 0;
  padding: 0;
  --transition: 0.15s;
  --border-radius: 0.5rem;
  --background: #ffc107;
  --box-shadow: #ffc107;
}

.cont-bg {
  min-height: 100vh;
  background-image: radial-gradient(
    circle farthest-corner at 7.2% 13.6%,
    rgba(37, 249, 245, 1) 0%,
    rgba(8, 70, 218, 1) 90%
  );
  padding: 1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.cont-title {
  color: white;
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 1rem;
}

.cont-main {
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  justify-content: center;
}

.cont-checkbox {
  width: 150px;
  height: 100px;
  border-radius: var(--border-radius);
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  background: white;
  transition: transform var(--transition);
}

.cont-checkbox:first-of-type {
  margin-bottom: 0.75rem;
  margin-right: 0.75rem;
}

.cont-checkbox:active {
  transform: scale(0.9);
}

input {
  display: none;
}

input:checked + label {
  opacity: 1;
  box-shadow: 0 0 0 3px var(--background);
}

input:checked + label img {
  -webkit-filter: none; /* Safari 6.0 - 9.0 */
  filter: none;
}

input:checked + label .cover-checkbox {
  opacity: 1;
  transform: scale(1);
}

input:checked + label .cover-checkbox svg {
  stroke-dashoffset: 0;
}

label {
  display: inline-block;
  cursor: pointer;
  border-radius: var(--border-radius);
  overflow: hidden;
  width: 100%;
  height: 100%;
  position: relative;
  opacity: 0.6;
}

label img {
  width: 100%;
  height: 70%;
  object-fit: cover;
  clip-path: polygon(0% 0%, 100% 0, 100% 81%, 50% 100%, 0 81%);
  -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */
  filter: grayscale(100%);
}

label .cover-checkbox {
  position: absolute;
  right: 5px;
  top: 3px;
  z-index: 1;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: var(--box-shadow);
  border: 2px solid #fff;
  transition: transform var(--transition),
    opacity calc(var(--transition) * 1.2) linear;
  opacity: 0;
  transform: scale(0);
}

label .cover-checkbox svg {
  width: 13px;
  height: 11px;
  display: inline-block;
  vertical-align: top;
  fill: none;
  margin: 5px 0 0 3px;
  stroke: #fff;
  stroke-width: 2;
  stroke-linecap: round;
  stroke-linejoin: round;
  stroke-dasharray: 16px;
  transition: stroke-dashoffset 0.4s ease var(--transition);
  stroke-dashoffset: 16px;
}

label .info {
  text-align: center;
  margin-top: 0.2rem;
  font-weight: 600;
  font-size: 0.8rem;
}

Checkbox

      <input type="checkbox" id="myCheckbox-1" />

          <svg viewBox="0 0 12 10">
            <polyline points="1.5 6 4.5 9 10.5 1"></polyline>
          </svg>

Mazda MX-5 Miata

      <input type="checkbox" id="myCheckbox-2" />

          <svg viewBox="0 0 12 10">
            <polyline points="1.5 6 4.5 9 10.5 1"></polyline>
          </svg>

Toyota Supra

Radio

      <input type="radio" name="myRadio" id="myRadio-1" />

          <svg viewBox="0 0 12 10">
            <polyline points="1.5 6 4.5 9 10.5 1"></polyline>
          </svg>

Mazda MX-5 Miata

      <input type="radio" name="myRadio" id="myRadio-2" />

          <svg viewBox="0 0 12 10">
            <polyline points="1.5 6 4.5 9 10.5 1"></polyline>
          </svg>

Toyota Supra

A: Place the checkbox in a div, and place a background image in said div. Here's an example:

<input id="check_box" type="checkbox" />


text:
Q: How to change the state of a sibling component in ReactJS for a Master/Slave checkbox system? I'm curious how to implement a Master/Slave checkbox system. The approach I am currently taking is to have an owner/ownee (parent/child) relationship between the Master/Slave checkboxes. However, I'm curious if there's a way to accomplish this in React if the checkboxes were siblings instead. I see here in the docs that it says to use your own global event system. Can someone please explain/show me an example of what they mean by this? Thanks!

A: In my Backbone+React application I use backbone events when I do not have any other options to communicate states between the components. I am pretty sure you can find other minimal event libraries or build your own to communicate events if you need to.
Below is an example code from the jsFiddle http://jsfiddle.net/kb3gN/2239/ ,I have supplied for your scenario.
From the 'MasterCheckbox' component's onChange event I trigger a global application wide 'checkbox:clicked' event on the event object that's accessible to other components/views.
//Global event object
window.App = _.extend({}, Backbone.Events);

//MasterCheckbox component's change handler
handleChange: function () {
  this.setState({checked: this.refs.master.getDOMNode().checked});
  App.trigger('checkbox:clicked', this.refs.master.getDOMNode().checked);
}

Then on the 'SlaveCheckbox' component I subscribe to that event and change the state of the
'SlaveCheckbox' component
componentDidMount: function(){
     App.on('checkbox:clicked', function(state){this.setState({checked: state}) }.bind(this));
}

A: You could wrap the two checkboxes into their own component to make a MasterSlaveComponent. Wasn't sure of the exact functionality you would want, but here is an example where turning on Master also turns on Slave.
var MasterSlaveCheckbox = React.createClass({
    getInitialState: function(){
      return {
        master: false,
        slave: false
      }
    },

    handleMasterChange: function() {
      var newMasterState = !this.state.master;

      if(newMasterState) {
        this.setState({master: true, slave: true});
      } else {
        this.setState({master: false});
      }
    },

    handleSlaveChange: function() {
      this.setState({slave: !this.state.slave});
    },

    render: function() {
        return

              <input type="checkbox" checked={this.state.master} onChange={this.handleMasterChange} />
              Master

              <input type="checkbox" checked={this.state.slave} onChange={this.handleSlaveChange}  />
              Slave

;
    }
});

https://jsfiddle.net/crob611/z6ozz62a/1/


text:
Q: Detect when a method is being run in javascript (event) Im looking to inject a variable into a page before a method is run. The situation is as follow
CUSTOM JS CAN GO HERE

my.var = 'cake';
my.function();

I dont have access to be able to modify the page directly, however there is a content area at the top of the page I can add some JS if i need to. Basically i need to overwrite the my.var variable with something else before my.function() is run. Is there a way to do this? (the site is running jQuery 1.4.2.
Thanks
Dan

A:
Basically i need to overwrite the my.var variable with something else before my.function() is run. Is there a way to do this?

var oldfunction = my.function;
my.function = function () {
    my.var = "whatever you want";
    oldfunction.apply(this, arguments);
}

This is, of course, if my or my.function isn't overwritten by the code you can't modify directly before the call to my.function (as my.var is).
For example, in the following scenario:
///your code goes here

///code you cannot modify below
var my = {};
my.function = something;
my.var = 'cake';
my.function();

what you want is impossible (unless you're able to redefine something or something in it in the same way).
Basically, in this case the only thing you could do is to write (let's assume something is function () { alert(my.var) })
var oldalert = window.alert;
window.alert = function (message) {
    oldalert(message === 'cake' ? 'whatever you want' : message);
}

Well, you've got an idea.
Injecting some code in between my.var = 'cake'; and my.function(); is, from the other side, imposible. Roughly speaking, you can choose between two options, whether your code will be executed before my.var = 'cake'; or after my.function();. Executing your code aftre my.var = 'cake'; but before my.function(); is impossible (if we're speaking of a production environment; of course you could do anything by hands using the debugger, if you need to modify my.var for a debugging purpose).