Q: Difference between `vector v;` and `vector v = vector();` What is the difference between
std::vector<int> v;

and
std::vector<int> v = std::vector<int>();

Intuitively, I would never use the second version but I am not sure if there is any difference. It feels to me that the second line is simply a default constructor building a temporary object that is then moved by a move assignment operator.
I am wondering whether the second line is not somehow equivalent to
std::vector<int> v = *(new std::vector<int>());

hence causing the vector itself to be on the heap (dynamically allocated). If it is the case, then the first line would probably be preferred for most cases.
How do these lines of code differ?

A: Starting from C++17 there's no difference whatsoever.
There's one niche use case where the std::vector = std::vector initialization syntax is quite useful (albeit not for default construction): when one wants to supply a "count, value" initializer for std::vector<int> member of a class directly in the class's definition:
struct S {
  std::vector<int> v; // Want to supply `(5, 42)` initializer here. How?
};

In-class initializers support only = or {} syntax, meaning that we cannot just say
struct S {
  std::vector<int> v(5, 42); // Error
};

If we use
struct S {
  std::vector<int> v{ 5, 42 }; // or = { 5, 42 }
};

the compiler will interpret it as a list of values instead of "count, value" pair, which is not what we want.
So, one proper way to do it is
struct S {
  std::vector<int> v = std::vector(5, 42);
};

A: The 1st one is default initialization, the 2nd one is copy initialization; The effect is same here, i.e. initialize the object v via the default constructor of std::vector.
For std::vector<int> v = std::vector<int>();, in concept it will construct a temporary std::vector then use it to move-construct the object v (note there's no assignment here). According to the copy elision (since C++17 it's guaranteed), it'll just call the default constructor to initialize v directly.

Under the following circumstances, the compilers are required to omit
  the copy and move construction of class objects, even if the copy/move
  constructor and the destructor have observable side-effects. The
  objects are constructed directly into the storage where they would
  otherwise be copied/moved to. The copy/move constructors need not be
  present or accessible, as the language rules ensure that no copy/move
  operation takes place, even conceptually:

*

*In the initialization of a variable, when the initializer expression
  is a prvalue of the same class type (ignoring cv-qualification) as the
  variable type:
T x = T(T(f())); // only one call to default constructor of T, to initialize x

(Before C++17, the copy elision is an optimization.)

this is an optimization: even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all),

BTW: For both cases, no std::vector objects (including potential temporary) will be constructed with dynamic storage duration via new expression.

A: You had asked:

What is the difference between
std::vector<int> v;

and
std::vector<int> v = std::vector<int>();

?

As others have stated since C++17 there basically is no difference. Now as for preference of which one to use, I would suggest the following:

*

*If you are creating an empty vector to be filled out later then the first version is the more desirable candidate.

*If you are constructing a vector with either a default value as one of its members and or a specified count, then the later version would be the one to use.

*Note that the following two are different constructors though:

*

*std::vector<int> v = std::vector<int>();

*Is not the same constructor as:

*std::vector<int> v = std::vector<int>( 3, 10 );

*The 2nd version of the constructor is an overloaded constructor.

*Otherwise if you are constructing a vector from a set of numbers than you have the following options:

*

*std::vector<int> v = { 1,2,3,4,5 };

*operator=( std::initializer_list)

*std::vector<int> v{ 1,2,3,4,5 };

*list_initialization
Here is the list of std::vector constructors.


Q: AngularJS ng-pattern and required can not work together on number field correctly? I have a form and i need to validate a field with both ng-pattern and required but they can't not work together correctly.
Form have only a number field which expects the value is an integer value.
When i type "0.3" the validation displays correctly. But when i type "abcd.." the validation displays "This field is required". It should be "Must be number"
I have create a plunk that demo my issues :
[link](http://plnkr.co/edit/yxqY51?p=preview)

Thank in advance


Q: How to modify mapping for already mapped entities in other assemblies? I'd like to custom mapping for entities in EF
For example, I have an entity:
public class User
{
    public int UserId { get;set;}
    public string Firstname { get;set;}
    public string ColA {get; set;}
    public string ColB {get; set;}
}

It's already added mapping in OnModelCreating() in EF in common use. If i have 2 functions in 2 seperate assemblies, call AssemblyA.dll and AssemblyB.dll and they are dynamically loaded by MEF framework.
AssemblyA.dll just needs ColA and has to remove ColB and vice versa for AssemblyB.dll, so i need to define 2 new mapping classes for these 2 services and it will dynamically run to remove column according to its assembly (AssemblyA will Ignore ColB, and AssemblyB ignore ColA). I don't want to modify code of current EF because it's already in production. All changes for each assembly should be in its own.
Do EF support us to do like this ? Or could you give me a direction.

A: It is not very clear what you are trying to do but:

*

*Every EF context can have each table and entity mapped only once

*It means if you load configuration for AssemblyA you cannot use configuration for AssemblyB

*It also means you cannot use default way how EF mapping is constructed inside OnModelCreating because that method is normally called only once for whole application lifetime.

*You can manually construct two DbModel insnaces, compile them to DbCompiledModel and pass them to DbContext constructor - that should allow you to have two different mapping configuration for AssemblyA and AssemblyB but you will never have both of them in the same context instance.

*EF migrations will most probably don't work because they expect single mapping set per database

Anyway if you are using MEF and modular architecture each entity should be either core (not related to any particular module and shared as is among modules) or module (not used by any other modules or core).


Q: Adding rows to gridView I want to add new rows after the inserted rows. I have a button that shows bootstrap modal with some DropDownLists and Textboxes. The button in modal on click should insert the data from modal to the table. The problem is that when i try to add new row it will replace current row. What im doing wrong? Here is sample of my code:
.cs:
protected void addTrip_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        dostawca = DropDownDostawca.SelectedValue.ToString();
        cel = txtCel.InnerText;
        krajZagr = "";
        kraj = DropDownKraj.SelectedValue.ToString();
        miasto = txtMiasto.Text;
        if(rbKraj.Checked == true)
        {
            krajZagr = "Krajowa";
        }
        if(rbZag.Checked == true)
        {
            krajZagr = "Zagraniczna";
        }

        if(cel=="" || miasto=="" || kraj=="" || dostawca=="" )
        {
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowPopup2();", true);

        }
        else
        {
            if(gridViewTrips.Columns.Count == 0)
            {

                DataRow dr = dt.NewRow();
                DataColumn dc = new DataColumn("DO_KOGO");
                DataColumn dc2 = new DataColumn("CEL");
                DataColumn dc3 = new DataColumn("KRAJOWA_ZAGRANICZNA");
                DataColumn dc4 = new DataColumn("KRAJ");
                DataColumn dc5 = new DataColumn("MIASTO");

                dt.Columns.Add(dc);
                dt.Columns.Add(dc2);
                dt.Columns.Add(dc3);
                dt.Columns.Add(dc4);
                dt.Columns.Add(dc5);

                dr["DO_KOGO"] = dostawca;
                dr["CEL"] = cel;
                dr["KRAJOWA_ZAGRANICZNA"] = krajZagr;
                dr["KRAJ"] = kraj;
                dr["MIASTO"] = miasto;

                dt.Rows.Add(dr);
                gridViewTrips.DataSource = dt;
                gridViewTrips.DataBind();
            }
            else
            {
                DataRow dr = dt.NewRow();
                dr["DO_KOGO"] = dostawca;
                dr["CEL"] = cel;
                dr["KRAJOWA_ZAGRANICZNA"] = krajZagr;
                dr["KRAJ"] = kraj;
                dr["MIASTO"] = miasto;

                dt.Rows.Add(dr);
                gridViewTrips.DataSource = dt;
                gridViewTrips.DataBind();
            }

        }

    }

.aspx:
<asp:GridView runat="server" id="gridViewTrips">
            <EmptyDataTemplate>
                <asp:Table ID="TableTrips" runat="server" CssClass="table table-bordered">
            <asp:TableHeaderRow>
                <asp:TableHeaderCell>Do kogo</asp:TableHeaderCell>
                <asp:TableHeaderCell>Cel</asp:TableHeaderCell>
                <asp:TableHeaderCell>Krajowa/Zagraniczna</asp:TableHeaderCell>
                <asp:TableHeaderCell>Kraj</asp:TableHeaderCell>
                <asp:TableHeaderCell>Miasto</asp:TableHeaderCell>

            </asp:TableHeaderRow>

        </asp:Table>
            </EmptyDataTemplate>

        </asp:GridView>

EDIT: Now I see when I debug my project the IF what i have: "if(gridViewTrips.Columns.Count == 0)" after inserted one row shows me that I dont have any columns. Any ideas what is going on?

A: What about create GridView column first...
https://msdn.microsoft.com/en-us/library/system.windows.controls.gridviewcolumn(v=vs.110).aspx
and then AddChild method?
https://msdn.microsoft.com/en-us/library/system.windows.controls.gridview(v=vs.110).aspx


Q: How Apache Mina SignalListner works? I want to terminate the Apache Mina Ssh Server on the basis of Ctrl+c that are basically SigInt I searched on the google and have looked there are SignalListener but not find any good example of it.
Please share any good example and use in ssh server.
A listener  will only trigger if any Sigint or a Signal is sent, Am I right ?

A: To get access to signal handling you have to use sun's private classes, which makes your code not portable any mode. Anyway...
    import sun.misc.Signal;

    public static void main(String[] args) {
        registerSignalHandler();
    }

    @SuppressWarnings("restriction")
    private static void registerSignalHandler() {
        Signal.handle(new Signal("HUP"), (Signal signal) -> {
             System.out.println("Hello signal!");
        });
    }


Q: What's the most Cocoaish way to show that a text field is invalid? I have a text field which is validated whenever it loses focus. I want to be able to indicate that the value invalid during input so the user has the opportunity to correct their mistake before explicitly moving focus away from the box and triggering validation.
I have seen various implementations, including placing a red border round the field, a little icon that comes up for invalid input, or a bit of warning text.
What is the best way to do this in a way that complies with the conventions of Cocoa and the Apple Human Interface Guidelines?

A: Set its background to light red. This is what Adium does when you go over the message length limit in a Twitter tab.
The specific color Adium uses is:

*

*Hue: 0.983

*Saturation: 0.43

*Brightness: 0.99

*Alpha: 1.0

as a calibrated (Generic RGB) color.

A: What about shaking the text field while making it slightly red? It may or may not work well in practice, but its used in the login field for both MobileMe and user switching on OS X.

A: I like the Windows solution and implemented a small tooltip popup myself.
I don't think that just changing colors doesn't will work. A textual explaination is often required too. Unfortunately MacOSX removed the balloon tips from old MacOS.


Q: Eclipse fails to build android project Background: this problem occured after an update through the android sdk Manager eclipse plugin.
Currently, when i try to build any android project, this error occurs.

THe information i gathered so far, is that this is a java related issue, as i'm trying to compile newer version code (version 52.0 stands for java 8) and run it in an older one. However, most of the solutions didn't work out.
Here are the compile setting for an android project :

Here are settings from the java compiler in Eclispe:

Here are the installed JREs

Finally, installed packets from the Android SDK:

I've  removed the packets for API 23, but with no luck. Could it be that Android tools are causing trouble, since the SKD doesn't support the java version (52)?

A: Problem was with JDK/JRE. They were installed separately. Deleted them and installed from a bundle. Although they were the same version, project building kept on crashing.


Q: strange
* padding issue chrome (padding only works sometimes in chrome) Ok so I am having a strange problem which only happens in the chrome web browser.
everything works fine in firefox and ie.
I have created a navigation menu using images.
I have place padding on each list item to space them out a bit.
so when using chrome sometimes the padding works, other times it doesn't.
if i refresh the page a few times the padding stops working and the list items have no padding anymore, refresh again a few times and it works again.
I have no idea what is causing this.
I will paste my code here if anyone has any ideas.
I have searched far and wide and cant seem to find anyone else with this issue.
**EDIT : **
I have hosted the images and used codepen,
with codepen padding doesnt work at all with chrome but is fine in firefox
codepen:
http://codepen.io/anon/pen/JEOZBN
HTML

Home

About

Audio

Art

3d

Programming

And the css
        .ground{
    position:fixed;
    left:0px;
    bottom:-1%;
    height:auto;
    width:100%;
    background:#999;
}

    /*nav menu */
#menu{
    position: fixed;
    list-style:none;
    margin: -5% 0% 0% 18%;
}

#menu li{
    float:left;  /*--- Make the list go horizontal ---*/
    margin:auto;

}

#menu li a{
    display:block;
    text-indent: -9999px; /*--- Push the text off screen to hide text---*/

        padding-left: 10% !important;
    padding-right: 10% !important;

}
#menu li#home a{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/home_menu_svyjuj.png) no-repeat;
    width:150px;
    height: 75px;

}
#menu li#home a:hover{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/home_menu_hover_g4rwhe.png) no-repeat;
}
#menu li#home a.current{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/home_menu_hover_g4rwhe.png) no-repeat;
    cursor:default;  /*--- Show pointer instead of hand cursor for the current page ---*/
}

/*About*/
#menu li#about a{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/about_menu_jcz8yx.png) no-repeat;
    width:150px;
    height: 75px;

}

#menu li#about a:hover{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/about_menu_hover_uurcba.png) no-repeat;
}

#menu li#about a.current{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/about_menu_hover_uurcba.png) no-repeat;
    cursor:default;
}

/*Graphic design*/
#menu li#art a{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/art_menu_mbywzq.png) no-repeat;
    width:150px;
    height: 75px;

}

#menu li#art a:hover{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/art_menu_hover_afaypq.png) no-repeat;
}

#menu li#art a.current{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/art_menu_hover_afaypq.png) no-repeat;
    cursor:default;
}

/*Modeling/Animation*/
#menu li#threed a{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/3d_menu_dptfpv.png) no-repeat;
    width:150px;
    height: 75px;

}

#menu li#threed a:hover{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/3d_menu_hover_pqnxfs.png) no-repeat;
}

#menu li#threed a.current{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/3d_menu_hover_pqnxfs.png) no-repeat;
    cursor:default;
}

/*Programming*/
#menu li#coding a{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/programming_hzslwa.png) no-repeat;
    width:150px;
    height: 75px;

}

#menu li#coding a:hover{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/programming_hover_crywht.png) no-repeat;
}

#menu li#coding a.current{
    background: url(.http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/programming_hover_crywht.png) no-repeat;
    cursor:default;
}

/*Audio*/
#menu li#audio a{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/audio_vvgdur.png) no-repeat;
    width:150px;
    height: 75px;

}

#menu li#audio a:hover{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/audio_hover_bnrvb0.png) no-repeat;
}

#menu li#audio a.current{
    background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/audio_hover_bnrvb0.png) no-repeat;
    cursor:default;
}

Any help is greatly appreciated Thank you.


Q: How to change the position of GameObjects with Unity Input.GetMouseButtonDown method? I already know how to click on 3D Objects in the scene by using the Input.GetMouseButtonDown. I'm trying to change the 3D Object position by clicking on the object. I added a Box Collider in the object and I'm calling the following method.
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            foreach (GameObject child in floorTiles) {
                BoxCollider box = child.GetComponentInChildren<BoxCollider>();

                if (hit.transform.name.Equals(box.name))
                {

                    handleOnMouseDown(hit.collider);
                }
            }
        }
    }
}

floorTiles is an array of GameObjects.
If I hit one of these objects the below function is called:
void handleOnMouseDown(Collider box)
{
    GameObject parent = box.transform.parent.gameObject;
    Vector3 position = parent.transform.position;

    positionX.GetComponent<TextMeshProUGUI>().text = position.x.ToString();

    posXButtonPlus.GetComponent<Button>().onClick.AddListener(() => handleOnChangePosition("posx", parent));
}

This works, however, when I click many objects, all the last objects clicked also keep changing their positions. How can I change one position per time?

A: Each click on an object, adds listener to your button, but you don't ever remove listeners. You end up with multiple listeners, that's why more objects are moved than intended.
You could remove listener after each button click, but that seems like a total overkill.
Instead of adding multiple listeners, consider adding just one which will remember the last clicked object, and clicking your button will move only that object.
Also, if you want to move objects just by clicking on them, not on button click, you can simplify all these, and move the object directly in handleOnMouseDown.
Remove listeners variant:
void handleOnMouseDown(Collider box)
{
    posXButtonPlus.GetComponent<Button>().onClick.AddListener(() => handleOnChangePosition("posx", box.gameObject));
}

void handleOnChangePosition(string pos, GameObject go)
{
    // I don't have code for moving, but I imagine looks something like this. right * 0.5f can be anything, did it just for tests.
    go.transform.position += Vector3.right * 0.5f;

    posXButtonPlus.GetComponent<Button>().onClick.RemoveAllListeners();
}

Last clicked variant:
GameObject lastClicked;

void Awake()
{
    posXButtonPlus.GetComponent<Button>().onClick.AddListener(() => handleOnChangePosition());
}
void handleOnMouseDown(Collider box)
{
    lastClicked = box.gameObject;

}

void handleOnChangePosition()
{
    lastClicked.transform.position += Vector3.right * 0.5f;
}

Without buttons and other stuff:
void handleOnMouseDown(Collider box)
{
    box.transform.position += Vector3.right * 0.5f;
}


Q: Apply a shadow to a fitted image with Tailwind CSS I wrote this code:

It gives this result:

But I want the shadow to apply to the image, not to the box that the image fits in.

A: Try to add drop-shadow instead of shadow

A: You can instead just extend the theme and use tailwind internal custom properties to get the color you want for the shadow.
here is an example in play.tailwind.
EDIT: Tailwind sample code into a snipet

/* ! tailwindcss v3.2.6 | MIT License | https://tailwindcss.com */

/*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/

*,
::before,
::after {
  box-sizing: border-box;
  /* 1 */
  border-width: 0;
  /* 2 */
  border-style: solid;
  /* 2 */
  border-color: #e5e7eb;
  /* 2 */
}

::before,
::after {
  --tw-content: '';
}

/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
5. Use the user's configured `sans` font-feature-settings by default.
*/

html {
  line-height: 1.5;
  /* 1 */
  -webkit-text-size-adjust: 100%;
  /* 2 */
  -moz-tab-size: 4;
  /* 3 */
  tab-size: 4;
  /* 3 */
  font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
  /* 4 */
  font-feature-settings: normal;
  /* 5 */
}

/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/

body {
  margin: 0;
  /* 1 */
  line-height: inherit;
  /* 2 */
}

/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/

hr {
  height: 0;
  /* 1 */
  color: inherit;
  /* 2 */
  border-top-width: 1px;
  /* 3 */
}

/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/

abbr:where([title]) {
  -webkit-text-decoration: underline dotted;
          text-decoration: underline dotted;
}

/*
Remove the default font size and weight for headings.
*/

h1,
h2,
h3,
h4,
h5,
h6 {
  font-size: inherit;
  font-weight: inherit;
}

/*
Reset links to optimize for opt-in styling instead of opt-out.
*/

a {
  color: inherit;
  text-decoration: inherit;
}

/*
Add the correct font weight in Edge and Safari.
*/

b,
strong {
  font-weight: bolder;
}

/*
1. Use the user's configured `mono` font family by default.
2. Correct the odd `em` font sizing in all browsers.
*/

code,
kbd,
samp,
pre {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  /* 1 */
  font-size: 1em;
  /* 2 */
}

/*
Add the correct font size in all browsers.
*/

small {
  font-size: 80%;
}

/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/

sub,
sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}

sub {
  bottom: -0.25em;
}

sup {
  top: -0.5em;
}

/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/

table {
  text-indent: 0;
  /* 1 */
  border-color: inherit;
  /* 2 */
  border-collapse: collapse;
  /* 3 */
}

/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/

button,
input,
optgroup,
select,
textarea {
  font-family: inherit;
  /* 1 */
  font-size: 100%;
  /* 1 */
  font-weight: inherit;
  /* 1 */
  line-height: inherit;
  /* 1 */
  color: inherit;
  /* 1 */
  margin: 0;
  /* 2 */
  padding: 0;
  /* 3 */
}

/*
Remove the inheritance of text transform in Edge and Firefox.
*/

button,
select {
  text-transform: none;
}

/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/

button,
[type='button'],
[type='reset'],
[type='submit'] {
  -webkit-appearance: button;
  /* 1 */
  background-color: transparent;
  /* 2 */
  background-image: none;
  /* 2 */
}

/*
Use the modern Firefox focus style for all focusable elements.
*/

:-moz-focusring {
  outline: auto;
}

/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/

:-moz-ui-invalid {
  box-shadow: none;
}

/*
Add the correct vertical alignment in Chrome and Firefox.
*/

progress {
  vertical-align: baseline;
}

/*
Correct the cursor style of increment and decrement buttons in Safari.
*/

::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
  height: auto;
}

/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/

[type='search'] {
  -webkit-appearance: textfield;
  /* 1 */
  outline-offset: -2px;
  /* 2 */
}

/*
Remove the inner padding in Chrome and Safari on macOS.
*/

::-webkit-search-decoration {
  -webkit-appearance: none;
}

/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/

::-webkit-file-upload-button {
  -webkit-appearance: button;
  /* 1 */
  font: inherit;
  /* 2 */
}

/*
Add the correct display in Chrome and Safari.
*/

summary {
  display: list-item;
}

/*
Removes the default spacing and border for appropriate elements.
*/

blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
  margin: 0;
}

fieldset {
  margin: 0;
  padding: 0;
}

legend {
  padding: 0;
}

ol,
ul,
menu {
  list-style: none;
  margin: 0;
  padding: 0;
}

/*
Prevent resizing textareas horizontally by default.
*/

textarea {
  resize: vertical;
}

/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/

input::placeholder,
textarea::placeholder {
  opacity: 1;
  /* 1 */
  color: #9ca3af;
  /* 2 */
}

/*
Set the default cursor for buttons.
*/

button,
[role="button"] {
  cursor: pointer;
}

/*
Make sure disabled buttons don't get the pointer cursor.
*/

:disabled {
  cursor: default;
}

/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
   This can trigger a poorly considered lint error in some tools but is included by design.
*/

img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
  display: block;
  /* 1 */
  vertical-align: middle;
  /* 2 */
}

/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/

img,
video {
  max-width: 100%;
  height: auto;
}

/* Make elements with the HTML hidden attribute stay hidden by default */

[hidden] {
  display: none;
}

*, ::before, ::after {
  --tw-border-spacing-x: 0;
  --tw-border-spacing-y: 0;
  --tw-translate-x: 0;
  --tw-translate-y: 0;
  --tw-rotate: 0;
  --tw-skew-x: 0;
  --tw-skew-y: 0;
  --tw-scale-x: 1;
  --tw-scale-y: 1;
  --tw-pan-x:  ;
  --tw-pan-y:  ;
  --tw-pinch-zoom:  ;
  --tw-scroll-snap-strictness: proximity;
  --tw-ordinal:  ;
  --tw-slashed-zero:  ;
  --tw-numeric-figure:  ;
  --tw-numeric-spacing:  ;
  --tw-numeric-fraction:  ;
  --tw-ring-inset:  ;
  --tw-ring-offset-width: 0px;
  --tw-ring-offset-color: #fff;
  --tw-ring-color: rgb(59 130 246 / 0.5);
  --tw-ring-offset-shadow: 0 0 #0000;
  --tw-ring-shadow: 0 0 #0000;
  --tw-shadow: 0 0 #0000;
  --tw-shadow-colored: 0 0 #0000;
  --tw-blur:  ;
  --tw-brightness:  ;
  --tw-contrast:  ;
  --tw-grayscale:  ;
  --tw-hue-rotate:  ;
  --tw-invert:  ;
  --tw-saturate:  ;
  --tw-sepia:  ;
  --tw-drop-shadow:  ;
  --tw-backdrop-blur:  ;
  --tw-backdrop-brightness:  ;
  --tw-backdrop-contrast:  ;
  --tw-backdrop-grayscale:  ;
  --tw-backdrop-hue-rotate:  ;
  --tw-backdrop-invert:  ;
  --tw-backdrop-opacity:  ;
  --tw-backdrop-saturate:  ;
  --tw-backdrop-sepia:  ;
}

::backdrop {
  --tw-border-spacing-x: 0;
  --tw-border-spacing-y: 0;
  --tw-translate-x: 0;
  --tw-translate-y: 0;
  --tw-rotate: 0;
  --tw-skew-x: 0;
  --tw-skew-y: 0;
  --tw-scale-x: 1;
  --tw-scale-y: 1;
  --tw-pan-x:  ;
  --tw-pan-y:  ;
  --tw-pinch-zoom:  ;
  --tw-scroll-snap-strictness: proximity;
  --tw-ordinal:  ;
  --tw-slashed-zero:  ;
  --tw-numeric-figure:  ;
  --tw-numeric-spacing:  ;
  --tw-numeric-fraction:  ;
  --tw-ring-inset:  ;
  --tw-ring-offset-width: 0px;
  --tw-ring-offset-color: #fff;
  --tw-ring-color: rgb(59 130 246 / 0.5);
  --tw-ring-offset-shadow: 0 0 #0000;
  --tw-ring-shadow: 0 0 #0000;
  --tw-shadow: 0 0 #0000;
  --tw-shadow-colored: 0 0 #0000;
  --tw-blur:  ;
  --tw-brightness:  ;
  --tw-contrast:  ;
  --tw-grayscale:  ;
  --tw-hue-rotate:  ;
  --tw-invert:  ;
  --tw-saturate:  ;
  --tw-sepia:  ;
  --tw-drop-shadow:  ;
  --tw-backdrop-blur:  ;
  --tw-backdrop-brightness:  ;
  --tw-backdrop-contrast:  ;
  --tw-backdrop-grayscale:  ;
  --tw-backdrop-hue-rotate:  ;
  --tw-backdrop-invert:  ;
  --tw-backdrop-opacity:  ;
  --tw-backdrop-saturate:  ;
  --tw-backdrop-sepia:  ;
}

.m-6 {
  margin: 1.5rem;
}

.inline-block {
  display: inline-block;
}

.h-\[200px\] {
  height: 200px;
}

.h-full {
  height: 100%;
}

.w-\[200px\] {
  width: 200px;
}

.w-full {
  width: 100%;
}

.space-x-3 > :not([hidden]) ~ :not([hidden]) {
  --tw-space-x-reverse: 0;
  margin-right: calc(0.75rem * var(--tw-space-x-reverse));
  margin-left: calc(0.75rem * calc(1 - var(--tw-space-x-reverse)));
}

.object-contain {
  object-fit: contain;
}

.shadow-blue-400 {
  --tw-shadow-color: #60a5fa;
  --tw-shadow: var(--tw-shadow-colored);
}

.shadow-gray-600 {
  --tw-shadow-color: #4b5563;
  --tw-shadow: var(--tw-shadow-colored);
}

.drop-shadow-custom {
  --tw-drop-shadow: drop-shadow(0 5px 5px var(--tw-shadow-color));
  filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
}


Q: How to validate file type in java I have created a text file with some content. I changed its extension to .xlsx.
I used this code to validate file-
String filepath = "C:\\Users\\prabhat.sameer\\Desktop\\test.xlsx";
File f = new File(filepath);
String mimetype= new MimetypesFileTypeMap().getContentType(f);
String type = mimetype.split("/")[0];
System.out.println("type " + type);
if (type.equals("text")) {
    System.out.println("It's an text file");
} else {
    System.out.println("It's NOT an text file");
}

Its content type also changed with change of extension. How to validate this?

A: If you open the file by double-clicking on it, are you able to read the data?  Usually a special library like POI is required to write to excel so I would be surprised if it does.
If your txt file has data in csv(comma separated) format, then changing the extension to .csv should work for you.


Q: PhpStorm can't resolve @ionic/angular I've got an Ionic v4 project that is running fine, but PhpStorm cannot find my references to @ionic.

It looks like the code is actually in the /dist directory, so if I change the reference to:
import { NavController } from '@ionic/angular/dist'

PhpStorm doesn't complain and I get code completion features for @ionic/angular.
However, when running ng serve the project won't compile and I get errors in the console:
ERROR in ./src/app/pages/home/home.component.ts
Module not found: Error: Can't resolve '@ionic/angular/dist'

How can I fix this?
Why does project compile when not specifying /dist?

Edit:
In PhpStorm, the entire node_modules directory is excluded, but not specifically the @ionic/angular.  Note, references to other modules are working fine.

Edit 2:
Here's how the folder coloring shows up:

*

*@ionic/angular doesn't work

*@ionic-native/core works

*@angular/core works

A: I thought I'd share the workaround that I ended up using.
I just added an index.d.ts file in the node_modules/@ionic/angular/ directory, with the following contents:
export * from './dist';

Of course it isn't ideal to modify the contents of your dependencies, but this simple fix keeps my IDE from driving me crazy... :-)


Q: Overloading constructor with 2 same datatype members lets say i have a class with two std::string member and one int value, like:
class DataGroup final {
 public:
  explicit DataGroup (const std::vector<int>& groupNr,
                                   const std::string& group1,
                                   const std::string& group2)
      : groupNr(groupNr)
      , group1(group1)
      , group2(group2){};

  std::vector<int> groupNrs{};
  std::string group1{};
  std::string group2{};
};

Can i somehow have 2 overloaded constructors where one will initialize groupNr and group1, and other ctor initializes groupNr and group2 ? One of the strings not initialized in ctor call would be empty string then.

A: There are several way to have expected behavior:

*

*Named constructor
class DataGroup final {
public:
    // ...
    static DataGroup Group1(const std::vector<int>& groupNr,
                      const std::string& group)
      { return DataGroup{groupNr, group, ""}; }
    static DataGroup Group2(const std::vector<int>& groupNr,
                      const std::string& group)
      { return DataGroup{groupNr, "", group}; }

    // ...
};

DataGroup d = DataGroup::Group2({1, 2}, "MyGroup");

*Tagged constructor
struct group1{};
struct group2{};
class DataGroup final {
public:
    // ...
    DataGroup(group1, const std::vector<int>& groupNr,
                      const std::string& group) : DataGroup{groupNr, group, ""} {}
    DataGroup(group2, const std::vector<int>& groupNr,
                      const std::string& group) : DataGroup{groupNr, "", group} {}

    // ...
};

DataGroup d{group2{}, {1, 2}, "MyGroup");

*named parameters (see there for possible implementation)
// ...
DataGroup d{groupNr = {1, 2}, group2 = "MyGroup");

A: For overloading a function/constructor, they must have 2 distinct signatures. Since your intended types to be supplied are the same for both cases, you have to supply a 3rd parameter with a possibly default value for one of them. But again, watch for uninitialized local fields, since they will be auto-initialized by the compiler-generated code.

A: One of the solutions here would be to simply have base class with "common" member
groupNr(groupNr)

and other two separate member have in each derived class, then you would initialize base member groupNr by calling constructor of base class when initializing derived one:
class DataGroup {
 public:
  explicit DataGroup (const std::vector<int>& groupNrs)
      : groupNrs(groupNr){};

  std::vector<int> groupNrs{};
};

class DataGroup1 : public DataGroup {
 public:
  explicit DataGroup1 (const std::vector<int>& groupNrs,
                                   const std::string& group1)
      : DataGroup(groupNrs)
      , group1(group1){};

  std::string group1{};
};

class DataGroup2 : public DataGroup {
 public:
  explicit DataGroup2 (const std::vector<int>& groupNrs,
                                   const std::string& group2)
      : DataGroup(groupNrs)
      , group2(group2){};

  std::string group2{};
};


Q: RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PublicKey.Key does not work in .NET Core I have an assembly compiled with .NET Framework 2.0 (yes, pretty old stuff) which performs encryption with a certificate's public key. The code is extremely simple:
X509Certificate2 objCert = new X509Certificate2(path);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;
byte [] EncrRes = rsa.Encrypt(data, false);

This continues to work with all recent versions of .NET Framework, but refuses to work under .NET Core. I got two different but similar error messages.
Windows 10:
Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'.
Linux:
Unable to cast object of type 'System.Security.Cryptography.RSAOpenSsl' to type 'System.Security.Cryptography.RSACryptoServiceProvider'.
Is there a way to code this simple operation so that it would work on both .NET Framework 2.0+ and .NET core?
Thanks in advance.

A: In .NET Core, X509Certificate2.PublicKey.Key and X509Certificate2.PrivateKey use platform-specific implementation of key. On Windows, there are two implementations, legacy RSACryptoServiceProvider and modern RSACng.
You have to change the way how you access these properties. And do not access them. Instead, use extension methods: X509Certificate2 Extension Methods. They return safe abstract classes you shall use. Do not try to use explicit cast to anything. For RSA keys use RSA class and so on.
X509Certificate2 objCert = new X509Certificate2(path);
// well, it is reasonable to check the algorithm of public key. If it is ECC,
// then call objCert.GetECDsaPublicKey()
RSA rsa = objCert.GetRsaPublicKey();
byte [] EncrRes = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);

A: Figured it out on my own. Instead of
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;

do
RSA rsa_helper = (RSA)objCert.PublicKey.Key;
RSAParameters certparams = rsa_helper.ExportParameters(false);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters paramcopy = new RSAParameters();
paramcopy.Exponent = certparams.Exponent;
paramcopy.Modulus = certparams.Modulus;
rsa.ImportParameters(paramcopy);

Works with .NET 2.0+ and .NET Core!


Q: Why technically does ScrewTurn uses .ashx to create wiki page? Why ScrewTurn Wiki does use ashx type to create wiki page? Isn't it dangerous to create asp.net page on the fly?
update:  they didn't create any physical pages. But how do they do that because the url is actually some-newpage.ashx ?

A: I think it uses the .ashx to 1.) trigger the use of the ASP.NET isapi filter and 2.) signal that the requests aren't mapped to any physical files, but URLs mapped to logical pages within the Wiki engine.
And I don't think it's dangerous to create ASP.NET page responses on the fly, which is essentially what they do. It's actually a quite brilliant way to let you, the user of the system, build up the hierarchy of the web site.

A: Does it actually really craete pages on the fiy on disc?
An ashx is a handler. It returns output as it wants. You can have a CMS that exposes it's tree thruogh a .ashx in between (/cms.ashx/some/page) but the pages NEVER EXIST.


Q: How to connect sockets and receive Data? I am new to sockets, I was hoping someone knows how to connect sockets on Android Studio and receive data.
This is the websocket which uses socket.io that I am trying to receive data from: https://ws-api.iextrading.com/1.0/stock/aapl/quote
This is a link to the API which explains the websocket: https://iextrading.com/developer/docs/#websockets
I am trying to get realtime stock data for my app, but I do not know how to connect to the socket then receive the data and my app crashes before it even opens, this is my code so far:
package com.example.android.stocksApp;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    private static Socket s;
    private static InputStreamReader isr;
    private static BufferedReader br;

    TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        result = (TextView)findViewById(R.id.result);

        stockData();

    }

    public void stockData (){
        myTask mTask = new myTask();
        mTask.execute();
    }

    class myTask extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... params) {
            try {
                s = new Socket("https://ws-api.iextrading.com/1.0/stock/aapl/quote", 80);
                InputStream is = s.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String quote = br.readLine();
                result.setText(quote);
                s.close();
                is.close();
                isr.close();
                br.close();

            } catch (IOException e){
                e.printStackTrace();
            }

            return null;
        }
    }
}

A: You're trying to connect to a Web service. Web services may return either a XML or JSON. The actual Socket library isn't needed nor used for this. This specific web service returns a JSON, so what you need is a library that is capable of making a GET request to this URL and parse the response. For Android, I recommend using Volley. You can include Volley in your project by adding this line to your build.gradle.
implementation 'com.android.volley:volley:1.0.0'

This question might help you get started.


Q: How can I use HttpClient-4.5 against a SOCKS proxy? How can I use a ClosableHttpClient from HttpClient-4.5 over a configured SOCKS proxy? Is there a way to accomplish this without specifying a global SOCKS proxy with java -DsocksProxyHost or setting a custom default ProxySelector?
The explicit documention about proxies, is as far as I understand only about HTTP proxies (which I imply by defining such a proxy as HttpHost). For me it looks like "Connection socket factories" is more relevant.


Q: why won't my text area show up I'm trying to implement a program where the client will send a fix message to the server side, and the UI I have for the server side will show up the FIX message on the text area.
However when I start the program, the textfields and all the labels will show, except the text area.  And when I try send a message from the client side, everything works besides the text area.
code
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Scanner;
    import java.util.StringTokenizer;
    import java.awt.*;        // using AWT containers and components
    import java.awt.event.*;  // using AWT events and listener interfaces

    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;

    public class TcpServerCompareCSV extends Frame implements ActionListener , WindowListener  {

           private Label lblPort;       // declare component Label
           private TextField tfPort;    // declare component TextField
           private int port;            // port number

           private Label lblLocation;       // declare component Label
           private TextField tfLocation;    // declare component TextField
           private String fileLocation;     // csv file location

           private Button btnCount;   // declare component Button            //________________________________________________________________________________\\

           private Label lblCSVLine;        // declare component Label from csv file line, server side
           private TextField tfCSVLine;     // declare component TextField  from csv file line, server side
           private String CSVLine;          // port number

           private Label lblFIXMsg;     // declare component Label from csv file line, server side
           private JTextArea tfFIXMsg;  // declare component TextField  from csv file line, server side
           private String FIXMsg;           // port number
           private JScrollPane jScrollPane1;//________________________________________________________________________________\\
           /** WindowEvent handlers */
           // Called back upon clicking close-window button
           @Override
           public void windowClosing(WindowEvent e) {
              System.exit(0);  // terminate the program
           }

           //constructor for frame
           public TcpServerCompareCSV () {
              setLayout(new FlowLayout());
                 // "this" Frame sets its layout to FlowLayout, which arranges the components
                 //  from left-to-right, and flow to next row from top-to-bottom.

              lblPort = new Label("Port");          // construct Label
              add(lblPort);                         // "this" Frame adds Label

              tfPort = new TextField("0", 40);  // construct TextField
              tfPort.setEditable(true);         //edit text
              add(tfPort);                      // "this" Frame adds tfCount
           //   tfPort.addActionListener(this);     // for event-handling

              lblLocation = new Label("CSV File Location"); // construct Label
              add(lblLocation);                             // "this" Frame adds Label

              tfLocation = new TextField("text", 40);       // construct TextField
              tfLocation.setEditable(true);                 //edit text
              add(tfLocation);                              // "this" Frame adds tfCount
          //________________________________________________________________________________\\

              setTitle("compare");      // "this" Frame sets title
              setSize(800,200);        // "this" Frame sets initial window size
              setVisible(true);         // "this" Frame shows

              lblCSVLine = new Label("CSV Line");           // construct Label
              add(lblCSVLine);                              // "this" Frame adds Label

              tfCSVLine = new TextField("text", 40);        // construct TextField
              tfCSVLine.setEditable(false);                 //edit text
              add(tfCSVLine);                               // "this" Frame adds tfCount

              lblFIXMsg = new Label("FIX message from client");             // construct Label
              add(lblFIXMsg);                               // "this" Frame adds Label

              tfFIXMsg = new JTextArea();       // construct TextField
              tfFIXMsg.setColumns(20);
              tfFIXMsg.setLineWrap(true);
              tfFIXMsg.setRows(50);
              tfFIXMsg.setWrapStyleWord(true);
              tfFIXMsg.setEditable(false);                  //edit text
              add(tfFIXMsg);                                // "this" Frame adds tfCount

              jScrollPane1 = new JScrollPane(tfFIXMsg);

  add(jScrollPane1);

              btnCount = new Button("Enter"); // construct Button
              add(btnCount);                  // "this" Frame adds Button
              btnCount.addActionListener(this); // for event-handling
              addWindowListener(this);
                // "this" Frame fires WindowEvent its registered WindowEvent listener
                // "this" Frame adds "this" object as a WindowEvent listener

           }

           /** ActionEvent handler - Called back when user clicks the button. */
           @Override
           public void actionPerformed(ActionEvent evt) {
            // Get the String entered into the TextField tfPort, convert to int
              port = Integer.parseInt(tfPort.getText());
              fileLocation = tfLocation.getText();
              String csvName = fileLocation;
            /*
            Scanner console = new Scanner(System.in);
            System.out.println("Type in CSV file location: ");
                //String csvName = console.nextLine();
                String csvName = "C:\\Users\\I593458\\Downloads\\orders.csv";

    */
          ServerSocket serverSocket = null;

          try {
               serverSocket = new ServerSocket(port);
              }
          catch (IOException e)
              {
               System.err.println("Could not listen on port: 57635.");
               System.exit(1);
              }
          Socket clientSocket = null;
          System.out.println ("Waiting for connection.....");
          try {
               clientSocket = serverSocket.accept();
              }
          catch (IOException e)
              {
               System.err.println("Accept failed.");
               System.exit(1);
              }
          System.out.println ("Connection successful");
          System.out.println ("Waiting for input.....");

          PrintWriter out = null;
        try {
            out = new PrintWriter(clientSocket.getOutputStream(),
                                                true);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          BufferedReader in = null;
        try {
            in = new BufferedReader(
                      new InputStreamReader( clientSocket.getInputStream()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

          String inputLine, outputLine;
          try {
            while ((inputLine = in.readLine()) != null)
                  {
                   System.out.println ("Server: " + inputLine);
                   tfFIXMsg.setText(inputLine);
                   if (inputLine.trim().equals("Bye.")) {
                       System.out.println("Exit program");
                       break;
                       }
                   Scanner input1 = new Scanner(new File(csvName));
                   Scanner input2 = new Scanner(new File(csvName));
                   Scanner input3 = new Scanner(new File(csvName));
                   Scanner input4 = new Scanner(new File(csvName));

                   String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1,  input2)), getCSVLine( input3,  input4) );
                   outputLine = compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));
                   out.println(outputLine);
                   tfCSVLine.setText(outputLine);
                   input1.close();
                   input2.close();
                   input3.close();
                   input4.close();
                  }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

          out.close();
          try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          try {
            clientSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          try {
            serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  }

A: You add the textArea to a JScrollPane, and then never do anything with the pane.
jScrollPane1 = new JScrollPane(tfFIXMsg);
You need add(jScrollPane1);


Q: PromiseKit flatMapError ReactiveSwift has this great function called flatMapError that allows you to respond with an event stream when an error occurs. A simple example might look like:
authenticationProducer.flatMapError { _ in self.reauthenticate() }

Whenever an error occurs, that error gets mapped into a producer that attempts to re-authenticate.
How would I build a similar operator using PromiseKit? The function signature would look like:
func flatMapError<U>(_ transform: @escaping (Error) -> Promise<U>) -> Promise<U>

My implementation so far:
func flatMapError<U>(_ transform: @escaping (Error) -> Promise<U>) -> Promise<U> {
    return Promise<U> { resolve, reject in
        self.catch { error in
            let promise = transform(error)
            let _ = promise.then { value in
                resolve(value)
            }
        }
    }
}

A: Use recover, it behaves as you request.
https://github.com/mxcl/PromiseKit/blob/master/Sources/Promise.swift#L254-L278


Q: Is it possible to use pattern matching on functions in python? Like, a function that will respond to multiple calls I am trying to make a class that acts like a list. However, I would like to be able to use all of the built-in list repr() functions and such, Is there any way to do something like this:
class myList:
  ...
  def __getitem__(self, index):
    #custom getitem function
  def __setitem(self,index,value):
    #custom setitem function
  def toList(self):
    #returns a list

  #and a catch-all case:
  def __*__(*args):
    return self.toList().__*__(*args)

So, My question is, is it possible to make a catch-all case for something like that in python, to catch things like __repr__, __str__, __iter__, etc.
Thanks!

A: It’s not possible to trap such calls with a single method, in CPython at least.  While you can define special methods like __getattr__, even defining the low-level __getattribute__ on a metaclass doesn’t work because the interpreter scans for special method names to build a fast lookup table of the sort used by types defined in C.  Anything that doesn’t actually possess such individual methods will not respond to the interpreter’s internal calls (e.g., from repr).
What you can do is dynamically generate (or augment, as below) a class that has whatever special methods you want.  The readability of the result might suffer too much to make this approach worthwhile:
def mkfwd(n):
  def fwd(self,*a): return getattr(self.toList(),n)(*a)
  return fwd
for m in "repr","str":
  m="__%s__"%m
  setattr(myList,m,mkfwd(m))


Q: OpenGL glTexImage2D cube map and width/height parameters I am trying to setup shadow mapping in OpenGL using cube maps so I can do shadows for point lights.
The following throws a GL_INVALID_ENUM at me:
for (uint32_t i = 0; i < 6; i++)
    GLCALL(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT32, windowWidth, windowHeight, 0, GL_DEPTH_COMPONENT32, GL_FLOAT, 0));

According to the docs, it is probably because of this:
GL_INVALID_ENUM is generated if target is one of the six cube map 2D image targets and the width and height parameters are not equal.

And I get if the width/height are different, they aren't really a cube, but when I have a screen resolution like 1920x1080 or any other resolution this is a problem.
Perhaps though I have missunderstod what to supply to the function call - isn't it the window width/height? What are the parameters supposed to be?

A:
Perhaps though I have missunderstod what to supply to the function call - isn't it the window width/height?

How in the world you think that the window resolution influences texture sizes is beyond me. You normally render shadow mapping depth maps using a framebuffer object, so the window dimensions are irrelevant.

What are the parameters supposed to be?

For a cube map: The edge length of the cube map texture.


Q: Granular error handling in Passport authenticate I am authenticating a user in a REST call and I implement a custom callback as explained in the docs.
app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    //.. do something with user here and send a response
  })(req, res, next);
});

Now I would like to pass an error if some validation failed in the strategy.
passport.use(new BasicStrategy(
function(email, password, callback) {

User.findOne({
  email: email
}, function(err, user) {
  if (err) {
    return callback(err);
  }

  if (!user) {
    return callback(new Error('User unknown'), false);
  }

  // Make sure the password is correct
  user.verifyPassword(password, function(err, isMatch) {
    if (err) {
      return callback(err);
    }

    // Password did not match
    if (!isMatch) {
      return callback(new Error('Password mismatch'), false);
    }

    // Success
    return callback(null, user);
  });
});

}
But the error is never passed to the callback in authenticate:
function(err, user, info) {
     // err is always null
}

How can I pass an error so I can give more granuate feedback to users?

A: I found two issues with your code. The first one is that you request for 'local' authentication strategy while you register a BasicStrategy. In order to do that you should replace 'local' with 'basic'.
The second one is that, if you want to use the BasicStrategy, you have to use the Base Authentication supported by the HTTP protocol, otherwise the BasicStrategy's callback will not be called and your authentication callback will run with err == null and user == false.
I tested this with Postman, and only after I sent Basic Auth info, did the BasicStrategy callback run.
I hope this helps.


Q: Fixed row on the bottom of grid
I have summary row in my table. But user can see it only when he will scroll down all grid. But it could be better, if summary row will be fixed at the bottom of the grid, and it will be visible always, when the grid is shown. How can I modify it?

A: I'm not sure how to fix a row like you're suggesting, but for something that needs to be visible 100% of the time, have you thought about adding a top bar or a bottom bar that displays these values?  You can use the displayfield xtype to show text in such a place.  I'm doing this in several projects.


Q: How to move database calls to application server behind a firewall I would like to use BreezeJS for data access in a Durandal SPA.  I have the initial app set up and working fine and uses a MVC 5 backend.
However, one of the requirements is that the public IIS server is not making calls directly to the database.  In other words, the Breeze controller should call another IIS server which is behind a firewall which then connects to Sql Server.
Is this possible, and if so, what is the basic architecture?


Q: Handling IAP Fullfilment results for Windows 10 Store When providing consumable In App Purchases on the Windows 10 Store, there are FullfillmentResults when ReportConsumableFullfillmentAsync is called.
The user of my app has had their IAP fullfilled by the time I get this result. This means they have their Coins/Gems/Potatoes.
But if I receive FulfillmentResult.PurchaseReverted, then what happened? How did the user just revert the purchase? Am I meant to withdraw their Coins/Gems/Potatoes?
What are scenarios behind the other error messages?
Note: I'm working with using Windows.ApplicationModel.Store

A:
But if I receive FulfillmentResult.PurchaseReverted, then what
  happened? How did the user just revert the purchase? Am I meant to
  withdraw their Coins/Gems/Potatoes?

The value PurchaseReverted means the transaction is canceled on the backend and users get their money back. So you should disable the user's access to the cosumable content (withdraw the Coins/Gems/Potatoes) as necessary.

What are scenarios behind the other error messages?

NothingToFulfill : The transaction id has been fulfilled or is otherwise complete
PurchasePending: The purchase is not complete. At this point it is still possible for the transaction to be reversed due to provider failures and/or risk checks. It means the purchase has not yet cleared and could still be revoked.
ServerError: There was an issue receiving fulfillment status. It might be the problem from the Store.
Succeed: The fulfillment is complete and your Coins/Gems/Potatoes can be offered again.
Here is the documentation about FulfillmentResult Enum


Q: Laravel elements in queue are processed multiple times We use the Laravel Redis Queue and a supervisor setup with multiple parallel running workers. Sometimes it happens that one element in the queue get processed multiple times.
Is there a trick, like a flag i can set or something else to avoid this behavior?

A: This is because the job messages become available for other consumers.

In your config/queue.php configuration file, each queue connection
  defines a retry_after option. This option specifies how many seconds
  the queue connection should wait before retrying a job that is being
  processed. For example, if the value of retry_after is set to 90, the
  job will be released back onto the queue if it has been processing for
  90 seconds without being deleted. Typically, you should set the
  retry_after value to the maximum number of seconds your jobs should reasonably take to complete processing.

See https://laravel.com/docs/5.7/queues#queue-workers-and-deployment
When a consumer receives and processes a message from a queue, the message remains in the queue. The queue doesn’t automatically delete the message. Because a queue is a distributed system, there’s no guarantee that the consumer actually receives the message (for example, due to a connectivity issue, or due to an issue in the consumer application). Therefore, the consumer must delete the message from the queue after receiving and processing it. Immediately after a message is received, it remains in the queue. To prevent other consumers from processing the message again, you should set the retry_after value to the maximum number of seconds your jobs should reasonably take to complete processing.
For Amazon SQS:
The only queue connection which does not contain a retry_after value is SQS. SQS will retry the job based on the Default Visibility Timeout which is managed within the AWS console. Amazon SQS sets a visibility timeout, a period of time during which Amazon SQS prevents other consumers from receiving and processing the message. The default visibility timeout for a message is 30 seconds.This means that other consumers can see and pickup the message again after 30 seconds.

A: If there is an exception or the job inexplicably fails, the job will automatically be retried. This will occur even if most of the job has already ran.


Q: Does it have closed form solution of KL Divergence between Logistic Distributions? KL Divergence between Gaussian Distributions
As above Figure, KL divergence between Gaussian distributions has closed-form solution.
Does it have closed form solution of KL Divergence between Logistic Distributions(https://en.wikipedia.org/wiki/Logistic_distribution)?


Q: how to detect which level on the dom is selected I have the following selector
$('#navigation ul li a').click(function(evt) {}
this get the elements i need, but also retries child elements.
ie i get me this as well
#navigation ul li li a  // extra li

Just wondering the best way to detect what level of the dom i am selecting.

A: You can use the > which is a parent > child selector ..
look at Child Selector (“parent > child”)
you could use it something like this
$('#navigation>ul>li>a')


Q: parseerror SyntaxError: Unexpected token < in JSON at position 1 I have an error: Unexpected token and uncaught in the promise in my code below.
function getReportData(type,shutdown,period){
    var applyButton = $("#apply-filter");
    var textApplyButton = applyButton.html();
    applyButton.attr("disabled", true);
    applyButton.html("Loading...");
    startStamp = new Date().getTime();
    $("#title-card").text("Loading Data..");
    timerInterval = setInterval(updateInterval, 1000);
    gridOptions.api.showLoadingOverlay();
    $.ajax({
        method: "POST",
        url: "<?php echo base_url();?>api/reportApi/getPRLinesAll",
        data: {type:type,shutdown:shutdown,period:period},
        dataType : 'json',
        headers:{api_key:"@scm-report@123"},
        success : function(data){
            var resData = data.data;
            var columnsData = resData.columns;
            var rowsData = resData.rows;
            var lastUpdate = data.last_update;
            var excelStyleData = resData.excelStyle;

            totalData = rowsData.length;
            gridOptions.api.setColumnDefs(columnsData);
            gridOptions.api.setRowData(rowsData);
            gridOptions.excelStyles = excelStyleData;
            autoSizeAll();

            if(totalData<=0){
                gridOptions.api.showNoRowsOverlay();
            }

            fileNameExcel = generateFileName(lastUpdate);
            $("#update-progress").html("Last Update on : "+lastUpdate+"");
        },
        complete: function(jqXHR,textStatus){
            gridOptions.api.hideOverlay();
            applyButton.attr("disabled", false);
            applyButton.html(textApplyButton);
            clearInterval(timerInterval);
        },
        error: function(httpRequest, textStatus, errorThrown){
            console.log("Error: " + textStatus + " " + errorThrown + " " + httpRequest);
            $("#update-progress").html("Something Error, Please Try Again");
            $("#title-card").text("Error happened...");
        }
    });
}

Error: parsererror SyntaxError: Unexpected token < in JSON at position 1 [object Object]
10.35.2.199/:1 Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
10.35.2.199/:1 Uncaught (in promise) {message: 'A listener indicated an asynchronous response by r…age channel closed before a response was received'}


Q: How can I get only the object with my arrays returned from a function with a promise? I want the data in res passed to my notes variable. But it's returning a bigger nested object. Why is it happening?
If I inspect in the console the value of cleanArrayOfNotes I get the object that I want, but once its assigned to notes it  becomes a quite bigger object. I understand it's part of the nature of the Promises, which at the moment I still trying to understand. Any help?
notes_service.js
var notesService = {notesObjectInService: [], newNote: null};

    notesService.getAll = function() {
        return $http.get('/notes.json').success(function(data){
            //console.log(data)
            angular.copy(data, notesService.notesObjectInService);
            //console.log(notesService)
        })
    };

navCtrl.js
var notes = notesService.getAll().then(function(res){

            var cleanArrayOfNotes = res.data;
            //navCtrl line12
            console.log(cleanArrayOfNotes);
            return cleanArrayOfNotes;
        });
        //navCtrl line16
        console.log(notes);

A: This should work for you:
notes_service.js
app.factory ('NoteService', function($http) {
    return {
        getAll: function() {
            return $http.get('/notes.json').then(function(response) {
                  return response.data;
            });
        }
    }
});

navCtrl.js
    NotesService.getAll().then(function(res){

        $scope.cleanArrayOfNotes = res.data;

    });

Or, if you want to return the result rather than the promise, you can:
notes_service.js
app.factory ('NoteService', function($http) {
    var notes = [];
    var promise = $http.get('/notes.json').then(function(response) {
          angular.copy(response.data, notes);
          return notes;
    });

    return {
        getAll: function() {
            return notes;
        },
        promise: promise
    }
});

navCtrl.js
     // get array of notes
     scope.cleanArrayOfNotes = NotesService.getAll();

     // or use promise
     NoteService.promise.then(function(response) {
         scope.cleanArrayOfNotes = response.data;
     });


Q: WinAPI. How to redraw window which has no background? Hi I have WNDCLASSEX structure which has this data:
m_wndClass.cbSize = sizeof(WNDCLASSEX);
m_wndClass.style = CS_NOCLOSE;
m_wndClass.lpfnWndProc = WndProc;
m_wndClass.cbClsExtra = 0;
m_wndClass.cbWndExtra = 0;
m_wndClass.hInstance = GetModuleHandle(NULL);
m_wndClass.hIcon = NULL;
m_wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
m_wndClass.hbrBackground = NULL;
m_wndClass.lpszMenuName = NULL;
m_wndClass.lpszClassName = Checkbox::CHECKBOX_CLASS.c_str();
m_wndClass.hIconSm = NULL;

I need to have window without background, because I need to draw text on parent window and text may be any color.
Drawing works fine, code for drawing:
case WM_PAINT:
{
    PAINTSTRUCT ps;
    HDC dc = BeginPaint(window, &ps);

    if (!classInfo->m_text.empty())
    {
        HDC wdc = GetDC(window);

        SetBkMode(wdc,TRANSPARENT);
        DrawText(wdc, classInfo->m_text.c_str(), -1, &classInfo->m_textRect, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOCLIP);
        ReleaseDC(window, wdc);
    }

    EndPaint(window, &ps);
    break;
}

However I have method to change text of label:
void Checkbox::SetText(const String& text)
{
    m_text = text;
    SetTextRectSize();   //calculates size of RECT
    if (m_window != NULL)
        InvalidateRect(m_window, NULL, TRUE);
}

After I create window with label I see label, however if I want to change text on it, it doesn't change (I need to manualy resize window and it changes after that). However I hadn't have this problem at the time when I used to have colored background, for example my window class had this:
m_wndClass.hbrBackground = HBRUSH(COLOR_3DFACE+1);

I want to ask, how to update window which, has no background.
EDIT:  I have tried some stuff
FillRect(dc, &rect, (HBRUSH)GetStockObject(NULL_BRUSH));
also tried to change window procedure:
case WM_CTLCOLORSTATIC:
{
    HDC hdc = (HDC) wp;
    SetBkMode (hdc, TRANSPARENT);
    return (LRESULT)GetStockObject(NULL_BRUSH);
}

And the result is that I draw new text on previous, after setting text into some longer text part of label becomes corupted!  see this but after resizing the main window my label becomes readable.

A: Your code doesn't set the device context's text foreground color for DrawText(), although the default is black.  See SetTextColor().
SetBkMode(..., TRANSPARENT) just sets the background color/mode for the DrawText() rect, not the entire window.

A: You are asking about how to draw the window so it is transparent, but the problem isn't with the drawing at all.
The answer is essentially that everything you have done so far towards making a transparent window is wrong. It looks like the window is transparent, but in fact it is not, as you can see from the behaviour you describe when you move and resize the window. That's the classic symptom.
In other words, you haven't made the window transparent, you have just stopped drawing the background. What you see as the background is just whatever happened to be underneath the window when it was first drawn.
You need make a Layered window. To find out how to make transparent windows, go here:

*

*http://msdn.microsoft.com/en-us/library/ms997507.aspx

A: Do you want Text/Check/Label be transparent on parent form?
You can Add WS_CLIPSIBLINGS and WS_EX_TRANSPARENT..
Use SetBkMode(hDC, TRANSPARENT) When WM_PAINT message


Q: C++: Containers of Arbitrary Template Type In C++, suppose I have a templatized class, like
template <typename T>
class Foo
{
    ...
};

and suppose that I have several kinds of Foo objects, like
Foo<int> intFoo = Foo<int>();
Foo<double> doubleFoo = Foo<double>();
...

and so on.
Actually, its worse than that. I really want an intFoo object of a class that inherits from Foo< int >, for instance.
I would like to do something like this:
std::vector<Foo<?> > aVector;
aVector.push_back(intFoo);
aVector.push_back(doubleFoo);

Keeping in mind that I have substantially oversimplified my design case, is there a simple way to do this?

A: Foo<int> and Foo<double> are 2 different classes despite they share the name Foo, so you can't just put them to vector as is. But you can use boost::variant and store a vector of variants.

A: A solution would be to have your Foo inheriting from an empty base class
struct CommonBase {};

template<typename T>
class Foo : public CommonBase
{
    // ...
};

and then have a container of pointers to the common base
vector<CommonBase*> v;

If you want to keep away from inheritance, you could use boost:any to store any type in your container.
An interesting topic to look into (if you want to manually implement this kind of things) is type erasure


Q: Prometheus sum of different Counters having common lables I have two counters like below . Both counter have common label interface_name.
Counter A=
{app_kubernetes_io_component="xyz-rest-ep",interface_name="N7",command="create","job="kubernetes-pods",monitor="prometheus",namespace="xyz-foo",pod="xyz-rest-ep-9f5686bc-dvtjr",pod_template_hash="9f5686bc",}
Counter B=
{app_kubernetes_io_component="xyz-rest-ep",interface_name="N7",command="delete",job="kubernetes-pods",monitor="prometheus",namespace="xyz-foo",pod="xyz-rest-ep-9f5686bc-dvtjr",pod_template_hash="9f5686bc",target_base_url="http://192.168.102.50:7044/"}
I would like to have addition of counter A and counter B by interface_name lable.
Note that Counter B have extra label as target_base_url which is absent in Counter A
Kindly let us know how to achieve this in Prometheus query.

A: You should take a look at the Vector matching section, especially at the on/ignoring keywords. If you just want to do an operation like counterA + counterB a query similar to:
counterA + ignoring(target_base_url) counters

should work. This will sum both counters matching on all labels except the target_base_url. If you want to match only on a subset of the labels you could use the on keyword.


Q: Using Stata Variable Labels in R I have a bunch of Stata .dta files that I would like to use in R.
My problem is that the variable names are not helpful to me as they are like "q0100," "q0565," "q0500," and "q0202."  However, they are labelled like "psu," "number of pregnant," "head of household," and "waypoint."
I would like to be able to grab the labels ("psu," "waypoint," etc. . .) and use them as my variable/column names as those will be easier for me to work with.
Is there a way to do this, either preferably in R, or through Stata itself?  I know of read.dta in library(foreign) but don't know if it can convert the labels into variable names.

A: You can convert the variable labels to variable names from within Stata before exporting it to a R or text file.
As Ian mentions, variable labels usually do not make good variable names, but if you convert spaces and other characters to underscores and if your variable labels aren't too long, you can re-label your vars with the varlabels quite easily.
Below is an example using the inbuilt Stata dataset "cancer.dta" to replace all variable names with var labels--importantly, this code will not try to rename variable with no variable labels.  Note that I also picked a dataset where there are lots of characters that aren't useful in naming a variable (e.g.: =, 1, ', .,  (), etc)...you can add any characters that might be lurking in your variable labels to the list in the 5th line:  "local chars "..." " and it will make the changes for you:
****************! BEGIN EXAMPLE
//copy and paste this code into a Stata do-file and click "do"//
sysuse  cancer, clear
desc
**
local chars "" " "(" ")" "." "1" "=" `"'"' "___" "__" "
ds, not(varlab "")    // <-- This will only select those vars with varlabs //
foreach v in `r(varlist)' {
    local `v'l "`:var lab `v''"
    **variables names cannot have spaces or other symbols, so::
        foreach s in `chars' {
    local `v'l: subinstr local `v'l "`s'" "_", all
              }
    rename `v' ``v'l'
    **make the variable names all lower case**
    cap rename ``v'l' `=lower("``v'l'")'
      }
desc
****************! END EXAMPLE

You might also consider taking a look at Stat Transfer and it's capabilities in converting Stata to R datafiles.

A: Here's a function to evaluate any expression you want with Stata variable labels:
#' Function to prettify the output of another function using a `var.labels` attribute
#' This is particularly useful in combination with read.dta et al.
#' @param dat A data.frame with attr `var.labels` giving descriptions of variables
#' @param expr An expression to evaluate with pretty var.labels
#' @return The result of the expression, with variable names replaced with their labels
#' @examples
#' testDF <- data.frame( a=seq(10),b=runif(10),c=rnorm(10) )
#' attr(testDF,"var.labels") <- c("Identifier","Important Data","Lies, Damn Lies, Statistics")
#' prettify( testDF, quote(str(dat)) )
prettify <- function( dat, expr ) {
  labels <- attr(dat,"var.labels")
  for(i in seq(ncol(dat))) colnames(dat)[i] <- labels[i]
  attr(dat,"var.labels") <- NULL
  eval( expr )
}

You can then prettify(testDF, quote(table(...))) or whatever you want.
See this thread for more info.

A: R does not have a built in way to handle variable labels. Personally I think that this is disadvantage that should be fixed. Hmisc does provide some facilitiy for hadling variable labels, but the labels are only recognized by functions in that package. read.dta creates a data.frame with an attribute "var.labels" which contains the labeling information. You can then create a data dictionary from that.
> data(swiss)
> write.dta(swiss,swissfile <- tempfile())
> a <- read.dta(swissfile)
>
> var.labels <- attr(a,"var.labels")
>
> data.key <- data.frame(var.name=names(a),var.labels)
> data.key
          var.name       var.labels
1        Fertility        Fertility
2      Agriculture      Agriculture
3      Examination      Examination
4        Education        Education
5         Catholic         Catholic
6 Infant_Mortality Infant.Mortality

Of course this .dta file doesn't have very interesting labels, but yours should be more meaningful.

A: I would recommend that you use the new haven package (GitHub)
 for importing your data.
As Hadley Wickham mentions in the README.md file:

You always get a data frame, date times are converted to corresponding R classes and labelled vectors are returned as new labelled class. You can easily coerce to factors or replace labelled values with missings as appropriate. If you also use dplyr, you'll notice that large data frames are printed in a convenient way.

(emphasis mine)
If you use RStudio this will automatically display the labels under variable names in the View("data.frame") viewer pane (source).

Variable labels are attached as an attribute to each variable. These are not printed (because they tend to be long), but if you have a preview version of RStudio, you’ll see them in the revamped viewer pane.

You can install the package using:
install.packages("haven")

and import your Stata date using:
read_dta("path/to/file")

For more info see:
help("read_dta")

A: When using the haven package:
if the data set you are importing is heavy, viewing the data in Rstudio might not be optimal.
You can instead get a data.frame with column names, column labels and an indicator for whether the column is labelled:
d <- read_dta("your_stata_data.dta")

vars <- data.frame(
                   "name" = names(d),
                   "label" = sapply(d, function(x) attr(x, "label"))  %>% as.character(),
                   "labelled" = sapply(d, is.labelled) )

Note: need to use as.characted in order to avoid NULL in the labels being dropped and therefore ending up with different vector lengths.


Q: Supported Device - Android I am uploading an app to the playstore and it is showing
Supported devices:
5569
Unsupported devices:
9628
Can someone please confirm me the total supported devices for:
minSdkVersion 21
targetSdkVersion 26
I am not using any hardware dependent features in the app.
How can increase these numbers.
Thanks.

A: The lower an Android API version becomes, the more devices it supports.  Thus, if the desire is to increase the amount of supported devices, it is best to decrease the API version, so long as the functionality you have already created is not impeded.
Here is data based on the number of devices that support each API as of January 8th, 2018:

A: The Android version is not the only condition, maybe your application uses devices such as GPS, accelerometers, sensors, telephony, minimal screen resolution etc that not all Android devices have/support them.
In general, more permissions declared in your app manifest means less compatible devices.


Q: Passing parameter between thread C# i have a regular multithread which process a parameter/value
  public void testThread (int fib)
  {
    int a = 1;
    int fib2 = fib + a;
    Console.WriteLine(" Thread : "+fib);
  }

how can i pass the result value back to MainThread or another Thread ?

A: You usually pass data between threads by writing the data into some shared data structure, like a queue that one thread is writing to and another thread is reading from.
There are other explicit ways, however.  For example, if you are trying to get data from a background thread to the UI thread, so you can invoke UI API's with that data, then there are techniques to execute bits of code on other thread contexts.
For example, you can use the Task class from System.Threading.Tasks to start a task on the UI thread if you know the TaskScheduler associated with the UI thread. You can get that from TaskScheduler.FromCurrentSynchronizationContext() when your code is executing on the UI thread, and save it in a static variable to use later.


Q: How don't let draggable div go outside of the screen I have this code:

$("#drag").draggable({
  cursor: "move",
  start: function() {
    $("#drag").css("transform", "translate(0, 0)")
  }
});
#main-div {
  text-align: center;
}

#drag {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 200;
}

#content {
  position: relative;
  background-color: red;
  width: 500px;
  height: 500px;
}

Bla bla.. Some text

    <button>I'm a button</button>

The dragging works good but I found a problem when I drag this div out of the screen. There is no scroll (which is good because I don't want scroll) so I can't drag this div back.
I tried to find solution but the only thing that I found was with scrolling and I don't want scrolling.
How can I prevent from dragging outside of the screen?
Thanks in advance and sorry for my english.


Q: Zipping a directory to a remote location in Java I'm trying to create a zip file from a directory in Java, then place that file on a remote server (a network share).  I'm currently getting an error because the Java File object cannot reference a remote location and I'm not really sure where to go from there.
Is there a way to zip a directory in Java to a remote location without using the File class?

A: Create the ZIP file locally and use either commons-net FTP or SFTP to move the ZIP file across to the remote location, assuming that by "remote location" you mean some FTP server, or possibly a blade on your network.
If you are using the renameTo method on java.io.File, note that this doesn't work on some operating systems (e.g. Solaris) where the locations are on different shares. You would have to do a manual copy of the file data from one location to another. This is pretty simple using standard Java I/O.


Q: Wrong owner upon file creation in particular directory I'm facing @subj . If I try to create a file/dir in my home directory it gets created as root:daemon instead of user:staff. I found this behaviour only for one directory ( all the other dirs aren't affected).
It used to create files properly before and now it sets root:daemon with 644.
I can't see any guid or sticky bits, etc.
What do I miss?
$ whoami
user
$ pwd
/home/user
$ touch 1
$ ll 1
-rw-r--r-- 1 root daemon 0 Jul 31 09:50 1
$ ls -ld /home/user/
drwxr-xr-x 13 user staff 4096 Jul 31 09:50 /home/user/
$ ls -ld /home/
drwxr-xr-x 5778 root staff 450560 Jul 31 08:21 /home/
$ umask
0022

A: I might be due to file access control set to root:daemon. If you run
getfacl /home/user

it should tell you if that was the problem. If yes, then you can set per-folder with the command setfacl with the parameters you prefer.
Another cause that comes to my mind is if that is a mountpoint masked with those particular user and group; you can check that with cat /etc/fstab.


Q: Gcloud LoadBalancer: change Google Managed certificate without downtime I intend to use Gcloud managed certificate. The way it works is that I already have a custom certificate managed by Let's Encrypt, which is assigned to my LoadBalancer. Now I want to swich to the Google Managed certificate. In order to achieve this I have to point the domains to the LoadBalncer's IP, then  go to Load balancing components page, then I have to create the Google Managed certificate at the CERTIFICATES tab and, finally, edit the LoadBalancer to change its Frontend Configuration of HTTPS protocol and select the newly created certificate. Then, and only then, GCP will be allowed to provision the certificate. The problem is that it may take a few minutes (like 10 minutes) to the certificate to be provisioned. During this time my application will eventually lose the certificate and the browser will block it. This is not an acceptable scenario for us.
So, in short, I need to replace the certificate of the LoadBalancer to another one not yet verifyed which will cause my application to be out for the time it takes to provision it. The ideal scenario would be to provision the certificate first, then edit the LoadBalancer to bind it with the new certificate.
Is there any way to achieve this? Otherwise I will have to still issue my certificates with  Let's Encrypt and manually replace it every time it's about to expire.

A: A load balancer front end can have more than one certificate attached.
Create a new managed certificate and attach it to the front end.
Once you have more than one certificate attached, you can then remove the one you no longer want to use without downtime.


Q: nhibernate: what are the best practices for implementing equality? I think that Entities should implement equality by primary key comparison as default, but the nhibernate documentation recommends using business identity:

The most obvious way is to implement Equals()/GetHashCode()  by comparing the identifier value of both objects. If the value is the same, both must be the same database row, they are therefore equal (if both are added to an ISet, we will only have one element in the ISet). Unfortunately, we can't use that approach. NHibernate will only assign identifier values to objects that are persistent, a newly created instance will not have any identifier value! We recommend implementing Equals() and GetHashCode() using Business key equality.
Business key equality means that the Equals() method compares only the properties that form the business key, a key that would identify our instance in the real world (a natural candidate key)

And the example (also from the doc):
public override bool Equals(object other)
{
    if (this == other) return true;

    Cat cat = other as Cat;
    if (cat == null) return false; // null or not a cat

    if (Name != cat.Name) return false;
    if (!Birthday.Equals(cat.Birthday)) return false;

    return true;
}

This got my head spinning because the notion of business identity (according to the example) is the same as comparison by syntax, which is basically the type of semantics I associate with ValueObjects. The reason for not using database primary keys as comparison values is because this will change the hashcode of the object if the primary key is not generated on the client side (for ex incremental) and you use some sort of hashtable collection (such as ISet) for storing your entities.
How can I create a good equality implementation which does not break the general rules for equality/hashcode (http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx) and conforms to nhibernate rules as well?

A: This is a known issue with ORM. Here I outline the solutions I know about and give a few pointers.
1 Surrogate/primary key: auto-generated
As you mentionned, if the object has not been saved, this doesn't work.
2 Surrogate/primary key: assigned value
You can decide to assign the value of the PK in the code, this way the object has always an ID and can be used for comparison. See Don't let hibernate steal your identity.
3 Natural key
If the object has another natural key, other than the primary key, you can use this one. This would be the case for a client entity, which has a numeric primary key and a string client number. The client number identifies the client in the real world and is a natural key which won't change.
4 Object values
Using the object values for equality is possible. But is has other shortcomings has you mentioned. This can be problematic if the values changes and the object is in a collection. For instance, if you have a Set with two objects that were different  at first, but then you change the values while they are reference in the set so that they become equal. Then you break the contract of the Set. See Hibernate equals and hashcode.
5 Mixed: value + autogenerate primary/surrogate keys
If the objects to compare have an ID already, use it. Otherwise, use the object values for comparison.
All have some pros and cons. IMHO, the best is 3, if it is possible with your domain model. Otherwise, I've used 5 and it worked, though there are still some trap when using collections. I never used 2 but that sounds also a sensible solution, if you find a way to generate the PK in the code. Maybe other people have pointers for this one.


Q: how to avoid code duplication with const and non-const member functions being input into templates when attempting to get functions' signatures when they are input into templates its fairly easy, just do the following:
template <class OutType, class... ArgTypes>
void foo(OutType (*func)(ArgTypes...));

it is only marginally more complicated to get a non-static member function:
template <class OutType, class MemberOf, class... ArgTypes>
void foo(OutType (MemberOf::*func)(ArgTypes...));

// or

template <class OutType, class MemberOf, class... ArgTypes>
void foo(OutType (MemberOf::*func)(ArgTypes...) const);

but how exactly do you combine the two function declarations above into one when it doesn't matter whether or not the input method is const?

A: Unfortunately, the presence or absence of const on a non-static member function is not a feature that can be deduced separately from the function type it appertains to. Therefore, if you want to write a single foo template declaration that is limited to accepting pointers to members (but accepts both const and non-const member functions) then it would have to be:
template <class MemberOf, class F>
void foo(F MemberOf::*func);

For example:
#include <type_traits>

template <class MemberOf, class F>
void foo(F MemberOf::*func) {
    static_assert(std::is_same<F, void(int) const>::value);
}

struct S {
    void bar(int) const {}
};

int main() {
    foo(&S::bar);
}

You cannot have F's argument types deduced at that point. You would have to dispatch to a helper function. (But we cannot deduce all the types at once while also writing a single declaration that accepts both const and non-const. If that's the only thing you'll accept, then sorry, it's not possible.) We can do this like so:
template <class T>
struct remove_mf_const;

template <class R, class... Args>
struct remove_mf_const<R(Args...)> {
    using type = R(Args...);
};

template <class R, class... Args>
struct remove_mf_const<R(Args...) const> {
    using type = R(Args...);
};

template <bool is_const, class F, class OutType, class MemberOf, class... ArgTypes>
void foo_helper(F func, OutType (MemberOf::*)(ArgTypes...)) {
    // now you have all the types you need
}

template <class MemberOf, class F>
void foo(F MemberOf::*func) {
    static_assert(std::is_function<F>::value, "func must be a pointer to member function");
    using NonConstF = typename remove_mf_const<F>::type;
    constexpr bool is_const = !std::is_same<F, NonConstF>::value;
    foo_helper<is_const>(func, (NonConstF MemberOf::*)nullptr);
}

Coliru link


Q: Android Thread Pool to manage multiple bluetooth handeling threads? So I have my Android Bluetooth application that has it's host and clients. The problem is, because I am making multiple connections, I need a thread to handle each connection. That's all milk'n'cookies, so I thought I'd stick all the threads in an array. A little research says a better method to doing this is using a Thread Pool, but I can't seem to get my head around how that works. Also, is it actually even possible to hold threads in an array?

A: A thread pool is built around the idea that, since creating threads over and over again is time-consuming, we should try to recycle them as much as possible. Thus, a thread pool is a collection of threads that execute jobs, but are not destroyed when they finish a job, but instead "return to the pool" and either take another job or sit idle if there is nothing to do.
Usually the underlying implementation is a thread-safe queue in which the programmer puts jobs and a bunch of threads managed by the implementation keep polling (I'm not implying busy-spinning necessarily) the queue for work.
In Java the thread pool is represented by the ExecutorService class which can be:

*

*fixed - create a thread pool with a fixed number of threads

*cached - dynamically creates and destroys threads as needed

*single - a pool with a single thread

Note that, since thread pool threads operate in the manner described above (i.e. are recycled), in the case of a fixed thread pool it is not recommended to have jobs that do blocking I/O operations, since the threads taking those jobs will be effectively removed from the pool until they finish the job and thus you may have deadlocks.
As for the array of threads, it's as simple as creating any object array:
Thread[] threads = new Thread[10]; // array of 10 threads


Q: Uncaught ReferenceError: getSelectedOption is not defined at HTMLButtonElement.document.getElementById.onclick I am a super beginner in javascript and html and doing an experiment to build an webapp.
I ran npm install http-server -g and http-server '' -o and it opened up a browser tab. But in the console, I get this error and cannot identify what is causing the problem.
Uncaught ReferenceError: getSelectedOption is not defined
at HTMLButtonElement.document.getElementById.onclick (app.js:5)
document.getElementById.onclick @ app.js:5

In the browser I see a pull down menu and  Refresh button. So why is getSelectedOption not defined?? I'm not sure if it's related to this problem, but even though I click the button, console.log("clicked!") doesn't print anything.
Here is my index.html

    <form>

        Store ID
        <select class="form-control" id="company">
          <option selected>All</option>
          <option>Air France</option>
          <option>Lufthansa</option>
        </select>
        <button  class="btn btn-primary" type='button' id="button">Refresh</button>

    </form>

Here is my app.js
console.log("button", document.getElementById("button"))

document.getElementById('button').onclick = function(){
    console.log("clicked!")
    let company = getSelectedOption('company');
    let headers = new Headers()
    let init = {
        method : 'GET',
        headers : headers
    }
    let params = {
        'company':company
    }

    $.get( "/getmethod/<params>" );

    $.get("/getpythondata", function(data) {
        console.log($.parseJSON(data))
    })

A: You need to use document.getElementById('company').value to get value of select box.i.e :

console.log("button", document.getElementById("button"))

document.getElementById('button').onclick = function() {
    console.log("clicked!")
    let company = document.getElementById('company').value;//get value of select box
    console.log(company)
    let headers = new Headers()
    let init = {
      method: 'GET',
      headers: headers
    }
    let params = {
      'company': company
    }

    $.get("/getmethod/<params>");

    $.get("/getpythondata", function(data) {
      console.log($.parseJSON(data))
    })

    }

<form>

    Store ID
    <select class="form-control" id="company">
      <option selected>All</option>
      <option>Air France</option>
      <option>Lufthansa</option>
    </select>
    <button class="btn btn-primary" type='button' id="button">Refresh</button>

</form>