text:
Q: Using MySQL With an HTML Page Using Javascript This might be a stupid question but i'm looking for a method to post and get from a MySQL database using JavaScript on a HTML web page. As I'm looking to make a small game and wanted to save information in real time. I can do it using PHP but of course this isn't going to be real time more on page load.
Thanks in advance.
Tim.
PHP Example
<?
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['btnP1Login'])) {
            $myFile=fopen("P1Status.txt","w") or exit("Can't open file!");
            fwrite($myFile, 'Online');
            fclose($myFile);
            header('Location: lobby.php');
        }
        if (isset($_POST['btnP2Login'])) {
            $myFile=fopen("P2Status.txt","w") or exit("Can't open file!");
            fwrite($myFile, 'Online');
            fclose($myFile);
            header('Location: lobby.php');
        }
    }
?>

Player 1 - Offline

            <form method="post" action="index.php">
                <input type="submit" name="btnP1Login">
            </form>

Player 2 - Offline

            <form method="post" action="index.php">
                <input type="submit" name="btnP2Login">
            </form>

A: You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:
var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close;

A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.
And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)


text:
Q: No event handlers are called on the second page when changing page in jQuery Mobile I use jQuery Mobile in my application. I have and index.html page, and I try to add another page to my application. So on the index.html page I have a link to the Camera.html page:
Take a photo   // A. version

When I click on the link, the camera's page swipes in (it redirects to the Camera.html page with swipe animation), but none of the event handlers are called on the Camera page (load, DOMContentLoaded, etc.). I think that jQuery Mobile uses ajax for redirecting to other pages and that's why the event handlers are not called.
If I change it to the following, the events are called, but the page redirection won't be animated:
Take a photo   // B. version

I'd like to keep the animation and I also prefer that on the Camera page some event to be called (I'd like to use it for initialization). So I have the following questions.

*

*Do you know at least one event, that will be called, if I use the A. version for redirecting to other page?

*If I use version A., could I somehow call some event on the other page manually?

*Should I redirect to another page in some other way?

Could you give me some code samples, please?

A: Please Clarify when you mean it swipes in, are you animating a div tag into the screen?
If the page is redirecting to Camera.html, then if you include your scripts in a script tag in Camera.html, they will only get executed when Camera.html loads
Additionally Try:

*

*If you are animating a div tag use the $('div').load() event

*Try adding
$('body id="camerabody"').load(function(){ alert("Body Loaded"); })

where camerabody is the id of the body tag in your Camera.html file

*

*If you are causing the animation using jquery.animate, you can specify a callback when the animation completes
$('div').animate(
         {height:'+=50'},
         1000,
         function(){ alert("animation complete");
});

A:
I'd like to keep the animation and I also prefer that on the Camera page some event to be >called (I'd like to use it for initialization).So I have the following questions.

Try using this to initialize your page with pageinit, or pageshow
jQuery('[data-role="page"]').live('pageinit', function(){
  /* page initialization */
})

pageinit is fired once - when page is created in DOM, and pageshow is fired every time the page is shown

redpajama_set_name: RedPajamaStackExchange


text:
Q: EclipseLink MOXy: Binding working and not working with same XPath Input:
<?xml version="1.0" encoding="UTF-8"?>
<foo:root xmlns:foo="http://www.domain.org/foo"
      xmlns="http://www.domain.org/foo"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <a xsi:type="foo:someType">
   <b  text="some text" />
  </a>
</foo:root>

Bindings:
<?xml version="1.0"?>
<xml-bindings
   xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
   package-name="test">

<xml-schema element-form-default="QUALIFIED" namespace="http://www.domain.org/foo">
    <xml-ns prefix="foo" namespace-uri="http://www.domain.org/foo" />
</xml-schema>

 <java-types>
    <java-type name="Root">
        <xml-root-element name="root"/>
        <java-attributes>
            <xml-element java-attribute="contentRoot" xml-path="." type="test.ContentRoot" />
        </java-attributes>
    </java-type>

    <java-type name="ContentRoot">
        <java-attributes>
            <xml-element java-attribute="text" xml-path="a/b/@text" />
            <xml-element java-attribute="contents" xml-path="a/b" type="test.Content" container-type="java.util.List" />
        </java-attributes>
    </java-type>

    <java-type name="Content">
        <java-attributes>
            <xml-element java-attribute="text" xml-path="@text" />
        </java-attributes>
    </java-type>
</java-types>

</xml-bindings>

Classes in package test:
public class Root {
 private List<ContentRoot> contentRoots = new LinkedList<ContentRoot>();
 public List<ContentRoot> getContentRoots() {
    return contentRoots;
 }
 public void setContentRoots(List<ContentRoot> contentRoots) {
    this.contentRoots = contentRoots;
 }
 public void setContentRoot(ContentRoot contentRoot) {
    this.contentRoots.add(contentRoot);
 }
}

public class ContentRoot {
 private List<Content> contents;
 private String text;
 public List<Content> getContents() {
    return contents;
 }
 public void setContents(List<Content> contents) {
    this.contents = contents;
 }
 public String getText() {
    return text;
 }
 public void setText(String text) {
    this.text = text;
 }
}

public class Content  {
 private String text;
 public String getText() {
    return text;
 }
 public void setText(String text) {
    this.text = text;
 }
}

Running Code:
Map<String, Object> jaxbContextProperties = new HashMap<String, Object>(1);
jaxbContextProperties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "bindings.xml");
JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {Root.class}, jaxbContextProperties);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Root root = (Root)unmarshaller.unmarshal(new File("input.xml"));
System.out.println(root.getContentRoots().get(0).getText());
System.out.println(root.getContentRoots().get(0).getContents().get(0).getText());

The result is, that text is set in ContentRoot but not in Content (I get a NullPointerException from the last System.out.println()). Can somebody tell me why?

A: There are a few items that are tripping you up:
ISSUE #1 - ContentRoot Contains Invalid Mappings
EclipseLink JAXB (MOXy) does not allow the following combination of mappings.  With the second xml-element you are telling MOXy to map the contents properties to the repeating element b that occur within the element a.  With the first xml-element you are trying to map the text attribute of one of the potentially many b elements to the String property text.
<java-type name="ContentRoot">
    <java-attributes>
        <xml-element java-attribute="text" xml-path="a/b/@text" />
        <xml-element java-attribute="contents" xml-path="a/b" type="test.Content" container-type="java.util.List" />
    </java-attributes>
</java-type>

The correct place to map the text attribute is on the Content class which you already had.  Instead of using the xml-element mapping with the xml-path pointing at the attribute (which would work), I would recomment using the xml-attribute mapping and specifying a name.
<java-type name="Content">
    <java-attributes>
        <xml-attribute java-attribute="text"/>
    </java-attributes>
</java-type>

ISSUE #2 - xml-path Is Not Properly Namespace Qualified
Since in bindings.xml you have associated the foo prefix with the http://www.domain.org/foo namespace URI.
<xml-schema element-form-default="QUALIFIED" namespace="http://www.domain.org/foo">
    <xml-ns prefix="foo" namespace-uri="http://www.domain.org/foo" />
</xml-schema>

When you specify the xml-path you need to include the prefix in order to get the correct namespace qualification.
<java-type name="ContentRoot">
    <java-attributes>
        <xml-element java-attribute="contents" xml-path="foo:a/foo:b"/>
    </java-attributes>
</java-type>

For More Information

*

*http://blog.bdoughan.com/2010/09/xpath-based-mapping-geocode-example.html
Alternatively you could have mapped it with an xml-element-wrapper as follows:
<java-type name="ContentRoot">
    <java-attributes>
        <xml-element java-attribute="contents" name="b">
            <xml-element-wrapper name="a"/>
        </xml-element>
    </java-attributes>
</java-type>

ISSUE #3 - xml-path="." Can Not Be Used on a Collection Property
Currently MOXy requires that each item in a collection correspond to its own element.  This means that at this time you can not specify the self XPath . for collection properties.

Full Example
Your demo code didn't seem to fully match your domain model.  Here is a complete example that pulls everything together:
Root
package test;

public class Root {

    private ContentRoot contentRoot;

    public ContentRoot getContentRoot() {
        return contentRoot;
    }

    public void setContentRoot(ContentRoot contentRoot) {
        this.contentRoot = contentRoot;
    }

}

ContentRoot
package test;

import java.util.List;

public class ContentRoot {

    private List<Content> contents;

    public List<Content> getContents() {
        return contents;
    }

    public void setContents(List<Content> contents) {
        this.contents = contents;
    }

}

Content
package test;

public class Content {

    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}

bindings.xml
<?xml version="1.0"?>
<xml-bindings xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="test"
    xml-accessor-type="FIELD">

    <xml-schema element-form-default="QUALIFIED" namespace="http://www.domain.org/foo">
        <xml-ns prefix="foo" namespace-uri="http://www.domain.org/foo" />
    </xml-schema>

    <java-types>
        <java-type name="Root">
            <xml-root-element/>
            <java-attributes>
                <xml-element java-attribute="contentRoot" xml-path="."/>
            </java-attributes>
        </java-type>

        <java-type name="ContentRoot">
            <java-attributes>
                <xml-element java-attribute="contents" xml-path="foo:a/foo:b"/>
            </java-attributes>
        </java-type>

        <java-type name="Content">
            <java-attributes>
                <xml-attribute java-attribute="text"/>
            </java-attributes>
        </java-type>
    </java-types>

</xml-bindings>

Demo
package test;

import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> jaxbContextProperties = new HashMap<String, Object>(1);
        jaxbContextProperties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "test/bindings.xml");
        JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {Root.class}, jaxbContextProperties);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        Root root = (Root)unmarshaller.unmarshal(new File("src/test/input.xml"));
        System.out.println(root.getContentRoot().getContents().get(0).getText());

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}


text:
Q: Remove a file in previous commit/changeset A few revisions ago I committed a piece of work in which I accidentally included a 300mb .flv file (don't ask...).
Is there a way I can edit that changeset to not include the aforementioned file?
UPDATE:
I think I can use the MQ extension and follow these instructions (chapter 6). However, when I run: hg qimport -r 11:tip, I receive the error: abort: out of memory.

A: Use hg convert with --filemap switch. Do note that IDs will change on modified changesets and their children. If you've already pushed it to a remote location, you need to use strip/convert on that repo as well, before pushing again.


text:
Q: MSVC: Bug with templated conversion operators and multiple inheritance I have the following code which does not compile with MSVC. It compiles fine with gcc, clang and icc. I guess it is a bug, right?
Do you have/know some workaround?
#include <type_traits>

struct A
{
    template <
        typename C
        ,typename = std::enable_if_t<std::is_same_v<C, int>>
    >
    operator C() const{
        return 12;
    }
};

struct B
{
    template <
        typename C
        , typename = std::enable_if_t<std::is_same_v<C, char>>
        , typename F = int
    >
    operator C() const
    {
        return 'A';
    }
};

struct AB : A, B
{
};

int main(){
    AB ab;
    int i = ab;
    char c = ab;
}

The error text is:
example.cpp

<source>(34): error C2440: 'initializing': cannot convert from 'AB' to 'char'

<source>(34): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Compiler returned: 2

I already posted a bug report to Microsoft.
See it here on godbolt

A: This seems really to be a bug in MSVC. The last base seems not to be considered in operator template deduction process. For ex.
struct AB : A, B // -> only A's templated operator considered
struct AB  : B, A // -> only B's templated operator considered

In your case you could just remove the templated operators and use the types directly (Live) ( using templates in this case doesn't make much sense anyway):
#include <type_traits>

struct A
{
    operator int() const{ return 12;}
};

struct B
{
    operator char() const { return 'A'; }
};

struct AB : A, B
{
};

int main(){
    AB ab;
    int i = ab;
    char c = ab;
}

or you could move to class templates instead, something like (Live):
#include <type_traits>

template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
struct A
{

    operator T() const{
        return 12;
    }
};

template <typename T, typename = std::enable_if_t<std::is_same_v<T,char>>>
struct B
{
    operator T() const
    {
        return 'A';
    }
};

struct AB : A<int>, B<char>
{
};

int main(){
    AB ab;
    int i = ab;
    char c = ab;
}

or you could  overload templated operatros within single class (Live):
struct A
{
    template <
        typename C
        , typename = std::enable_if_t<std::is_same_v<C, int>>
    >
        operator C() const {
        return 12;
    }

    template <
        typename C
        , typename = std::enable_if_t<std::is_same_v<C, char>>
        , typename F = int
    >
        operator C() const
    {
        return 'A';
    }
};

struct AB : A
{
};

int main() {
    AB ab;
    int i = ab;
    char c = ab;
}

A: I found a workaround.
Here you can see my solution. I changed my inheritance hierarchy and I introduced a forwarding conversion operator:
#include <type_traits>
#include <utility>

struct A
{
    template <
        typename C
        ,typename = std::enable_if_t<std::is_same_v<C, int>>
    >
    operator C() const{
        return 12;
    }
};

struct B : A
{
    template <
        typename C
        , typename = std::enable_if_t<
            std::is_same_v<C, char>
        >
    >
    operator C() const
    {
        return 'A';
    }

    template <
        typename C
        , typename Base = A
        , typename = std::enable_if_t<
            std::is_convertible_v<Base, C>
            &&
            !std::is_same_v<C, char>
        >
    >
    operator C() const
    {
        return static_cast<C>(*static_cast<const Base*>(this));
    }
};

struct AB : B
{
};

int main(){
    AB ab;
    int i = ab;
    char c = ab;
}


text:
Q: Set margin top value in odoo qweb-pdf reporting according to field value Set margin top value in odoo qweb-pdf reporting according to field value
Eg:  Hello
ab is field se in the model..it can have any value..if it is 4 margin-top is to 4cm ,if it is 7 margin-top to be 7cm....

A: You can use t-attf-$name to define the style attribute.

There are two equivalent syntaxes for format strings: "plain_text {{code}}" (aka jinja-style) and "plain_text #{code}" (aka ruby-style).

Example:
Inherit sale order template and set the margin on h2 tag
<template id="report_saleorder_document_inherit" inherit_id="sale.report_saleorder_document">
    <xpath expr="//h2" position="attributes">
        <attribute name="t-attf-style">margin:{{doc.margin}}cm</attribute>
    </xpath>
</template>


text:
Q: how to make an active element in dropdowns with html, css, bootstrap I have provided a snippet, however the output is different from here and so please beware. I am trying to achieve where:

*

*When the user clicks 'Home 1' under 'Home', it will be an active element

*In addition, when the user clicks 'Home 2', 'Home 1' will be inactive and 'Home 2' will be an active element

Same goes for the 'Pages' dropdown list. May I know what are the solutions?

/*
    DEMO STYLE
*/

@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";

body {
    font-family: 'Poppins', sans-serif;
    background: #fafafa;
}

p {
    font-family: 'Poppins', sans-serif;
    font-size: 1.1em;
    font-weight: 300;
    line-height: 1.7em;
    color: #999;
}

a,
a:hover,
a:focus {
    color: inherit;
    text-decoration: none;
    transition: all 0.3s;
}

.navbar {
    padding: 15px 10px;
    background: #fff;
    border: none;
    border-radius: 0;
    margin-bottom: 40px;
    box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
}

.navbar-btn {
    box-shadow: none;
    outline: none !important;
    border: none;
}

.line {
    width: 100%;
    height: 1px;
    border-bottom: 1px dashed #ddd;
    margin: 40px 0;
}

i,
span {
    display: inline-block;
}

/* ---------------------------------------------------
    SIDEBAR STYLE
----------------------------------------------------- */

.wrapper {
    display: flex;
    align-items: stretch;
}

#sidebar {
    min-width: 250px;
    max-width: 250px;
    background: #7386D5;
    color: #fff;
    transition: all 0.3s;
}

    #sidebar.active {
        min-width: 80px;
        max-width: 80px;
        text-align: center;
    }

        #sidebar.active .sidebar-header h3,
        #sidebar.active .CTAs {
            display: none;
        }

        #sidebar.active .sidebar-header strong {
            display: block;
        }

    #sidebar ul li a {
        text-align: left;
    }

    #sidebar.active ul li a {
        padding: 20px 10px;
        text-align: center;
        font-size: 0.85em;
    }

        #sidebar.active ul li a i {
            margin-right: 0;
            display: block;
            font-size: 1.8em;
            margin-bottom: 5px;
        }

    #sidebar.active ul ul a {
        padding: 10px !important;
    }

    #sidebar.active .dropdown-toggle::after {
        top: auto;
        bottom: 10px;
        right: 50%;
        -webkit-transform: translateX(50%);
        -ms-transform: translateX(50%);
        transform: translateX(50%);
    }

    #sidebar .sidebar-header {
        padding: 20px;
        background: #6d7fcc;
    }

        #sidebar .sidebar-header strong {
            display: none;
            font-size: 1.8em;
        }

    #sidebar ul.components {
        padding: 20px 0;
        border-bottom: 1px solid #47748b;
    }

    #sidebar ul li a {
        padding: 10px;
        font-size: 1.1em;
        display: block;
    }

        #sidebar ul li a:hover {
            color: #7386D5;
            background: #fff;
        }

        #sidebar ul li a i {
            margin-right: 10px;
        }

    #sidebar ul li.active > a,
    a[aria-expanded="true"] {
        color: #6d7fcc;
        background: #fff;
    }

a[data-toggle="collapse"] {
    position: relative;
}

.dropdown-toggle::after {
    display: block;
    position: absolute;
    top: 50%;
    right: 20px;
    transform: translateY(-50%);
}

ul ul a {
    font-size: 0.9em !important;
    padding-left: 30px !important;
    background: #6d7fcc;
}

ul.CTAs {
    padding: 20px;
}

    ul.CTAs a {
        text-align: center;
        font-size: 0.9em !important;
        display: block;
        border-radius: 5px;
        margin-bottom: 5px;
    }

a.download {
    background: #fff;
    color: #7386D5;
}

a.article,
a.article:hover {
    background: #6d7fcc !important;
    color: #fff !important;
}

/* ---------------------------------------------------
    CONTENT STYLE
----------------------------------------------------- */

#content {
    width: 100%;
    padding: 20px;
    min-height: 100vh;
    transition: all 0.3s;
}

/* ---------------------------------------------------
    MEDIAQUERIES
----------------------------------------------------- */

@media (max-width: 768px) {
    #sidebar {
        min-width: 80px;
        max-width: 80px;
        text-align: center;
        margin-left: -80px !important;
    }

    .dropdown-toggle::after {
        top: auto;
        bottom: 10px;
        right: 50%;
        -webkit-transform: translateX(50%);
        -ms-transform: translateX(50%);
        transform: translateX(50%);
    }

    #sidebar.active {
        margin-left: 0 !important;
    }

    #sidebar .sidebar-header h3,
    #sidebar .CTAs {
        display: none;
    }

    #sidebar .sidebar-header strong {
        display: block;
    }

    #sidebar ul li a {
        padding: 20px 10px;
    }

        #sidebar ul li a span {
            font-size: 0.85em;
        }

        #sidebar ul li a i {
            margin-right: 0;
            display: block;
        }

    #sidebar ul ul a {
        padding: 10px !important;
    }

    #sidebar ul li a i {
        font-size: 1.3em;
    }

    #sidebar {
        margin-left: 0;
    }

    #sidebarCollapse span {
        display: none;
    }
}

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />

Bootstrap Sidebar

                BS

                        Home

                            Home 1

                            Home 2

                            Home 3

                        Pages

                            Page 1

                            Page 2

                            Page 3

A: try this use  jquery to control style
https://codepen.io/anon/pen/ZVbVYw
$(document).ready(function () {
    $('#homeSubmenu li, #pageSubmenu li').on('click', function () {
        $('#homeSubmenu li, #pageSubmenu li').removeClass('active');
        $(this).addClass('active');
    });
});


text:
Q: facebook reference from nuget packages in windows phone 8 I'm trying to add facebook reference from nuget packages in my windows phone 8 application and I get this error:
Could not install package 'Facebook 6.1.4'. You are trying to install this package into a project that targets 'WindowsPhone,Version=v8.0', but the package does not contain any assembly references that are compatible with that framework. For more information, contact the package author.
How can I solve this?
Thanks,
Hanna

A: Update your Nuget from version 2.0 to 2.1 or 2.2. As Windows Phone 8 supports 2.1 and Higher version. And then insatll using Install-Package Facebook in Library package manager
http://docs.nuget.org/docs/release-notes/nuget-2.1#Targeting_Windows_8_and_Windows_Phone_8_Projects

A: You can only add packages to a Windows Phone 8 project which targets a specialized framework which comes with Windows Phone SDK. Facebook package you're trying to add targets good old .net framework.
Refer to the following link which gives more info on Windows Phone packages on nuget:
Targeting Windows 8 and Windows Phone 8 Projects


text:
Q: Will Ashley ever forgive me?
Possible Duplicate:
Are my romance options in ME3 limited if I cheated on my ME1 romance in ME2?

So, in Mass Effect 1, I had a romantic relationship with Ashley (what can I say, blue just doesn't do it for me).  In Mass Effect 2, I left her in the dust and shacked up with Tali.
Is there any way in Mass Effect 3 for me to repair my relationship with Ashley?  Should I just pursue Tali again instead?  I haven't gotten to the point where she's a squad member yet, but I do understand I'll pick her up eventually.  Will either of these cause problems between the two of them?
(Alternate title: I've got 99 problems, and a Quarian's one)


text:
Q: How to get mouse and keyboard moves? - python I am looking for a way to achieve these goals. Please read them and if you know of a way that can get me (directly or indirectly) to even some of these goals. Do not hesitate please.

*

*get pressed key.

*

*It is better to be in the shape of an aunt
for example:

... # defund or import

@event # for all of keys
def on_key_press(key):
   ...

@event # for ctrl key (for example)
def on_ctrl_press(key):
   ...

*Press a key
like this:

press('ctrl')

*

*and do the same for pc mouse

A: The module pynput (https://pynput.readthedocs.io/en/latest/keyboard.html) should solve your problem. It allows you to press buttons on keyboard and mouse as well as get when a button is pressed. You may need to perform pip install pynput


text:
Q: Enforcing method order in a Python module What is the most Pythonic way to deal with a module in which methods must be called in a certain order?
As an example, I have an XML configuration that must be read before doing anything else because the configuration affects behavior.
The parse_config() must be called first with the configuration file provided.  Calling other supporting methods, like query_data() won't work until parse_config() has been called.
I first implemented this as a singleton to ensure that a filename for the configuration is passed at the time of initialization, but I was noticing that modules are actually singletons. It's no longer a class, but just a regular module.
What's the best way to enforce the parse_config being called first in a module?
It is worth noting is that the function is actually parse_config(configfile).

A: If the object isn't valid before it's called, then call that method in __init__ (or use a factory function). You don't need any silly singletons, that's for sure.

A: The model I have been using is that subsequent functions are only available as methods on the return value of previous functions, like this:
class Second(object):
   def two(self):
     print "two"
     return Third()

class Third(object):
   def three(self):
     print "three"

def one():
   print "one"
   return Second()

one().two().three()

Properly designed, this style (which I admit is not terribly Pythonic, yet) makes for fluent libraries to handle complex pipeline operations where later steps in the library require both the results of early calculations and fresh input from the calling function.
An interesting result is error handling.  What I've found is the best way of handling well-understood errors in pipeline steps is having a blank Error class that supposedly can handle every function in the pipeline (except initial one) but those functions (except possibly terminal ones) return only self:
class Error(object):
   def two(self, *args):
      print "two not done because of earlier errors"
      return self
   def three(self, *args):
      print "three not done because of earlier errors"

class Second(object):
   def two(self, arg):
     if arg == 2:
       print "two"
       return Third()
     else:
       print "two cannot be done"
       return Error()

class Third(object):
   def three(self):
     print "three"

def one(arg):
   if arg == 1:
      print "one"
      return Second()
   else:
      print "one cannot be done"
      return Error()

one(1).two(-1).three()

In your example, you'd have the Parser class, which would have almost nothing but a configure function that returned an instance of a ConfiguredParser class, which would do all the thing that only a properly configured parser could do.  This gives you access to such things as multiple configurations and handling failed attempts at configuration.

A: As Cat Plus Plus said in other words, wrap the behaviour/functions up in a class and put all the required setup in the __init__ method.
You might complain that the functions don't seem like they naturally belong together in an object and, hence, this is bad OO design.  If that's the case, think of your class/object as a form of name-spacing.  It's much cleaner and more flexible than trying to enforce function calling order somehow or using singletons.

A: It comes down to how friendly you want your error messages to be if a function is called before it is configured.
Least friendly is to do nothing extra, and let the functions fail noisily with AttributeErrors, IndexErrors, etc.
Most friendly would be having stub functions that raise an informative exception, such as a custom ConfigError:  configuration not initialized.  When the ConfigParser() function is called it can then replace the stub functions with real functions.
Something like this:
File config.py
class ConfigError(Exception):
    "configuration errors"

def query_data():
    raise ConfigError("parse_config() has not been called")

def _query_data():
    do_actual_work()

def parse_config(config_file):
    load_file(config_file)
    if failure:
        raise ConfigError("bad file")
    all_objects = globals()
    for name in ('query_data', ):
        working_func = all_objects['_'+name]
        all_objects[name] = working_func

If you have very many functions you can add decorators to keep track of the function names, but that's an answer for a different question.  ;)
Okay,  I couldn't resist -- here is the decorator version, which makes my solution much easier to actually implement:
class ConfigError(Exception):
    "various configuration errors"

class NeedsConfig(object):
    def __init__(self, module_namespace):
        self._namespace = module_namespace
        self._functions = dict()
    def __call__(self, func):
        self._functions[func.__name__] = func
        return self._stub
    @staticmethod
    def _stub(*args, **kwargs):
        raise ConfigError("parseconfig() needs to be called first")
    def go_live(self):
        for name, func in self._functions.items():
            self._namespace[name] = func

And a sample run:
needs_parseconfig = NeedsConfig(globals())

@needs_parseconfig
def query_data():
    print "got some data!"

@needs_parseconfig
def set_data():
    print "set the data!"

def okay():
    print "Okay!"

def parse_config(somefile):
    needs_parseconfig.go_live()

try:
    query_data()
except ConfigError, e:
    print e

try:
    set_data()
except ConfigError, e:
    print e

try:
    okay()
except:
    print "this shouldn't happen!"
    raise

parse_config('config_file')
query_data()
set_data()
okay()

And the results:
parseconfig() needs to be called first
parseconfig() needs to be called first
Okay!
got some data!
set the data!
Okay!

As you can see, the decorator works by remembering the functions it decorates, and instead of returning a decorated function it returns a simple stub that raises a ConfigError if it is ever called.  When the parse_config() routine is called, it needs to call the go_live() method which will then replace all the error raising stubs with the actual remembered functions.

A: The simple requirement that a module needs to be "configured" before it is used is best handled by a class which does the "configuration" in the __init__ method, as in the currently-accepted answer. Other module functions become methods of the class. There is no benefit in trying to make a singleton ... the caller may well want to have two or more differently-configured gadgets operating simultaneously.
Moving on from that to a more complicated requirement, such as a temporal ordering of the methods:
This can be handled in a quite general fashion by maintaining state in attributes of the object, as is usually done in any OOPable language. Each method that has prerequisites must check that those prequisites are satisfied.
Poking in replacement methods is an obfuscation on a par with the COBOL ALTER verb, and made worse by using decorators -- it just wouldn't/shouldn't get past code review.

A: A module doesn't do anything it isn't told to do so put your function calls at the bottom of the module so that when you import it, things get ran in the order you specify:
test.py
import testmod

testmod.py
def fun1():
    print('fun1')

def fun2():
    print('fun2')

fun1()
fun2()

When you run test.py, you'll see fun1 is ran before fun2:
python test.py
fun1
fun2


text:
Q: allow "&" character in primefaces keyfilter I would need a regex that allows the & character in primefaces keyfilter for a p:autocomplete field
My current keyFilter looks like this:
<p:keyFilter for="xyzComponent" preventPaste="false" regEx="/[A-Za-z-ÁÀȦÂÄǞǍĂĀÃÅǺǼǢĆĊĈČĎḌḐḒÉÈĖÊËĚĔĒẼE̊ẸǴĠĜǦĞG̃ĢĤḤáàȧâäǟǎăāãåǻǽǣćċĉčďḍḑḓéèėêëěĕēẽe̊ẹǵġĝǧğg̃ģĥḥÍÌİÎÏǏĬĪĨỊĴĶǨĹĻĽĿḼM̂M̄'NŃN̂ṄN̈ŇN̄ÑŅṊÓÒȮȰÔÖȪǑŎŌÕȬŐỌǾƠíìiîïǐĭīĩịĵķǩĺļľŀḽm̂m̄'nńn̂ṅn̈ňn̄ñņṋóòôȯȱöȫǒŏōõȭőọǿơP̄ŔŘŖŚŜṠŠȘṢŤȚṬṰÚÙÛÜǓŬŪŨŰŮỤẂẀŴẄÝỲŶŸȲỸŹŻŽẒǮp̄ŕřŗśŝṡšşṣťțṭṱúùûüǔŭūũűůụẃẁŵẅýỳŷÿȳỹźżžẓǯßœŒçÇ0-9! \/ \.\?_-]/i"/>

i tried & and \& inside the "[]", but I get the following error:
Error Parsing xyz.xhtml : Error Traced[line: 82] The entity name must immediately follow the '&' in the entity reference.


text:
Q: Different Rows To Combine This is my table:
    Company   Year  CustomerCount1  CustomerCount2
    1         2010  100             150
    1         2011  120             130
    1         2012  300             140
    2         2010  50              90
    2         2011  45              110
    2         2012  60              120

CustomerCount1 is the number of customers in the begining of the year
CustomerCount2 is the number of customers in the middle of the year
How woud you run a query to get such an output
    Company   Year2010        Year2012
    1         100             140
    2         50              120

where
100 is the CustomerCount1 in 2010 for company1
140 is the CustomerCount2 in 2012 for company1
50 is the CustomerCount1 in 2010 for company2
120 is the CustomerCount2 in 2012 for company2

A: Seems that your data structures could use some normalization. But you can easily use conditional aggregation for something like this.
declare @Something table
(
    Company int
    , Year int
    , CustomerCount1 int
    , CustomerCount2 int
)

insert @Something
values
(1, 2010, 100, 150)
, (1, 2011, 120, 130)
, (1, 2012, 300, 140)
, (2, 2010, 50, 90)
, (2, 2011, 45, 110)
, (2, 2012, 60, 120)

select Company
    , max(case when Year = 2010 then CustomerCount1 end) as Year2010
    , max(case when Year = 2012 then CustomerCount2 end) as Year2012
from @Something
where Year in (2010, 2012)
group by Company


text:
Q: Should I always verify if an object is NULL? I have a object built through a factory containing my parameters read from the url.
From this object, I can get the language parameter

$language =
  $my_parameters->getLanguage();

$language is NULL if it isn't been set.
$language may also be invalid ( $language->isValid() returns false ).
So, to build my page, I need some parameters.
The page is also built trough a factory. Then I know which parameters I need to build it. If it miss parameters, I build them with a valid default value according to the page asked.
At this point, into the page factory, if a have an invalid parameter, I throw an exception.
My page object contains a body object that needs a language parameter. I know that my parameters are valid when I build my body object.
Into my body object, I retrieve the language

$language =
  $my_parameters->getLanguage();

At this point, $language ** MUST ** be valid.
So I verify again
$language = $my_parameters->getLanguage();
if( is_null( $language ) or !$language->isValid() ) {
   throw new Exception( 'Language must be valid.' );
}

If I need 4 parameters, I have 4 ifs that verify if the object is not NULL and not invalid.
I do it because the  method is public  where $language is used in the body object .
And the body object may be built outside the factory. Who knows...
Is it correct to verify in that case ?
What are the best-practices about that ?

A: Here is the case for not checking for null in a recent blog post from the Google Testing blog.
The argument is that it gets in the way of writing clear, easy unit tests, because you can't actually fake the pieces that don't matter, because your exceptions/assertions will be thrown.
The author (Miško Hevery) does qualify the commentary by saying that if it's an external API, it might still be worth checking for an error condition.

A: i know very little about your domain, but in the general case, i like to assert(not null) all over the place, because typically if i end up with a null object somewhere, its a bug.
it's also good practice to prefer reference types which typically can't even be null.

A: I come from a very old school of C programming; so my thing is that variables that are not being used or that have been free()'d should always be NULL.  That's just my opinion though.
Edit: Building on that, you should always check to see if a variable is NULL before using it as well.  If the variable is NULL and shouldn't be then you should log an error.  Crashing should not be a feature.

A: You can make life simpler for yourself by splitting the getLanguage() into two methods:
function getLanguageIfValid() {
  // this method return a Language object, but only if it can be created
  // correctly and the isValid() method returns TRUE. If the Language object
  // can't be created correctly, then it will return null instead.
}

function getLanguageMustBeValid() {
    // this method will always return an instance of Language, or else
    // an exception will be thrown
    if($return = $this->getLanguageIfValid())
        return $return;
    throw new Exception("Couldn't get Language object");
}

Once you've done that, in places where it is reasonable to say that the language item might not be created properly, you use the first method:
// we may or may not be able to get our Language object here
if($language = $my_parameters->getLanguageIfValid())
    do_stuff($language);

If you're certain the language object should be created, then use the 2nd method which will throw the exception for you.
// we know the Language object is created at this point
$language = $my_parameters->getLanguageMustBeValid();
do_stuff($language);

So the answer to your question is No - you don't have to verify an object is not null as long as you can get it from a function that us guaranteed not to return null.

A: Throw your exception from ->getLanguage().
To me, exceptions should be thrown automatically. What you are doing seems like a mixture of error-code checkup and exception throwing.


text:
Q: Inconsistent solder mask on vias When looking at PCBs in consumer products or PCBs I have ordered from manufacturers myself, I notice that, while many of the vias are covered in soldermask, it seems like a few random vias are missing it for no apparent reason.  This is true even if I specify soldermask to cover all of the vias.

Why is this?  Does the soldermask get wicked down inside the vias during manufacturing?  Is there a way to prevent this?
All of the vias on my projects are a minimum of 15 mils.  If I used smaller vias would this not happen?

A: Could be sloppy design, could be the solder mask just didn't stick.
However, it is generally better practice to relieve the solder mask around vias especially if the board is to be flow soldered. Solder filling the via improves the quality of the connection through the board.
If you WANT the mask to cover the holes, you are asking a bit much of a fluid to consistently bridge over air. Add in heating processes during soldering and the chances of a few popping is pretty high.

A: Judging by thus picture there are plugged vias and just normal ones. In normal via usually solder mask leaves a small uncovered margin to ensure solder mask doesn't get inside the via.
Edit: on this picture its even more like all vias are of same stackup (one side plugged), but some are "on top", others "on bottom".


text:
Q: Securing certain parts of an application If someone logs on to my application this user contains a dictionary with certain permissions.
ex: module.view.workspace = true
    module.view.reporting = false
    ...

Then we know to what parts of the application the user has access.
What I want to know is how we can apply these permissions on the view.
We are working in an AS 3 (FLEX) environment.
This is what we came up with so far (but I wanna have an idea of other possibilities).
We have a modelLocator storing the loggedOnUser (which contains it's permissions).
these permissions are added to a permissionObject in the modellocator.
We Create a SecurityManager class that has a function called hasAccess("permission").
This object will check the PermissionObject in the modellocator and return true/false.
In the view we just check if the user has access and then show the control.
If (SecurityManager.hasAccess("module.view.workspace") {
     // code that generates the workspace;
}

I just don't know if this is the best practice.
Please help me out here.

A: Sem,
I have a similar method and it worked fine so far. My application is written in C#.NET but the method is still valid. Since mine is a WinForms application I have to do other stuff but basically there is at some point an If statement asking that very same "question".
Martin.

A: The approach is basically valid.  I would recommend defining a class with static const that map to your different permissions and referencing that:
SecurityManager.hasAccess(SecurityManager.MODULE_VIEW_WORKSPACE)

This will save you a lot of manual search/replace work if you start to change the names of your permission items.


text: Q: User's data and local storage in cordova app I have a webapp which saves user's data in local storage. I want to use cordova to port in mobile (e.g. apk). If I release an update (another apk) the user's data are lost? I must substitute necessarily local storage with filesystem?


text:
Q: Matching russian vowels in C++ I wanted to write a function which returns true if a given character is a russian vowel. But the results I get are strange to me. This is what I've got so far:
#include <iostream>

using namespace std;

bool is_vowel_p(char working_char)
// returns true if the character is a russian vowel
{
    string matcher = "аяё×эеуюыи";

    if (find(matcher.begin(), matcher.end(), working_char) != matcher.end())
        return true;
    else
        return false;
}

void main()
{
    cout << is_vowel_p('е') << endl; // russian vowel
    cout << is_vowel_p('Ж') << endl; // russian consonant

    cout << is_vowel_p('D') << endl; // latin letter
}

The result is:
1
1
0

what is strange to me. I expected the following result:
1
0
0

It's seems that there is some kind of internal mechanism which I don't know yet. I'm at first interested in how to fix this function to work properly. And second, what is going on there, that I get this result.

A: string and char are only guaranteed to represent characters in the basic character set - which does not include the Cyrillic alphabet.
Using wstring and wchar_t, and adding L before the string and character literals to indicate that they use wide characters, should allow you to work with those letters.
Also, for portability you need to include <algorithm> for find, and give main a return type of int.

A: C++ source code is ASCII. You are entering unicode characters. The comparison is being done using 8 bit values. I bet one of the vowels fulfills the following:-
vowel & 255 == (code point for 'Ж') & 255

You need to use unicode functions to do this, not ASCII functions, i.e. use functions that require wchar_t values. Also, make sure your compiler can parse the non-ASCII vowel string. Using MS VC, the compiler requires:-
L"аяё×эеуюыи" or TEXT("аяё×эеуюыи")

the latter is a macro that adds the L when compiling with unicode support.
Convert the code to use wchar_t and it should work.

A: Very useful function in locale.h
setlocale(LC_ALL, "Russian");

Past this in the beginning of the program.
Example:
#include <stdio.h>
#include <locale.h>

void main()
{
    setlocale(LC_ALL, "Russian");

    printf("Здравствуй, мир!\n");//Hello, world!
}

A: Make sure your system default locale is Russian, and make sure your file is saved as codepage 1251 (Cyrillic/Windows). If it's saved as Unicode, this won't ever work.
The system default locale is the one used by non-Unicode-compliant programs. It's in Control Panel, under Regional settings.
Alternatively, rewritte to use wstring and wchar_t and L"" string/char literals.


text:
Q: remove periods, not decimal points I have a long string variable (many sentences separated by ".") with some important numerical information, generally with a decimal point (e.g., "6.5 lbs").
I would like to regex out the all periods when they appear at the end of a sentence, but leave them when they appear between numbers.
FROM:
First sentence.  Second sentence contains a number 1.0 and more words.  One more sentence.

TO:
First sentence  Second sentence contains a number 1.0 and more words  One more sentence

I am doing this in Stata, using Unicode regex functions which follow this standard: http://userguide.icu-project.org/strings/regexp
What I thought I was doing in the following is: `replace the period w/ a space when the previous character is a lowercase letter'.
gen new_variable = ustrregexrf(note_text, "(?<=[a-z])\.", " ")

I find that it will remove one period per line, but will not remove all of them.  Maybe what I need to do is tell it: do this for all the periods you find satisfying the condition, but since it's not working the way I think it is already maybe I need an explanation of what it actually is doing.
Bonus points if you can tell me how to remove a period when there is a number followed by a space:
number is 1.0.  Next sentence -> number is 1.0 Next sentence
EDIT: there are occasionally strings like end sentence.begin next sentence without spacing so separating on white space won't handle all of my cases.

A: Method 1
Maybe,
\.(?=\s|$)

might be OK to look into.
Demo 1

Method 2
\d+\.\d+(*SKIP)(*FAIL)|\.

Demo 2
is another option to look at, and it would work by installing the regex module:
$ pip3 install regex

Test
import regex as re

string = '''
First sentence.  Second sentence contains a number 1.0 and more words.  One more sentence.First sentence.  Second sentence contains a number 1.0 and more words.  One more sentence.
'''

expression = r'\d+\.\d+(*SKIP)(*FAIL)|\.'

print(re.sub(expression, '',  string))

Output

First sentence  Second sentence contains a number 1.0 and more words
  One more sentenceFirst sentence  Second sentence contains a number 1.0
  and more words  One more sentence


text:
Q: Angular front-end getting error when calling api on c# back-end I have an Angular front-end and a c# webAPI back-end.  The Angular front-end can retrieve data from other urls (e.g. http://reqres.in/api/users and json-server --watch db.json).  The c# webAPI successfully returns data to api calls (entered in browser and sent from Postman (Get, http://localhost:49566/api/people)).
When the front-end calls the back-end, gets the following:
HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).
(XHR)OPTIONS - http://localhost:49566/people
Any suggestions on what the problem is, or whether it is on the front-end or the back-end?
I have reviewed several Angular httpclient examples; but continue to experience the same thing--works with other urls; but not with my c# webAPI's url.
I have tried adding a post option; but that did not resolve it.
C# code:
        public IEnumerable<Person> Get()
        {
            return SQLiteDataAccess.GetPeople();
        }

Angular data service code:
  people: object;

  constructor(private http: HttpClient) { }

    searchClick(searchString: string) {
    return console.log('clicked ' + searchString);
  }

  getPeople() {
    const httpOptions = {
      headers: new HttpHeaders({
          'Access-Control-Allow-Origin': 'http://localhost:4200/',
          'Access-Control-Allow-Methods': 'GET',
          'Access-Control-Allow-Headers': '*',
          'Content-Type': 'application/json',
          'Accept': 'application/json'
      })
    };
    return this.http.get('http://localhost:49566/api/People', httpOptions )
}
}

What I need is for the front-end to successfully retrieve data from the back-end; so I can display it.

A: Change
   return this.http.get('http://localhost:49566/api/People', httpOptions )

to
   return this.http.get('http://localhost:49566/api/people', httpOptions )

the URL is case-sensitive.
Good luck!

A: The issue is related to CORS (on server-side) and method signature on server side.
First of all, enable CORS in your API code (C#). Please search MSDN for appropriate namespaces/dlls (e.g. System.Web.Cors) needed.
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.EnableCors();

In API controller-derived class (e.g.), please do this to ensure the CORS is allowed. * means all URLs are allowed. Change as per your client (Angular app uri) needs.
/// <summary>
    /// Provides API for Order entity.
    /// </summary>
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class OrderController : ApiController
    {

In CORS, a pre-flight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. It is sent before sending a GET or POST.
Coming back to API code, in web.config, please ensure you have the following:
<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

<remove name="OPTIONSVerbHandler" /> ensures that IIS doesn't intercept OPTIONS requests.
Also in web.config, do the following. This ensures GET, POST and OPTIONS methods are allowed.
<httpProtocol>
      <customHeaders>
        <!--...omitted for brevity-->

        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
      </customHeaders>

Finally:
[HttpGet]
public IEnumerable<Person> Get()
        {
            return SQLiteDataAccess.GetPeople();
        }

There's no need to do anything about CORS in client-side code in Angular. Hope that helps.


text:
Q: Rotating through multiple arrays I'm trying to do a simple slideshow with the following javascript code, but it is not working for me. I've triple checked the spelling, made sure that all the elements correlate with my HTML.
Javascript:
var pic_rotation = ["pic1.jpg", "pic2.jpg", "pic3.jpg"],
    cap_rotation = ["caption 1", "caption 2", "caption 3"];
var int = 0;

function rotatePicCap(){
    if (int < pic_rotation.length){
        int++;
    }
    else if (int == pic_rotation.length){
        int = 0;
    }
    document.getElementById("pic").src = pic_rotation[int];
    document.getElementById("cap").innerHTML = pic_rotation[int];
}

setInterval(function slideShow(){rotatePicCap()}, 4000);

HTML:

caption 1

Any thoughts on why this wouldn't be working?

A: The problem is here:
if (int < pic_rotation.length) int++;

Look at your browser console - it'll tell you what the problem is. On the last iteration, int will be the same as the length of the array. But for an array of length 3, arr[3] is undefined.
Better to use modulo:
function rotatePicCap(){
  int = (int + 1) % pic_rotation.length;

One other thing - only use innerHTML when you're deliberately using or inserting HTML markup (which can have security and encoding problems). When you're setting or retrieving text values, use textContent instead.
document.getElementById("cap").textContent = pic_rotation[int];

A: Your code is fine how it's written for the most part. The issue is like @CertainPerformance says though (the if-statement).
You are checking and incrementing int before displaying your information. So at the start with int being 0, you first display pic2 due to int incrementing to 1 before displaying. Your if-statement checks properly that int is less than the length but then you increment it before displaying.
Make the following change and you are fine:
function rotatePicCap(){
    if (int == pic_rotation.length){
        int = 0;
    }
    document.getElementById("pic").src = pic_rotation[int];
    document.getElementById("cap").innerHTML = pic_rotation[int];
    int++;
}

This will still increment but you will do a check before. If int is greater then you restart at 0.


text:
Q: Getters and setters in pure C? Can I use getters and setters in pure C instead of using extern variables?

A: First of all, don't listen to anyone saying "there is no object-orientation in language x" because they have truly not understood that OO is a program design method, completely apart from language syntax.
Some languages have elegant ways to implement OO, some have not. Yet it is possible to write an object-oriented program in any language, for example in C. Similarly, your program will not automagically get a proper OO design just because you wrote it in Java, or because you used certain language keywords.
The way you implement private encapsulation in C is a bit more crude than in languages with OO support, but it does like this:
// module.h
void set_x (int n);
int get_x (void);

// module.c
static int x; // private variable

void set_x (int n)
{
  x = n;
}

int get_x (void)
{
  return x;
}

// main.c
#include "module.h"

int main (void)
{
  set_x(5);
  printf("%d", get_x());
}

Can call it "class" or "ADT" or "code module" as you prefer.
This is how every reasonable C program out there is written. And has been written for the past 30-40 years or so, as long as program design has existed. If you say there are no setters/getters in a C program, then that is because you have no experience of using C.

A: Yes, it's very much possible and sometimes even useful. C supports opaque types:
struct Context;

C code compiled with only this declaration in scope can not access any hypothetical members of the struct, and can't use value of type Context either. But it can still handle pointers to Context values, so functions like these are possible:
Context *make_context(...);
int context_get_foo(Context *);
void context_set_foo(Context *, int);

This pattern insulates the client C code from any changes to the size or internal layout of Context. Note that this is a stronger guarantee than simply declaring but not documenting the members: Even if the programmers duly ignore the undocumented members, by-value use of the struct is permitted (and will certainly slip in), and now the code has to be recompiled when the size changes. In other words, opaque types only handled through pointers give greater ABI stability.

A: Another approach is by using a global variable and inline functions:
// module.h
inline void set_x (int n) {extern int x; x = n;}
inline int get_x (void) {extern int x; return x;}

// module.c
int x; // global variable

// main.c
#include "module.h"

int main (void)
{
  set_x(5);
  printf("%d", get_x());
}

It has two advantages:

*

*Getters and setters become easily inlineable

*It becomes clear to the compiler that getters have no side effects, which allows further optimizations and produces no warnings in cases like this one:
// warning: compound statement with side effects
if(get_x() || get_y())

Of course, a "dedicated" (read: dumb) programmer can always write extern int x; in their code and use the variable directly. On the other hand, a "dedicated" programmer can also easily remove the static keyword and use it anyway...


text:
Q: Relationship between Convergence and Open sets If you show that convergence of nets in a topological vector space $V$ with topology $\tau$ is equivalent to convergence of nets in a topological vector space $V$ With topology $\sigma$, does it necessarily follow that $\tau = \sigma$?

A: Yes.
You may find this easier to prove by showing that $\sigma$ and $\tau$ have the same closed sets, since closed sets are easier to describe in terms of nets than open sets are.


text:
Q: Error en mi form con un webview? que error pueden ver aquí?. Ya que en los navegadores funciona bien la carga de archivos, pero cuando uso un webview (probado con otra web de testeo y que funciona bien) en mi web no funciona, por ende, todo indica que a mi form algo le falta.
Necesito que sea compatible con la mayor cantidad de versiones posibles y si se trata de 4.4.2 muestre un mensaje (un Toast o algo diciendo que no es compatible), en caso de que no exista tal posibilidad, me interesa mas que sea compatible para versiones iguales o superiores a la 5.0 .
Desde ya muchas gracias.
Aquí el code: (uso materialize css)
<form method="POST" class="col s12 m12 l12 offset-l0 m0 s0 white blue-text" name="formulario" enctype="multipart/form-data">

                                report_problem
                                <input id="icon_prefix" type="text" class="validate" name="txtNombre">
                                Titulo

                                textsms
                                <textarea id="icon_prefix2" class="materialize-textarea" name="txtDescripcion" value="0/500"></textarea>
                                Descripcion

                                        <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
                                        Archivo
                                        <input type="file" name="imagen" id="imagen">

                                    <input class="file-path validate" type="text" placeholder="PDF, JPG, JPEG, PNG, GIF, DOC, XLS, DOCX, PPT, XLSX">

                                  <button class="btn waves-effect waves-light blue" type="submit" name="action">Enviar
                                  send</button>

                    </form>

A: Este es un problema conocido para los webview de Android. Necesitas implementar la lógica de subida de ficheros para el webview. Te paso una solución que funciona muy bien planchada descaradamente de aquí:
public class MyWb extends Activity {
/** Called when the activity is first created. */

WebView web;
ProgressBar progressBar;

private ValueCallback<Uri> mUploadMessage;
 private final static int FILECHOOSER_RESULTCODE=1;

 @Override
 protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
  if(requestCode==FILECHOOSER_RESULTCODE)
  {
   if (null == mUploadMessage) return;
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
  }
  }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    web = (WebView) findViewById(R.id.webview01);
    progressBar = (ProgressBar) findViewById(R.id.progressBar1);

    web = new WebView(this);
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://www.script-tutorials.com/demos/199/index.html");
    web.setWebViewClient(new myWebClient());
    web.setWebChromeClient(new WebChromeClient()
    {
           //The undocumented magic method override
           //Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            MyWb.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);

           }

        // For Android 3.0+
           public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
           mUploadMessage = uploadMsg;
           Intent i = new Intent(Intent.ACTION_GET_CONTENT);
           i.addCategory(Intent.CATEGORY_OPENABLE);
           i.setType("*/*");
           MyWb.this.startActivityForResult(
           Intent.createChooser(i, "File Browser"),
           FILECHOOSER_RESULTCODE);
           }

        //For Android 4.1
           public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
               mUploadMessage = uploadMsg;
               Intent i = new Intent(Intent.ACTION_GET_CONTENT);
               i.addCategory(Intent.CATEGORY_OPENABLE);
               i.setType("image/*");
               MyWb.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MyWb.FILECHOOSER_RESULTCODE );

           }

    });

    setContentView(web);

}

public class myWebClient extends WebViewClient
{
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);

        progressBar.setVisibility(View.GONE);
    }
}

//flipscreen not loading again
@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
}

// To handle "Back" key press event for WebView to go back to previous screen.
/*@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
        web.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}*/
}

EDITADO:
Según lo que hemos hablado en el chat, te paso el código de un activity con un caso de uso completo para más versiones de Android y con soporte para el acceso a la cámara del dispositivo también.
Espero que lo encuentres de utilidad:
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.provider.Settings;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.GeolocationPermissions;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@SuppressLint("SetJavaScriptEnabled")
public class WebActivity extends Activity {
    //region WebView vars
    private WebView wv;
    private WebSettings webSettings;
    //endregion
    //region File Chooser vars
    private static final int INPUT_FILE_REQUEST_CODE = 1;
    private static final int FILECHOOSER_RESULTCODE = 1;
    private static final String TAG = MainActivity.class.getSimpleName();
    private ValueCallback<Uri> mUploadMessage;
    private Uri mCapturedImageURI = null;
    private ValueCallback<Uri[]> mFilePathCallback;
    private String mCameraPhotoPath;
    //endregion

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

        wv = (WebView) findViewById(R.id.web_view);

        wv.loadUrl("http://www.script-tutorials.com/demos/199/index.html");

        WebSettings wv_settings = wv.getSettings();
        wv_settings.setJavaScriptEnabled(true);
        wv_settings.setJavaScriptCanOpenWindowsAutomatically(true);
        wv_settings.setAppCacheEnabled(true);
        wv_settings.setDatabaseEnabled(true);
        wv_settings.setDomStorageEnabled(true);
        wv_settings.setGeolocationEnabled(true);
        wv_settings.setAllowFileAccess(true);
        wv_settings.setLoadWithOverviewMode(true);

        wv.setWebViewClient(new CustomWebClient());
        wv.setWebChromeClient(new CustomWebChromeClient());

        wv.clearCache(true);
    }

    //region File Selection Helpers
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File imageFile = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        return imageFile;
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
                super.onActivityResult(requestCode, resultCode, data);
                return;
            }
            Uri[] results = null;
            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data, then we may have taken a photo
                    if (mCameraPhotoPath != null) {
                        results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }
                } else {
                    String dataString = data.getDataString();
                    if (dataString != null) {
                        results = new Uri[]{Uri.parse(dataString)};
                    }
                }
            }
            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
        } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
                super.onActivityResult(requestCode, resultCode, data);
                return;
            }
            if (requestCode == FILECHOOSER_RESULTCODE) {
                if (null == this.mUploadMessage) {
                    return;
                }
                Uri result = null;
                try {
                    if (resultCode != RESULT_OK) {
                        result = null;
                    } else {
                        // retrieve from the private variable if the intent is null
                        result = data == null ? mCapturedImageURI : data.getData();
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "activity :" + e,
                            Toast.LENGTH_LONG).show();
                }
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }
        return;
    }
    //endregion

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) {
            wv.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }

    public class CustomWebChromeClient extends WebChromeClient {

        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        //region File Chooser
        // For Android 5.0
        public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
            // Double check that we don't have any existing callbacks
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePath;
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.e(TAG, "Unable to create Image File", ex);
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[]{takePictureIntent};
            } else {
                intentArray = new Intent[0];
            }
            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Selector de imagen");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
            return true;
        }
        // openFileChooser for Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            // Create AndroidExampleFolder at sdcard
            // Create AndroidExampleFolder at sdcard
            File imageStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES)
                    , "AndroidExampleFolder");
            if (!imageStorageDir.exists()) {
                // Create AndroidExampleFolder at sdcard
                imageStorageDir.mkdirs();
            }
            // Create camera captured image file path and name
            File file = new File(
                    imageStorageDir + File.separator + "IMG_"
                            + String.valueOf(System.currentTimeMillis())
                            + ".jpg");
            mCapturedImageURI = Uri.fromFile(file);
            // Camera capture image intent
            final Intent captureIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            // Create file chooser intent
            Intent chooserIntent = Intent.createChooser(i, "Selector de imagen");
            // Set camera intent to file chooser
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
                    , new Parcelable[] { captureIntent });
            // On select image call onActivityResult method of activity
            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
        }
        // openFileChooser for Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }
        //openFileChooser for other Android versions
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }
        //endregion File Chooser
    }

    public class CustomWebClient extends WebViewClient {
        ProgressDialog progressDialog;
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // If url contains mailto link then open Mail Intent
            if (url.contains("mailto:")) {
                // Could be cleverer and use a regex
                //Open links in new browser
                view.getContext().startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                // Here we can open new activity
                return true;
            }else {
                // Stay within this webview and load url
                view.loadUrl(url);
                return true;
            }
        }
        //Show loader on url load
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // Then show progress  Dialog
            // in standard case YourActivity.this
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(WebActivity.this);
                progressDialog.setMessage("Cargando...");
                progressDialog.show();
            }
        }
        // Called when all page resources loaded
        public void onPageFinished(WebView view, String url) {
            try {
                // Close progressDialog
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }
}


text:
Q: Btree details on Postgresql How can i know details about an index on postgresql like how many nodes, and tree height?
It is possible to access the data structure itself?
i havent found any catalog tables that exposes such that detailed information
Thanks in advance!

A: See the bt_metap function in the pageinspect extension.
http://www.postgresql.org/docs/current/static/pageinspect.html

A: You can use pgstattuple extension.
create extension pgstattuple;
SELECT * FROM pgstatindex('your_index_name');

For example,
ycsb=# select * from pgstatindex('usertable_pkey');
 version | tree_level | index_size | root_block_no | internal_pages | leaf_pages | empty_pages | deleted_pages | avg_leaf_density | leaf_fragmentation
---------+------------+------------+---------------+----------------+------------+-------------+---------------+------------------+--------------------
       2 |          3 | 5488721920 |         44337 |           4464 |     665545 |           0 |             0 |               52 |                 11
(1 row)

You can refer to documentation;
https://www.postgresql.org/docs/current/static/pgstattuple.html


text:
Q: BLL Return String Or DTO I'm confused how to return the result from the business layer. Sometimes I need to return the message if it does not pass the criteria. For example:
public SalesDTO GetSalesByPrescriptionNo(string prescriptionNo)
{
    int count = unitOfWork.SalesRepository.GetNumberOfPrescriptionUsed(prescriptionNo);
    if (count > 5)
        // I cannot return string/error information
        // since the function is return SalesDTO type
        return "Cannot used anymore";

    var sales = unitOfWork.SalesRepository.GetSalesByPrescriptionNo(prescriptionNo);
    var salesDTO = Mapper.MapToDTO(sales);
    return salesDTO;
}

Based on the good OOP/OOD implementation, how should I handle the multiple result from the BLL?

A: It's an exceptional case when the method cannot deliver the expected result.
The caller have either not validated the information used when calling the method, or trying to fetch something that simply do not exist.
If you use a return value to indicate that, you will always have to deal with two different execution paths for every method call. The code gets much more cluttered then.
Exceptions on the other hand will automatically travel back through all method invocations until it comes to a try/catch statement. Hence no need to check for exceptions unless you really can handle it.

it's not an error, why it should be treated as an exception? it's a good oop approach?

It is an exception. The method GetSalesByPrescriptionNo indicates that it will deliver the sales. It's nothing in the name, the contract, that indicates that it may not be able to return sales in some situations. Hence the caller expect the method to succeed.
Either name the method TryGetSalesByPrescriptionNo or throw an exception.
If you choose the exception path you typically have another method somewhere which can check if it's OK to invoke other methods on that prescription. (i.e. your counter check)
You can do something like:
if (IsPrescriptionActive(prescriptionNo))
{
    var sales = GetSalesByPrescriptionNo(prescriptionNo);
    //do something with sales
}

imho I like that better than:
if (!TryGetSalesByPrescriptionNo(prescriptionNo, out sales))
{
    //do something with sales
}

because you can't understand by looking at the call why the method fails. That you can with the first alternative.
However, If you expect that the user have entered a valid prescription number (which is still active) there is no reason to use an extra check. Simply use:
var sales = GetSalesByPrescriptionNo(prescriptionNo);
//do something with sales

As it's really an exceptional case in that situation. i.e. if you use IsPrescriptionActive you are hiding a bug (as the valid subscription got invalid somewhere on the road).
Summary

*

*The prescription should be validated in the UI and reported directly to the user.

*If an invalid prescription is found in the business layer, throw an exception.


text:
Q: Building a struct with a field name which has a comma I'm trying to create a struct based on a response I get.
I have no control over the response, and in it's structure there are field names which use comma as part of the filed name itself
JSON Example:
        "date": "2022-09-09 00:00:00 UTC",
        "Sum": {
            "Change, %": "0.10",
            "Price": "254",
            "Value, $": "455.26",
            }

When trying to create a struct the "regular" way, I get an error since once I use the comma character, reflect.StructTag.Get expects something specific and not the rest of the name.
Struct Example:
Date   string `json:"date"`
Sum    struct {
    Change  string `json:"Change, %"`
    Price   string `json:"Price"`
    Value   string `json:"Value, $"`
} `json:"Sum"`

The error I receive is:
"struct field tag json:"Value, $" not compatible with reflect.StructTag.Get: suspicious space in struct tag value"
The goal is to later manipulate and use this data (hopefully using my simple names), so "just" printing the JSON or moving it to an array or similar option cannot be the final step.
The 'Price' field is working as expected, but the problem is with the fields using the comma.
I couldn't find a way around it or a similar question.
Would love to understand how to deal with this issue.
Thanks!

A: You may unmarshal the Sum JSON object into a Go map, and assign the values from the map to the struct fields. The restriction only applies to struct tags (that they may not contain arbitrary characters like comma), but maps may hold any keys.
For example:
type Sum struct {
    Change string
    Price  string
    Value  string
}

func (s *Sum) UnmarshalJSON(data []byte) error {
    var m map[string]string
    if err := json.Unmarshal(data, &m); err != nil {
        return err
    }

    s.Change = m["Change, %"]
    s.Price = m["Price"]
    s.Value = m["Value, $"]
    return nil
}

type model struct {
    Date string `json:"date"`
    Sum  Sum    `json:"Sum"`
}

func main() {
    var m model
    if err := json.Unmarshal([]byte(src), &m); err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", m)
}

const src = `{
  "date": "2022-09-09 00:00:00 UTC",
  "Sum": {
    "Change, %": "0.10",
    "Price": "254",
    "Value, $": "455.26"
  }
}`

This will output (try it on the Go Playground):
{Date:2022-09-09 00:00:00 UTC Sum:{Change:0.10 Price:254 Value:455.26}}


text:
Q: Flutter display blank screen when tap on button the flutter code below executes a view, when I click on the FaIcon(FontAwesomeIcons.calendar) to show the calendar selection, I get the completely blank screen what is this due to?
Flutter Code:
import 'dart:async';
import 'dart:developer';

import 'package:custom_date_range_picker/custom_date_range_picker.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:nice_button/nice_button.dart';
import 'package:quote/Model/Ferie.dart';
import 'package:quote/Model/Supporto.dart';
import 'package:quote/Model/Utente.dart';
import 'package:quote/View/Home.dart';
import 'package:quote/utils/support.dart';
import 'package:rflutter_alert/rflutter_alert.dart';

import '../Barcode/BarcodeManager.dart';
import 'dialog/CustomDialog.dart';

bool isShowingMainData = true;
var status = false;
String base64File = null;
var urlprofiloImage;

class FerieScreen extends StatefulWidget {
  const FerieScreen({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _FerieScreenState();
  }
}

class _FerieScreenState extends State<FerieScreen> {
  DateTime startData, endData;
  List<Ferie> listaFerie;
  var check = false;

  Future<bool> loadData() async {
    listaFerie = await Ferie.ricerca();
    urlprofiloImage = await Utente.getProfiloImmagine();
    return true;
  }

  inserisci(BuildContext context) {
    if (startData != null && endData != null) {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return CustomDialogBox(
              title: "Invio Richiesta Ferie",
              descriptions:
                  "Data Inizio: " + Verifica.castDate(startData) + "\nData Fine: " + Verifica.castDate(endData),
              text: "Invia Richiesta",
              dataFine: endData,
              dataInzio: startData,
            );
          });
    } else {
      log("Date non compilate");
      alert(context, "Attenzione", "Le date devono essere selezionate", AlertType.error);
    }
  }

  ///Funzione che mostra una data a video
  Future<void> selectDate(BuildContext context) async {
    showCustomDateRangePicker(context, dismissible: true, minimumDate: DateTime.now(), endDate: DateTime.now(),
        onApplyClick: (start, end) {
      startData = start;
      endData = end;
    }, onCancelClick: () {}, maximumDate: null);
  }

  Widget getFerieWidget(BuildContext context) {
    return listaFerie != null
        ? Expanded(
            child: ListView.builder(
            itemCount: listaFerie.length,
            itemBuilder: (context, index) {
              final item = listaFerie[index];
              return Card(
                  child: ListTile(
                title: Text("Stato Richiesta Ferie: " + item.Stato.toString(),
                    style: TextStyle(
                        fontWeight: FontWeight.w800,
                        color: item.Stato == "INATTESA"
                            ? Colors.orange
                            : item.Stato == "APPROVATA"
                                ? Colors.green
                                : Colors.red)),
                subtitle: Text(
                    "Data Inizio: " +
                        item.DataInizio.toString() +
                        "\nData Fine: " +
                        item.DataFine.toString() +
                        "\nMotivazione: " +
                        item.Motivazione,
                    style: const TextStyle(fontWeight: FontWeight.bold)),
              ));
            },
          ))
        : Container(
            alignment: Alignment.topCenter,
            margin: const EdgeInsets.only(top: 20),
            child: const CircularProgressIndicator(
              value: 0.8,
            ),
          );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: loadData(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return new Text("Not data load");
          } else {
            return Scaffold(
              resizeToAvoidBottomInset: true,
              body: Column(children: [
                const SizedBox(
                  height: 50,
                ),
                Row(
                  children: [
                    const Expanded(
                      child: ListTile(
                        title: Text('Richiesta Ferie'),
                        subtitle: Text("Clicca qui sul button del calendario"),
                      ),
                    ),
                    Expanded(
                      child: IconButton(
                        icon: const FaIcon(FontAwesomeIcons.calendar),
                        onPressed: () {
                          selectDate(context);
                        },
                      ),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 10,
                ),
                new NiceButton(
                  radius: 30,
                  padding: const EdgeInsets.all(20),
                  text: "Richiesta Ferie",
                  icon: Icons.local_airport,
                  gradientColors: [secondColor, firstColor],
                  onPressed: () {
                    inserisci(context);
                  },
                  background: null,
                ),
                Row(
                  children: [
                    Align(
                        alignment: Alignment.bottomLeft,
                        child: Expanded(
                          child: IconButton(
                            icon: const FaIcon(FontAwesomeIcons.backward),
                            onPressed: () {
                              const gp = const HomeViewScreen();
                              Navigator.push(context, MaterialPageRoute(builder: (context) => gp));
                            },
                          ),
                        ))
                  ],
                ),
                getFerieWidget(context),
              ]),
            );
          }
        });
  }
}


text:
Q: Cannot remove Event Listeners from object on Angular I have an image with mouseenter and mouseleave attributes. When the cursor first hovers this image, it calls startCalc(id) method and in this I am calculating some stats with addEventListener. When the cursor leaves this image I call stopCalc() and in this method I save my calculations, then remove event listeners. But event listeners are not removing.
Here is my code:
    <img id="img-1" class="img" (mouseenter)="startCalc('img-1')" (mouseleave)="stopCalc()" src="{{url}}" />

Backend side:
    startCalc(imgID: string) {
        var img = document.getElementById(imgID);
        img.addEventListener("mousemove", calc);

        function calc(e) {
            // doing some calculations
        }
    }

    stopCalc() {
        // saving those calculations

        var elements = document.getElementsByClassName("img");

        for (let i = 0; i < elements.length; i++) {
            elements[i].addEventListener("mousemove", null);
        }
    }

What am I missing here?


text:
Q: How can I get WooCommerce attributes to display custom meta/text on selection? I'm selling artwork using Wordpress and WooCommerce and I have an attribute for Frame Style. I love that when the user selects a frame I can update the photo with a custom image to match that frame, similarly I'm trying to figure out a way to display custom text based on the users selection.
So to clarify, if someone selects "Black Scoop Frame" I want to be able to have that specific frames size and description display. And if they change their selection to "Red Wood Frame" I want the description to change with it.
WooCommerce allows descriptions to be added to attributes and I have been trying for dayys to figure out how to call that meta data and have it change with the drop down selection change.
Any help or even pointing me in the right direction would be appreciated!

A: Frst of all, give your options
function your_options() {
    $sample_select_options = array(
        '0' => array( 'value' => '0', 'label' => __( '', '_s' ) ),
        '1   ' => array( 'value' => '1   ', 'label' => __( 'Something1', '_s' ) ),
        '2   ' => array( 'value' => '2   ', 'label' => __( 'Something2', '_s' ) );
    return apply_filters( 'your_options', $give_me_options );
}

Than set up selecting options on your page
<select name="" id="" style="width: 300px;">
        <?php
            $selected = options['give_me_options'];
            $p = '';
            $r = '';

            foreach ( your_options() as $option ) {
                $label = $option['label'];
                if ( $selected == $option['label'] ) // Make default first in list
                    $p .= "\n\t<option style=\"padding-right: 10px;\" selected='selected' value='" . esc_attr( $option['label'] ) . "'>$label</option>";
                else
                    $r .= "\n\t<option style=\"padding-right: 10px;\" value='" . esc_attr( $option['label'] ) . "'>$label</option>";
            }
            echo $p . $r;
        ?></select>

And at the end, put action to your page, where to give it and of course save function :)
This is only a guide how to do it, not a specific code.


text:
Q: Gaming performance bad on M17x (GTX 680m) I'm having problems with gaming performance and have no idea how to solve it right now. I know this machine should be able to perform better than this and I was hoping for some tips. Hopefully I'll find the problem.
My machine is

*

*Alienware m17x R4, Intel i7

*Graphics card is GTX 680m from nVidia.

*24gb RAM.

*Windows 8 OS.

I am running into problems with a game called StarCraft 2 which shouldn't be too demanding.
The problems I'm having is that during too many animations is running (big fights etc.) the framerate drops from ~25 to ~5 and freezes completely on occasions. When the freeze is over, the game runs really fast for a second until it 'catches up' so to speak. Mostly it just drops framerate until the big fight/animations are over.
Since this is a completely new PC with high performance gfx card, I'm pretty much sure that there shouldn't be any problems like this.
I installed drivers from nVidia, the ones that they recommended. I also installed latest drivers for chipset.
I investigated the possibility that I might be running on the internal gfx card instead of the GTX, and learned that I can switch between them by pressing fn+F7. That did not help, and I could barely run the game.
Graphics card performance
I installed GPU-z as instructed and it gives me some information about the graphics cards.
To set which card should be used for certain programs you can go to the nVidia control panel (Right click desktop -> nVidia control panel -> Manage 3D settings). I have made sure that the game is in this list with proper settings, however this does not solve my problem.
I have logged the sensors from GPU-z and put the log in a gist . During this log I'm playing a game and experiencing lag, FPS down to 3.
Benchmarks
Checking some tests I see a different (better) result than I'm having.
On the following link testing this game they get around 50 FPS on highest settings. I get dips to 10 FPS on lowest setting, when they suggest you get 250 FPS on low settings with this GFX card.
http://www.notebookcheck.net/NVIDIA-GeForce-GTX-680M.72679.0.html
3Dmark benchmark seems to give me OK results: http://www.3dmark.com/3dm/592251
Other games
I have tested one other game (Diablo 3) with maximum video settings and it runs like a charm - very smoothly with high FPS, never dipping below 25 even in huge fights with lots of animations.
Any idea is appreciated.


text:
Q: Does JBoss run well on Windows? It appears that we will have to build/deploy one of our new JBoss apps on Windows.
All our current deployments are on Solaris so we were slightly concerned with the stability of this model.  Apparently half of JBoss deployments are on Windows if this article is accurate.  But I was wondering what the community had to say..  Is Windows considered a solid platform to deploy JBoss on?

A: Should be fine. The JBoss folks have paid careful attention to how their software behaves on Windows, even working with Microsoft on it. Make sure you look at the up to date recommendations for running JBoss on Windows. There are multiple ways to set it up and some are no longer recommended. If you just google it, you'll likely find instructions for the outdated setup.

A: For development I run JBoss on a Windows platform and it runs without any problems.
One pitfall I tapped in was the different sorting behaviour of the file systems. I had two jar files that happened to contain different versions of the same class. On a Linux system one jar was loaded first, on Windows the other, resulting in strange errors. But of course, you should never have two versions of the same class at one time, so this happens only in a badly configured system.

A: JBoss AS is tested for server editions of Windows - 2003, 2008 etc.
Also, some JBoss AS developers develop on Windows, some on Macs.
See the list of tested JBoss EAP configurations.
Yes, JBoss AS should run well on Windows.


text:
Q: Build the hash query from array for mongoid rails I have query like this for postgresql:
users = users.where(search_string.join(' or '), search: "%#
{params[:search][:value]}%")

But I need to rebuild it for mongoid cos of Error ArgumentError (wrong number of arguments (given 2, expected 1))
can someone explain how to do it?


text:
Q: Robot/spam picture filter for Rails I'm looking for a plugin or gem that has the picture of letters or words to filter spam and robots.
Has anyone seen one of these for rails?

A: There isn't really a shortage of them.


text:
Q: Counterintuitive percentages I wanted found if is better composed yield (a x b) or sum of yields (a + b) and why.
And while on that i found one quite counterintuitive thing, namely that:
0.9 * 1.2 = 1.08

is same as
1.2 * 0.9 = 1.08

I know that this is very basic commutative law.
But if you use your experience with percentages, you know that depends on the base. It is something else to add 20% to 100 or to 120. So base number matters. But in the case above, it is same result if you add 20% to 100 and then take 90% of it, or take 90% of 100 and then add 20% to it. It is little bit counterintuitive, or is it just me?

A: No, it is not counterintuitive. Basically the bigger your base is, the more you add or take a way.
So if you add 20% and then take away 10% you take away more, as the base is larger.
If instead you take away 10% and then add 20% you add less, as the base is smaller.


text:
Q: Does UINavigationBar retain UINavigationItems pushed onto its stack? Does UINavigationBar retain nav items pushed onto its stack? In other words, after doing this:
_myNavItem = [[UINavigationItem alloc]initWithTitle:@"Home"];
[self.navBar pushNavigationItem:_myNavItem animated:NO];

do I need to release _myNavItem with:
    [_myNavItem release];

in order to avoid a memory leak?
Also, how do I find out in general whether or not an object will be retained? Is it just a convention that any Objective C collection maintains ownership of all elements added to it?

A: The ADC UINavigationBar Class Reference mentions at the definition of the items property it is storing all UIViewControllers pushed onto the navigation stack with an NSArray.
Moving on to the NSArray Class Reference, it is stated that the default implementation of the NSArray class retains every object inserted into it and releases it when it is removed.
Putting these two things together it is safe to imply that UINavigationController retains all of its UIViewControllers when they are pushed onto the stack.

A: Yes, the UINavigationBar retains its UINavigationItems. Just like an NSArray or NSDictionary retains its objects, so does a UINavigationBar.


text:
Q: What sublime text 3 language works with json like code? Sublime Text 3 works great for editing, however it doesn't seem to have support for json like languages that use comments.
For example: HCL (hashicorp language) is compatible with json, but also allows comments
{
  "foo":"bar"
   #here is a comment, can't do this in regular json
}

Another example is logstash configs
input {
  stdin {codec => json}
}
filter {
  mutate {
    rename => [ "FOO", "foo" ]
  }
output { stdout { codec => rubydebug} }

I don't see any languages in sublime that support syntax highlighting with these types of documents. Is there one?

A: Using the YAML parser will provide syntax highlighting for Hashicorp Language (HCL) style code including logstash configs.