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: Удаление картинки при нажатии на нее JS Есть код, который при нажатии на ссылку открывает блок и при этом сама ссылка удаляется - прекрасно работает, если внутри текст, но если там картинка   не срабатывает, что не нравится?
https://jsfiddle.net/hibinyru/1vquoj30/1/
.hidden { display: none;}

document.addEventListener('click', function(e){
  if( !e.target.matches('.js-show-text') ) return;

  e.target.nextElementSibling.classList.remove('hidden');
  e.target.outerHTML = "";
});

Показать
Скрытый текст

Скрытый-2

или может быть подскажите решение тоже самого на jquery ? с учетом что на странице таких блоков может быть несколько


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 can I use an iPhone Personal Hotspot and at the same time stay connected to a Local Network for File Sharing? I am on a WinXP machine in a LAN.
Through the LAN my computer connects to a server that has some shared drives I need to access.
I usually connect to the internet through that server (which also functions as DHCP, and has a broadband network).
Today our internet service is down so I connected my computer to my iPhone's Personal Hotspot via USB. This makes my "Network Connections" in the control panel to show two different "LAN or High-Speed Internet" connections.
The problem is that, for my computer to be able to access the Internet I have to disable the Network Adapter that I use to connect to the LAN and the Server (and the shared drives). Otherwise, Windows just ignores the iPhone's adapter and tries to connect to the internet via the LAN (which of course fails).
Is there a way in which I can tell the computer to use the iPhone's Connection for internet, and simultaneously use the regular Network Card for all the local access stuff?
I was reading something about the "default gateway", but I am not sure whether I can modify this without disabling the "Obtain IP address automatically" setting on the Network Card.
Any ideas?

A: Multiple default gateways will be a problem in this scenario. Which one is used is based on an interface metric which is based on speed. However, since both will provide a similar metric (in this case) it will default to the first one via Automatic Metric. Overcome this by setting the metric yourself (for the time being).
For both interfaces:
 1. Open the properties of your adapter (by reading your post it seems you are familiar with this).
 2. Click Internet Protocol Version 4 (TCP/IP).
 3. Click Properties.
 4. Click Advanced.
 5. Uncheck Automatic Metric.
 6. Change the Metric of the one you want to be "master" to 1 and the other to 2.
 7. In this case your iPhone would be 1 and the other would be 2.
 8. When done change it back.

This should work based on local / remote lookups, I haven't tested it, but in theory it is correct.


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: What are industry standards and professional best practices in network hosts naming?
Possible Duplicate:
Naming convention for computers

It seems an important and difficult dilemma for me how to name network hosts (routers, servers (while a server can be a router and host diverse services at the same time), virtual machines (while they host important services and can migrate), workstations and notebooks (using pc-username is not the best idea as users may change), printers & MFUs, surveillance IP cameras, etc).
Are there known and accepted best practices for this task?
Excuse me if there already was a similar question here (I think it probably was), I haven't found it.

A: Only these as far as I know:
https://www.rfc-editor.org/rfc/rfc952
https://www.rfc-editor.org/rfc/rfc1123
https://www.rfc-editor.org/rfc/rfc273
https://www.rfc-editor.org/rfc/rfc236
Any other conventions are linked to particular limitations like for mainframes

A: There is no 'industry standard' (naming convention) when it comes to naming network hosts.   There are plenty of ideas here:
https://serverfault.com/search?q=naming+convention


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: Can I use Entity Framework with a SOAP API layer over a database? We have a hierarchical database at our institution that has exposed a SOAP endpoint as the only way to make CRUD operations against it.  We are primarily a .NET Core shop.  I'm trying to conceptualize how the architecture of an app that uses the WDSLs would look.  The main use case is to display account info in a pleasing manner as well as being able to modify it with business logic behind the CRUD operations.
Is there a way to use Entity Framework Core with a SOAP API layer to access the database?  If not, what is the recommended approach when architecting a solution that doesn't use Entity Framework Core for its connections?  I'm trying to apply the Clean Architecture approach to this solution, but all examples I see use EF Core.
I've begun the task of storing the results of the main WSDL call, "getAccount", into a temporary SQL database on startup.  Then I could query the SQL database as normal.  I wasn't sure if this was standard practice or not.
The other approach would be to map all of the SOAP calls into a REST interface using Web API.  Then I could just call the Web API and it would make the SOAP calls for me.  I have started doing this manually, but I've seen tools that can "proxy" the SOAP layer.  Would that be applicable?

A: EF is an ORM (Object-Relational Mapper). It's used to easily turn a relational database structure into .NET objects. Since you aren't connecting to a database (you have a SOAP API), I don't see what role EF would play here.
Your first solution describes forcing a role for EF by creating an unnecessary middle-man database where one wasn't before, just so EF can be used. I've never heard of that before, and I would cry a little inside if I had to work on a project with that kind of misdirection in place.
The most straightforward solution is just call the SOAP services directly (on the server side), which should be pretty easy to do. You're probably going to have all of the same WebAPI endpoints any way, it's just that the code behind them will be consuming a SOAP service instead of an EF context.


Q: Sharepoint 2010 - multiple ip addresses I have Sharepoint 2010 installed in local network. SPS has local address http://sps2010, and has a public IP (e.g. http://1.2.3.4).
When I access SP via a public IP there are some links like ("Create Document", "Departments" etc) contain local server name. I would then get an error when browsing.
How can I setup multiple hostnames(IP's) for Sharepoint?

A: Check with Configure an Alternate Access Mapping in SharePoint 2010.
http://technet.microsoft.com/en-us/sharepoint/ff679917.aspx


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: SSH connection sometimes works other no from WIN10 client to linux server I'm trying to connect in ssh on port 22 (with client putty,mobaxterm..) on a remote machine with Linux, the connection sometimes works and other no. My pc run on win10 and if I try on cmd the command ssh "host" I get the following error:
C:\Users\User>ssh kex_exchange_identification: banner line contains invalid characters
Can somebody help me? Regards.


Q: Can I update my system with a Live CD? I've installed Ubuntu from a Live CD in VMWare, After that I configured everything for my need and of course I installed some additional tools. Everything works fine, But regularly I receive a new Live CD with updated software and some new installed tools which I need to use.
Is it possible to update Ubuntu with the new Live CD? Else I have always to reconfigure and install my personal stuff from scratch.
I'm also interested in a solution which need some action on the "Live CD-Producer", But of course if there is something that I can do, This will be preferred.

A: Boot from the cd, a window like this should come out, PS: This is an old screenshot, i expect that the 12.04 is the same, you should choose the upgrade option.
I hope that works
http://lh6.googleusercontent.com/_1QSDkzYY2vc/TWzh8Z786xI/AAAAAAAADNw/8lXqgCMgicY/ubuntu11.04-installer.png


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: How do I change the brightness in iOS 7? I used to be able to double the home button and swipe right to change the brightness. How do I change the brightness in iOS 7 without going to the Settings app?

A: Ask Siri to change the brightness and you can get to the control straight away.

A: You can change the brightness from the new Control Center, which you access by swiping up from the bottom of the screen.

A: Swipe up from the bottom of the screen to open Control Center, then slide the brightness slider.
Control Center is enabled by default, but can be enabled/disabled through Settings > Control Center.

A: Swipe up from the bottom to bring up the Control Center.  The top slider will let you change the brightness:


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: Forcibly resize unresisable window in gnome I've been digging around and cant find any obvious ways to forcibly resize a unresizable window in gnome 42 (I'm specifically using fedora). Is this even possible? I'm not particularly worried about what happens to the application being resized.


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: How does windows file sharing actually work? I know that when communicating over HTTP, the source has to be downloaded first to be viewed on the browser. But what mechanism is actually at play when using windows file sharing (Both when sharing over a network router and sharing directly e.g a LAN cable from PC-1 to PC-2)?

*

*Is a request sent to the server, which starts transmitting data on a certain port to be received by the client?

*Does the client access the server's drive like a conventional drive, read data and copy it to it's own drive?

*Does the server copy the file to the client's hard disk?

A: How does windows file sharing actually work?

Microsoft SMB Protocol Authentication
The security model used in Microsoft SMB Protocol is identical to the
  one used by other variants of SMB, and consists of two levels of
  security—user and share. A share is a file, directory, or printer that
  can be accessed by Microsoft SMB Protocol clients.
User-level authentication indicates that the client attempting to
  access a share on a server must provide a user name and password. When
  authenticated, the user can then access all shares on a server not
  also protected by share-level security. This security level allows
  system administrators to specifically determine which users and groups
  can access a share.
Share-level authentication indicates that access to a share is
  controlled by a password assigned to that share only. Unlike
  user-level security, this security level does not require a user name
  for authentication and no user identity is established.
Under both of these security levels, the password is encrypted before
  it is sent to the server. NTLM and the older LAN Manager (LM)
  encryption are supported by Microsoft SMB Protocol. Both encryption
  methods use challenge-response authentication, where the server sends
  the client a random string and the client returns a computed response
  string that proves the client has sufficient credentials for access.
source

Microsoft SMB Protocol and CIFS Protocol Overview
The Server Message Block (SMB) Protocol is a network file sharing
  protocol, and as implemented in Microsoft Windows is known as
  Microsoft SMB Protocol. The set of message packets that defines a
  particular version of the protocol is called a dialect. The Common
  Internet File System (CIFS) Protocol is a dialect of SMB. Both SMB and
  CIFS are also available on VMS, several versions of Unix, and other
  operating systems.
The technical reference to CIFS is available from Microsoft
  Corporation at Common Internet File System (CIFS) File Access
  Protocol.
Although its main purpose is file sharing, additional Microsoft SMB
  Protocol functionality includes the following:

*

*Dialect negotiation

*Determining other Microsoft SMB Protocol servers on the network, or    network browsing

*Printing over a network

*File, directory, and share access authentication

*File and record locking

*File and directory change notification

*Extended file attribute handling

*Unicode support

*Opportunistic locks
In the OSI networking model, Microsoft SMB Protocol is most often used
  as an Application layer or a Presentation layer protocol, and it
  relies on lower-level protocols for transport. The transport layer
  protocol that Microsoft SMB Protocol is most often used with is
  NetBIOS over TCP/IP
  (NBT).
  However, Microsoft SMB Protocol can also be used without a separate
  transport protocol—the Microsoft SMB Protocol/NBT combination is
  generally used for backward compatibility.
The Microsoft SMB Protocol is a client-server implementation and
  consists of a set of data packets, each containing a request sent by
  the client or a response sent by the server. These packets can be
  broadly classified as follows:

*

*Session control packets—Establishes and discontinues a connection to    shared server resources.

*File access packets—Accesses and manipulates files and directories on    the remote server.

*General message packets—Sends data to print queues, mailslots, and    named pipes, and provides data about the status of print queues.
Some message packets may be grouped and sent in one transmission to
  reduce response latency and increase network bandwidth. This is called
  "batching." The Microsoft SMB Protocol Packet Exchange
  Scenario
  section describes an example of a Microsoft SMB Protocol session that
  uses packet batching.

Topic: Microsoft SMB Protocol Dialects

*

*Description: To establish a connection between a client and a server using Microsoft SMB Protocol, you must first determine the
  dialect with the highest level of functionality that both the client
  and server support.
Topic: Microsoft SMB Protocol Authentication

*

*Description: The security model used in Microsoft SMB Protocol is identical to the one used by other variants of SMB, and consists of
  two levels of security—user and share. A share is a file, directory,
  or printer that can be accessed by Microsoft SMB Protocol clients.
Topic: Microsoft SMB Protocol Packet Exchange Scenario

*

*Description: Example of a Microsoft SMB Protocol packet exchange between a client and a server.
source

Comment Clarification
File access packets—Accesses and manipulates files and directories on the remote server.' How does this happen? Where is the response packet to give the requested data to client? Kraken

Each packet is typically a basic request of some kind, such as open
  file, close file, or read file.  The server then receives the packet,
  checks to see if the request is legal, verifies the client has the
  appropriate file permissions, and finally executes the request and
  returns a response packet to the client.  The client then parses the
  response packet and can determine whether or not the initial request
  was successful.
source

Further Resources
A diagram and an explanation of the authentication aspects involved in establishing a client-server session with the protocol.

*

*3.2.4.2.4.1 Sequence Diagram

Reads for further detail on SMB.

*

*Microsoft SMB, SMB2, NetBIOS, WINS protocol suite

*Server Message Block

*Server Message Block Protocol (SMB)


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>


Q: Java initializing iVars outside the scope of any method New to Java, and I am a little confused about this piece of code:
public class CitiesDialog extends DialogFragment {
    private AsyncHttpClient client = new AsyncHttpClient();
}

client is being initialized outside the scope of any method. What does this exactly mean? Does each instance of CititiesDialog have a separate client object? Or is this some sort of static/class variable ?
And lastly, is this the norm in Java? to initialize variables outside the scope of constructors/methods, etc...
Thanks

A: client is an instance variable of CitiesDialog
every CitiesDialog that you make is going to have it's own client.
That kind of initialization is just for when you first make an instance of your class.  you can change client afterwards.

A: This is perfectly normal to see in Java.
What you see here is private AsyncHttpClient, which is by itself just a class variable.
Then you see the declaration new AsyncHttpClient(), which gets assigned to client. This will happen for every new object that gets created.
To address whether this is the norm? I think yes, a common use case is lists, it is best to initialize them as early as possible:
public class A {
    private final List<String> list = new ArrayList<>();
}

This will prevent that you get a NPE at a later point, because you have forgotten to declare the list.
One other thing that also helps is to declare the field final if it should never be changed after assignment, then it is also ensured by the compiler that the field gets initialized either in the declaration or in a constructor.

A:
Does each instance of CititiesDialog have a separate client object?

Yes, since it is not marked as static.

is this the norm in Java? to initialize variables outside the scope of constructors/methods, etc...

It's not abnormal, especially if you have multiple constructors and do not want to duplicate initialization.

A:
And lastly, is this the norm in Java? to initialize variables outside the scope of constructors/methods

Actually this is just syntactic sugar which eliminates the need to repeat the same initialization in each costructor. When compiled, the initialization code will become a part of each constructor (except those which delegate to other constructors).