text:
Q: Windows domain authentication using HOST files I am currently setting up remote office PCs running Windows 7 Professional to authenticate back to a domain controller running Windows 2008 R2 in the headquarters. Is it possible to simply define the domain name of the domain controller using the local PC's hosts file instead of having to query a DNS server?

A: Unfortunately, no.  The hosts file is only a suitable replacement for proper DNS when you need host (A) records and their associated reverse lookup (PTR) records.
Active Directory also requires a bunch of SRV records to function, which you can see in your DNS setup under the _msdcs.mydomain.com DNS zone; these records cannot be set up with just a hosts file.
This article documents the necessary non-host records (in the context of setting up a BIND server to serve them)

A: I know this is dead-thread revival, but here goes. According to
https://technet.microsoft.com/en-us/library/cc959846.aspx
and
https://support.microsoft.com/en-us/kb/180094
you can add entries in an LMHOSTS file for the domain controller. The file resides at C:\Windows\System32\Drivers\etc and is called LMHOSTS (no extension). The format for the domain controller entry is:

10.0.0.1   PDCNAME   #PRE #DOM:DOMAIN-NAME
10.0.0.1   "DOMAIN-NAME    \0x1b"   #PRE


text:
Q: Chrome App webview behavior on chrome extension I'm trying to create editor that lets you edit and changes your website.
So in the editor, I want to show iframe with a website.
Since there are many click-jack protections against website being opened withing iframe (headers and js), I't became impossible to do for some websites.
I came across the "webview" element, in the "Chrome app" documentation,
And I wonder, Is there any way to use "webview" or control that have the same behavior in chrome extension.
P.S: The only access I seek is using "postMessage".

A: Nope, there is no way to use <webview> outside a Chrome App.
So in theory you could make your editor an App.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a browser plugin like Flash I would like to create a browser plugin which works LIKE flash, with embedded content from my application on the page.
How would I go about doing this? Is it doable with .net applications?
Thanks for the help.
EDIT: To clarify, I have no intention of making something EXACTLY like flash, or remotely similar. I merely wish to be able to embed my application in-browser, and let the user pass parameters or whatever.

A: For FF/Chrome etc you need NPAPI. Can't imagine doing it in .Net
For IE it's just a COM object. Theoretically you could do it in .Net
If you are not accessing any local resources (special hardware etc) on the browsers computer then you might as well just use Silverlight. Lot of samples of what Silverlight can do

A: Flash and Silverlight are both decent platforms for writing your own custom apps which run in the browser and display custom content.  If you're familiar with .NET, then writing a Silverlight app should be pretty straightforward.
Silverlight is probably what you are looking for since it allows you to write self contained .NET apps which run inside the browser.  You can pass parameters to it, or allow it to make any sort of WCF call(REST/SOAP/XML-RPC/etc) or call any javascript function on your page.

A: Be aware that if you actually want more than a handful of people to be able
to use your plug-in you'll need to deal with versions for all sorts of operating
systems and platforms. If it's just for something on a local office intranet
you might be ok, but otherwise you'll end up needing to write Mac, Windows, Windows 64bit, Linux, Linux 64bit, iPhone, Android, etc. versions. You'll
then need to take care of really complex security issues and weird bugs
that people have all the time. It's not a small undertaking.
Do you want to do something that you can't already do just by using one of the existing plugins like Flash or Java?

A: I've been looking into this recently - you clearly have to do a lot of per-platform and per-browser work (I haven't found a magical one size fits all solution).
My application was 3d rendering, so this series was pretty useful (obviously substituting the Irrlicht stuff for your own code/library):
http://copperbit.com/?p=20
There is also a follow up article on FireFox...


text:
Q: Getting run-time crash log notes your content must have a ListView whose id attribute is 'android.R.id.list', not sure why? I am getting a run time exception java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'. Not sure what is wrong here.I looked at some other answers and it seemed that changing the ListView id to list was the issue but that does not seem to be working.
activity_search.xml

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" >
        </ListView>

    </LinearLayout>

list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<!--  Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold" >
</TextView>

SearchActivity.java
package com.chance.squat;

import com.chance.squat.R;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class SearchActivity extends ListActivity {

    // url to make request
    private static String url = "http://192.168.1.115:3000/bathrooms/nearby.json/?lat=45.580639&lon=-122.677682";

    // JSON Node names
    private static final String TAG_BATHROOMS = "bathrooms";
    private static final String TAG_ID = "ID";
    private static final String TAG_NAME = "name";
    private static final String TAG_DISTANCE = "distance";

    // contacts JSONArray
    JSONArray bathrooms = null;

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

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> bathroomList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            bathrooms = json.getJSONArray(TAG_BATHROOMS);

            // looping through All Contacts
            for(int i = 0; i < bathrooms.length(); i++){
                JSONObject c = bathrooms.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String name = c.getString(TAG_NAME);
                String distance = c.getString(TAG_DISTANCE);
                String distanceTrimmed = distance.substring(0,4) + " " + "miles away";

                System.out.println(name);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_NAME, name);
                map.put(TAG_DISTANCE, distanceTrimmed);

                // adding HashList to ArrayList
                bathroomList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /**
         * Updating parsed JSON data into ListView
         * */

        ListAdapter adapter = new SimpleAdapter(this, bathroomList,
                R.layout.list_item,
                new String[] { TAG_NAME}, new int[] {
                         R.id.name });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                //String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                //String distance = ((TextView) view.findViewById(R.id.distance)).getText().toString();

                // Starting new intent
                //Intent in = new Intent(getApplicationContext(), SeachActivity.class);
                //in.putExtra(TAG_NAME, name);
                //in.putExtra(TAG_DISTANCE, distance);
                //startActivity(in);

            }
        });

    }

}

A: change ListView id to android:id="@android:id/list" because when you are extending ListActivity you must have ListView id android.R.id.list
<ListView
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >
</ListView>


text:
Q: Implementing A-Star algorithm. Help please? I am trying to implement an A* algorithm for my pathfinding robot in JavaScript. The only problem is that I do not understand what does it mean to find all adjacent squares. I am using the Manhattan Distance formula as I cannot let my bot go diagonally. Here is my code (for now):
var open = new Array();
var closed = new Array();
start = [9,18]; //do not take this literally
goal = [1,0]; //again don't
open.push(start);
while (open.length != 0) {
    for(var x = 0; x < open.length; x++) {
        heuristicValue[x] = computeHeuristicV(maplayout, start[0], start[1], open[x][0], open[x][1], goal[0], goal[1]);
    }
    minimum = Math.min(100000,heuristicValue[0]);
    for(var x = 1; x < open.length; x++) {
        minimum = Math.min(minimum, heuristicValue[x]);
    }
    for(var x = 0; x < open.length; x++) {
        if (minimum == heuristicValue[x]) {
            current = [open[x][0], open[x][1]];
        }
    }
    closed.push(current);
    //INCOMPLETE
}

The computeHeuristicV function computes the heuristic value in the code above.

A: "All adjacent squares" means every possible next hop on the path.

A: A* is a great algorithm to master and use. The two key elements are finding neighbors and the heuristic. A heuristic is used to estimate the distance between your current location, and the end. Also, the statement "find all adjacent squares" is referencing a neighbors function. For example, you might have the following:
var heuristic = function(state) {
    var endLocation = MyGame.getEndLocation();
    return Math.abs(state.x - endLocation.x) + Math.abs(state.y - endLocation.y)
}

var neighbors = function(state){
    var neighborStates = [];
    MyGame.setPlayer({
        x: state.x,
        y: state.y
    });
    neighborStates.push(MyGame.moveUp.getState());
    neighborStates.push(MyGame.moveRight.getState());
    neighborStates.push(MyGame.moveDown.getState());
    neighborStates.push(MyGame.moveLeft.getState());
    return neighborStates;
}

So, getting the "adjacent squares" is just asking you for the neighboring states or options. Personal plug: I just authored a simple a-star algorithm here: https://github.com/tssweeney/async-astar. Reading the description might help you to better understand the problem.


text:
Q: Update nodes detail in XML using XSLT I want to update some nodes in XML using XSLT. Like contact detail and Email.
Currently I am using  command like:
<xsl:template match="@*|node()*">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

<xsl:template match="/Metadata/contact/node/Email">

      <xsl:variable name="OName" select="/Metadata/contact/organisationName/CharacterString"/>
      <xsl:variable name="Email" select="/Metadata/contact/node/Email/CharacterString"/>

          <xsl:choose>
            <xsl:when test="contains($OName,'TestOrg')">
              <CharacterString>
                <xsl:value-of select="'test@Test.com'"/>
              </CharacterString>
            </xsl:when>
            <xsl:otherwise>
              <CharacterString>
                <xsl:value-of select="$Email"/>
              </CharacterString>
            </xsl:otherwise>
          </xsl:choose>

  </xsl:template>

As Contact nodes are multiple and in each Contact node there are one organizaion name and email id. For ex of contact nodes are 3 and currently it fetch 3 values in $OName variable and $Email variable so nodes are not match. So how can I update only some nodes in xml using XSLT?

A: The very first template you have is a so called "Identity template" and will loop through your complete source XML:
<xsl:template match="@*|node()*">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

The second template you have will match on every /Metadata/contact/node/Email. I would write this template a little bit different. Instead of matching the absolute path, I think it is best to match the Email/CharacterString node and then perform your actions.
I would use a template like:
<xsl:template match="Email/CharacterString">
    <xsl:copy>
        <xsl:choose>
            <xsl:when test="contains(ancestor::contact/organisationName/CharacterString,'TestOrg')">
                <xsl:value-of select="'test@Test.com'"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="."/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:copy>
</xsl:template>

Above template only matches the node you want to change (being Email/CharacterString). Once matches the xsl:copy copies the current selected node (CharacterString). The value will be filled depending on the value of ancestor::contact/organisationName/CharacterString. I am using the XPath Axe ancestor overhere. Which will be handy when changing the template.
If I would now change the template, for example only select the contact nodes that I would like to change, the second template can be written as:
<xsl:template match="contact[organisationRole/CharacterString = '1']/node/Email/CharacterString">
    <xsl:copy>
        <xsl:choose>
            <xsl:when test="contains(ancestor::contact/organisationName/CharacterString,'TestOrg')">
                <xsl:value-of select="'test@Test.com'"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="."/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:copy>
</xsl:template>

Here I only apply the template to contact nodes where ([]) the organisationRole/CharacterString equals the value 1. Note that the body of the template did not change. Therefore you can see why the use of the XPath Axe is usefull.
Complete XSLT
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <!-- Identity template -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="contact[organisationRole/CharacterString = '1']/node/Email/CharacterString">
        <xsl:copy>
            <xsl:choose>
                <xsl:when test="contains(ancestor::contact/organisationName/CharacterString,'TestOrg')">
                    <xsl:value-of select="'test@Test.com'"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="."/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Source XML
<?xml version="1.0" encoding="UTF-8"?>
<Metadata>
    <contact>
        <organisationRole>
            <CharacterString>1</CharacterString>
        </organisationRole>
        <organisationName>
            <CharacterString>TestOrg</CharacterString>
        </organisationName>
        <postalCode>
            <CharacterString>2020</CharacterString>
        </postalCode>
        <node>
            <Email>
                <CharacterString>some@user.com</CharacterString>
            </Email>
        </node>
    </contact>
    <contact>
        <organisationRole>
            <CharacterString>2</CharacterString>
        </organisationRole>
        <organisationName>
            <CharacterString>Example Org</CharacterString>
        </organisationName>
        <postalCode>
            <CharacterString>8080</CharacterString>
        </postalCode>
        <node>
            <Email>
                <CharacterString>somebody@else.com</CharacterString>
            </Email>
        </node>
    </contact>
    <contact>
        <organisationRole>
            <CharacterString>1</CharacterString>
        </organisationRole>
        <organisationName>
            <CharacterString>Real Org</CharacterString>
        </organisationName>
        <postalCode>
            <CharacterString>9050</CharacterString>
        </postalCode>
        <node>
            <Email>
                <CharacterString>user@example.com</CharacterString>
            </Email>
        </node>
    </contact>
</Metadata>

Produced output
<?xml version="1.0" encoding="UTF-8"?>
<Metadata>
    <contact>
        <organisationRole>
            <CharacterString>1</CharacterString>
        </organisationRole>
        <organisationName>
            <CharacterString>TestOrg</CharacterString>
        </organisationName>
        <postalCode>
            <CharacterString>2020</CharacterString>
        </postalCode>
        <node>
            <Email>
                <CharacterString>test@Test.com</CharacterString>
            </Email>
        </node>
    </contact>
    <contact>
        <organisationRole>
            <CharacterString>2</CharacterString>
        </organisationRole>
        <organisationName>
            <CharacterString>Example Org</CharacterString>
        </organisationName>
        <postalCode>
            <CharacterString>8080</CharacterString>
        </postalCode>
        <node>
            <Email>
                <CharacterString>somebody@else.com</CharacterString>
            </Email>
        </node>
    </contact>
    <contact>
        <organisationRole>
            <CharacterString>1</CharacterString>
        </organisationRole>
        <organisationName>
            <CharacterString>Real Org</CharacterString>
        </organisationName>
        <postalCode>
            <CharacterString>9050</CharacterString>
        </postalCode>
        <node>
            <Email>
                <CharacterString>user@example.com</CharacterString>
            </Email>
        </node>
    </contact>
</Metadata>

EDIT
If you only want to change the Email/CharacterString from the contacts where the organisationName/CharacterString contains the text TestOrg the XSLT would look like this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <!-- Identity template -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="contact[contains(organisationName/CharacterString,'TestOrg')]/node/Email/CharacterString">
        <xsl:copy>
            <xsl:value-of select="'test@Test.com'"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

A: From your description it seems your variables selects need to be relative to the context node of your template:
<xsl:template match="/Metadata/contact/node/Email">

  <xsl:variable name="OName" select="../../organisationName/CharacterString"/>
  <xsl:variable name="Email" select="CharacterString"/>

otherwise you will always start selecting from the root node for each match of the template and you will select all existing contact nodes every time.


text:
Q: Raphael path not displayed I believe I have a syntax error, but I have tried everything and can't figure this out.  I am using the Raphael Javascript vector graphics library, and trying to draw a black line from 170, 170 to 150, 150, but nothing is being displayed. Can anyone tell why?

A: You're misusing the Paper.path() constructor. Call it with a single string argument, representing the path string:
var newpath = paper.path("M170, 170 L150, 150");

If you wish to change the path's attributes, e.g. stroke color, fill, fonts use the attr() method, like so:
newpath.attr({
    'stroke' : 'black',
    'stroke-width' : 3
});

Raphaël Reference:

*

*Paper.path()

*Element.attr()


text:
Q: Shiny: IF with multiple functions depending on checkboxInputs & actionButton I am trying to build an app for data cleaning text data.
Once their file is uploaded the cleaning options appear (I stripped it out from this example code because that works already perfectly) and I want users to clean their data based on clickable options, so with checkboxInputs, and one selctizeInput (that pulls all words out of the file and you can pick which other words to remove from the dataset). It should all run once an action button is clicked. I have build a first "if" in the server, assuming all are clicked.
However it does nothing in my actual app. I am not sure where the actual mistake is, but have a feeling there are a few.
Any help much appreciated!
 ui:
 checkboxInput("clean1", label = "Remove Punctuation", value = TRUE),
 checkboxInput("clean2", label = "Remove Numbers", value = TRUE),
 checkboxInput("clean3", label = "Convert to lower case", value = TRUE),
 selectizeInput(
  'removeWords', 'Remove also these words', multiple = TRUE, choices = filebywords$words),
   actionButton("preprocessing", "Clean up my data")

  server:
  cleandata <- eventReactive(input$preprocessing, {

  if (input$clean1==TRUE &&
  input$clean2==TRUE &&
  input$clean3==TRUE && )
{

  df <- filedata()
  docs <- Corpus(DirSource(df))

  # clean 1 function
  docs <- tm_map(docs, removePunctuation)

  #clean 2 function
  docs <- tm_map(docs, removeNumbers)

  #clean 3 function
  docs <- tm_map(docs, tolower)

  # selctizeInput  words
  toremovedwords <- reactive({
    str(sapply(sprintf('removeWords'), function(id) {
      input[[id]]
    }, simplify = FALSE))
  })

   # remove words added in selectizeinput
  docs <- tm_map(docs, removeWords, c(toremovedwords()))

    }
  })


text:
Q: Cron job every x hours from a particular time, perpetually Let's say I want my cron job to run every 7 hours, it would look like this: 0 */6 * * * foo
But what I'd like to do is run it every 7 hours starting at a particular time.
If I want it to start at say 1am, I know I can do something like 0 1,8,15,22 * * * foo, but the issue is that this will reset the next day and start at 1 am.
What I'm looking for is a series like:

*

*1am

*(+7) 8am

*(+7) 3pm

*(+7) 10pm

*(+7) 5am on the next day

*(+7) 12pm

*(+7) 7pm

*(+7) 2am on the day after that

*etc..

How can I accomplish this?


text:
Q: Null pointer exception when referencing an object I'm writing a dice roller program for a project, and it prints an error when I try to access the Calculations object. Everything else works, from what I can tell (the variables are set correctly, everything prints in order.
Calculations c;
int stage = 0;
int number;
int die;
int mod;
int modnum;
int inc = 0;
int[] num = new int[20];
boolean plusminus;
int spot = 0;
void setup() {
  startScreen(inc);
}

void draw() {
}
//initial prompt screen
void startScreen(int stage) {
  switch(stage) {
  case 0:
    println("How many dice? (up to 9)");
    break;
  case 1:
    number = num[spot];
    //noLoop();
    println("Modifiers? (press + or -)");
    break;
  case 2:
    mod = num[spot];
    if (mod == 10) {
      plusminus = true;
    }
    if (mod == 11) {
      plusminus = false;
    }
    //noLoop();
    println("how much?");
    //loop();
    break;
  case 3:
    modnum = num[spot];
    //noLoop();
    println("which dice? (1 = d2, 2 = d3, 3 = d4, 4 = d6, 5 = d8, 6 = d10, 7 = d12, 8 = d20, 9= d100");
    break;
  case 4:
    die = num[spot];
    c.finalcalc();
    break;
  }
}

void keyPressed() {

  if (keyPressed) {
    if (keyCode == ENTER) {
      inc++;
      loop();
      startScreen(inc);
      noLoop();
    }

    if (keyCode != ENTER) {
      if (key == '1') {
        num[spot] = 1;
        println(num[spot]);
      } else if (key == '2') {
        num[spot] = 2;
        println(num[spot]);
      } else if (key == '3') {
        num[spot] = 3;
        println(num[spot]);
      } else if (key == '4') {
        num[spot] = 4;
        println(num[spot]);
      } else if (key == '5') {
        num[spot] = 5;
        println(num[spot]);
      } else if (key == '6') {
        num[spot] = 6;
        println(num[spot]);
      } else if (key == '7') {
        num[spot] = 7;
        println(num[spot]);
      } else if (key == '8') {
        num[spot] = 8;
        println(num[spot]);
      } else if (key == '9') {
        num[spot] = 9;
        println(num[spot]);
      } else if (key == '+') {
        num[spot] = 10;
        println(num[spot]);
      } else if (key == '-') {
        num[spot] = 11;
        println(num[spot]);
      }
    }
  }
}

class Calculations {
  int dice() {
    int i = 0;
    if (die == 1) {
      i = round(random(2));
    }
    if (die == 2) {
      i = round(random(3));
    }
    if (die == 3) {
      i = round(random(4));
    }
    if (die == 4) {
      i = round(random(6));
    }
    if (die == 5) {
      i = round(random(8));
    }
    if (die == 6) {
      i = round(random(10));
    }
    if (die == 7) {
      i = round(random(12));
    }
    if (die == 8) {
      i = round(random(20));
    }
    if (die == 9) {
      i = round(random(100));
    }
    return i;
  }
  int finalcalc() {
    int[] roll = new int[key];
    int result = 0;
    for (int i = 0; i > roll.length; i++) {
      roll[i] = dice();
      if (plusminus == true) {
        result = dice() + modnum;
      }
      if (plusminus == false) {
        result = dice() - modnum;
      }
    }
    return result;
  }
}

I've made sure that my arrays are initialized properly, and I made sure that each of my variables are being referenced correctly, but this hasn't changed anything. I'm not sure what else I need to do.
Here is the error:
java.lang.NullPointerException: Cannot invoke "Final_Project$Calculations.finalcalc()" because "this.c" is null
    at Final_Project.startScreen(Final_Project.java:68)
    at Final_Project.keyPressed(Final_Project.java:80)

A: It's missing : Calculations c= new Calculations();


text:
Q: Unable to glTranslate() light source I am having a problem translating the light source.
I have coded a program that accepts up, down, left, and right keys to increase/decrease the x, y, and z values to reposition the light source. But the problem right now is the  x, y, and z value does change but the light source remains in the same place. I believe the problem shall be somewhere inside the void lighting() function.
below is my code:
#include <Windows.h>
#include <gl/GL.h>
#include <math.h>
#include <gl/GLU.h>

#pragma comment (lib, "OpenGL32.lib") //link library
#pragma comment(lib, "Winmm.lib")

#define WINDOW_TITLE "Lighting"

bool isOrtho = true;
float ONear = -10.0, OFar = 10.0;   //Ortho Near & Far
float PNear = 1.0, PFar = 21.0;     //Perspective Near & Far
float exeDif[3] = { 1.0,0.0,0.0 };  //Red diffuse light
float x =6 , y=0, z=0;
float exePosD[3] = { 6,0,0 };
float exeDifM[3] = { 1.0,0.0,0.0 };
bool isLightOn = false;     //is light on?

LRESULT WINAPI WindowProcedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_DESTROY:
        PostQuitMessage(0);//quit application
        break;

    case WM_KEYDOWN:
        if (wParam == VK_ESCAPE) PostQuitMessage(0);
        else if (wParam == VK_SPACE) {
            isLightOn = !isLightOn;
        }
        else if (wParam == VK_UP) {
            y = y + 1.0;
        }
        else if (wParam == VK_DOWN) {
            y = y - 1.0;
        }
        else if (wParam == VK_LEFT) {
            x = x - 1.0;
        }
        else if (wParam == VK_RIGHT) {
            x = x + 1.0;
        }
        else if (wParam == 'Q') {
            z = z - 1.0;
        }
        else if (wParam == 'E') {
            z = z + 1.0;
        }

        break;
    default:
        break;
    }

    return DefWindowProc(hWnd, msg, wParam, lParam);
}

bool initPixelFormat(HDC hdc)
{
    PIXELFORMATDESCRIPTOR pfd;
    ZeroMemory(&pfd, sizeof(PIXELFORMATDESCRIPTOR));

    pfd.cAlphaBits = 8;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 24;
    pfd.cStencilBits = 0;

    pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;

    pfd.iLayerType = PFD_MAIN_PLANE;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;

    // choose pixel format returns the number most similar pixel format available
    int n = ChoosePixelFormat(hdc, &pfd);

    // set pixel format returns whether it sucessfully set the pixel format
    if (SetPixelFormat(hdc, n, &pfd))
    {
        return true;
    }
    else
    {
        return false;
    }
}

void lighting() {
    if (isLightOn) {
        glEnable(GL_LIGHTING);          //Turon on lighting for the whole scene
    }
    else {
        //Turn off lighting for the whole screen
        glDisable(GL_LIGHTING);
    }

    glPushMatrix();
    glTranslatef(x, y, z);
    glLightfv(GL_LIGHT0, GL_POSITION, exePosD);
    glPopMatrix();

    glLightfv(GL_LIGHT0, GL_DIFFUSE, exeDif);

    glEnable(GL_LIGHT0);
}

void projection() {
    glMatrixMode(GL_PROJECTION);    //refer to projection matrix
    glLoadIdentity();               //reset projection matrix
    if (isOrtho) {
        //Ortho View
        glOrtho(-10.0, 10.0, -10.0, 10.0, ONear, OFar); //Ortho view
    }
    else {
        //Perspective view
        gluPerspective(20, 1.0, -1.0, 1.0);
        glFrustum(-10.0, 10.0, -10.0, 10.0, PNear, PFar);
    }
}

void drawSphere(double r) {
    GLUquadricObj* sphere = NULL;
    sphere = gluNewQuadric();
    gluQuadricDrawStyle(sphere, GLU_FILL);
    gluSphere(sphere, r, 30, 30);
    gluDeleteQuadric(sphere);
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    projection();                   //projection
    lighting();

    glMatrixMode(GL_MODELVIEW);     //refer to modelview matrix
    glLoadIdentity();               //reset
    drawSphere(3.0);

    //red color diffuse
    glMaterialfv(GL_FRONT, GL_DIFFUSE, exeDifM);

    glColor3f(0.0, 0.0, 1.0);       //blue
    drawSphere(3.0);
}

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, int nCmdShow)
{
    WNDCLASSEX wc;
    ZeroMemory(&wc, sizeof(WNDCLASSEX));

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.hInstance = GetModuleHandle(NULL);
    wc.lpfnWndProc = WindowProcedure;
    wc.lpszClassName = WINDOW_TITLE;
    wc.style = CS_HREDRAW | CS_VREDRAW;

    if (!RegisterClassEx(&wc)) return false;

    HWND hWnd = CreateWindow(WINDOW_TITLE, WINDOW_TITLE, WS_OVERLAPPEDWINDOW,
        720, 10, 300, 300,
        NULL, NULL, wc.hInstance, NULL);

    //--------------------------------
    //  Initialize window for OpenGL
    //--------------------------------

    HDC hdc = GetDC(hWnd);

    //  initialize pixel format for the window
    initPixelFormat(hdc);

    //  get an openGL context
    HGLRC hglrc = wglCreateContext(hdc);

    //  make context current
    if (!wglMakeCurrent(hdc, hglrc)) return false;

    //--------------------------------
    //  End initialization
    //--------------------------------

    ShowWindow(hWnd, nCmdShow);

    MSG msg;
    ZeroMemory(&msg, sizeof(msg));

    while (true)
    {
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            if (msg.message == WM_QUIT) break;

            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        display();

        SwapBuffers(hdc);
    }

    UnregisterClass(WINDOW_TITLE, wc.hInstance);

    return true;
}

This is the output screen:

A: The light position is transformed with the modelview matrix, but not with the projection matrix. Therefore you need to switch to the modelview matrix after projection() and before lighting():
projection();                   //projection

glMatrixMode(GL_MODELVIEW);     //refer to modelview matrix
glLoadIdentity();

lighting();


text:
Q: Solutions of 2nd order Fuchsian differential equations as Heun or Hypergeometric functions. I have been trying to find a solution on any of these Fuchsian differential equations...
$v''(z)+\frac{A_1+B_1z }{z (z-1) }v'(z)+\frac{C_1+ D_1 z}{z^2 (z-1)^2 }v(z)=0$
$u''(z)+\frac{A_0+B_0 z^2 }{z(z-1) (z+1)}u'(z)+\frac{C_0+D_0 z^2 }{z^2(z-1)^2 (z+1)^2}u(z)=0$
$A_0,A_1,B_0,B_1,C_0,C_1,D_0,D_1$ $\in \mathbb{C}$ and aren't integers.
I would say that the first one looks exactly as the Fuchsian form of the Hypergeometric differential equation, since the singular points it has, are in $0$,$1$ and $\infty$
The second one seems more complicated to me. Based on what I have read, it  should be possible to express it as the Heun differential equation,  but I do not really understand how to do that.
I  understand that this form is one of the most "canonical" since the regular points are in $0$,$1$, $-1$ and $\infty$
How could I try to solve this 2 differential equations? And which one could be easier to solve?
Also, I wonder, I tried to solve these differential equations using Mathematica. And it gave results for both in terms of the Hypergeometric functions. So I guess the solutions of the Heun differential equation (The heun functions )can be expressed as Hypergeometric functions as well, Is there any advantage of doing so?
Could you please recommend me an introductory book on this topic?
I recently started in this topic, and some books are kind of much advanced for a newbie.
Something that I have been using as reference:
https://www.ams.org/journals/mcom/2007-76-258/S0025-5718-06-01939-9/S0025-5718-06-01939-9.pdf
Thanks in advance, for any comments/suggestions/ideas!


text:
Q: Displaying user location in a paragraph When this page is loaded, an alert asks you if you would like to let the website use your current address. I want to change this code so that when the user clicks okay, the address is posted to a paragraph tag in the body instead of the alert.
How would one go about this?
<!DOCTYPE html>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>

this is whats in my body section

A: You should put some elements in your body and write to them instead.
Since you are using jquery, you can access them with $("#IDNAME") selectors, and apply text changes to them with the .text(NEWTEXT) function, and comment out the alert functions so they do not activate.
Example is here: http://jsfiddle.net/htthzx6a/

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Reverse Geocoding</title>


text:
Q: Stylus issues on ubuntu 18.04 Even though Ubuntu's Wacom setting detects my Wacom Bamboo pad the stylus barely works, and it acts more like a barely functioning mouse than a digital pen. I can only draw faint straight lines after it lags. I'm using the gnome Xorg build as many users suggested in similar situations but the results are the same.  It works on the Unity build but Ubuntu freezes ten minutes after I log in so that's not an option anymore.
Even the Xinput list detects the stylus:
themadbaron@themadbaron-desktop:~$ xinput --list
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ Wacom Wireless Bamboo PAD Pen stylus      id=8    [slave  pointer  (2)]
⎜   ↳ Wacom Wireless Bamboo PAD Finger touch    id=9    [slave  pointer  (2)]
⎜   ↳ USB Keyboard                              id=11   [slave  pointer  (2)]
⎜   ↳ Wacom Wireless Bamboo PAD Pen eraser      id=16   [slave  pointer  (2)]
⎜   ↳ Logitech USB Receiver                     id=12   [slave  pointer  (2)]
⎜   ↳ Logitech USB Receiver                     id=14   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Power Button                              id=7    [slave  keyboard (3)]
    ↳ USB Keyboard                              id=10   [slave  keyboard (3)]
    ↳ Eee PC WMI hotkeys                        id=15   [slave  keyboard (3)]
    ↳ USB Keyboard                              id=17   [slave  keyboard (3)]
    ↳ Logitech USB Receiver                     id=13   [slave  keyboard (3)]
themadbaron@themadbaron-desktop:~$

But no luck


text:
Q: Kubernetes: Is it possible to get master nodes IP/Name in GKE regional cluster As per the google GKE documentation, for regional cluster's masters and nodes are spread across multiple zones. Is there anyway in GKE to see the master nodes with which zone it is running?
I also tried kubectl cluster-info and it gives me the below result. Is that mean my cluster have only one master running ?
Kubernetes master is running at https://xx.xx.xx.xx
GLBCDefaultBackend is running at https://xx.xx.xx.xx/api/v1/namespaces/kube-system/services/default-http-backend:http/proxy
Heapster is running at https://xx.xx.xx.xx/api/v1/namespaces/kube-system/services/heapster/proxy
KubeDNS is running at https://xx.xx.xx.xx/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
Metrics-server is running at https://xx.xx.xx.xx/api/v1/namespaces/kube-system/services/https:metrics-server:/proxy

A: In GKE you don't have a master per say.
GKE and EKS takes care of master node for you, this is mostly the adventage of those features instead of using AWS and GCP to just spawn a VM.

A: Master nodes in GKE are managed by google, thus you will not be able to see them.
By default, a regional GKE cluster will create three master nodes spread across three zones.
Therefore, only a single static API endpoint is provided for the entire cluster.
The https://xx.xx.xx.xx represents your cluster API endpoint.
I invite you to visit this documentation to have an insight on how GKE operates.


text:
Q: The AWS Access Key Id you provided does not exist in our records I had written a library in PHP using the AWS to communicate with the ECS server. Now I am migrating my code to java. In java I am using the same key and secret which I used in PHP.
In php I used the following method:
$s3 = Aws\S3\S3Client::factory(array( 'base_url' => $this->base_url, 'command.params' => array('PathStyle' => true), 'key' => $this->key, 'secret' => $this->secret ));

In java I am using following method
BasicAWSCredentials(String accessKey, String secretKey);

I am getting the following exception:
Exception in thread "main" com.amazonaws.services.s3.model.AmazonS3Exception: The AWS Access Key Id you provided does not exist in our records. (Service: Amazon S3; Status Code: 403; Error Code: InvalidAccessKeyId; Request ID: 3A3000708C8D7883), S3 Extended Request ID: U2rG9KLBBQrAqa6M2rZj65uhaHhOpZpY2VK1rXzqoGrKVd4R/JdR8aeih/skG4fIrecokE4FY3w=
at      com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1401)
    at         com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:945)
    at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:723)
    at com.amazonaws.http.AmazonHttpClient.doExecute(AmazonHttpClient.java:475)
    at com.amazonaws.http.AmazonHttpClient.executeWithTimer(AmazonHttpClient.java:437)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:386)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3996)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3933)
    at com.amazonaws.services.s3.AmazonS3Client.listBuckets(AmazonS3Client.java:851)
    at com.amazonaws.services.s3.AmazonS3Client.listBuckets(AmazonS3Client.java:857)
    at com.justdial.DocUpload.DocUpload.main(DocUpload.java:22)

Do I need a new key and secret for Java or the previous one can be used.
My questions are:
1 -  Is then any prerequisite that we need to follow before using AWS's  BasicAwsCredentials() method.
2 -  Do we need to create the IAM roles.
3 -  If we do then how will it come to know which IP to hit as in case of PHP in Aws\S3\S3Client::factory method I was specifying the base url.

A: Following code worked for me.
String accesskey = "objuser1";
String secret = "xxxxxxxxxxxxxxxx";
ClientConfiguration config = new ClientConfiguration();
config.setProtocol(Protocol.HTTP);
AmazonS3 s3 = new AmazonS3Client(new BasicAWSCredentials(accesskey, secret), config);
S3ClientOptions options =  new S3ClientOptions();
options.setPathStyleAccess(true);
s3.setS3ClientOptions(options);
s3.setEndpoint("1.2.3.4:9020");  //ECS IP Address
System.out.println("Listing buckets");
for (Bucket bucket : s3.listBuckets()) {
    System.out.println(" - " + bucket.getName());
}
System.out.println();

A: AWS access key and secret access keys are independent of SDKs you use (doesn't matter whether you use PHP, Java or Ruby etc), it's more about granting and getting access to services you run/use on AWS.
Root cause of the error is I think you've not set AWS region though you've given access key and secret access key. Please check this to set AWS credentials for Java.
To answer your questions.

*

*As far as I know BasicAwsCredentials() itself acts as prerequisite step before you want to do anything with Amazon services. Only prerequisite for BasicAwsCredentials() is to have the authentication keys.

*No, it's not mandatory step. It's an alternative. Please check the definition of IAM role from this link.

*You can use the 'endpoint' to do the same job in Java. Check 'endpoint' details from this link.
Please take a look at the examples from here.
Using the same method I'm able to successfully do the 'BasicAwsCredentials()'. And also cross check whether 'access key' and 'secret access key' have necessary permissions to access Amazon services as per your need. Check IAM user, group and ensure they've necessary AWS permissions.


text:
Q: keyboard avoid view not enough height keyboard pushes "CreateComment" component to top but not enough height ,it's still hides the "CreateComment" component which it includes "InputText"

     <ScrollView >
                 ....
      </ScrollView>

     <KeyboardAvoidingView behavior='position'>
      <View  style={styles.footer}>
       <CreateComment GetComments={()=>this.GetComments()}
        roomId={this.state.postID} />
       </View>
      </KeyboardAvoidingView>

</View>

and here is stlye:
container: {
flex: 1,
},
footer :{
 position:'absolute',
 bottom:0 },
...

A: You can change the height you want to specify yourself.
You can use offset
Example
<KeyboardAvoidingView
          behavior="position"
          keyboardVerticalOffset={100}
        >


text:
Q: Have the chapter title stick out of the type area I'm trying to place my chapter titles to the edge of the page, with a colored background box surrounding them. The surrounding boxes would need to be set outside of the body of the document. So far I have read the documentation of typearea, geometry, layouts, titlesec, TikZ and others but haven't been able to find a solution.
See http://latex-project.org/guides/lb2-ch4.pdf for an example of the effect I want to achieve. There the chapter title reaches farther right than the text body.
What I want is to have my chapter titles in a a colored box similar to the headings on the 2nd page of the attached document on the left edge on the page.
Here is the code for the box. I just need a way to place it on the left page edge.
\documentclass[a4paper,12pt]{report}

\usepackage{tikz}
\usepackage[uppercase, sf, explicit, raggedright]{titlesec} %
\usepackage{xcolor}

\makeatletter
\titleformat{\chapter}
{\sffamily\huge\bfseries}
{}
{0pt}
{
    \usetikzlibrary{backgrounds}
    \tikzstyle{background rectangle}=[fill=cyan]
    \begin{tikzpicture}[framed]
    \color{white}
    \draw (0,0) +(3ex,0) node[anchor=west]{Chapter \thechapter{} \filright#1};
    \end{tikzpicture}
}
\makeatother
\begin{document}
\chapter{Chaptertitle}
\end{document}

A: You can simply set the 4th argument of \titleformat to a negative value.
In the following MWE I've set it at the left margin of the page:
\documentclass[a4paper,12pt]{report}

\usepackage{tikz}
\usetikzlibrary{backgrounds}

\usepackage[uppercase, sf, explicit, raggedright]{titlesec} %
\usepackage{xcolor}
\usepackage{lipsum} % only for the example

\titleformat{\chapter}
{\sffamily\huge\bfseries}
{}
{\dimexpr-\oddsidemargin-\hoffset-1in}
{%
    \tikzstyle{background rectangle}=[fill=cyan]%
    \begin{tikzpicture}[framed]
    \color{white}
    \draw (0,0) +(3ex,0) node[anchor=west]{Chapter \thechapter{} \filright#1};
    \end{tikzpicture}%
}
\begin{document}
\chapter{Chaptertitle}
\lipsum[1-5]
\end{document}

Output:

Some remarks:

*

*\makeatletter...\makeatother is not needed since no @ character is involved.

*I've put \usetikzlibrary{backgrounds} outside the definition.

*I've removed some spurious spaces in the definition adding % at the end of some lines

EDIT
To achieve the same result for unnumbered chapters as \tableofcontents you have to declare a separate \titleformat:
\titleformat{name=\chapter,numberless}
{\sffamily\huge\bfseries}
{}
{\dimexpr-\oddsidemargin-\hoffset-1in}
{%
    \tikzstyle{background rectangle}=[fill=cyan]%
    \begin{tikzpicture}[framed]
    \color{white}
    \draw (0,0) +(3ex,0) node[anchor=west]{#1};
    \end{tikzpicture}%
}

Complete MWE
\documentclass[a4paper,12pt]{report}

\usepackage{tikz}
\usetikzlibrary{backgrounds}

\usepackage[uppercase, sf, explicit, raggedright]{titlesec} %
\usepackage{xcolor}
\usepackage{lipsum} % only for the example

\titleformat{\chapter}
{\sffamily\huge\bfseries}
{}
{\dimexpr-\oddsidemargin-\hoffset-1in}
{%
    \tikzstyle{background rectangle}=[fill=cyan]%
    \begin{tikzpicture}[framed]
    \color{white}
    \draw (0,0) +(3ex,0) node[anchor=west]{Chapter \thechapter{} \filright#1};
    \end{tikzpicture}%
}

\titleformat{name=\chapter,numberless}
{\sffamily\huge\bfseries}
{}
{\dimexpr-\oddsidemargin-\hoffset-1in}
{%
    \tikzstyle{background rectangle}=[fill=cyan]%
    \begin{tikzpicture}[framed]
    \color{white}
    \draw (0,0) +(3ex,0) node[anchor=west]{#1};
    \end{tikzpicture}%
}

\begin{document}
\tableofcontents

\chapter{Chaptertitle}
\lipsum[1-5]
\end{document}

Output (ToC)


text:
Q: Como converter uma view para string no controller? Gostaria de converter essa view para string e ter o valor em string em meu controller
O problema é que eu gostaria que ela executasse um trecho de script que está nessa view
O método atual que tenho, apenas converte, sem executar o script que está nessa view
Atualmente está assim:
  public static string PartialViewToString(this Controller controller, string viewName, object model)
    {
      if (string.IsNullOrEmpty(viewName))
      {
        viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
      }

      controller.ViewData.Model = model;

      using (StringWriter stringWriter = new StringWriter())
      {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, stringWriter);
        viewResult.View.Render(viewContext, stringWriter);
        return stringWriter.GetStringBuilder().ToString();
      }
    }

Em meu controller chamo:
var htmlString = helper.PartialViewToString(this,"NomeView",model);

A: Os scripts na view só são executados do lado do cliente - no browser - depois do HTML ter sido gerado e enviado para o cliente.
Vais precisar de outra view sem javascript para gerar o PDF. Até existem javascript engines para correr do lado do servidor, mas acho que isso seria desnecessário, seria considerado um "hack", e sem duvida iria afectar a performance do servidor.


text:
Q: Using RenderScript Intrinsic BLAS to perform matrix operations in Android but I got wrong result? I need to perform matrix operations in Android, so I searched about the RenderScript, and I got useful information here
I tried the program in the answer above like this:
private void compute(){
    mRs = RenderScript.create(this);

    Type.Builder builder = new Type.Builder(mRs, Element.U8(mRs));
    Type a_type = builder.setX(3).setY(2).create();
    Type b_type = builder.setX(3).setY(2).create();
    Type c_type = builder.setX(2).setY(2).create();
    Allocation A = Allocation.createTyped(mRs, a_type);
    Allocation B = Allocation.createTyped(mRs, b_type);
    Allocation C = Allocation.createTyped(mRs, c_type);

    A.copyFrom(new byte[]{1, 2, 3, 1, 2, 3});
    B.copyFrom(new byte[]{1, 1, 1, 0, 1, 0});

    ScriptIntrinsicBLAS BLAS =  ScriptIntrinsicBLAS.create(mRs);
    BLAS.BNNM(A, 0, B, 0, C, 0, 1);

    byte[] result = new byte[]{1,2,3,4};
    C.copyTo(result);

    for(int i = 0; i < result.length; ++i){
        Log.i(TAG, i + " " + result[i]);
    }
}

My gradle file is like this following:
targetSdkVersion 25
renderscriptTargetApi 25
renderscriptSupportModeEnabled true
renderscriptSupportModeBlasEnabled true

But I got the wrong results that all items in the matrix C is zero:
08-25 16:31:05.384 30771-30771/cn.jy.testsiblas I/tag: 0 0
08-25 16:31:05.384 30771-30771/cn.jy.testsiblas I/tag: 1 0
08-25 16:31:05.384 30771-30771/cn.jy.testsiblas I/tag: 2 0
08-25 16:31:05.384 30771-30771/cn.jy.testsiblas I/tag: 3 0

Someone knows how to solve this?
Besides, I have just found there seems to be limitation in the dimensions of matrix that can be handled with ScriptIntrinsicBLAS? here is a question about this
Anyone know about this limitation? If limitation is real, I'm afraid I have to find out another way to handle matrix operation on Android.

A: It's because of this from the docs: Calculations are done in 1.10.21 fixed-point format for the final output, just before there's a shift down to drop the fractional parts.
So any calculated value which is less than 2^21 (~2million) will be shifted out of the answer.
If you want to do calculations on numbers in this range you need to shift your values into the high bits of the input.


text:
Q: Randomly directed to the bottom of the page instead of the correct post/comment The issue only started occurring recently.
Usually, when clicking on a link to a specific answer/comment, the new page automatically scrolls to a position where the answer/comment is shown at the top of the visible screen. However it recently started going all the way down and directly present me with the bottom of the page.
I have not found a stable way to reproduce the problem, but I promise it is there. It confused me for quite a while, and made me hesitate for another while before posting this question here. In general it has a higher chance to occur on comments, and on a significantly higher chance on links where another link to another item on the same page has this issue.
It occurred on two of my Android phones running A 5.1 and A 7.1, Google Chrome 52, 58 and 64 (all from Play store), so I guess it's not my fault.


text:
Q: CorePlot Remove bar shadow effect In iPhone App i am using core Plot vertical bar chart.
How to Remove shadow effect in Vertical Bars?
Here as shown in figure bars are displaying with shadow

Here is the code:
CPBarPlot *barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor colorWithComponentRed:111 green:129  blue:113 alpha:1.0] horizontalBars:NO];
barPlot.shadowColor=NO;
How can I remove this shadow effect?
Please Help and Suggest.
Thanks

A: Haven't tested this, but my guess is that what you see is not a shadow but a gradient fill generated by the use of "tubularBarPlotWithColor". The shadow is probably something outside the bar borders.
Instead, try creating the bar plot with:
CPBarPlot *barPlot = [[CPBarPlot alloc] init];

Then use:
barPlot.fill = [CPFill fillWithColor:myCPColor];

Or if you actually want a gradient fill:
fillGradient = [CPGradient gradientWithBeginningColor:myCPColorBegin endingColor:myCPColorEnd];
barPlot.fill = [CPFill fillWithGradient:fillGradient];

Hope this helps!
Claes

A: I faced the white colored plots isssue
yourPlot.fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:80.0f / 255.0f green:186.0f / 255.0f blue:224.0f / 255.0f alpha:1.0f]];
this gives me the desired color..


text:
Q: How should the backend code be if I want to give a part of a large amount of data and provide more and more as the frontend asks? I'm currently using loopbackjs for making the API endpoints, and graphQL as an intermediate for making queries from the frontend, where I use Relay and React framework.
Now, I have an application where a user can view a list of projects (The project has very generic information like creation date, name, etc.). This list of projects can be very large. So its infeasible to just send all the projects at once. Now, I want to send the first few projects to the frontend and then as the user scrolls down, I want to send a part of the remaining projects when the user reaches the end of the list provided to him/her in the frontend.
I've thought about maintaining a pointer sort of a thing, that indicates till where I've fetched the projects in the list so that I know from where I would fetch the further projects. But this pointer is dependent on the user so for every user I need to maintain a pointer. This gets everything very messy.
Is there a clean approach for doing what I want with the current stack I am using?

A: Here is how I fetch my first 25 projects:
projects(first: 25, after: $lastID) {
  ...
}

You could probably change the either variables passed to graphql to return you the infinite scrolling of list of projects. First 25 already helps u limit the amount u get back.
For more references you could find it here https://facebook.github.io/relay/docs/graphql-connections.html


text:
Q: Symfony render author name I'm new in symfony and I want to know how to render the username of an author from my Comment table. I just don't know how to work with that key to render values from another Table. Also, if you see something that I should change, I appreciate it. If someone can give me an example, it would be great!
The Error/twig:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Proxies\__CG__\AppBundle\Entity\User could not be converted to string").

                            {{ item.author }} {{ item.publishedAt|date('Y-m-d H:i:s') }}
                            {% if is_granted('ROLE_USER') %}
                                Add Comment
                            {% endif %}

                            {{ item.content }}

User Entity:
 /**
 * @ORM\Entity
 * @ORM\Table(name="user")
 * @UniqueEntity(fields={"email"}, message="It looks like your already have an account!")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @Assert\NotBlank()
     * @Assert\Email()
     * @ORM\Column(type="string", unique=true)
     */
    private $email;

    /**
     * @ORM\Column(type="string")
     */
    private $password;

    /**
     * @Assert\NotBlank(groups={"Registration"})
     * @var string
     */
    private $plainPassword;

    /**
     * @ORM\Column(type="json_array")
     */
    private $roles = array();

    /**
     * @ORM\OneToMany(targetEntity="Comment", mappedBy="author")
     */
    private $user;

    public function __construct()
    {
        $this->user = new ArrayCollection();
    }

    public function getUsername()
    {
        return $this->email;
    }

    public function getRoles()
    {
        $roles = $this->roles;

        if (!in_array('ROLE_USER', $roles))
        {
            $roles[] = 'ROLE_USER';
        }

        return $roles;
    }

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

    public function getPassword()
    {
        return $this->password;
    }

    public function getSalt()
    {
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function eraseCredentials()
    {
        $this->plainPassword = null;
    }

    /**
     * @param mixed $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }

    /**
     * @param mixed $password
     */
    public function setPassword($password)
    {
        $this->password = $password;
    }

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

    /**
     * @param mixed $plainPassword
     */
    public function setPlainPassword($plainPassword)
    {
        $this->plainPassword = $plainPassword;
        $this->password = null;
    }

    /**
     * @param mixed $roles
     */
    public function setRoles($roles)
    {
        $this->roles = $roles;
    }

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

}

Comment Entity:
/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CommentRepository")
 * @ORM\Table(name="comments")
 */
class Comment
{
    public function __construct()
    {
        $this->publishedAt = new \DateTime();
    }

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Product
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Product")
     * @ORM\JoinColumn(nullable=false)
     */
    private $product;

    /**
     * @var string
     *
     * @ORM\Column(type="text")
     * @Assert\Length(
     *     min=5,
     *     minMessage="Comment is too short!",
     *     max=10000,
     *     maxMessage="Comment is too long!"
     * )
     */
    private $content;

    /**
     * @var User
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="user")
     * @ORM\JoinColumn(name="author_id", referencedColumnName="id")
     */
    private $author;

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

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Comment")
     * @ORM\JoinColumn(nullable=false)
     */
    private $comment;

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

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return Product
     */
    public function getProduct()
    {
        return $this->product;
    }

    /**
     * @param Product $product
     */
    public function setProduct($product)
    {
        $this->product = $product;
    }

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

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

    /**
     * @return User
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * @param User $author
     */
    public function setAuthor($author)
    {
        $this->author = $author;
    }

    /**
     * @return \DateTime
     */
    public function getPublishedAt()
    {
        return $this->publishedAt;
    }

    /**
     * @param \DateTime $publishedAt
     */
    public function setPublishedAt($publishedAt)
    {
        $this->publishedAt = $publishedAt;
    }

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

    /**
     * @param mixed $commentlist
     */
    public function setCommentlist($comment)
    {
        $this->comment = $comment;
    }

}

A: {{ item.author }} is User object
Specify users property you want to show:
Ex.:
{{ item.author.username }}


text:
Q: Batch Difficulty Using Variables The values a1 through a9 are equal to some number that is modulus 13 (0-12) and the values 0 through 12 are then equal to the card range 2-A. I am trying to call A from 0 from a3 or the 7 from 8 from a1 with this code:
for %%R in (1 3) do (for %%S in (!a%%R!) do if !b%%R!==4 echo P1 has a !%%S! 4 of a kind
if !b%%R!==3 echo P1 has a !%%S! 3 of a kind
if !b%%R!==2 echo P1 has a !%%S! pair)
for %%T in (2 4) do (for %%U in (!a%%T!) do if !b%%T!==4 echo CP has a !%%U! 4 of a kind
if !b%%T!==3 echo CP has a !%%U! 3 of a kind
if !b%%T!==2 echo CP has a !%%U! pair)

But the output is simply either "P1 has a  pair" or "CP has a  3 of a kind" without the value that I need. b1 through b4 are unimportant, they just signify the number of repeated cards there are to identify pairs and such.
How do I receive the output that I desire and also, how can I simplify this:
set 0=A
set 1=2
set 2=3
set 3=4
set 4=5
set 5=6
set 6=7
set 7=8
set 8=9
set 9=10
set 10=J
set 11=Q
set 12=K

A: To shorten the sequence of set commands -
setLocal enableDelayedExpansion
set i=0
for %%a in (A 1 2 3 4 5 6 7 8 9 10 J Q K) do (
    set !i!=%%a
    set /a i+=1
)

A: Your code have a couple problems. In first place, the second for command is not appropriately nested because it apply just to the first if command. This way, in the second and third if commands the %%S replaceable parameter is not defined. The way you write your code makes difficult to isolate this types of errors, so my first recommendation is to always use justification in nested commands and to place the closing parentheses in a way that clearly mark the end of each for or if construct. Below there is an example of such format.
In second place, a trace of your code results in these actions:
%%R = 1
%%S = !a%%R! = !a1! = a numeric value between 0 and 12
if !b1!==4 echo P1 has a !%%S! 4 of a kind

In the last line %%S has a numeric value, so !%%S! tries to replace the value of a variable whose name is a number! I think you forgot an array here, so I inserted card as the name of the array that store the card names as you show above:
@echo off
setlocal EnableDelayedExpansion

rem Define names of cards
set i=0
for %%a in (A 2 3 4 5 6 7 8 9 10 J Q K) do (
   set card!i!=%%a
   set /A i+=1
)

rem The values a1 through a9 are equal to some number that is modulus 13 (0-12)
for /L %%i in (1,1,9) do set /A a%%i=!random! %% 13

rem b1 through b4 ... signify the number of repeated cards there are to identify pairs and such.
set "b1=2"    // two cards of b1 type
set "b2=0"    // no cards of b2 type
set "b3=4"    // four cards of b3 type
set "b4=1"    // one card of b4 type

rem I am trying to call A from 0 from a3 or the 7 from 8 from a1 with this code:
for %%R in (1 3) do for %%S in (!a%%R!) do (
   if !b%%R!==4 echo P1 has a !card%%S! 4 of a kind
   if !b%%R!==3 echo P1 has a !card%%S! 3 of a kind
   if !b%%R!==2 echo P1 has a !card%%S! pair
)
for %%T in (2 4) do for %%U in (!a%%T!) do (
   if !b%%T!==4 echo CP has a !card%%U! 4 of a kind
   if !b%%T!==3 echo CP has a !card%%U! 3 of a kind
   if !b%%T!==2 echo CP has a !card%%U! pair
)

Output example:
C:\> test
P1 has a A pair
P1 has a Q 4 of a kind

You may also do a further simplification this way:
for %%R in (1 3) do for %%S in (!a%%R!) do (
   if !b%%R! gtr 1 echo P1 has a !card%%S! !b%%R! of a kind
)
for %%T in (2 4) do for %%U in (!a%%T!) do (
   if !b%%T! gtr 1 echo CP has a !card%%U! !b%%T! of a kind
)

In the last simplification, you may also define an array of "names of multiples" like "2=pair", "3=3 of a kind", etc. if you want to show a more precise result.

A: I can't vouch for the logic of your code. But you are missing a set of parentheses within each inner FOR loop. As currently written, %%S and %%U are only defined for one IF statement each. You need them each for three statements, like so:
for %%R in (1 3) do (
  for %%S in (!a%%R!) do (
    if !b%%R!==4 echo P1 has a !%%S! 4 of a kind
    if !b%%R!==3 echo P1 has a !%%S! 3 of a kind
    if !b%%R!==2 echo P1 has a !%%S! pair
  )
)
for %%T in (2 4) do (
  for %%U in (!a%%T!) do (
    if !b%%T!==4 echo CP has a !%%U! 4 of a kind
    if !b%%T!==3 echo CP has a !%%U! 3 of a kind
    if !b%%T!==2 echo CP has a !%%U! pair
  )
)

Or you could shorten it a bit as follows:
for %%R in (1 3) do for %%S in (!a%%R!) do (
  if !b%%R!==4 echo P1 has a !%%S! 4 of a kind
  if !b%%R!==3 echo P1 has a !%%S! 3 of a kind
  if !b%%R!==2 echo P1 has a !%%S! pair
)
for %%T in (2 4) do for %%U in (!a%%T!) do (
  if !b%%T!==4 echo CP has a !%%U! 4 of a kind
  if !b%%T!==3 echo CP has a !%%U! 3 of a kind
  if !b%%T!==2 echo CP has a !%%U! pair
)

Note that there is no need to keep changing the letters used for each independent FOR block. It would work just as well using
for %%R in (1 3) do for %%S in (!a%%R!) do (
  if !b%%R!==4 echo P1 has a !%%S! 4 of a kind
  if !b%%R!==3 echo P1 has a !%%S! 3 of a kind
  if !b%%R!==2 echo P1 has a !%%S! pair
)
for %%R in (2 4) do for %%S in (!a%%R!) do (
  if !b%%R!==4 echo CP has a !%%S! 4 of a kind
  if !b%%R!==3 echo CP has a !%%S! 3 of a kind
  if !b%%R!==2 echo CP has a !%%S! pair
)


text:
Q: sqlite sum values from same date and return in 1 row I am writing an android application storing workout dates and calories burned. Below is an example of the data in my table:
this is returned by:
SELECT month, day, calories FROM workouts ORDER BY year ASC, month ASC, day ASC LIMIT 12;

(month | day | calories)
3|2|714
3|3|945
3|4|630
3|10|446
3|16|396
3|20|255
3|22|108
3|23|112
3|23|169
3|23|2160

the code i've written for the above is:
  public Cursor getLastTwelveDays(){
  Cursor c;
  String[] s = {KEY_MONTH, KEY_DAY, KEY_CALORIES};
  String order = KEY_YEAR + " ASC, " + KEY_MONTH + " ASC, " + KEY_DAY + " ASC LIMIT 12" ;
  c = db.query(WORKOUT_TABLE, s, null, null, null, null, order);
  return c;
}

I would like to combine the rows with the same day and month into a single row like so:
3|2|714
3|3|945
3|4|630
3|10|446
3|16|396
3|20|255
3|22|108
3|23|2441    (112 + 169 + 2160)

Also, it would be nice if it were easy to use with android's query function.
Thanks in advance.

A: What you are looking for is the group by clause.  Use the SUM() method to get the total calories for each date. I believe the group by clause should go before the ORDER BY clause.
SELECT month, day, SUM(calories) FROM workouts GROUP BY month, day

A: Sounds like you want a subquery (i.e. one query to calculate the SUM of the daily calories, inside another query that gets the calorie totals per day).
Try looking up QUERY and sub-query examples. Perhaps the query function allows you to pass a raw query into it, in order to do the kind of more advanced query that you're describing.

A: Without seeing your schema - look at SUM and GROUP BY as well.


text:
Q: Using shasum along with compression in MAC OS-X I am trying to understand why the following sequence of commands (in a MAC OSX terminal) produce a different checksum between the first and second iterations.
$ tar czf General.tar.gz General/
$ shasum -a 256 General.tar.gz
e722ed697871c611cf08dcd2085aefb017efcc6cf87986afa34b9ca4d70ac077  General.tar.gz
$ rm General.tar.gz
$ tar czf General.tar.gz General/
$ shasum -a 256 General.tar.gz
b2b2b0a2a3d243a561861cfa4af82e1b930254c4cbec3e20b48dfa4c10bbb91d  General.tar.gz

Basically, I am compressing (using tar) a folder at two different times with no changes in between as far as the contents of the folder is concerned. So, I would expect the .tar.gz file checksum to be the same between the first and second iterations. In fact, this is what I see when I did this in Windows, but it doesn't work this way in MAC OSX. What is the reason for this?
Also, is there a way I can make this work the same way as in Windows? Basically, I am trying to compress files in a directory before sending them over the network and I don't want to do it unless the file/directory contents themselves change.
Thanks in advance for your help !


text:
Q: Import autocompletes an incorrect path in Visual Studio Code I have a TypeScript project and, naturally, when typing import MainLa..., it will autocomplete the import.
However, in this particular project, for some reason the path is usually incorrect.
Regardless of which file I am importing to, I always get a path starting from the root of the project, like this:
import MainLayout from "resources/layouts/MainLayout"

This would be correct, if I was in the root of the project, but I am not.
The correct path would be:
import MainLayout from "../../../resources/layouts/MainLayout"

It seems it is not taking into account the directory I am currently working in.
Where in Visual Studio Code and/or a TypeScript project could I correct this behavior?
There is a tsconfig.json in the root of the project with "rootDir": "./" and "baseUrl": "./".


text:
Q: ASP Core Azure Active Directory Login use roles I created an Azure Active Directory Application and i want to use role based security. I followed the tutorial on: https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect-aspnetcore/
The login works, I added roles to the application manifest and assigned the role Approver to my own account. Now i want to use these roles.
After login the following works in the controller:
[Authorize]

But when adding the role the user is not authorized:
[Authorize(Roles="Approver")]

Also the following returns false:
User.IsInRole("Approver");

It seems the roles are not retreived, any suggestions on how to add the role functionality to this demo project?

A: While using Azure AD For Groups, group membership information does not magically appear in an application, You will either need to use Graph API to get groups for a user after authenticating, Or Configure Azure AD to send back claims representing a user's group membership.
Configure Azure AD to send Group Claims:
Change application manifest by going Under Azure Portal => Azure Active Directory => App Registrations => All Apps => Select Your App => click the manifest from top action bar
Change groupMembershipClaims to SecurityGroup,

Once you have that, you should be receiving Group claims From Azure AD, We Can quickly see that by iterating over User 's Claims Property.
The value of claim will be Object IDs, You'll need to know the object ID of the group or groups.

With the ID in hand, you can now define an ASP.NET Core authorization policy like below,
        services.AddAuthorization(options => {
            options.AddPolicy("Approver",
                    policyBuilder => policyBuilder.RequireClaim("groups",
                    "c63b2f53-eff9-4d68-8b47-07f151270c74"));
        });

You are all set to check against this policy, like below:
   [Authorize("Approver")] OR
   [Authorize(Policy = "Approver")]

A: This code sample works for me after assign roles to account . Please debug application in this line: User.IsInRole("Approver"); , check whether {http://schemas.microsoft.com/ws/2008/06/identity/claims/role: Approver}exists in user claims . And make sure you add roles which allowedMemberTypes is user , for example :
{
      "allowedMemberTypes": [
        "User"
      ],
      "displayName": "Approver",
      "id": "fc803414-3c61-4ebc-a5e5-cd1675c14bbb",
      "isEnabled": true,
      "description": "Approvers have the ability to change the status of tasks.",
      "value": "Approver"
    },

And you have assign the user role  in Enterprise applications-->All applications--> find your app-->Users and groups--> add/edit a user and assign roles :

A: Please take a look at the following repo: https://github.com/Azure-Samples/active-directory-dotnet-webapp-roleclaims
You need to register your application in the Azure portal and then go to the manifest settings to add the roles and GUIDs for each role.


text:
Q: Relação entre tabelas de mesmos valores nas colunas Quero fazer uma consulta sql que relacione duas colunas de duas tabelas diferentes, que armazenam os mesmos tipos de valores, mas uma possui alguns que a outra não contém, exemplo:
Tabela 1 possui a coluna codigo e
Tabela 2 possui a coluna code
Quero fazer uma consulta que exiba todas as linhas(valores) de code que não estejam em codigo
Desde já, agradeço por qualquer ajuda

A: Uma solução (entre outras) é usar um sub-select com not exists, verifica a existência de valores no sub-select
select *
from tabela2
where not exists (select null
                  from tabela1
                  where tabela1.codigo = tabela2.code)


text:
Q: Imprimir con json_encode un Array sale en doble Al imprimir en json_encode un Array devuelto de una consulta MySql sale el resultado en doble:
primero muestra los resultados en base al numero array y luego lo muestraen array String
[

 {
  "0" : "Nombre",
  "1" : "Apellido",
  "idNombre" : "Nombre",
  "idApellido" : "Apellido",
 }

]

Consulta ::
$con = conexion();
    $consulta = $con->prepare("select * from nombres where Nombre='$genero' order by Nombre asc");
    $consulta->execute();
    $resultado=$consulta->fetchAll();
    return $resultado;

Imprimir ::
$consulta=nombres::genero($_GET['Genero']);
        echo json_encode($consulta);

A: Causa del problema
Eso es debido al estilo de fetch que se está aplicando sobre los datos.
Si lees la documentación, fetchAll() (y los otros métodos fetch de PDO pueden recibir en parámetro uno de los fetch style  indicados aquí.
Cuando no se indica ninguno, PDO asume el método por defecto, que es PDO::FETCH_BOTH el cual devuelve los datos en forma asociativa y numérica, o el que tenga el objeto establecido en la configuración (que se puede hacer mediante setAttributes() o en el cuarto parámetro (opciones) que puedes pasar en el constructor.
Solución
La forma más simple de resolver esta situación es indicando a fetchAll() de qué modo quieres los datos.
Si los quieres como array asociativo:
$resultado=$consulta->fetchAll(PDO::FETCH_ASSOC);

En este caso los resultados serían:
[

 {
  "idNombre" : "Nombre",
  "idApellido" : "Apellido",
 }

]

Si lo quieres como array numérico:
$resultado=$consulta->fetchAll(PDO::FETCH_NUM);

En este caso los resultados serían:
[

 {
  "0" : "Nombre",
  "1" : "Apellido"
 }

]

Queda claro que la forma de lectura de $resultado variará según el estilo que uses...
Recomendación sobre la seguridad
Tu consulta es altamente vulnerable a ataques de Inyección SQL. Por norma, no pases nunca variables en las consultas. Un usuario mal intencionado puede manipularla y causar daños irreparables en varios niveles de tu sistema, no sólo en la base de datos.
En PDO es relativamente fácil blindar el código:
$con = conexion();
$consulta = $con->prepare("select * from nombres where Nombre=? order by Nombre asc");
$consulta->execute( array($genero) );
$resultado=$consulta->fetchAll(PDO::FETCH_ASSOC);
return $resultado;

La consulta preparada en este caso consiste en cambiar el valor que pasabas directamente por un marcador ? y el dato se pasa en forma de array en el método execute(). De ese modo PDO neutralizará cualquier intento de ataque.


text:
Q: Embedding manifest to exe file I have a .manifest file which is linked with a .exe program file so that it asks for admin privileges when opened. Now it is a separate file called program_name.exe.manifest which is is the same folder as program_name.exe. Is there any way by which we can embed the manifest file into the .exe file so that it can be one single file instead of two.
BTW the program is created using C++

A: Yes. Declare the manifest as a resource and then just build the resource object file and link it to your exe.
In your resource.rc file, define your manifest resource like so:
IDR_RT_MANIFEST1        RT_MANIFEST            "program_name.exe.manifest"

In your resource.h file declare it with the value 1
#define IDR_RT_MANIFEST1    1

Build the resource file with windres: windres resource.rc -o resource.o
Link the resource when building your project: -l resource.o
.........................................................................
If your're using Visual Studio you don't need to build it explicitly, but there are 2 options which should be set beforehand:
1) Project > Project_Name Properties > Configuration Properties > Linker > Manifest File -> Generate Manifest set to No
2) Project > Project_Name Properties > Configuration Properties > Manifest Tool > Embed Manifest set to Yes
Also add your manifest file to your project as existing item.

A: If you are using windows CL, like powershell, try
program_name.exe –manifest program_name.exe.manifest -outputresource:program_name.exe;1
That should do the trick.


text:
Q: How to convert a *.txt file (copy/pasted variables) into a tabular format I have a bunch of variables (roughly 80) which I copy+paste into my editor (get those variables from a different *.txt file). After this, it looks a bit messy like
ka15 1-2 tre15 3-4 hsha15 5
juso15 6
kl15 7-9 kkjs15 10

but I'd like to have it structured to get a better idea of what's going on inside the code. I also have to strip away the 15 from each variable. Ideally I would get something like
ka     1-2   tre   3-4   hsha   5
juso   6     kl    7-9   kkjs   10

Is there a clever way to achieve this? I am using SAS Enterprise Guide Editor and VSCode but couldn't find a way. For Example, when I find and replace the 15 I would wish I could replace it with a tab, but couldn't find that option in neither editors. Any ideas to get this automated or at least not do everything by hand?

A: I found a hacky solution to your problem, if anyone finds a better solution, I'll delete mine, but here it goes ¯\_(ツ)_/¯:
1) Copy all content of file(for example I copied yours twice):
ka15 1-2 tre15 3-4 hsha15 5
juso15 6
kl15 7-9 kkjs15 10
ka15 1-2 tre15 3-4 hsha15 5
juso15 6
kl15 7-9 kkjs15 10

2) Ctrl+H and replace all 15 with nothing (leave empty) using Ctrl+Alt+Enter.
3) Ctrl+F and turn Regular expressions in search box. Now type \s to select whitespace and it should select one whitespace after every word. Now select all occurrences with Alt+Enter and press Backspace followed by Enter. This will delete spaces between the words and place one word on one line of code like so:
ka
1-2
tre
3-4
hsha
...

Press Escape to remove multiple cursors.
4) Press Ctrl+F again and in search box type $ sign. This wil select end of every line. Again, press Alt+Enter to select all occurrences a press Space 5-8 times. Notice however that cursors are not properlly aligned. Press Escape to remove multiple cursors.

5) Place cursor a few spaces from a first word. Then, hold Ctrl+Alt+↓ to add multiple cursors below first one. Then, press Shift+End to select all the whitespace to the end of every line and press Delete to delete it. Press Delete again to align all words in one line seperated by n spaces.

6) Unfortunately, I couldn't find regex for the last part. Cursor should be placed after every 6th variable, but I solved it with by placing cursor next to every 7th word and pressing Enter.

I usually don't type too much like this, but I liked the problem you had. It was more puzzle than a problem to me.

A: I've come up with 3 regex's that will do what you want.  In order to run them all  sequentially you will need the regreplace extension or similar.
This goes in your settings:
"regreplace.on-save": false,

"regreplace.commands": [
  {
    "name": "Transform Data to Table Format, step 1",
    "regexp": "([a-zA-Z]+|[\\d-]+)(15)?(\\s[\r\n]?)*",
    "replace": "$1      \n",
    "priority": 1,
  },
  {
    "name": "Transform Data to Table Format, step 2",
    "regexp":
      "(([\\S-] {6})(.*))|(([\\S-]{2} {5})(.*))|(([\\S-]{3} {4})(.*))|(([\\S-]{4} {3})(.*))",
    "replace": "$2$5$8$11",
    "priority": 2,
  },
  {
    "name": "Transform Data to Table Format, step 3",
    "regexp":
      "((.*)\n)((.*)\n)((.*)\n)((.*)\n)((.*)\n)((.*?)(\\s*\\n))",
    "replace": "$2$4$6$8$10$12\n",
    "priority": 3,
  }
],

It creates a rule for each of the three regex steps.  All three rules can be run sequentially by running the regreplace.regreplace command.  Here is a demo:

The regex's are designed to look good with data items up to 4 characters long but could be easily modified for longer items.
In step 1, increase the number of spaces before the \n in the replace rule to something like 16 or so.
In step 2, you will have to sense the pattern of the regex groups  like (([\\S-]{4} {3})(.*) to modify them.  A 13 character long variable might require something like (([\\S-]{13} {3})(.*) as the last group and ([\\S-] {15})(.*))as the first in the sequence, etc. modifying all the other groups in order.  Let me know if you need help with that.
Step 3 needs no modification unless you want to change how many data items appear on each line - right now there are 3 variables with their data on each line hence 6 groups in that regex.
It does not matter how many data-value pairs are in any row prior to running the command.
[Two items of caution:  There should not be any empty lines before the start of the data, although if necessary you could a regex as the first rule to remove empty lines.  Empty lines within the data or at the end are not a problem.
Secondly, the extension cannot be run on selected text only so you will have to place your data at the top of an empty file to convert it and then copy it elsewhere if you wish.]
There is also the replace rules extension which works like regreplace but will according to the docs run on a selection only but it didn't work for me here for some unknown reason.  It does have a nicer interface though - all regex's could go into a single rule which could then be independently run.


text:
Q: Expandable UITableView Sticking I am creating an expandable UITableView.  It works fine but the issue I am running into is when a given row is expanded and the user scrolls up, the opened section row scrolls up to the top of the visible table and stick.

In the below image, the detail row material and the succeeding section rows scroll OVER the opened section row.

I would expect that the section row would scroll off the top of the visible table view.
Am I missing something that would allow the section row to scroll up rather than stick?


text:
Q: php - how to get value from an array object I use php code and I have a problem with getting value of an array object. When I use var_dump($arr), I get this (the code below is formatted for better readability):
object(League\OAuth2\Client\Provider\GoogleUser)#5 (1) {
    ["response":protected]=> array(5) {
        ["emails"]=> array(1) {
            [0]=> array(1) {
                ["value"]=> string(21) "thienlam129@gmail.com"
            }
        }
        ["id"]=> string(21) "115281634466837725533"
        ["displayName"]=> string(18) "thiên lâm trần"
        ["name"]=> array(2) {
            ["familyName"]=> string(6) "trần"
            ["givenName"]=> string(11) "thiên lâm"
        }
        ["image"]=> array(1) {
            ["url"]=> string(98) "https://lh3.googleusercontent.com/-SpWfKGTcQt8/AAAAAAAAAAI/AAAAAAAAAB8/IlGQQnvy7so/photo.jpg?sz=50"
        }
    }
}

Please, tell me how to get emails value.

A: The main reason you're facing this problem is probably because the object is not an array at all.
As mentioned in the comments, the GoogleUser object has a public getEmail method which you can use to retrieve the email address.
You can use it like this:
$email = $googleUser->getEmail();

(In the above code sample I took the liberty of calling it a $googleUser rather than an $arr because it's not an arr but a google user)

A: You could cast the object as an array as such:
var_dump((array) $object);

Or
$array = (array) $object;

And access all its properties but you might have to array walk and filter the name of the class out.
But this is a hack and an example of bad practise. Accessing protected properties by its methods is the way to go or else request json object instead, if possible.
Naturally, you would say
$object = (object) $inputObject;
$value = (string) $object->getValue();

Or
$value = (array) $object->getArray();


text:
Q: Crawling WoS with Python I'm trying to download information from WoS (Web of Science) database. I need information such as name of article, authors, times cited, volume and others

This is my code:
import sys
from BeautifulSoup import BeautifulSoup
import urllib
import re
    var = raw_input("Link WoS: ")
    conn = urllib.urlopen(var)
    html = conn.read()
    soup = BeautifulSoup(html)
    titles = re.findall('<value lang_id="">(.+?)</value>',str(soup))
    volume = re.findall('Volume: <value>(.+?)</value>', str(soup))
    print(volume)

It works perfect for obtaining titles. However I have problems getting the following info: volume, issue, pages, date (published) and times cited. This is the source of the webpage:

<value>
EDUCATIONAL RESEARCH
</value>
  Volume:
<value>35</value>
   Issue:
<value>1</value>
   Pages:
<value>3-25</value>
   Published:
<value>SPR 1993</value>

<nobr>             </nobr>

Full Text

View Abstract<nobr></nobr>Close Abstract<nobr></nobr>

Times Cited: 487

I think that I have problems because the data is numeric... Can you please help me?

A: Beautifulsoup has its own regex functionality
html = 'Volume: <value>20</value>'
soup = BeautifulSoup(html)
matches = soup.findAll(text=re.compile('Volume'))
for match in matches:
    element = match.parent
    #o/p: Volume:
    sibling_tag = element.findNextSibling()
    #o/p: <value>20</value>
    print sibling_tag.find('value').text
    #o/p: u'20'

Note: This is just an example without having access to the actual html

A: BeautifulSoup will do a lot of heavy lifting for you. Regex is usually a last resort where HTML is concerned. It's also best to use the most up-to-date version of this product, as seen in the following code.
HTML = '''\
<value>
EDUCATIONAL RESEARCH
</value>
  Volume:
<value>29</value>
  Issue:
<value>2</value>
  Pages:
<value>26-152</value>
  Published:
<value>JUN 1987</value>
'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(HTML, "html.parser")

items = soup.findAll('span', attrs = {'class': 'label' })
for item in items:
    label = item.contents[0]
    sibling = item.find_next_sibling('span')
    value = sibling.select('value')[0].text
    print (label, value )

Result:
Volume:  29
Issue:  2
Pages:  26-152
Published:  JUN 1987

I am far from clever enough to have written this without trying some possibilities that failed. Are you using something like IDLE that suggest alternatives and to try out snippets of code to see what results they give?
PS: When you come back to SO again please post HTML and other text as text (not as image files), so that answerers can use cut-and-paste.

A: I finally did it! I just wrote this:
numericValues= re.findall('<value>(.+?)</value>', str(soup))

This gave the followig output:
['100-121', '35', '1', '3-25', 'SPR 1993']

The first number I don't know what it was, but the next ones were the ones that I needed. Then I just iterate the values:
i = 0
while i < len(numericValues):
    columnVolume.append(numericValues[i+1])
    columnIssue.append(numericValues[i+2])
    columnPages.append(numericValues[i+3])
    columnDate.append(numericValues[i+4][-4:])
    i = i + 5

Thank you all for your help!


text:
Q: Maui build and publication issues I have a MAUI project that references 3 .dll's that are built with netstandard2.1. I am working on a Mac with Ventura MacOS and Visual Studio 2022 17.4.2. I am having a problem building the .ipa for the iOS platform. I can compile all of the elements of the project but when I run the command
"dotnet publish -f:net6.0-ios -c:Release /p:ArchiveOnBuild=true -r:ios-arm64 --no-self-contained"
I get 3 errors all related to the .dll project files not referencing .net6.0-ios.

/usr/local/share/dotnet/sdk/6.0.404/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(267,5):
error NETSDK1005: Assets file
'/Users/davidrutter/Projects/RadixIQDealerPortal/aspnet-core/src/RadixDealerPortal.HttpApi.Client/obj/project.assets.json'
doesn't have a target for 'net6.0-ios'.

I've tried several things and searched all over trying to find a solution but without success. If anyone has an idea how to resolve this I would be truly appreciative.

A: You want to use the framework net6.0, net6.0-ios should not make a difference here as you are using --no-self-contained.
Leaving the options for net6.0-ios out should work too, as you already have the runtime defined.
TLDR;
remove -f:net6.0-ios


text:
Q: Programmatically how do I get at -VM option in eclipse.ini file entries Sorry guys may be a silly question. Eclipse starts by using a .ini file. How do I find the value of -vm in a plugin that I may develop?
Programmatically from my plugin.java code?
Regards,
Jemrug

A: You can programmatically get the value of -vm with System.getProperty("eclipse.vm").
See also Help > About Eclipse IDE: Installation Details, tab Configuration section *** System properties:.


text:
Q: Cloudant : query in http navigator I'm using cloudant, with no auth, Cors enabled.
it works very well, Limit and skip working good.
but i can't find how to search for something .
I'm trying to find a document where cp is 24000 , for example with this query :
https://1c54473b-be6e-42d6-b914-d0ecae937981-bluemix.cloudant.com/etablissements/_all_docs?skip=0&limit=10&include_docs=true&q=cp:24000

But, the query doesn't return the right document.
I've also tried
   https://1c54473b-be6e-42d6-b914-d0ecae937981-bluemix.cloudant.com/etablissements/_all_docs?skip=0&limit=10&include_docs=true&_search({'cp':24000})

with no luck.
oh, and by the way, do you know if jquery.couch.js lib has been discontinued? I cant even find it on github, nor on my hard disk while im using foxant, and it is not in the directory also..

A: The /db/_all_docs endpoint hits the primary index of the database where all of the documents in the database can be found in _id order.
If you wish to query the database to get a subset of the data you have three options

*

*Cloudant Query - hit the POST /db/_find endpoint passing in a JavaScript object containing the selector which defines the query you wish to perform (like the WHERE clause of a SQL query) e.g. {selector: {cp: 24000}}

*MapReduce - create a Map function in a design document that filters the documents you are interested it. It creates a materialized view that can be queried and filtered later. e.g. function(doc){ emit(doc.cp, null);}

*Cloudant Search - this uses the Apache Lucene library to generate an index on the fields you specify. You can then query the index: q=cp:24000, which looks similar to the query you are looking to perform.


text:
Q: Angular2 directive usage in template I have found an recursive object view component that shows an object/array structure as a structured list.
Here is the working component:
https://embed.plnkr.co/Anxv8zImWmD0WzizCSVT/
What i tried was to use the directive in an template that is loaded via templateUrl instead using template.
Here is my not working example:
https://embed.plnkr.co/mHEKcxnUcTk85OSffbCe/
Can you tell me what did I do wrong in my example?
Thanks

A: Your app won't start because it's unable to find your template file. In app.ts, change:
templateUrl: './my-template.html'

With:
templateUrl: 'src/my-template.html'

By the way, if you're just learning Angular, I strongly recommend that you work with the latest version. Your example is based on version 2 beta 15 and Angular has changed significantly since then, including many breaking changes.
Work with this plunkr instead.  Angular team keeps it up to date with the latest version (currently 2 rc.5)


text:
Q: How to solve a non well formed numeric value encountered in PHP? I am having an error. A non well formed numeric value encountered. Kindly check my code below and guide me what I am doing wrong:
...
    $i++;
    $item_count += $item['quantity'];
    $sub_total += ($product['price'] * $item['quantity']);
    $sub_total = (float)$sub_total;

}
$tax_rate = 18;

$tax = ($tax_rate * $sub_total) / 100;
// Here I am having an error - A non well formed numeric value encountered
$tax = number_format($tax, 2); // 2 decimal digit
$grand_total = $tax + $sub_total;

Kindly suggest what I am doing wrong.
Your suggestions would be welcome.
Thank You

A: number_format is function used for formatting strings. You may and should use it to view values, not to calculate them. You may change lines:
$grand_total = $tax + $sub_total;
$tax = number_format($tax,2);

But it would be a bit safer to use another variable:
$view_tax = number_format($tax,2);
$grand_total = $tax + $sub_total;
// now $grand_total uses $tax and to view
// tax, just use $view_tax variable


text:
Q: How to select particular column from table if another column includes all the set of requested values? I have a table in MySQL named table1 which has three columns id, user_id(foreign_key) and destination_id(foreign_key). One user can have multiple destinations.
E.g Table1

id      user_id       destination_id
1         10            2
2          5            3
3         10            4
4         10            5
5          9            10
6          5            12
7          8            2

I get a request from the client side in PHP script; the request includes destination ids in an array.
E.g. $request = array('destination_id' => [2,4,5]);

I just want to get all the user_id from table1 if and only if the particular user_id contains all requested destinations.
I tried to achieve this using 'IN' operator.
i.e.
     SELECT user_id FROM table1 WHERE destination_id IN ($requestedDestinationsInCommaSeparatedString)

It gives row including user_id 8 along with user_id 10 but I just need user_id 10. I just wanted to know the concept regarding the solution to the following problem. I am a beginner in SQL, any help would be very appreciable. Thanks.

A: You can check that a user_id refers to all requested destination by grouping and counting the destinations.
SELECT user_id
FROM table1
WHERE
    destination_id IN (2,4,5)
GROUP BY
    user_id
HAVING count(*) = 3
-- count must be the number of elments in (2,4,5)

For doing so, the field combination of user_id and destination_id must be unique over all records.

A: The only thing I can think of is to use multiple subselects and build the query string in PHP.
So for your specific example the SQL-Query-String generated should be
SELECT user_id
FROM table1

WHERE user_id IN
    (SELECT user_id FROM table1 WHERE destination_id = 2)
AND user_id IN
    (SELECT user_id FROM table1 WHERE destination_id = 4)
AND user_id IN
    (SELECT user_id FROM table1 WHERE destination_id = 5)

GROUP BY user_id

I think programming the function which generates the middle part for you shouldn't be too hard.


text:
Q: grep challenge - extract search pattern after searching any number of characters Lets say I did this:
 echo stackoverflow > file
 grep sta[a-z]*w file

grep result is stackoverflow
But how do I get only original pattern sta & w?

A: grep -oE 'sta|w'

or
grep -o 'sta\|w'

should give what you want. e.g:
kent$   echo "stakoverflow"|grep -oE 'sta|w'
sta
w

A: If you plan to generalize sta and w, then this version may be helpful:
echo stackoverflow > file
grep 'sta[a-z]*w' file | sed 's/\(sta\)[a-z]*\(w\)/\1 \2/'


text:
Q: How to access Google Analytics from BlackBerry? I'm trying to access Google Analytics API from my BlackBerry's Mobile App (written in JavaScript) using Google's OAuth 2.0 procedure described here:
https://developers.google.com/accounts/docs/OAuth2InstalledApp .
I have no problem with it's first step - "Forming the URL". I've registered my App as "installed application" in the Google APIs Console (with redirect URIs - "urn:ietf:wg:oauth:2.0:oob" and "localhost"), and after logging in into the Google's account I'm obtaining an authorization code.
The problem arises when I'm trying to use this code to get Google's access token (which I could use later to connect with the Google Analytics API). I'm using the following XMLHttpRequest:
var req = new XMLHttpRequest();
req.open('POST', 'https://accounts.google.com/o/oauth2/token?code='+code+'&client_id='+clientId+'&client_secret='+clientSecret+'&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code', false);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send('');

and the response to this request is:
{"error" : "invalid_request"} .
What am I doing wrong? Any help will be greatly appreciated.

A: The query should be in the body of the POST request instead of the url. This is a common gotcha.