text:
Q: $(a,b,c) \cdot (f_x, f_y, -1) = 0$, is the vector $(a,b,c)$ also in the plane tangent to the surface $z = f(x,y)$? Suppose I have a surface $z = f(x,y)$, then we know at a particular point its normal vector is $(f_x, f_y, -1)$.
Suppose further that I have a vector $(a, b, c)$, where $a,b$, and $c$ are themselves functions of $x$ and $y$, and that
$$(a,b,c) \cdot (f_x, f_y, -1) = 0$$
By definition then the vector $(a,b,c)$ is orthogonal to the normal vector $(f_x, f_y, -1)$. I am following a set of notes which then claims that because of the above dot product, we can conclude that $(a,b,c)$ must lie in the tangent plane to the surface $z$, but I cannot see why or how this holds. What prevents the vector $(a,b,c)$ from being parallel to the surface $z$?

A: We are thinking of these vectors not as starting at the origin but as starting from an arbitrary base point in $\mathbb R^3$. In this particular case, the base point is taken to be some point on the surface $z=f(x,y)$. Hence, the dot product condition implies $(a,b,c)$, thought of as a vector coming out of some point on the surface, is orthogonal to the normal to the surface at that point. This implies that $(a,b,c)$ is in the tangent plane of the surface pretty much by definition.


text:
Q: Lead Landing Page in Visual Force Currently we have a lead landing page similar to the one shown below.
https://www.commbank.com.au/personal/home-loans/make-an-appointment.html
I am wondering whether I will be able to develop a similar aesthetically appealing landing page in Visualforce site.
My Qs
a) Is it possible for me to add jazzy UI stuff like CSS/jQuery etc in a Site ?
b) Will it be possible to expose this site to the internet without requiring any authentication ?. Basically we want this to be public facing without any restriction whats so ever for entering the data.

A: Yes and yes. We have done this before. You will definitely be able to add css and jQuery into public site and open to everybody with no issue.

A:
a) Is it possible for me to add jazzy UI stuff like CSS/jQuery etc in
  a Site ?

Of course it is! See a demo site that I am working on demo site & find details here. It is beta but is using CSS and jQuery behind the scenes to make jazzy UI :)

b) Will it be possible to expose this site to the internet without
  requiring any authentication ?. Basically we want this to be public
  facing without any restriction whats so ever for entering the data.

Refer to the demo site site again.
Hope this helps.
On a side note, if you want to host a page developed in visualforce on your website, that can be done as well using iframes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typescript internal module not recognized by VS Code I am trying to separate my typescript classes in separate files using internal modules. However, the main.ts file will not load or recognize the sub modules.
main.ts
/// <reference path="Car.ts" />
module Vehicles {
    var c = new Vehicles.Car("red");
}

car.ts
module Vehicles {
    export class Car {
        color: string;
        constructor(color: string) {
            this.color = color;
            console.log("created a new " + color + " car");
        }
    }
}

tsconfig.json
{
    "compilerOptions": {
        "sourceMap":  true,
        "out": "everything.js main.ts car.ts"
    }
}

Update: edited the "out" flag in tsconfig to try and compile main.ts and car.ts into everything.js - this is the last part that is not working: everything.js is not created. Instead, VS Code creates a main.js and a car.js. It seems that the "out" flag is ignored. I have also tried "outFile" with the same result.

A: main.ts
/// <reference path="car.ts" />
var c = new Car("red");

car.ts
class Car {
    color: string;
    constructor(color: string) {
        this.color = color;
        console.log("created a new " + color + " car");
    }
}

tsconfig.json
{
    "compilerOptions": {
        "sourceMap":  true,
        "outFile": "main.js"
    },
    "files": [
        "main.ts",
        "car.ts"
    ]
}

tasks.json

Kokodoko: I finally found the problem! You have to OMIT the "args" option inside "tasks.json", only then will the arguments in
  tsconfig.json be used! I found the answer here:
  github.com/Microsoft/typescript/wiki/tsconfig.json. It says: When
  input files are specified on the command line, tsconfig.json files are
  ignored

For further information about Modules, don't forget to have a look at the TypeScript Handbook

A: To compile several .ts files into one big .js file using a VS Code task, you need to remove the 'args' from tasks.json and add the "out" argument to tsconfig.json
tasks.json
{
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "showOutput": "silent",
    "problemMatcher": "$tsc"
}

tsconfig.json
{
    "compilerOptions": {
        "sourceMap":  true,
        "out": "myapp.js"
    }
}

Note:
When input files are specified on the command line, tsconfig.json files are ignored.


text:
Q: How to design a MongoDB for blog? I'm building a simple blog system for multiple users, they can access data by userID, username and nodeID(blog).
In RDBMS, normally we will have user/table/ownership tables. In mongoDB, some suggest to put them in a single users collection. However, as far as i know, it could be very slow if users want to access specific nodeID, since mongoDB may go through every document. Indexing will significantly drop the create speed, in my case, that means both createUser() and createNode(), right?
Therefore, is there any "Best Practices" we can follow?
Thanks.

A: Three Collections Inside the DB, Namely,
"Users",
"UserPosts",
"UserComments"

Users Collection's Field could be
"name",
"age",
"occupation",
"profileImage",
"numberOfPosts",
"birthdate",
"joiningDate",
"session"

etc.
UserPosts Collection's Field could be
    "Id",
    "revisionId",
    "author",
    "type",
    "language",
    "userId",
    "status",
    "title",
    "tags",
    "content"

etc.
UserComments Collection's Field could be
    "Id",
    "userPostId",
    "author",
    "type",
    "language",
    "userId",
    "status",
    "comment",

etc.
User Comment will be maintained by UserPostId Field It contains.


text:
Q: is there a better way to do this XML scraping task in R? I have some XML that looks like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
    <key>bbox.NE.lat</key>
    <string>-27.45433</string>
    <key>bbox.NE.lon</key>
    <string>153.01474</string>
    <key>bbox.SW.lat</key>
    <string>-27.45706</string>
    <key>bbox.SW.lon</key>
    <string>153.01239</string>
    <key>crs</key>
    <string>EPSG 4326</string>
    <key>found</key>
    <string>1</string>
</dict>
<array>
    <dict>
        <key>bbox</key>
        <dict>
            <key>bbox.NE.lat</key>
            <string>-27.45433</string>
            <key>bbox.NE.lon</key>
            <string>153.01474</string>
            <key>bbox.SW.lat</key>
            <string>-27.45706</string>
            <key>bbox.SW.lon</key>
            <string>153.01239</string>
        </dict>
        <key>centroid</key>
        <dict>
            <key>lat</key>
            <dict>
                <key>lat</key>
                <string>-27.45513</string>
                <key>lon</key>
                <string>153.0137</string>
            </dict>
        </dict>
        <key>id</key>
        <string>33037721</string>
        <key>properties</key>
        <dict>
            <key>amenity</key>
            <string>university</string>
            <key>name</key>
            <string>Queensland University of Technology</string>
            <key>osm_element</key>
            <string>way</string>
            <key>osm_id</key>
            <string>26303436</string>
        </dict>
    </dict>
</array>
</array>
</plist>

For reproducibility's sake, I grabbed the XML with a loop:
# initialize the vector
queries<-(0)
# loop over coordinates - signups$latlong is just a vector of coordinates
# signups$latlong[1] = "51.5130004883%20-0.1230000034
# the space between lat & long is URL encoded
for(i in 1:length(signups$latlong)){
#self-imposed rate-limiting
Sys.sleep(0.05)
# if query returns an error, write NA and move on, also output to console so I can keep an eye on it
if(class(try(queries[i]<- getURL(paste("http://geocoding.cloudmade.com/[API KEY HERE]/geocoding/v2/find.plist?object_type=university&around=",signups$latlong[i],"&results=5&distance=closest", sep="")), silent=T))=="try-error")
  {
    queries[i]<-NA
    print("NA")
    print(i)
    }
  # just a progress indicator
  else(print(i))
}

and I'm just after the name of the university. I don't know much about XML, but I've figured out that this works:
pagetree<-(0)
for (i in 1:length(queries)){
  plist<-xmlTreeParse(queries[i])$doc$children$plist
  nodes<-getNodeSet(plist, "//array//array//dict")
  if(class(try(pagetree[i]<-xmlValue(nodes[[5]][[4]]), silent = T))=="try-error") pagetree[i]<-NA
}

However, I've seen mention of xmlXPathApply() and I am wondering if the parsing loop couldn't be re-written to use it.
Where I'm stuck is that I don't know how to write the XPath for the piece I want, because there are multiple nodes with the same name.
Don't be hesitant to suggest a better way to do the error handling, as well.

A: After fixing the xml...
The way to traverse this with xpath is:
> plist = xmlParse('data.xml')
> xpathSApply(plist, '/plist/array/dict/dict/string', xmlValue)
[1] "-27.45433"                           "153.01474"
[3] "-27.45706"                           "153.01239"
[5] "university"                          "Queensland University of Technology"
[7] "way"                                 "26303436"

The output you can index like normal.
However, if the nodes had attributes, for example <string type='uniname">...</string>, then you could have used the nice "@" syntax like:
> xpathSApply(plist, '/plist/array/dict/dict/string[@type='uniname']', xmlValue)

Another way, which might be better for this plist formatting, is:
> sapply(getNodeSet(plist, '//key[text() = "name"]'), function(x) xmlValue(getSibling(x)))
[1] "Queensland University of Technology"


text:
Q: How to make a line of it height more than 4096 pixel by android? Here's the link to my other question: SurfaceView setMeasuredDimension() with height greater than 4096 crashes It shows my question but so far I didn't find a way to solve it.
In fact,I just want to make a vertical curve line on the phone screen but its height should not be limited to less than 4096 pixels! I previously  designed it with 'SurfaceView',so the issue occurs as shown in that link.
Is there another way to achieve it?

A: If your curve can be drawn procedurally on the fly, I would do that. Preparing such a large image may lead to performance issues.
If you really want to create image larger than your GPU texture limit, you can turn off hardware acceleration for that drawing.


text:
Q: a question about measurablity Let $X$ be a stochastic process with every sample path RCLL(right continuous on $[0,\infty)$ and with left-hand finite limits on $(0,\infty)$). Let $A$ be an event that $X$ is continuous on $[0,t_0)$. Show $A\in\mathcal{F}_{t_0}^X$.
For $(t_n)_n$ a dense sequence contained in $(0,t_0)$, if we can show
$$A=\{\omega: \lim_{s\rightarrow t_n-}X_s(\omega)=X_{t_n}(\omega),\ \ \forall n\geq 1,\ \ t_n<t\}$$
then  $A\in\mathcal{F}_{t_0}^X$ since every $\{\omega: \lim_{s\rightarrow t_n-}X_s(\omega)=X_{t_n}(\omega)\}\in\mathcal{F}_{t_0}^X$. Could someone show how to prove
$$A=\{\omega: \lim_{s\rightarrow t_n-}X_s(\omega)=X_{t_n}(\omega),\ \ \forall n\geq 1,\ \ t_n<t\}$$

A: Thanks to Nate Eldredge, I could have a solution here.
Set $\{t_n\}_{n\geq 1}=\mathbb{Q}\cap [0,t_0)$, then we firstly we prove $X$ is continuous on $[0,t_0)$ if and only if its restriction on $\{t_n\}_{n\geq 1}$ is uniformly continuous:
if $X$ is continuous on $[0,t_0)$, by definition we can extend $X$ on $[0,t_0]$ by defining $X_{t_0}:=\lim_{t\rightarrow t_0-}X_t$, then $X$ is continuous on $[0,t_0]$ and so it is uniformly continuous on $[0,t_0]$;
if $X$ is uniformly continous on $\{t_n\}_{n\geq 1}$, then by Cauchy's criterion, we can define $\widetilde{X}$ on $[0,t_0]$ by
$$\widetilde{X}_t:=\lim_{s\rightarrow t, s\in\{t_n\}_{n\geq 1}}X_s$$
Evidently $\widetilde{X}$ is continuous. For $X$ is right-continuous, we have necessarily $X=\widetilde{X}$, so $X$ is continuous on $[0,t_0)$.
Secondly by an argument largely used to describe the continuity of a function, we have
\begin{eqnarray}
A&=&\{\omega: X(\omega) \text{ is uniformly continuous on } \{t_n\}_{n\geq 1}\}\\
&=&\bigcap_{m\geq 1}\bigcup_{k\geq 1}\bigcap_{n\geq 1}\{\omega: |X_t(\omega)-X_{t_n}(\omega)|<\frac{1}{m},\ \ \forall t\in \{t_l\}_{l\geq 1} \text{ with } |t-t_n|<\frac{1}{k}\}
\end{eqnarray}
So $A$ is measuralbe $\clubsuit$


text:
Q: Java виртуальная память Как задать максимальное количество используемой памяти для java ?
Держу сервер MineCraft - максимально можно задать в поддержку для сервера 1гб виртуалки, каким способом можно задать большее количество выделяемой памяти ?
A: Задать 2 гига хипа/кучи:

java -xmx2g <myClass>

Вообще почитайте документацию к Java. Запустите

java -X


text:
Q: Why does python read my file twice? I'm trying to read a binary file bit by bit because it may be large. My code is:
import bz2

read_buffer_size = 10000

with open(r'C:\Python27\python.exe', 'rb') as f:
    data = f.read(read_buffer_size)
    while data:
        print len(data)
        data = f.read(read_buffer_size)

and it gives me output of:
100
10000
10000
8160
10000
10000
8160

In this case the file is 28160 bytes, so I was expecting to see:
10000
10000
8160

Why is python reading my file twice?

A: The problem was that my script was called bz2.py so the import at the start was causing it to import itself, which caused it to run once when it was imported, then again when the rest of it ran.


text:
Q: How to unescape special characters from BeautifulSoup output? I am facing issues with the special characters like ° and ® which represent the  degree Fahrenheit sign and the registered sign,
when i print the string the contains the special characters, it gives output like this:
Preheat oven to 350° F
Welcome to Lorem Ipsum Inc®

Is there a way I can output the exact characters and not their codes? Please let me know.

A: $ python -c'from BeautifulSoup import BeautifulSoup
> print BeautifulSoup("""<html>Preheat oven to 350° F
> Welcome to Lorem Ipsum Inc®""",
> convertEntities=BeautifulSoup.HTML_ENTITIES).contents[0].string'
Preheat oven to 350° F
Welcome to Lorem Ipsum Inc®

A: Here's a script which for tolerant unescaping of HTML references from web pages - it assumes that the references are e.g. in ° format with a semicolon after them though (Preheat oven to 350° F for example):
from htmlentitydefs import name2codepoint

# Get the whitespace characters
nums_dict = {0: ' ', 1: '\t', 2: '\r', 3: '\n'}
chars_dict = dict((x, y) for y, x in nums_dict.items())
nums_dict2XML = {0: ' ', 1: '	', 2: '
', 3: '
'}
chars_dict2XML = dict((nums_dict[i], nums_dict2XML[i]) for i in nums_dict2XML)

s = '1234567890ABCDEF'
hex_dict = {}
for i in s:
    hex_dict[i.lower()] = None
hex_dict[i.upper()] = None
del s

def is_hex(s):
    if not s:
        return False

    for i in s:
        if i not in hex_dict:
            return False
    return True

class Unescape:
    def __init__(self, s, ignore_whitespace=False):
        # Converts HTML character references into a unicode string to allow manipulation
        self.s = s
        self.ignore_whitespace = ignore_whitespace
        self.lst = self.process(ignore_whitespace)

    def process(self, ignore_whitespace):
        def get_char(c):
            if ignore_whitespace:
                return c
            else:
                if c in chars_dict:
                    return chars_dict[c]
                else: return c

        r = []
        lst = self.s.split('&')
        xx = 0
        yy = 0
        for item in lst:
            if xx:
                split = item.split(';')
                if split[0].lower() in name2codepoint:
                    # A character reference, e.g. '&'
                    a = unichr(name2codepoint[split[0].lower()])
                    r.append(get_char(a)) # TOKEN CHECK?
                    r.append(';'.join(split[1:]))

                elif split[0] and split[0][0] == '#' and split[0][1:].isdigit():
                    # A character number e.g. '4'
                    a = unichr(int(split[0][1:]))
                    r.append(get_char(a))
                    r.append(';'.join(split[1:]))

                elif split[0] and split[0][0] == '#' and split[0][1:2].lower() == 'x' and is_hex(split[0][2:]):
                    # A hexadecimal encoded character
                    a = unichr(int(split[0][2:].lower(), 16)) # Hex -> base 16
                    r.append(get_char(a))
                    r.append(';'.join(split[1:]))

                else:
                    r.append('&%s' % ';'.join(split))
            else:
                r.append(item)
            xx += 1
            yy += len(r[-1])
        return r

def get_value(self):
    # Convert back into HTML, preserving
    # whitespace if self.ignore_whitespace is `False`
    r = []
    for i in self.lst:
        if type(i) == int:
            r.append(nums_dict2XML[i])
        else:
            r.append(i)
    return ''.join(r)

def unescape(s):
    # Get the string value from escaped HTML `s`, ignoring
    # explicit whitespace like tabs/spaces etc
    inst = Unescape(s, ignore_whitespace=True)
    return ''.join(inst.lst)

if __name__ == '__main__':
    print unescape('Preheat oven to 350° F')
print unescape('Welcome to Lorem Ipsum Inc®')

EDIT: Here's a simpler solution which only replaces the character references with characters and not &#xx; references:
from htmlentitydefs import name2codepoint

def unescape(s):
    for name in name2codepoint:
        s = s.replace('&%s;' % name, unichr(name2codepoint[name]))
    return s

print unescape('Preheat oven to 350° F')
print unescape('Welcome to Lorem Ipsum Inc®')

A: In Beautiful Soup 4:
my_text = """Preheat oven to 350° F
Welcome to Lorem Ipsum Inc® """

soup = BeautifulSoup(my_text, 'html.parser')

print(soup)

Result:
Preheat oven to 350° F
Welcome to Lorem Ipsum Inc®

A: I think somewhere, a program is quoting &deg and &reg without a semicolon.
Try to use "&deg"+";" and "&reg"+";" in your HTML file, if it indeed is an HTML file.
And please explain the context.


text:
Q: Rename default button in the Date Picker(android) How i can rename default button("SET") in the  DatePicker dialog?
My dialog:
case IDD_SET_NAME:
final Calendar c = Calendar.getInstance();
myYear = c.get(Calendar.YEAR);
myMonth = c.get(Calendar.MONTH);
myDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog DatePicker = new DatePickerDialog(this, myCallBack, myYear, myMonth, myDay);
return DatePicker;

A: You can change DatePickerDialog Set button text as:
DatePickerDialog datePicker = new DatePickerDialog(this, myCallBack, myYear, myMonth, myDay);
datePicker.setButton(DatePickerDialog.BUTTON_POSITIVE, "Enter text here", datePicker);


text:
Q: PHP and Ajax does not always return a response I am new in web programming. currently I've been trying to make a login/register website. here is my HTML code:
<!DOCTYPE html>

<link href="test.css" type = "text/CSS" rel = "stylesheet" >

<form>
     First Name:

    <input class = "inp" type = "text" name = "fname" id = "fname"> </input>

     Last Name:

    <input class = "inp"  type = "text" name = "lname" id = "lname"> </input>

     Email:

    <input class = "inp"  type = "text" name = "email" id = "email">     </input>

     Username:

    <input  class = "inp" type = "text" name = "usrname" id = "usr">     </input>

     Password:

    <input  class = "inp" type = "password" name = "psw" id = "psw"> </input>

    <input type = "submit" id = "submit" >  </input>

     Login:

    <input class = "inp" type = "text" name = "login" id = "log"> </input>

     Password:

    <input  class = "inp" type = "password" name = "logPsw" id = "logPsw"> </input>

    <input type = "submit" id = "logSub" >  </input>
</form>

here is my JavaScript code:
$(document).ready(function(){
$("#submit").click(function(){
    var fn = $("#fname").val();
    var ln = $("#lname").val();
    var email = $("#email").val();
    var usr = $("#usr").val();
    var psw = $("#psw").val();
    $.ajax(
    {
    type: "POST",
    url: "register.php",
    data: {
        fname: fn,
        lname: ln,
        email: email,
        usr: usr,
        psw: psw
    },
    success: function(result){

    }
    }
    );
});

$('#logSub').click(function(){
    var login = $("#log").val();
    var psw = $("#logPsw").val();
    $.ajax(
    {
        type: "POST",
        url: "login.php",
        data: {
            login: login,
            password: psw
        },
        success: function(result){
            alert(""+result);
        }

    }
    );
});
});

and here is my PHP code:
<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "admin_db";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$login = $_POST['login'];
$psw = $_POST['password'];

$sql = "select * from user where userName = \"$login\" and password = \"$psw\"";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "Yes";
}
else{
    echo "No Such Account";
}
$conn->close();

?>

The problem here is that if I enter an incorrect login/password, it should alert "No Such Account", but 1 out of 5 attempts it doesn't. First it does, second it does and after third attempt it just doesn't say anything and then after fourth attempt it continues to work fine. Can you give me the reason?
P.S I tried to surf every post here and on other forums but none of them seem helpful so if this post is a duplicate please just tell me and I will delete it.

A: The main reason of the problem is that as there is no specific action and method set to form, it automatically submits with 'GET' method so sometimes it submits it faster than the ajax.


text:
Q: Uncaught TypeError: Cannot read property '0' of undefined (what is it supposed to instead?) Uncaught TypeError: Cannot read property '0' of undefined
I am trying to pass in an array of objects. I am getting this error for the line in bold below. I am not sure what it is supposed to be instead of 0 since it is the beginning of the array.
question: ${questionData.results[0].question},
const questions = [
    {
        question: `${questionData.results[0].question}`,
        answers: [
            `${questionData.results[0].correct_answer }` === true ,
            `${questionData.results[0].incorrect_answers[0] }` === false,
            `${questionData.results[0].incorrect_answers[1] }` === false,
            `${questionData.results[0].incorrect_answers[2] }` === false
        ]
    }

A: it means questionData.results is undefined or empty. so trying to access the first record [0] is not going to be possible.
try adding a console.log(questionData) statement to see what you are dealing with.

A: It indicates that questionData does not contain results, so when you try questionData.result, it returns undefined, instead of the array you are expecting.


text:
Q: How do I check to make sure the form is filled on button click in React? I have a button that does a calculation based on the numbers provided by the user and populates the result to the page. That same button also saves the product to a database while also visually populating the page with those same products from the database. So basically it shows the total and the previous totals from whatever the user input into the fields. My issue is that I want to include error handling so that if the number is either 0 or NaN because they didn't fill all the forms, it would throw an alert and also not push the data to the database. This was my attempt and it does not work, if the result is NaN it still displays it and pushes the NaN value to the database, how do I achieve this? Attempt is bellow:
handleClick = (event, billInfo) => {
event.preventDefault();
const dbRef = firebase.database().ref();

const result =
  (billInfo.amount / billInfo.group) * (billInfo.tip / 100 + 1);

// ATTEMPT START ======

result === NaN
  ? alert("Please fill all forms!")
  : dbRef.push({
      result: result.toFixed(2),
      name: billInfo.name,
    });

// ATTEMPT END ======

this.setState({
  total: result.toFixed(2),
});

This is the form component with the button that links to the main app.js:
class inputForm extends Component {
  constructor() {
    super();
    this.state = {
      name: "",
      group: "",
      amount: "",
      tip: "",
    };
  }

  handleChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value,
    });
  };

  clearForm = (event) => {
    event.preventDefault();

    this.setState({
      name: "",
      group: "",
      amount: "",
      tip: "",
    });
  };

  render() {
    return (
      <form className="tipApp">

            Group Name?

          <input
            onChange={this.handleChange}
            type="text"
            id="groupName"
            value={this.state.name}
            placeholder="Name your group"
            name="name"
          />

            How many?

          <input
            onChange={this.handleChange}
            type="number"
            id="groupSize"
            value={this.state.group}
            min="1"
            step="1"
            placeholder="Add the group size"
            name="group"
            required
          />

            How much?

          <input
            onChange={this.handleChange}
            type="number"
            id="billAmount"
            value={this.state.amount}
            min="0"
            step=".01"
            placeholder="Add the bill total"
            name="amount"
            required
          />

            Tip?

          <input
            onChange={this.handleChange}
            type="number"
            id="tipAmount"
            value={this.state.tip}
            min="10"
            step="5"
            placeholder="Add the tip %"
            name="tip"
          />

        <button onClick={(event) => this.props.getTotal(event, this.state)}>
          Split it!
        </button>
        <button onClick={this.clearForm}>Reset</button>
      </form>
    );
  }
}

This is the full app.js main file that I attempted to error handle on:
class App extends Component {
  constructor() {
    super();
    this.state = {
      bills: [],
      total: 0,
    };
  }

  componentDidMount() {
    const dbRef = firebase.database().ref();

    // Event listener that watches the database
    dbRef.on("value", (snapshot) => {
      const firebaseData = snapshot.val();

      const billData = [];

      for (const bill in firebaseData) {
        billData.push({
          id: bill,
          name: firebaseData[bill].name,
          value: firebaseData[bill].result,
        });
      }
      this.setState({
        bills: billData,
      });
    });
  }

  handleClick = (event, billInfo) => {
    event.preventDefault();
    const dbRef = firebase.database().ref();

    const result =
      (billInfo.amount / billInfo.group) * (billInfo.tip / 100 + 1);

    result === NaN
      ? alert("Please fill all forms!")
      : dbRef.push({
          result: result.toFixed(2),
          name: billInfo.name,
        });

    this.setState({
      total: result.toFixed(2),
    });
  };

  deleteBill = (billId) => {
    const dbRef = firebase.database().ref();

    dbRef.child(billId).remove();
  };

  render() {
    return (

Spl|tr

Bill Splitting App

        <Form getTotal={this.handleClick} />

${this.state.total}

Previous Bills

        <Bills receipts={this.state.bills} delete={this.deleteBill} />

    );
  }
}

And this is the Bills.js component that populated the page with the previous items below the form on button click:
const Bills = (props) => {
  return (

      {props.receipts.map((bill) => {
        return (

{bill.name}

${bill.value}

            <button onClick={() => props.delete(bill.id)}>

            </button>

        );
      })}

  );
};

A: Your handler updates state regardless of valid result or not. A small refactor should allow either a valid result and push to DB and update state OR an invalid result and alert. Both 0 and NaN are falsey values, so you can simply check if result is truthy/falsey.
handleClick = (event, billInfo) => {
  event.preventDefault();
  const dbRef = firebase.database().ref();

  const result =
    (billInfo.amount / billInfo.group) * (billInfo.tip / 100 + 1);

  if (result) {
    dbRef.push({
      result: result.toFixed(2),
      name: billInfo.name,
    });
    this.setState({
      total: result.toFixed(2),
    });
  } else {
    alert("Please fill all forms!")
  }
};


text:
Q: sitecore search index with GUID value I need to find a way to find the field value (GUID value) of results from Sitecore search index viewer.
Same thing when we click on Sitecore indexviewer and search for index in return provides a result with number of documents(fieldvalues and field name). Now I need to exclude all the fields which start with "__" and I need to exclude these fields in config file.
Please provide a way on how can I find the field values and the code on how to exclude fields values in config field.

A: Be aware of the way guids are stored, as short id's?
In most cases you should make sure guids are not tokenized during indexing and searching. (use keyword query and NO_TOKENIZE).


text:
Q: When printing from command line how to know what was the default font and font size is being used to print I am printing from a text file. I would like to know what was the default font and font size is being used. Is there a way to find out?
lp template.html -d TVS_MSP-250CH-custom

A: The post
How to change font size in msp240 star tvs printer
has the following procedure.
The printer model is pretty close to yours.

*

*Press the "Menu" button on the device's keypad to access the menu.

*Press "Menu" again to enter the "Configuration options" page.

*Press the "Down" button to select "Font Options."

*Press the "Down" button and select "Size." Press the "Right" button to raise the size by one bullet point, the "Left" button to lower it.

*Repeat this until you have reached your desired size, then press "Menu" again to exit the menu and commit your changes.


text:
Q: How To Modify Alfresco Share Login Page? I've been messing around with this for some time, but I can't seem to find the exact file I need to change in order to get the Share login page to look how I want.
Basically I wanted to do was:

*

*Change the logo that appears (done..I modified the C:\Alfresco\tomcat\webapps\share\themes\default\login.css)

*Get rid of the copyright text (done..I modified the C:\Alfresco\tomcat\webapps\share\themes\default\login.css)

*Center the logo, the input boxes and the "login" button

*Remove the "Alfresco >> Login" title at the top left of the page.

I've been looking around on Google, and I was surprised to not see more people having tried to do this. Does anyone have any experience with this or know what I might need to do to get the Share login page to look exactly how I want it?
Btw, here is my login.css page now if it matters...
.login-panel
{
   text-align: left;
}

.login-panel input
{
   border: 1px solid #C5D6E2;
   padding: 2px;
   font-weight: normal;
   font:99% arial,helvetica,clean,sans-serif;
}

.alfresco-share .sticky-wrapper
{
   background-color: #B4B4B4;
}

.yui-panel-container.shadow .underlay
{
   display: none;
}

.yui-skin-sam .yui-panel
{
   border-style: none;
}

.login-panel
{
   width: 502px;
   height: 289px;
   background: transparent url("./images/loginbg.png") no-repeat;
   padding-left: 28px;
   font-family: Arial,Helvetica,sans-serif;
   font-size: 12px;
   font-weight: bold;
   color: #515354;
   visibility: hidden;
}

.login-button
{
   background-color: #f0f0f0;
}

.login-copyright
{
   font-family: Arial,Helvetica,sans-serif;
   font-size: 0px;
   font-weight: normal;
   color: #ffffff;
}

.login-logo
{
   position: absolute;
   top: 16px;
   height: 64px;
   width: 450px;
   background: transparent url("./images/newLogo.gif") no-repeat;
}

A: I think you need to change the slingshot-login.ftl which is in alfresco/templates/org/alfresco/global/slingshot-login.ftl
Just copy that file to the web-extension and change the things you like :)

A: Perhaps you are interested in a extensions-based approach. Extension modules is a new feature available since 4.0 version.
You can do a lot of customization by taking advantage of this feature, but in order to do what you need to do, you can simply provide an extra CSS file which overrides login.css (regardless the theme applied) on every request. If you are interested, this post will be useful to you.
Hope it helps.


text:
Q: drawImage draw the image on canvas but after any event it disappear image fabricjs I am drawing an image on canvas via drawImage method, it draw the image but when any event is called is become blank and disappear. I tried different ways but not success. I want to show the image on canvas and not disappear, Because I convas this canvas to dataUrl which become blank.
My working Link
Please anyone who know please guide me where i am going wrong.
Below is my code.

<!DOCTYPE html>

<title>Canvas.dataURL tainted(polluted) Issue</title>

<canvas id="canvas" height=758 width=497 style="border:1px solid lightgrey;display:inline-block;"></canvas>

<button type="button" id="clickme">Click Me!</button>

A: Check this Fiddle.
You are getting this problem because you are drawing that in context and not adding that to canvas object. So after drawing in context you get that context data using ctx.getImageData(0, 0, img.width, img.height); After that create a canvas element and put that image datac.getContext('2d').putImageData(data, 0, 0); then create an fabricjs image object from that canvas image data.
*Crossorigin problem is there so fiddle not working, you can check this in your local server

A: Working fiddle
You have to add image on fabric canvas as below.
 var imgbase64 = new fabric.Image(img, {})
 canvas.add(imgbase64);

And then it will work. Just make sure to check this on your local server as here it will throw CROS error.
I've changed image src to get it work as getting CORS error from your sample.

var canvas = new fabric.Canvas('canvas');

var offsetY = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 29.5, 30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9, 30, 29.5, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 29.5, 30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9, 30, 29.5, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 29.5, 30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9, 30, 29.5, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 29.5, 30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9, 30, 29.5, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 29.5, 30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9, 30, 29.5, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 29.5, 30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9, 30, 29.5, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 29.5, 30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9, 30, 29.5, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 29.5, 30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9, 30, 29.5, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 29.5, 30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9, 30, 29.5, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 29.5, 30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9, 30, 29.5, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0]

var ctx = canvas.getContext("2d");
var immg = 'http://i.imgur.com/3tU4Vig.jpg';

var img = new Image();

img.crossOrigin = "anonymous";
img.src = immg;

img.onload = function() {
  var imgbase64 = new fabric.Image(img, {
    width: 400,
    height: 500
  })
  canvas.add(imgbase64);
  canvas.deactivateAll().renderAll();

}

canvas.renderAll();

$(document).on('click', '#clickme', function() {

  var imagedatafinal = canvas.toDataURL('image/png');
  console.log(imagedatafinal);
  $('#curveImg').attr('src', imagedatafinal);
  var imgdatafinal = imagedatafinal.replace(/^data:image\/(png|jpg);base64,/, "");
  //ajax call to save image inside folder
  $.ajax({
    url: '../save_image.php',
    data: {
      imgdata: imgdatafinal
    },
    type: 'post',
    success: function(response) {
      $('#curveImg').attr('src', response);
      console.log(response);
    }
  });
});
<!DOCTYPE html>

  <title>Canvas.dataURL tainted(polluted) Issue</title>

  <canvas id="canvas" height=758 width=497 style="border:1px solid lightgrey;display:inline-block;"></canvas>

  <button type="button" id="clickme">Click Me!</button>


text:
Q: Video streaming fails over rtp protocol Video streaming between Unix Server (ffmpeg) and Windows client (vlc) completed without errors.
Server side:
ffmpeg -f v4l2 -r 25 -i /dev/video0 http://192.168.1.114:27018/feed1.ffm

Client side:
vlc player: Media -> Open Network Stream: http://192.168.1.114:27018/test.swf
However, video streaming has approximately 10 s. delay. For this reason, I tried using rtp instead http, but without result. Specifically, on server side I run:
ffmpeg -f v4l2 -r 25 -i /dev/video0 rtp://192.168.1.114:27018/feed1.ffm
After the stream begun, on client side I typed: rtp://@:27018 but it doesn't respond.
What I am missing? Is there any other way I could avoid delay?
EDIT:
vlc player's messages (Verbosity: 2 Debug) (new port used: 27020):
main debug: adding item `rtp://:27020' ( rtp://@:27020 )
qt4 debug: Adding a new MRL to recent ones: rtp://@:27020
main debug: processing request item: rtp://:27020, node: null, skip: 0
main debug: rebuilding array of current - root Playlist
main debug: rebuild done - 1 items, index 0
main debug: starting playback of the new playlist item
main debug: resyncing on rtp://:27020
main debug: rtp://:27020 is at 0
main debug: creating new input thread
main debug: Creating an input for 'rtp://:27020'
main debug: meta ok for (null), need to fetch art
main debug: looking for meta fetcher module matching "any": 1 candidates
lua debug: Trying Lua scripts in C:\Users\Demetres\AppData\Roaming\vlc\lua\meta\fetcher
lua debug: Trying Lua scripts in C:\Program Files (x86)\VideoLAN\VLC\lua\meta\fetcher
lua debug: Trying Lua playlist script C:\Program Files (x86)\VideoLAN\VLC\lua\meta\fetcher\tvrage.luac
main debug: using timeshift granularity of 50 MiB, in path 'C:\Users\Demetres\AppData\Local\Temp'
main debug: `rtp://@:27020' gives access `rtp' demux `' path `@:27020'
main debug: using meta fetcher module "lua"
main debug: creating demux: access='rtp' demux='' location='@:27020' file='\\@:27020'
main debug: removing module "lua"
main debug: searching art for rtp://:27020
main debug: looking for access_demux module matching "rtp": 12 candidates
main debug: looking for art finder module matching "any": 2 candidates
main debug: net: opening any datagram port 27020
lua debug: Trying Lua scripts in C:\Users\Demetres\AppData\Roaming\vlc\lua\meta\art
lua debug: Trying Lua scripts in C:\Program Files (x86)\VideoLAN\VLC\lua\meta\art
lua debug: Trying Lua playlist script C:\Program Files (x86)\VideoLAN\VLC\lua\meta\art\00_musicbrainz.luac
main debug: using access_demux module "rtp"
lua debug: Trying Lua playlist script C:\Program Files (x86)\VideoLAN\VLC\lua\meta\art\01_googleimage.luac
main debug: looking for meta reader module matching "any": 2 candidates
lua debug: Trying Lua scripts in C:\Users\Demetres\AppData\Roaming\vlc\lua\meta\reader
lua debug: Trying Lua scripts in C:\Program Files (x86)\VideoLAN\VLC\lua\meta\reader
lua debug: Trying Lua playlist script C:\Program Files (x86)\VideoLAN\VLC\lua\meta\reader\filename.luac
lua debug: Trying Lua playlist script C:\Program Files (x86)\VideoLAN\VLC\lua\meta\art\02_frenchtv.luac
main debug: no meta reader modules matched
main debug: `rtp://@:27020' successfully opened
lua debug: Trying Lua playlist script C:\Program Files (x86)\VideoLAN\VLC\lua\meta\art\03_lastfm.luac
main debug: no art finder modules matched
main debug: art not found for rtp://:27020
qt4 debug: IM: Setting an input


text:
Q: Adverbs of Manner Does it sound correct to say;
"A man was pointing loudly out to sea. Everyone looked to see what he was pointing at. There, only a few hundred yards out to sea, was the tell-tale triangular fin of a shark moving fast towards the beach.
Can the adverb loudly modify the phrase point out?
I mean, does it sound logical?

A: 'Loudly' can mean "ostentatiously; conspicuously; showily; glaringly", but its primary meaning is related to sound. You could use it in your context, it might confuse a minority of people and cause some others to reach for the dictionary, but it is interesting use of language. Logically then, you could say "he loudly pointed out the shark", but if you don't want to have a debate with your English teacher you might be better going for a safer adverb.
More common choices might be:

*

*frantically

*furiously

*energetically

For example:

*

*He frantically pointed out to sea

*A man was pointing furiously out to sea


text:
Q: jQuery - AJAX call of Servlet I'm building a web app for store scientific publications. I've used MySQL, JSP, jQuery and JAVA.
I have a form inside a JSP page, like this:
<form method="get">
    <input type="text" id="code">
    <button onclick="request()">Search</button>
</form>

The function request() is:
function request() {
    var code = $('#code').val();
    var data='code='+code;
    $.ajax({
          url: "Servlet",
          type: "GET",
          data: data,
          success: function(){
              alert("success");
          },
          error:function(){
              alert("failure");
          }
        });
};

The Servlet do some stuff and then save the resultset of query in the request object and forward the result on the index like this
request.setAttribute("result", resultSet);
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);

The index.jsp contains:
 <%  if(request.getAttribute("result")!=null){ %>
        <jsp:include page="table.jsp" />
  <%}%>

check if the result set is already filled, then include table.jsp, the page scan the resultset and put the values in a table.
This code doesn't work, someone can help me?
1- The query runs correctly
2- jQuery is called correctly
but the
if(request.getAttribute("result"))

is always null.


text:
Q: Error when connecting to powerbi dataset using adomd I am completely new to xmla and attempting to use the 19.22.0.1 version of Microsoft.AnalysisServices.SdomdClient.NetCore.retail.amd64 to connect to a dataset in a Powerbi premium workspace.  I lifted the connection string from the excel file generated by the analyze in excel option but attempting to use it results in a the following AdomdConnectionException.  Updating the connection string based upon the documentation guidance results in the same beahvior.   The excel spreadsheet works fine which I believe means the xmla endpoints settings are set appropriately.  I am able to access the dataset and linked reports via app.powerbi.com which suggest that I have the necessary permissions.
var tenantId = "<AAD Tenant Guid>";
var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
    VisualStudioTenantId = tenantId,
    VisualStudioCodeTenantId = tenantId,
    SharedTokenCacheTenantId = tenantId,
    InteractiveBrowserTenantId = tenantId,
});
var token = await credential.GetTokenAsync(new TokenRequestContext(scopes: new[] { "https://analysis.windows.net/powerbi/api" }));
// https://learn.microsoft.com/en-us/analysis-services/instances/connection-string-properties-analysis-services?view=asallproducts-allversions
var connectionString = @$"Provider=MSOLAP.8;Integrated Security=ClaimsToken;Persist Security Info=True;Initial Catalog=<DataSet Name>;Data Source=powerbi://api.powerbi.com/v1.0/myorg/<workspace>;MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error;Password={token.Token}";

Exception 1 - bad schema in the URL

Microsoft.AnalysisServices.AdomdClient.AdomdConnectionException: The
remote server returned an error: (401) Unauthorized.  --->
System.Net.WebException: The remote server returned an error: (401)
Unauthorized.    at System.Net.HttpWebRequest.GetResponse()    at
Microsoft.AnalysisServices.AdomdClient.ASAzureUtility.PutHttpJsonData[TRequest,TResult](Uri
uri, Dictionary`2 headers, TRequest requestObject, Int32 timeoutMs)
at
Microsoft.AnalysisServices.AdomdClient.ASAzureUtility.ResolvePowerBICluster(Uri
discoverUrl, String token, TimeLeft timeLeft, AsInstanceType
asInstanceType)    --- End of inner exception stack trace ---    at
Microsoft.AnalysisServices.AdomdClient.ASAzureUtility.ThrowConnectionException(WebException
ex, AsInstanceType asInstanceType)    at
Microsoft.AnalysisServices.AdomdClient.ASAzureUtility.ResolvePowerBICluster(Uri
discoverUrl, String token, TimeLeft timeLeft, AsInstanceType
asInstanceType)    at
Microsoft.AnalysisServices.AdomdClient.ConnectionInfo.ValidateAndSetPbiDatasourceAndLocation()
at
Microsoft.AnalysisServices.AdomdClient.ConnectionInfo.HandleAsAzureconnections()
at
Microsoft.AnalysisServices.AdomdClient.ConnectionInfo.ValidateAndCompleteConnectionConfiguration()
at
Microsoft.AnalysisServices.AdomdClient.ConnectionInfo.SetConnectionString(String
cs)    at
Microsoft.AnalysisServices.AdomdClient.ConnectionInfo..ctor(String
connectionString)    at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Microsoft.AnalysisServices.AdomdClient.AdomdConnection.IXmlaClientProviderEx.set_ConnectionString(String
value)    at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection.set_ConnectionString(String
value)    at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection..ctor(String
connectionString)

Update #1
A couple of tweaks to get further.

*

*the connection string I got from excel used the schema azurebi instead of powerbi

*shifted the token scope to https://analysis.windows.net/powebi/api
This allows the AdomdConnection to be instantiated but now when attempting to Open() the connection it throws exception #2 below.
Exception 2

Microsoft.AnalysisServices.AdomdClient.AdomdConnectionException: The
remote server returned an error: (401) Unauthorized.
Technical Details: RootActivityId:
025c6866-1776-48e0-a43f-677cdde76a20 Date (UTC): 7/8/2021 11:36:14 PM
---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.    at System.Net.HttpWebRequest.GetResponse()
at
Microsoft.AnalysisServices.AdomdClient.HttpRequestResponseExtensions.GetResponseWithErrorHandling(HttpWebRequest
httpWebRequest, Boolean isPbiPremium)    at
Microsoft.AnalysisServices.AdomdClient.HttpStream.WaitForAndUpdateHttpResponseContainingXmlaPayload()
at
Microsoft.AnalysisServices.AdomdClient.HttpStream.GetResponseStream()
--- End of inner exception stack trace ---    at Microsoft.AnalysisServices.AdomdClient.ASAzureUtility.ThrowConnectionException(WebException
ex, AsInstanceType asInstanceType)    at
Microsoft.AnalysisServices.AdomdClient.HttpStream.GetResponseStream()
at
Microsoft.AnalysisServices.AdomdClient.HttpStream.GetResponseDataType()
at
Microsoft.AnalysisServices.AdomdClient.CompressedStream.GetResponseDataType()
at
Microsoft.AnalysisServices.AdomdClient.XmlaClient.EndRequest(Boolean
useBinaryXml)    at
Microsoft.AnalysisServices.AdomdClient.XmlaClient.EndRequest()    at
Microsoft.AnalysisServices.AdomdClient.XmlaClient.CreateSession(ListDictionary
properties, Boolean sendNamespaceCompatibility, String sessionToken)
at
Microsoft.AnalysisServices.AdomdClient.XmlaClient.CreateSession(ListDictionary
properties, Boolean sendNamespaceCompatibility)    at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Microsoft.AnalysisServices.AdomdClient.AdomdConnection.IXmlaClientProviderEx.CreateSession(Boolean
sendNamespaceCompatibility)    at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection.ConnectToXMLA(Boolean
createSession, Boolean isHTTP)    at
Microsoft.AnalysisServices.AdomdClient.AdomdConnection.Open()


text:
Q: Unsafe Pointer iteration and Bitmap - why is UInt64 faster? I have been doing some unsafe bitmap operations and have found out that increasing the pointer less times can lead to some big performance improvements. I am not sure why is that so, even though you do lot more bitwise operations in the loop, it still is better to do less iterations on the pointer.
So for example instead of iterating over 32 bit pixels with a UInt32 iterate over two pixels with UInt64 and do twice the operations in one cycle.
The following does it by reading two pixels and modifying them (of course it will fail with images with odd width, but its just for testing).
    private void removeBlueWithTwoPixelIteration()
    {
        // think of a big image with data
        Bitmap bmp = new Bitmap(15000, 15000, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        TimeSpan startTime, endTime;

        unsafe {

            UInt64 doublePixel;
            UInt32 pixel1;
            UInt32 pixel2;

            const int readSize = sizeof(UInt64);
            const UInt64 rightHalf = UInt32.MaxValue;

            PerformanceCounter pf = new PerformanceCounter("System", "System Up Time"); pf.NextValue();

            BitmapData bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
            byte* image = (byte*)bd.Scan0.ToPointer();

            startTime = TimeSpan.FromSeconds(pf.NextValue());

            for (byte* line = image; line < image + bd.Stride * bd.Height; line += bd.Stride)
            {
                for (var pointer = line; pointer < line + bd.Stride; pointer += readSize)
                {
                    doublePixel = *((UInt64*)pointer);
                    pixel1 = (UInt32)(doublePixel >> (readSize * 8 / 2)) >> 8; // loose last 8 bits (Blue color)
                    pixel2 = (UInt32)(doublePixel & rightHalf) >> 8; // loose last 8 bits (Blue color)
                    *((UInt32*)pointer) = pixel1 << 8; // putback but shift so A R G get back to original positions
                    *((UInt32*)pointer + 1) = pixel2 << 8; // putback but shift so A R G get back to original positions
                }
            }

            endTime = TimeSpan.FromSeconds(pf.NextValue());

            bmp.UnlockBits(bd);
            bmp.Dispose();

        }

        MessageBox.Show((endTime - startTime).TotalMilliseconds.ToString());

    }

The following code does it pixel by pixel and is around 70% slower than the previous:
    private void removeBlueWithSinglePixelIteration()
    {
        // think of a big image with data
        Bitmap bmp = new Bitmap(15000, 15000, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        TimeSpan startTime, endTime;

        unsafe
        {

            UInt32 singlePixel;

            const int readSize = sizeof(UInt32);

            PerformanceCounter pf = new PerformanceCounter("System", "System Up Time"); pf.NextValue();

            BitmapData bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
            byte* image = (byte*)bd.Scan0.ToPointer();

            startTime = TimeSpan.FromSeconds(pf.NextValue());

            for (byte* line = image; line < image + bd.Stride * bd.Height; line += bd.Stride)
            {
                for (var pointer = line; pointer < line + bd.Stride; pointer += readSize)
                {
                    singlePixel = *((UInt32*)pointer) >> 8; // loose B
                    *((UInt32*)pointer) = singlePixel << 8; // adjust A R G back
                }
            }

            endTime = TimeSpan.FromSeconds(pf.NextValue());

            bmp.UnlockBits(bd);
            bmp.Dispose();

        }

        MessageBox.Show((endTime - startTime).TotalMilliseconds.ToString());
    }

Could someone clarify why is incrementing the pointer a more costly operation than doing a few bitwise operations?
I am using .NET 4 framework.
Could something like this be true for C++?
NB. 32 bit vs 64 bit the ratio of the two methods is equal, however both ways are like 20% slower on 64 vs 32 bit?
EDIT: As suggested by Porges and arul this could be because of decreased number of memory reads and branching overhead.
EDIT2:
After some testing it seems that reading from memory less time is the answer:
With this code assuming the image width is divisible by 5 you get 400% faster:
[StructLayout(LayoutKind.Sequential,Pack = 1)]
struct PixelContainer {
    public UInt32 pixel1;
    public UInt32 pixel2;
    public UInt32 pixel3;
    public UInt32 pixel4;
    public UInt32 pixel5;
}

Then use this:
            int readSize = sizeof(PixelContainer);

            // .....

            for (var pointer = line; pointer < line + bd.Stride; pointer += readSize)
            {
                multiPixel = *((PixelContainer*)pointer);
                multiPixel.pixel1 &= 0xFFFFFF00u;
                multiPixel.pixel2 &= 0xFFFFFF00u;
                multiPixel.pixel3 &= 0xFFFFFF00u;
                multiPixel.pixel4 &= 0xFFFFFF00u;
                multiPixel.pixel5 &= 0xFFFFFF00u;
                *((PixelContainer*)pointer) = multiPixel;
            }

A: This is a technique known as loop unrolling. The main performance benefit should come from reducing the branching overhead.
As a side note, you could speed it up a bit by using a bitmask:
*((UInt64 *)pointer) &= 0xFFFFFF00FFFFFF00ul;

A: It's not the incrementing the pointer that is slower, but reading from memory. With 32-bit units, you're doing twice as many reads.
You should find it faster again if you write once instead of twice in the 64-bit version.


text:
Q: Excel VBA, Sort according to a specific limit I wrote an Excel VBA code but for some reason it's not working completly fine.
I have a specific length of 21 (cell E2) and a list of sotred numbers below (column E in the picture)
The code runs on each cell in column E and adds it's value to a specific sum. if the sum up to this cell is lower or equel to 21 (cell E2) then the cell on the right gets the number "1". If it's higher then 21 then we restart the sum and do it again until we reach the limit (21) and all the cells on the right get the number "2" and so on until the end of the list.
As you can see from the picture its working except for the last cell (colored in yellow) where it's supposed to be 4 and not 3 (because 5+5+5+4+3=22>21)

I can't find where I have a problem. This is my code:
   Length = Range("E2").Value
   Range("E3").Select
   i = 1
   sumOfLen = 0

    Do Until Selection.Offset(1, 0).Value = Empty
        Do Until sumOfLen > Length Or Selection.Value = Empty
            Selection.Offset(0, 1).Value = i
            sumOfLen = sumOfLen + Selection.Value
            Selection.Offset(1, 0).Select
        Loop
        Selection.Offset(-1, 0).Select
        sumOfLen = 0
        i = i + 1
    Loop

Any help would be appreciated.

A: It's because you're resetting the sum to 0 rather than the current Range's value (e.g. 5).
May I suggest the following code?
Option Explicit

Public Sub doIt()
    Dim i As Long
    Dim curSum As Long
    Dim maxSum As Long
    Dim curRange As Range

    maxSum = Range("E2").Value
    Set curRange = Range("E3")
    i = 1

    Do While (curRange.Value <> "")
        curSum = curSum + curRange.Value
        If (curSum > maxSum) Then
            i = i + 1
            curSum = curRange.Value
        End If

        curRange.Offset(0, 1).Value = i
        Set curRange = curRange.Offset(1, 0)
    Loop
End Sub

If you'd like to keep your code, you need to change this:
sumOfLen = 0
to this
sumOfLen = Selection.Value


text:
Q: Logging error Traceback (most recent call last):File "/usr/lib/python3.7/logging/__init__.py", line 1025, in emit msg = self.format(record) I am trying to make a custom logging class.
import logging

logging_level = 'INFO'

class Logger:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.getLevelName(logging_level))
        formatter = logging.Formatter('%(asctime)s - %(name)s%(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S%p')
        file_handler = logging.FileHandler('logFile.log')
        file_handler.setFormatter(format)
        stream_handler = logging.StreamHandler() #if we want to print to consol
        stream_handler.setFormatter(format)
        self.logger.addHandler(file_handler)
        self.logger.addHandler(stream_handler)

    def logInfo(self):
        self.logger.info("Hi")

log = Logger()
log.logInfo()

I keep receiving this error
--- Logging error ---
Traceback (most recent call last):
  File "/usr/lib/python3.7/logging/__init__.py", line 1025, in emit
    msg = self.format(record)
  File "/usr/lib/python3.7/logging/__init__.py", line 869, in format
    return fmt.format(record)
AttributeError: 'builtin_function_or_method' object has no attribute 'format'
Call stack:
  File "/home/usr/.../python_scripts/Logger.py", line 22, in <module>
    log.logInfo()
  File "/home/usr/.../python_scripts/Logger.py", line 19, in logInfo
    self.logger.info("Hi")
Message: 'Hi'
Arguments: ()

I must be doing something wrong the the oo programming in python. IT makes the log file but it is empty.

A: You had a typo in your logInfo method and in the "format" paramater which should have been formatter, I also changed a bit the setLevel method to use getLevelName so you could change it dynamically:
import logging

logging_level = 'INFO'

class Logger:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.getLevelName(logging_level))
        formatter = logging.Formatter('%(asctime)s - %(name)s%(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S%p')
        file_handler = logging.FileHandler('logFile.log')
        file_handler.setFormatter(formatter)
        stream_handler = logging.StreamHandler() #if we want to print to consol
        stream_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)
        self.logger.addHandler(stream_handler)

    def logInfo(self):
        self.logger.info("Hi")

log = Logger()
log.logInfo()

Output
07/18/2022 06:24:39PM - __main__INFO: Hi


text:
Q: PHP MongoDB - Retain the array as array not object This is the object which I inserted to mongodb.
{
    '_array': [1,2,3],
    '_ass_array': [{'num': 1, 'name': 'One'}],
    '_obj': {'key': 'val'}
}

If I query on terminal, I can get the same as I inserted. But while querying via PHP's MongoCollection::findOne()/ MongoCollection::find(), I am getting following format.
{
    '_array': { 0: 1, 1: 2, 2: 3},
    '_ass_array': {
       0: {'num': 1, 'name': 'One'}
     },
    '_obj': {'key': 'val'}
}

Is there any way I can get the array as array and object as object? if required, I can update the question with the complete code.

A: On the same data this works for me. Just wondering if you are doing something different in a serialization since the JSON syntax in the post. As expected $data is a PHP array.
<?php

$dbhost = 'localhost';
$dbname = 'test';

$m = new Mongo("mongodb://$dbhost");
$db = $m->$dbname;

$col = $db->data;

$data = $col->findOne();

echo json_encode( $data ) . "\n";

?>

A little intrigued how you arrived at your result, as various people here have that format in their MongoDB documents.


text:
Q: All images are not downloaded when using Glide with RecyclerView on Android This problem I have faced a lot when using Glide (v3.8.0) to load list of images in a RecyclerView.

*

*I am trying to load 9 images (jpg format and 1000 x 1000 size) from server. Glide downloads few images and show it. But some are not downloaded and I have to re-open the Activity to download the remaining images.

*As Glide download images. The Activity gets slower and slower. The scrolling is very laggy.
Here is the onBindViewHolder of the RecyclerView.
RequestManager manager;
Context context;
List<Gallery> galleryList;

public BaseAdapter(Context context, List<Gallery> galleryList, RequestManager glide) {
    this.context = context;
    this.galleryList = galleryList;
    this.manager = glide;
}

@Override
public void onBindItemViewHolder(final KolamViewHolder holder, final int itemPosition) {
    Log.e("BaseAdapter", galleryList.get(itemPosition).getImage());
    manager.load(galleryList.get(itemPosition).getImage()).asBitmap()
            .diskCacheStrategy(DiskCacheStrategy.RESULT)
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    holder.kolamImage.setImageBitmap(resource);
                    holder.progressBar.setVisibility(View.GONE);
                    Log.e("BaseAdapter", "Ready");
                    //click listener to pass the gallery image to the bot
                    holder.kolamImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onItemClickListener.onItemClicked(galleryList.get(itemPosition));
                        }
                    });
                }
            });
}

Where am I making a mistake? How can I load all the images and without making any lag while scrolling?

A: There may be a chance of garbage collecting the SimpleTarget object. So sometimes your image won't be set in the image view. In order to solve this, you should set the target image view using into() method of builder class and put a placeholder for showing loading by placeholder() method.And implement onclick() on the image view.

A: You can simple load images from URL using Glide without creating bitmap for all. I think that process is unnecessary for you.
Glide.with(context).load(galleryList.get(itemPosition).getImage())
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.dontAnimate()
.override(150,150) // Customize size as per requirement
.placeholder(ContextCompat.getDrawable(context, R.mipmap.ic_user_placeholder_50dp))
.listener(new RequestListener<String, GlideDrawable>() {
    @Override public boolean onException(Exception e, String model,
        Target<GlideDrawable> target, boolean isFirstResource) {
        return false;
    }

    @Override public boolean onResourceReady(GlideDrawable resource, String model,
        Target<GlideDrawable> target, boolean isFromMemoryCache,
        boolean isFirstResource) {
        return false;
    }
})
.into(holder.kolamImage);

Hope it will help...


text:
Q: Voltage from IO pin at max current I'm trying to use an ATTiny84 pin to power an LED. I initially thought that I would get around a 3 V output at all voltages, but there is a graph in the datasheet showing that that isn't the case:

However, the graph stops at 20 mA. I might be using up to the maximum current output allowed from the pin (40 mA). Is there a way to figure out what the voltage would be at this current? Also, why didn't the designers put those values in the graph?

A: According this datasheet
The Absolute Maximum Ratings for DC current per IO pin is indeed 40 mA.

However, you should not operate a device at its Absolute Maximum Ratings, but at their Recommended Operation conditions.
Although the output current is not explicitly stated, there are tiny notes in the recommended operating conditions:

The reliable sink/source current at 3V supply is only 5 mA.
So, I'd suggest using a transistor instead of driving the LED directly by the uP.

Is there a way to figure out what the voltage would be at this current?

Yes, by testing and measuring it yourself.

Also, why didn't the designers put those values in the graph?

See, answer above. They still exceeded the 5 mA, but the tiny notes say the data is not guaranteed.

A: As mentioned, you do NOT want to drive the pin at 40mA.  Never operate anywhere near the maximum ratings for any device.  Not if you want a reliable circuit.  Run them below the recommended nominal conditions if you can.  Be nice to your chips, they'll be nice to you   ;)
Anyhow, hypothetically, you do have enough information to make an informed guess.
Basically, there's a resistance to the I/O port, right?   (i.e. "Output Impedance")
You have a number of "V" and "I" values, and by using ohms law, you can deduce this resistance.
For the 25-degree line, at 10mA, VOH=2.65V, while at 20mA, VOH=2.35V
Take the difference in voltages, and the difference in the currents...
E/I = R
(2.65V - 2.35V) / (20mA - 10mA) = 0.3V / 10mA = 30 ohms
So if you try to source 40mA, it has to pass through that 30 ohms, and you end up losing (40mA * 30 ohm) = 1.2V
Your output voltage would be VCC - 1.2V
That is, until your chip melts down    ;)


text:
Q: RuntimeError: input(): lost sys.stdin Написал простой код на Python.
name = input("Имя: ")

print(name)

Сохранил, решил преобразовать его в .exe через pyinstaller:
pyinstaller -w --onefile УказалПутьКФайлу.py

Файл вроде бы преобразовался и появился в папке dist, но при его запуске появляется следующее:
Traceback (most recent call last):

  File "example.py" line 1, in <module>

RuntimeError: input(): lost sys.stdin

A: Уберите ключ -w, без него работает. Что он значит, в доке не смотрел :)


text:
Q: How to stack promises dynamically? I have a nested object subprojects with a property of type array: userEstimates holding object(s) Estimate.
I am looking to iterate through userEstimates and push a fetch/promise to an array without calling it.
main (inside async function)
await subproject.getUserEstimates(true);
let stack = [];

subproject.userEstimates.forEach(ue =>
    stack.push(ue.fetchAvailableRates)
);

console.log(stack);  // 3) [ƒ, ƒ, ƒ]

await Promise.all(stack);

fillForm(subproject);

however, attributes on subproject are not defined when calling fillForm
function definition for fetchAvailableRates:
fetchAvailableRates = () => {
  this.availableRates = fetch(...)
  .then((resp) => {
    if (resp.ok) return resp.json();
    else throw new Error("Something went wrong");
  })
  .then((r) => {
    ...

    return {
      Rate.get(), // returns class
      ...
    };
  })
  .catch((e) => {
    console.error(e);
  });
};

EDIT: Changed my wording frrom queue to stack as i'm trying to run all requests at once, and I don't care about order

A: Your definition for fetchAvailableRates uses this, but when you refer to an object's function without calling it (like stack.push(ue.fetchAvailableRates)), it loses the reference to this and simply becomes a function.
To refer to a function that calls ue.fetchAvailableRates on the ue instance at the time, you should call either () => ue.fetchAvailableRates() or ue.fetchAvailableRates.bind(ue).
That's not the only change you'd need to make―Promise.all() doesn't accept functions, only promises, so the right call is probably to make ue.fetchAvailableRates() return the Promise and add that to the stack.


text:
Q: flex datagrid - making grid height dynamic and component that contains it HI,
i want to build a datagrid which will have a dynamic height value because the number of rows will always be different. I also want to communicate the height back to the component holiding it so that it also grows with the datagrid. Can anyone help me out on the best way to create such a dynamic datagrid.
Thanks

A: The DataGrid's height is controlled by its rowCount property. If you want your DataGrid to always be exactly high enough to show all the contained elements (and, for example, wrap it inside a Scroller to handle the situation where the DataGrid is too big for the available space, rather than having the DataGrid itself scroll), simply bind it to an appropriate property of your data source:
<mx:DataGrid dataProvider="{myData}" rowCount="{myData.length}"/>
<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;

        protected var myData:ArrayCollection;
    ]]>
</fx:Script>

A: Can you be more specific? Are you saying you don't want the datagrid to scroll? What about cases where the number of rows exceeds what can be seen on screen? -- Once you answer those questions, I can edit this to be a more specific answer.
As for communicating from your custom DataGrid implementation up to the parent object, what you want to do is broadcast an event indicating that the height should change, and attach some value -- the number of rows or the new height, probably -- to that event.
After learning the basics of event broadcasting in Flex, I realized they were way overcomplicated and learned the Swiz framework, which makes event Broadcasting and Handling about as simple as they could possibly be (among several other awesome things).


text:
Q: MIPS Trouble Detecting Null Terminating Character A little backstory:
This is an application designed to take a string and for each character, add a key (1-26) to the ascii value and place it back into the string.  The only problem is that my end character is always manipulated as well, even when I have my program designed to terminate on null characters (beqz).
encrypt:
# store string address in $t0
la $t0, ($a0)
#store key in $t1
move $t1, $a1
# initialize index, $t2 to 0
add $t2, $zero, $zero
li $t4, 26

encrypt_loop:
# load the byte at index in $t3
lb $t3, ($t0)

# check if it's the end of the string
beqz $t3, encrypt_end
# also check if it's a space
beq $t3, 32, incr

# subtract to make a = 0 etc
addi $t3, $t3, -97
# add key
add $t3, $t3, $t1
# modulo to make sure that it isn't over 26
div $t3, $t4
mfhi $t3
# add 97 back to get it back to its position
addi $t3, $t3, 97

# store byte back where you found it
sb $t3, ($t0)

#la $a0, ($t3)
#jal _put_char

incr:
# increment address
la $t0, 1($t0)

#jump back to beginning of the loop
j encrypt_loop

Example ->
Enter a message: super happy
Enter a key: 5
Encrypted message: xzujw mfuud]
Can anyone spot a reason that this code would manipulate that last character and change it into an ending bracket?  Thanks.

A: Turns out that the string was terminating correctly, but what I did not see was the carriage return at the end of a string that is entered into the console.  Once I accounted for that, I was able to get rid of the mysterious character.


text:
Q: Reset RealVnc Server Advanced Options On Pi When connecting to Real Vnc Server running on Raspberry Pi 3B I mistakenly set the advanced option here to directly render apps
When I connect now (from various clients) I just get a black screen with the message "Cannot currently show the desktop" I also tried removing and re-creating the connection on the client devices and lowering the screen resolution etc but no dice there either.
To try and resolve this I removed and purged RealVnc Server via cli rebooted and re-installed it. This doesn't work however.
Does anyone know where the config files are to remove this rendering option? Had a good look online and in the file system but cant see anything obvious to help.
Thanks
J

A: realvnc's settings for your user should be installed in ~/.vnc in your user's /home directory.
system-wide settings can be configured in /etc/vnc
you could try a couple of things; manually check in ~/.vnc folder and see if you can remove the specific problematic setting, or you could backup the config, then purge/delete your configs.
that should reset all of your settings.

A: The resolution is given by the RealVNC people at -
https://help.realvnc.com/hc/en-us/articles/5060068870813
If you have enabled direct capture with the KMS driver enabled and need to disable it, you can do so at the command line by connecting to your Raspberry Pi using SSH and running the below commands:
sudo sed -i '/CaptureTech/d' /root/.vnc/config.d/vncserver-x11
sudo vncserver-x11 -service -reload


text:
Q: Is there a function to convert a string to an integer in vb.net? I would like to convert for example the string "98" to the integer 98. Also, is there a way to specify that the value contained in the string is in hexadecimal and that "98" gets converted to 152?

A: Convert.ToInt32("98")
Convert.ToInt32("98", 16)

A: I've always been a fan of Integer.TryParse  The docs for .NET 4 are here.  This method accepts an Integer variable by reference, and returns a Boolean indicating whether the conversion was successful, so you don't have to do any error handling when calling TryParse.
If you use the overload that accepts NumberStyle, you can specify that the string contains a hexadecimal number.  Here is the overload.

A: You would convert the value to Integer with the Parse method:
Dim intValue As Integer = Integer.Parse("98")

To convert an hexadecimal value you can use the AllowHexSpecifier option:
Dim intValueFromHex As Integer = Integer.Parse("98", Globalization.NumberStyles.AllowHexSpecifier)

You can also use the TryParse method if the input value can be in the wrong format:
Dim intValue as integer
If Integer.TryParse("98", intValue)
    Console.WriteLine(intValue)
Else
    Console.WriteLine("Not an integer value")
End If

A: To convert string "98" to the integer 98, use CInt function. For example:
Dim MyString As String = "98"
Dim MyInteger As Integer

MyInteger = CInt(MyString)

Now MyInteger = 98

A: To convert using decimal notation (base-10):
Dim value = Convert.ToInt32("98")

or
Dim value = Integer.Parse("98")

or
Dim value As Integer
If Integer.TryParse("98", value) Then
  Console.WriteLine(value)
End If

To convert using hexadecimal notation (base-16):
Dim value = Convert.ToInt32("98", 16)

or
Dim value = Integer.Parse("98", NumberStyles.HexNumber)

or
Dim value As Integer
If Integer.TryParse("98", NumberStyles.HexNumber, Nothing, value) Then
  Console.WriteLine(value)
End If

The NumberStyles enumeration is in the System.Globalization namespace.


text:
Q: Communicating with a Blackstar ID Core Guitar Amplifier through its USB Entrance and C++ I currently own a Blackstar ID Core 10w Amp. It has a lot of built in guitar effects such as Reverb, Delay and Modulation, all of which have various depths and levels. By connecting a USB cable from the amp to my computer, I'm able to use Blackstar's Insider software, which allows me to save these effects settings and switch to any of them with just a double click. However, the need for a double click makes it impossible for you to play your guitar and change effects during a song (which is what a pedal does).
However, I wanted to know if it's possible to use C++ to do something more ambitious than the manufacturer allows: I wanted to create a software that would play a backing track (voice+drums but no guitar) of a song and allow the user to set where during that song he wants his effects changed, and to what. This way, one would be able to play a song from start to end, not needing to worry about having to change effects.
This would also be a school project, so it can't really be a "mouse manager" or anything of this sort. It would need to be something more robust.
FYI, as far as I'm concerned, Blackstar does not give us any API we could work with. So I'd like to know if this project is even possible and, if so, where I should start.
Thank you!

A: I feel your pain regarding Blackstar's awful Insider software.
To answer your question, is this project even possible, of course it is, the Insider software obviously is able to control the amp via USB. You just have to figure out what its protocol is.
You can use a USB sniffer like this one to see what commands Insider sends to the amp when you perform actions. With enough experimentation you should be able to reverse-engineer the protocol.
It's probably easier than you think. As evidence I offer the Insider software itself, which is not very sophisticated. The settings are probably modeled more or less as a struct.

A: This existing project is likely to help provide clues for you to reverse engineer what Insider does and rewrite that in C++.
https://github.com/jonathanunderwood/outsider


text:
Q: Scikit-Learn Encoding Categorical Features - ValueError: setting an array element with a sequence I am trying to use sklearn.preprocessing.OneHotEncoder to binarize my categorical variables before use in some regression methods such as OLS, the Lasso etc.
I have a nested list like so:
l = [[0, 0, 0], [0, 1, 1], [1, 2, 2], [0, 3, 2], [1, 4, 0], [0, 5, 2], [2, 2, 2], [0, 6, 2], [1, 7, 2], [0, 8, 3], [3, 4, 2], [0, 8, 4], [0, 9, 2], [1, 7, 1], [0, 10, 2], [0, 2, 5], [1, 11, 2], [1, 2, 3], [4, 12, 2], [1, 4, 2], [0, 13, 2], [0, 14, 2], [0, 15, 2], [0, 16, 0], [0, 17, 6], [5, 17, 2], [4, 17, 2], [0, 17, 3], [0, 2, 6], [0, 8, 6], [4, 2, 2], [4, 4, 2], [5, 15, 3], [0, 2, 3], [0, 7, 2], [1, 15, 2], [0, 17, 2], [0, 8, 2], [0, 2, 2], [4, 16, 2], [0, 1, 2], [5, 15, 2], [4, 8, 0], [0, 18, 3], [3, 11, 2], [6, 7, 2], [0, 8], [0, 19, 2], [1, 1, 2], [0, 7, 0], [0, 1, 0], [0, 4, 2], [0, 15, 3], [7, 8, 2], [1, 8, 0], [1, 16, 2], [0, 20, 2], [1, 8], [1, 8, 2], [0, 11, 1], [1, 21, 2], [4, 1, 2], [5, 1, 2], [2, 1, 2], [0, 22, 2], [8, 8, 2], [1, 8, 3], [1, 17, 2], [0, 8, 7], [0, 0, 2], [7, 7, 2], [2, 2, 8], [9, 8, 2], [5, 8, 2], [4, 8, 2], [0, 4, 3], [0, 23, 0], [0, 24, 2], [0, 2, 0], [3, 1, 2], [0, 25, 2], [0, 2, 9], [0, 11, 2], [1, 12, 2], [1, 26, 3], [0, 23, 2], [0, 27, 3], [3, 8, 2], [6, 8, 2], [6, 27, 2], [0, 16, 2], [0, 28, 2], [0, 29, 2], [0, 8, 0], [0, 8, 10], [0, 27, 2], [4, 7, 2], [0, 21, 2], [6, 11, 2], [0, 30, 2], [2, 8, 2], [0, 23, 3]]

from sklearn import preprocessing
enc = preprocessing.OneHotEncoder()
enc.fit(l)

However, I am running into the error:
ValueError: setting an array element with a sequence
Here is the most telling callback as far as I can see:
    C:\Program Files\Anaconda\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order)
    458
    459     """
--> 460     return array(a, dtype, copy=False, order=order)
    461
    462 def asanyarray(a, dtype=None, order=None):

To try and solve this problem I have attempted to convert my list to a matrix and array in numpy but have had no luck.
In addition, I have made sure that each value in each of the nested lists is an integer. I have also tried converting them to floats, again with no success.
Any help would be wonderful. Thanks.


text:
Q: How to convert PCollection to Long in Dataflow Apache beam using Java When we try to convert the Pcollection to Long we are getting Type casting exception. kindly have a look into below code.
error
java.lang.Integer cannot be cast to java.lang.Long

Creating the pcollection
PCollection<Row> count = pt.apply(SqlTransform.query(Constants.total_count));
        PCollectionView<Long> outputCount = detail_count
                .apply("Row to long",
                        ParDo.of(new RowToLong())).apply(View.asSingleton());

Query
String total_count  = select sum(cast(col1 as INT)) as total_count from

Converting RowTo method
public class RowToLong extends DoFn<Row, Long> {
    public static final Logger LOG = LoggerFactory.getLogger(RowToLong.class.getName());

    private PCollectionView<Long> outputCount;

    @ProcessElement
    public void processElement(ProcessContext context) {

    //  Long total_count=((Number)c.element().getInt64("total_count")).longValue();
        Long total_count= Long.valueOf(context.element().getInt64("total_count"));
          context.output(total_count);
    }

}

A: Try this using below code.
Query
String total_count  = select sum(cast(col1 as bigint)) as total_count from

Converting row to method
Long total_count = context.element().getInt64("total_count").longValue();


text:
Q: Динамически изменяющаяся форма Django Сломал голову о простую задачу. Суть такова: делаю автоматический генератор расписаний в формате ics. Конечный результат - сайт, написанный на Django. Сейчас споткнулся вот обо что: есть база данных, содержащая события, которые являются, по сути, университетскими занятиями. У каждого события есть курс, к которому оно относится, форма обучения, шифр программы и код группы.
Идея в том, чтобы пользователь мог последовательно выбрать сначала форму обучения, затем курс, затем шифр программы, и в самом конце - код группы.
Важно, чтобы если пользователь выбрал определенную форму обучения (например, очную), ему были предоставлены варианты выбора, соответствующие только очной форме обучения. Затем, когда он выберет курс, ему должны быть предоставлены такие шифры программ, которые соответствуют условию "выбранная форма обучения"+"выбранный курс".
В итоге пользователь должен получить адекватный набор групп, среди которых он сможет выбрать свою, т.к. если ему дать все сразу, то придется выбирать из нескольких десятков.
Поскольку база данных (sqlite3) постоянно обновляется новыми событиями с новыми специальностями, я рассчитываю на метод SELECT DISTINCT для нахождения уникальных значений в столбцах БД. Но каких-то более конкретных идей у меня нет.
В общем, вероятно, для опытного программиста эта задача простая. Заведомо не пишу сюда код, т.к. ожидаю в целом концепцию. Пока не могу понять, как это можно реализовать и как вообще это реализовывают на Django. Спасибо!
если что, мой тг: uro8oros


text:
Q: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in mysql php I am using prepared statement and executing
$search = trim($_GET['s']);
if($stmtgetproducts = $mysqli->prepare("SELECT s.store_id, product_id, product_name, product_desc, product_price, product_discount, product_views, product_date, product_code, product_category, product_image1, product_image2, sale_id,s.store_name,s.store_username
  FROM store_products sp
  INNER JOIN store_product_categories spc ON sp.product_category=spc.id
  INNER JOIN store s ON sp.store_id=s.store_id WHERE MATCH(product_name, product_desc) AGAINST('?' IN BOOLEAN MODE);")){
$stmtgetproducts->bind_param("s",$search);
$stmtgetproducts->execute();
$getproducts=$stmtgetproducts->get_result();
$stmtgetproducts->close();
}
else
{
 echo $mysqli->error;
}

Since, I am giving it just one parameter to take as argument and binding param just one that is $search it gives me this error
mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement

this if form
<form action="" method="GET">
                  Search Product: <input type="text" name="s" placeholder="Enter product name">
                </form>

if I change this
$stmtgetproducts->bind_param("ss",$search);

then this error comes
mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables

A: $stmtgetproducts = $mysqli->prepare("SELECT s.store_id, product_id, product_name, product_desc, product_price, product_discount, product_views, product_date, product_code, product_category, product_image1, product_image2, sale_id,s.store_name,s.store_username
  FROM store_products sp
  INNER JOIN store_product_categories spc ON sp.product_category=spc.id
  INNER JOIN store s ON sp.store_id=s.store_id WHERE MATCH(product_name, product_desc) AGAINST(? IN BOOLEAN MODE);"))

changed my prepared statement to this


text:
Q: Does a real function constructed from a holomorphic function still satisfy the same conditions for complex theorems? Consider the following explicit construction:
Let $f$ be a holomorphic function on an open set $\Omega\subseteq\mathbb{C}$. Suppose $(x_n)_n$ is a sequence in $\Omega$ such that $x_n\in \Omega \cap\mathbb{R}$ for all $n$ and $x_n\to z_0\in\Omega\cap\mathbb{R}$ (but $(x_n)_n$ not constant). Furthermore, for all $n$ we have $f(x_n) \in \mathbb{R}$.
This is all to say that $f$ is holomorphic on an open set such that $f$ is real on a convergent sequence in its domain with limit point inside the domain.
Now take $r>0$ such that the disk $D_r(z_0)$ around $z_0$ is contained in $\Omega$. I want to show that for all $x\in D_r(z_0)$ the image $f(x)$ is real.
To do this I construct $$g:\Omega\cap\mathbb{R}\to \mathbb{R}:z\mapsto \Im(f(z)).$$
This is a real function which will still be differentiable because $f$ is holomorphic.
I now want to use the theorem for complex functions that says that if a holomorphic function vanishes for a sequence of points with limit point in its domain, then that function is identically zero. Applying this theorem to $g$ would prove that $f$ is real on the region $D_r(z_0)\cap\mathbb{R}$. But can I just apply this theorem to $g$?


text:
Q: Equality of two sets from homogenous differential equation solutions I'm currently having a very specific difficulty for the end of the proof of this theorem about homogenous differential equation solutions :

Let $a$ be a continuous function over some interval $I$ in $\mathbb{R}$ with values within $\mathbb{K}=\mathbb{R}$ or $\mathbb{C}$.
The solutions to the homogenous differential equation $(E_h):y'+ay=0$ over $I$ are the functions of the form $Cf_0$, with $f_0$ any non-zero solution to $(E_h)$ over $I$, and $C\in\mathbb{K}$.

After finding the set of solutions to $(E_h)$ to be $S_h=\{Cf_1, C\in\mathbb{K}\}$ (for $f_1$ some convenient function), we have to prove we can pick any of these functions to build the whole set of solutions.
The documentation i'm using proves it like so :

If $f_0$ is any non-zero solution to $(E_h)$, then $\exists C_0\in\mathbb{K}^*/f_0=C_0f_1$.
But then, $S_h=\{Cf_1,C\in\mathbb{K}\}=\{\frac{C}{C_0}C_0f_1,C\in\mathbb{K}\}=\{\frac{C}{C_0}f_0,C\in\mathbb{K}\}\subset\{C'f_0,C'\in\mathbb{K}\}$
and $\{Cf_0, C\in\mathbb{K}\}=\{CC_0f_1,C\in\mathbb{K}\}\subset\{C'f_1,C'\in\mathbb{K}\}$
Eventually : $S_h=\{Cf_0,C\in\mathbb{K}\}$

Even though i completely understand that to prove that two sets are equal, mutual inclusion is a common technique, i thought one could directly write :

$S_h=\{Cf_1,C\in\mathbb{K}\}=\{\frac{C}{C_0}C_0f_1,C\in\mathbb{K}\}=\{\frac{C}{C_0}f_0,C\in\mathbb{K}\}=\{C'f_0,C'\in\mathbb{K}\}$

and conclude in one line.
Either i don't see something very subtle, or the person who wrote this proof down went an extra mile.
Any clarifications ?
Thanks in advance, and cheers !


text:
Q: Write speed efficient code in python While surfing stack exchange, I have seen many people mentioning speed efficiency in their answers. How is one code faster than the other one which does the same function?

*

*What makes the code run faster? Less lines?

*Does importing mean loss of performance?

*What things should I keep in mind to write performance efficient code?

*Why do I need a performance efficient code?

I have also seen people writing

Loose on speed to gain on beauty?

Why are beautiful codes slow?

A: I'll try to give you a concrete answer. Your question is too abroad and involves a lot of things that are not trivial to explain.
How is one code faster than the other one which does the same function?
For example, you have to find an element in an array. You can look for it in every cell until the end or stop when you have found it. This is the most trivial example I can give you, but I think that is good to a initial idea.
Well, now you would look for "bubble sort" and "quickSort" as examples of algorithm to sort arrays. They do the same job, but the second one much faster.
What makes the code run faster? Less lines?
Not really, you may be interested in learn something about complexity of algorithms. Search on "Big O Notation", which is a way of describing the asymptotic performance of algorithms.
Does importing mean loss of performance?
It depends on the context. If you need to save resources because of hardware where you will execute your code may yes. In another situations may the differences about performance is very little so you don't have a real problem.
What things should I keep in mind to write performance efficient code?
You have to learn differents skills about algorithms. (backtracking algorithms, divide and conquer algorithms, dynamic programming algorithms, greedy algorithms, branch and bound algorithms...)
Before that, you will usually use brute force algorithms whick makes your code less efficient.
Why do I need a performance efficient code?
You have a cpu which is not God. If the mayority of the code which is actually run in your computer aren't efficient you would have a problem, everything will be slower. And in some cases impossible to maintain.
Loose on speed to gain on beauty?
Beautiful code is usually code that is easy to understand.
Often more efficient algorithm are harder to understand, and there are other costs in time to write and maintain the code.
But you can reduce that effect if you get used to write Clean Code.
Your code will be much better, beauty and more efficient in a lot of ways.
It's very important trying to make your code understandable, but if you can't, give some information in comments or documentation about what are you doing in these lines.
I hope this helps you.

A: Picking a better algorithm can often lead to remarkable speed improvements.
For example, replacing bubble sort with quicksort; same job, better algorithm, much faster.
The faster algorithm may be harder to understand, and there are other costs in time to write and maintain the code; but I have seen a job which took 4 days to run reduced to 25 seconds by a better algorithm.
For more detail, search on "Big O Notation" - a way of describing the asymptotic performance of algorithms.


text:
Q: how convert Object to int only digit in python dataframe? this is my datafarame with pandas
2020-02-05
2020-03-02

I wanna convert to int for plot to bar histogram chart. So i use regular expression to get only digit. after that i will try to convert int. but my regular expression function get error.
below function is to get digit in string
import re

def split_it(data):
    return re.findall('(\d+)',data)[0]

and this is my error
expected string or bytes-like object

so i try again with another source code.

import re

def split_it(data):
    return re.findall('(\d+)',str(data))

and result it's below.
[2020, 02, 05]

[2020, 03, 02]

[2020, 02, 19]

would you tell me how can i get 20200205 as type int?
and why second function is return list type?

A: that doesnt look like a dataframe and you dont show us how you call it but here is how i would do it
series = pandas.to_datetime(['2020-02-05','2020-03-02'])
#this is actually a datetimeindex, that does not use .dt accessor
new_series = series.strftime("%Y%m%d").astype(int)

if it is a dataframe you would do it slightly different
#assumes a column named datetime exists, use its .dt accessor
int_series = df['datetime'].dt.strftime("%Y%m%d").astype(int)

A: Try with replace
data['col'].str.replace('-','').astype(int)


text:
Q: Does devise require session affinity? As I am using load balancer in my app, it becomes important to know whether devise uses cookie based authentication or only session based authentication?
It would be great to use cookie based authentication, then I do not have to reserve the same server for a signed it user for all his requests, and it will be easier to manage load balancing.
So, does devise use cookie based authentication out of the box? or do I have to enable it? or it supports session based authentication only?


text:
Q: Django count() function (noob question I know) Hi everybody, I keep having a problem with the count() function.
In my website I added some items to the database, then I'd like to show on the hompage the number of items, but the count doesn't show up. I really can't figure out what I'm doing wrong.
this is the code:
View.py:
class homeView(TemplateView):
    template_name = 'search/home.html'

    def conto(self):
        album = Info.objects.all().count()
        return album

Html file:

 ALBUM TOTALI: {{album}}

A: You need to override the get_context_data method of the TemplateView you are inheriting from:
class homeView(TemplateView):
    template_name = 'search/home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['album'] = Info.objects.all().count()
        return context

A: You can render this with:

 ALBUM TOTALI: {{ view.conto }}

This works because the ContextMixin [Django-doc] passes the view to the template under the name view, and you can thus access the method with view.conto.


text:
Q: how to do the same button for three screens? I have some trouble. So i have AvPlayer and UIButton with play/stop.
Also: I have three UiViewControllers. I need that when I click on the first button on the first UIVIewController on the second controller, the third controller button is pressed also, respectively, on the contrary, too. How its make? Any proposition?
It's simple code - push on button - play URL Stream and also when push again stop music.
-(IBAction)playRadioButton:(id)sender
{
    if(clicked == 0) {
        clicked = 1;
        NSLog(@"Play");
        NSString *urlAddress = @"http://URLRADIOSTREAM";
        NSURL *urlStream = [NSURL URLWithString:urlAddress];
        myplayer = [[AVPlayer alloc] initWithURL:urlStream];
        [myplayer play];
        [playRadioButton setTitle:@"Pause" forState:UIControlStateNormal];
    }
    else
    {
        NSLog(@"Stop");
        [myplayer release];
        clicked = 0;
        [playRadioButton setTitle:@"Play" forState:UIControlStateNormal];
    }
}

A: If you have several controllers that you need to notify about an event on another controller you can use NSNotificationCenter
Eg. in one controller in ViewDidLoad
[[NSNotificationCenter defaultCenter]    addObserver:self
                                            selector:@selector(playBtnClicked:)
                                                name:@"BTN_CLICKED"
                                              object:nil];

Also in the same controller define the selector e.g.
-(void)playBtnClicked:(NSNotification *)pNotification
{
// do something
}

In the other controller trigger it by using
    [[NSNotificationCenter defaultCenter]
                    postNotificationName:@"BTN_CLICKED" object:nil];

A: If you don't want to use nsnotifications then use protocol and notify other viewcontrollers by using delegates

A: First of all, are the 3 view controllers allocated and initialized at once? If not, I recommend you set a property on your AppDelegate class, like this:
@interface AppDelegate

@property (nonatomic, assign) BOOL commonButtonPressed;
// All your code here

@end

And you can set this property like this:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.commonButtonPressed = YES; // or NO;

Then, from your UIViewController classes:
- (void)viewWillAppear:(BOOL)animated {

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (appDelegate.commonButtonPressed) {

        // Logic of what happens to the button goes here.
    }
}

Another way of doing this, without touching your AppDelegate class is using NSUserDefaults, like this:
[[NSUserDefaults standardDefaults] setBool:(<YES or NO>) forKey:@"commonButtonPressed"];
[[NSUserDefaults standardDefaults] synchronize];

You can read back the value like this:
BOOL buttonPressed = [[NSUserDefaults standardDefaults] boolForKey:@"commonButtonPressed"];


text:
Q: Enabling ssl through existing certificate in solr I need to load the existing .crt file in solr, jetty-9 web server to enable ssl using keytool/openssl commands. Anyone help me to solve this out ?
when i try to use the existing certifacate, i can see this in console,
Waiting to see Solr listening on port 8443 [-]
Started Solr server on port 8443 (pid=61455). Happy searching!

but in browser,
This webpage is not available
ERR_CONNECTION_CLOSED

Self-signed certificate is working well (reference : https://cwiki.apache.org/confluence/display/solr/Enabling+SSL)


text:
Q: jBoss Profile - how? I want to profile my jBoss Apps on a remote server. I've tried the Eclipse TPTP project but with an invoked agent my jBoss Portal doesn't start and it ends in unlimited lines of exceptions.
jProfiler doesn't work either, portal doesn't boot.
Netbeans IDE Profiling seems only to work on local machines or did I missed something?
How do you profile your web apps?

A: The VisualVM from the JDK6 works with JBoss Portal (tested with Portal 2.7.1).

A: I use YourKit to profile JBoss servers, and not just in development, either - the YourKit agent runs on production servers, with no performance impact until the GUI is attached. Works very well.