text:
Q: Nonabelian infinite nilpotent groups Can you give examples of nonabelian infinite nilpotent groups?
Here's what I got so far:

*

*The Heisenberg group.

*The free nilpotent group of class $s$ (thanks Arturo for your comment here).

*The group of (some) symmetries of polynomials of degree up to by $s$ generated by the symmetry which adds a constant polynomial (for each constant polynomial) and translation of the argument of the polynomial by a scalar (for each scalar).

(got the last 2 examples from http://terrytao.wordpress.com/2009/12/21/the-free-nilpotent-group/).
I'm looking for more examples of such groups. Infinite nonabelian groups which are not nilpotent, but have a nilpotent subgroup of finite index are also of interest to me.

A: For example, these are constructed in Robinson's A Course in the Theory of Groups, 2nd Edition:

*

*Let $R$ be a ring (not necessarily commutative, not necessarily with identity); if $n\gt 0$, then we let $R^{(n)}$ be the set of all sums of products of $n$ elements of $R$; then $R^{(n)}$ is a subring of $R$, and $R^{(n)}=0$ if and only if every product of $n$ elements of $R$ is equal to $0$. If $R^{(n)}=0$ for some $n\gt 0$, we say that $R$ is a nilpotent ring.
Now let $S$ be a ring with identity, and assume that $R$ is a subring of $S$ that is a nilpotent ring (in particular, $R$ does not contain the identity). Let $U$ be the set of all elements of the form $1+x$ with $x\in R$. Then $U$ is a group under the operation given by multiplication in $S$: that is, given $1+x$ and $1+y$ in $U$, then
$$(1+x)(1+y) = 1 + (x + y + xy) \in U$$
and
$$(1+x)^{-1} = 1 + (-x + x^2 - x^3 + x^4 -\cdots + (-1)^{n-1}x^{n-1})\in U,$$
where $x^n = 0$.
Then $U$ is a nilpotent group, and if we let $U_i = R^{(i)}$, then
$$1 = U_n \leq U_{n-1}\leq\cdots\leq U_1 = U$$
is a central series for $U$.
For example, let $S$ be the ring of $n\times n$ matrices over an infinite commutative ring with identity $T$, and let $R$ be the set of upper zero triangular matrices; then $R$ is nilpotent, and the corresponding $U$ is the group of upper unitriangular matrices over $T$, which is nilpotent of class exactly $n-1$. (This generalizes the Heisenberg group).

*Let $A$ be a nontrivial abelian group, let $D=A\times A$, and let $\delta\colon D\to D$ be given by $\delta(a,b) = (a,ab)$. Let $G=D\rtimes\langle \delta\rangle$. Then $G$ is nilpotent of class $2$. If $A$ is infinite, so is $G$.


text:
Q: Reducing reactive power by using a resistor I have a school exercise that goes like this:

Voltage is 230V. Frequency is 50Hz. Inductor is 400mH.

How big of a resistor should be added with the inductor (in a series) to reduce reactive power by 75%? (The correct answer is apparently 218 ohms.)

How do you calculate this? Is this even possible? I know only of capacitors reducing reactive power.
I can only figure out that 25% of the reactive power is be 105,24 var. Also sorry, I don't study in English, so the terms might be a bit strange. Thank you.

A: The resistor in series with the inductor just serves to reduce the overall current draw through the inductor. Thus, the resulting reactive drop (Q) in the inductor goes down.
The reactive drop in the inductor is,
$$ Q = I^2X_L$$
You can calculate the current with the formula I give above.

A: Well, the real power is given by:
$$\text{P}=\text{V}_\text{rms}\text{I}_\text{rms}\cos\left(\varphi\right)\tag1$$
Where \$\varphi=\left|\arg\left(\underline{\text{V}}\right)-\arg\left(\underline{\text{I}}\right)\right|\$.
The complex power is given by:
$$\text{Q}=\text{V}_\text{rms}\text{I}_\text{rms}\sin\left(\varphi\right)\tag2$$
And the apparent power is given by:
$$\text{S}=\sqrt{\text{P}^2+\text{Q}^2}=\text{V}_\text{rms}\text{I}_\text{rms}\tag3$$
So, for your circuit we get:

*

*Real power:
$$\text{P}=\text{V}_\text{rms}\cdot\underbrace{\frac{\text{V}_\text{rms}}{\sqrt{\text{R}^2+\left(\omega\text{L}\right)^2}}}_{=\space\text{I}_\text{rms}}\cdot\underbrace{\frac{1}{\sqrt{1+\left(\frac{\omega\text{L}}{\text{R}}\right)^2}}}_{=\space\cos\left(\varphi\right)}=\frac{\text{R}\text{V}_\text{rms}^2}{\text{R}^2+\left(\omega\text{L}\right)^2}\tag4$$

*Complex power:
$$\text{Q}=\text{V}_\text{rms}\cdot\underbrace{\frac{\text{V}_\text{rms}}{\sqrt{\text{R}^2+\left(\omega\text{L}\right)^2}}}_{=\space\text{I}_\text{rms}}\cdot\underbrace{\frac{\omega\text{L}}{\text{R}}\cdot\frac{1}{\sqrt{1+\left(\frac{\omega\text{L}}{\text{R}}\right)^2}}}_{=\space\sin\left(\varphi\right)}=\frac{\omega\text{L}\text{V}_\text{rms}^2}{\text{R}^2+\left(\omega\text{L}\right)^2}\tag5$$

*Apparent power:
$$\text{S}=\text{V}_\text{rms}\cdot\underbrace{\frac{\text{V}_\text{rms}}{\sqrt{\text{R}^2+\left(\omega\text{L}\right)^2}}}_{=\space\text{I}_\text{rms}}=\frac{\text{V}_\text{rms}^2}{\sqrt{\text{R}^2+\left(\omega\text{L}\right)^2}}\tag6$$
Now, we want to solve:
$$\frac{\text{V}_\text{rms}^2}{\omega\text{L}}\left(1-\frac{\eta\space\text{%}}{100}\right)=\frac{\omega\text{L}\text{V}_\text{rms}^2}{\text{R}^2+\left(\omega\text{L}\right)^2}\tag7$$
Using your values, we get:
$$\frac{230^2}{2\pi\cdot50\cdot400\cdot10^{-3}}\cdot\left(1-\frac{75}{100}\right)=\frac{2\pi\cdot50\cdot400\cdot10^{-3}\cdot230^2}{\text{R}^2+\left(2\pi\cdot50\cdot400\cdot10^{-3}\right)^2}\space\Longrightarrow\space$$
$$\text{R}=40 \sqrt{3} \pi\approx217.656\space\Omega\tag8$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP + Apache2: No errors are showing inside my classes, cannot debug properly I am currently developing in a machine that is running Ubuntu 16.04 LTS with Apache 2.4.18. I use Google Chrome Version 58.0.3029.81 (64-bit) as browser.
When I type phpinfo(); in my PHP scripts running on localhost, I get this:
PHP Version   7.0.18-1+deb.sury.org~xenial+1
display_errors    On
error_reporting   32767
Both in "local value" and "master value".
The problem is that I cannot see any errors when debugging inside my PHP classes, no matter what I try. I've tried to ini_set both display_errors and error_reporting in the index.php of my application, but it just does not work anyway, I just keep getting blank pages that have no output that I can examine when viewing the source code.
I have tried to access the apache2 log folder and use tail -f myproject.error.log, but I only get old errors that have no relevant information for me.
I also tried to try logging the PHP errors with error_logging, but I guess that I do not have set the right permissions for the folder / log itself, because the folder exists but there is no file within the specificied folder.
I am legit going crazy with this problem, because it makes debugging my code a complete nightmare, since I am a beginner in PHP development and it is so frustrating to not be able to see my errors as I try to develop the code.
I created my PHP application following this tutorial https://github.com/PatrickLouys/no-framework-tutorial/. I am using the "Woops" library for error handling.
Any help is appreciated, thanks in advance.

A: After testing so many different things, I came up with a solution myself.
My Apache server was configurated properly. All I had to do was add the following lines to the top of my "Boostrap.php" file, the file that is included in my index.php file.
So, the Bootstrap.php file begins like this:
<?php declare(strict_types = 1);
namespace Myproject;
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/Includes/config.php';
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', "On");
ini_set('log_errors', "On");
Basically if you are using strict_types = 1 you have to declare the ini_set instructions as Strings, and the Bootstrap file (or your autoloader file) has to contain the Error Reporting / Displaying instructions, not your index.php.


text:
Q: Mongodb and expressjs post method not working I started working on a MERN App today and im having trouble using the post method to store data in my mongodb database. I have connected to the database successfully.
I am connecting to the database as follows:
const mongoose = require("mongoose");
const routes = require("./controllers/postMessageController");

mongoose.connect(
    "mongodb://localhost:27017/postManagerDB",
    { useNewUrlParser: true, useUnifiedTopology: true },
    (err) => {
        if (!err) {
            console.log("MongoDB connection succeeded");
        } else {
            console.log(
                "Error while connecting to MongoDB: " +
                    JSON.stringify(err, undefined, 2)
            );
        }
    }
);

As mentioned before, the connection is all successfull. Now when i try to post a message to my database i have postman run continuosly until i cancel the request getting the following error:
Error while creating new record : {
  "driver": true,
  "name": "MongoError",
  "index": 0,
  "code": 13297
}

The following is my message model:
const mongoose = require("mongoose");

var PostMessage = mongoose.model("PostMessage", {
    title: { type: String },
    message: { type: String },
});

module.exports = { PostMessage };

I also worked on my routes ./controllers/postMessageController
const express = require("express");
var router = express.Router();
var ObjectID = require("mongoose").Types.ObjectId;

var { PostMessage } = require("../models/postMessage");

router.get("/", (req, res) => {
    PostMessage.find((err, docs) => {
        if (!err) res.send(docs);
        else
            console.log(
                "Error while retrieving all records : " +
                    JSON.stringify(err, undefined, 2)
            );
    });
});

router.post("/", (req, res) => {
    var newRecord = new PostMessage({
        title: req.body.title,
        message: req.body.message,
    });

    newRecord.save((err, docs) => {
        if (!err) res.send(docs);
        else
            console.log(
                "Error while creating new record : " +
                    JSON.stringify(err, undefined, 2)
            );
    });
});

In index.js i call the following:
require("./db");

const express = require("express");
const bodyParser = require("body-parser");

var postMessageRoutes = require("./controllers/postMessageController");

var app = express();
app.use(bodyParser.json());
app.listen(4000, () => {
    console.log("Server started at: 4000");
});

app.use("/postMessages", postMessageRoutes);

I am very confused, the GET method works fine but the POST method is giving me issues. Any help appreciated.

A:
Now when i try to post a message to my database i have postman run
continuosly until i cancel the request getting the following erro

The reason is you're not sending any response to the client so the connection simply times out instead of sending any data.
Look at this code:
router.post("/", (req, res) => {
    var newRecord = new PostMessage({
        title: req.body.title,
        message: req.body.message,
    });

    newRecord.save((err, docs) => {
        if (!err) res.send(docs);
        else
            console.log(
                "Error while creating new record : " +
                    JSON.stringify(err, undefined, 2)
            );
    });
});

You see you're only console.log printing the response, not sending anything after the else statement if there is error to the client. You are getting error, but you need to send that error to the client if you don't want it to run out.
Example:
router.post("/", (req, res) => {
    var newRecord = new PostMessage({
        title: req.body.title,
        message: req.body.message,
    });

    newRecord.save((err, docs) => {
        if (!err) res.send(docs);
        else
            res.send(err)
    });
});


text:
Q: Using forms with models How would I display form based on models when I am using composition with them? As an example
class House(models.Model):
    number_of_roommates = models.IntegerField(default=0)

class Posting(models.Model):
    title = models.CharField(max_length=150)
    description = models.CharField(max_length=500)
    house = models.OneToOneField(House)

I am stumped on what the view should be like. Right now I have two form classes for each of the Models.
def form_view(request):

    if request.method == "POST":
        Post = Posting(request.POST) ##Not really sure what to do here
        house = House(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('co_op.views.list_view')
    else:
        descriptionForm = PostDescription()
        houseForm = HouseDescription()
    return render(request, 'co_op/form_view.html', {
                                                    'descForm' : descriptionForm, 'houseForm' : houseForm,})

A: You should use django Modelform for this.
By calling your models classes by PostDescription() etc , you are just creating objects of those classes, not forms.

A: I think you are confused about how forms work in Django.Apart from the documentation,please go through http://www.tangowithdjango.com/book17/chapters/forms.html is much more easier to understand and execute what you want.For beginners , I think this is much more helpful than the actual docs.


text:
Q: Understanding origin of jQuery $each() parameters? Whilst reading jQuery Cookbook (Oreilly) last night I came across an each function that produces a question that I can't seem to find an answer in the book for, or online.
The code I use for this question is found from jQuery site and I included it below as a reference:
<script>
    $(document.body).click(function () {
      $("div").each(function (i) {            //Where does the 'i' come from?
        if (this.style.color != "blue") {
          this.style.color = "blue";
        } else {
          this.style.color = "";
        }
      });
    });
</script>

I would like to know the origin and purpose of the 'i' parameter as I fail to see where it comes from (client code) and what it is used for? As a Java guy I will grasp the concept a lot easier as I familiar with method or 'function' params in the context of Java.
Here I don't see the client code (I presume it's in the library) and I don't see how it (the i) is relevant in the function as it's not referenced.
Can someone from the community give a clear explanation for this or refer me to a guide on this?
I understand the purpose of the each function and the 'this' reference so you don't need to explain these unless you feel it relevant to future viewers of this question.

A: When you call $().each(), you pass it a function reference. The way the .each() function works is that for each element in the jQuery object, it calls the function you gave it with the current element as the context (i.e. inside the function call, the this variable is the current element).
Now, when jQuery calls the function you gave it, it can pass in optional arguments, just as if you were calling a function in code. With .each(), whenever it calls the function you gave it, it passes in two arguments : an index and the current element.
It's as if jQuery is calling it like:
$('div').each(foo);

// results in something like
for(var i=0; i < $('div').length; i++) {

    // calling the foo function
    foo(i, $('div')[i]);

    // this is simplified, of course.
    // this doesn't take into account the function context, or "this" variable.
}

You may find that the official documentation explains it better too.

A: In that case, there was no need to declare the i. The signature of the each method is stated in the jQuery docs:

.each( function(index, Element) )

As you can see, it takes one argument, and that argument is a function that takes 2 arguments, index and Element.
In your code, i is an identifier for index, which is passed to the callback function by jQuery each time it is called (once for each iteration). It also passes a second argument, but you have not declared an identifier for it so it will only be accessible through the arguments object.
You can see exactly what is passed to the callback by logging that arguments object:
$("div").each(function () { //No arguments listed in callback signature...
    console.log(arguments); //But arguments are still passed
});

Here's a working example of the above.
Here's the relevant code from jQuery itself (comments added):
//...
each: function( object, callback, args ) {
    //...

    //Iterate over the matched set of elements
    for ( ; i < length; ) {
        /* Call the callback in the context of the element, passing in the
           index and the element */
        if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
            break;
        }
    }
}

A: As it says in the API the 'i' is the index.
That could be usefull if you want to make a difference between the even and uneven elements
Like:
$(document.body).click(function () {
  $("div").each(function (i) {            //Where does the 'i' come from?
    if (i % 2 == 0) {
      this.style.color = "blue";
    } else {
      this.style.color = "";
    }
  });
});

A: The "origin" of these parameters is "lets be different from prototype.js."
It makes much more sense to pass the params in the opposite order as the index is seldom needed.
Consider this example:
which call & function makes the most sense?
$('.my-selector').each( modifyNodeA );
$('.my-selector').each( function(){
    // this wrapper anonymous function is cruft
    modifyNodeB(this);
});
$('.my-selector').each( modifyNodeB ); // this one won't work
$('.my-selector').each( modifyNodeC );
$('.my-selector').each( function(){
    // just using 'this' makes sense here.. it's evident that this is a jQuery closure
});

function modifyNodeA(i, node) {
    // this one works...  but gotta have i in the func signature.
    //   it won't be used and doesn't make contextual sense
    //  can also use 'this', but where the heck did it come from..  it's not evident
}

function modifyNodeB(node, i) {
    // 'i' could/should be an optional 2nd param
    //   this function could function on it's own
}

function modifyNodeC() {
    // gotta use the magic 'this' scope var..  where did it come from?
    // contextually, it would be nice to have the var passed... it is... as the 2nd param!
}

Simply summarized here:
Why I STILL prefer Prototype over jQuery - Section 8 - Other Nit-picks

$.each and $().each both pass first the index, and then the value to
  the callback. This means that if I have no need for the index, I can't
  just leave it off the function declaration like I can in Prototype.


text:
Q: Is there a way to know when a tkinter ComboBox option is clicked? In tkinter , Buttons have a parameter called command which causes some function to run whenever the button is clicked.
Is the same possible to do with the options of a tkinter Combobox ?
For example :
I have three options in the tkinter Combobox : #1 , #2 , #3
Now , As soon as #1 is or clicked , I want to print something like Options 1 Selected.
Is it possible to do ?
P.S , As @Atlas435 pointed out about getting the selected value from the tk.Combobox() , I really dont want the value of the Combobox() , what I am asking is that whether there is way to make Combobox options work like Buttons which when clicked , causes some function to execute.

A: Take a look at this example, which does what you are asking for:
from tkinter import *
from tkinter import ttk

root = Tk()

def select(event): #the function to get triggered each time you choose something
    if c.get() == lst[0]: #if it is the first item
        print('Option 1 is selected')
    elif c.get() == lst[1]: #if it is the second item
        print('Option 2 is selected')
    else: #or if it is the third item
        print('Option 3 is selected')

lst = ['#1','#2','#3'] #creating option list

c = ttk.Combobox(root,values=lst,state='readonly') #creating a combobox
c.current(0) #setting first element as the item to be showed
c.pack(padx=10,pady=10) #putting on screen

c.bind('<<ComboboxSelected>>',select) #the event that your looking for

root.mainloop()

Ive commented it to understand better, if any doubts or errors, do let me know


text:
Q: jQuery tooltip set dynamic content in loop is returning last value The variable intcontent is always the same value for all tooltip elements. How do I pass the correct value to the tooltip content function?
for(var x=0; x<arr_dj[i].style.length; x++){
  if(x != 0)$divstyle.append($(' / '));
    var $span = $('');
    $span.append(getconststr(arr_dj[i].style[x]));
    var intcontent = arr_dj[i].style[x];
    $span.tooltip({
      items: "div",
      tooltipClass: "style_tooltips",
      position: {
        my: "left-25 top",
        at: "right bottom "
      },
      content: function(e) {
        var html = getmusicdef(intcontent);
        return html;
      }
    });
    $divstyle.append($span);
  }
}

A: The variable intcontent is available as a closure in the content function but by the time that function is executed it is set to the last value. Use IIFE to set it to the correct value for each iteration:
for(var x=0; x<arr_dj[i].style.length; x++){
  if(x != 0){//not sure what you wanted to do here, posted code has too many }
    $divstyle.append($(' / '));
    var $span = $('');
    $span.append(getconststr(arr_dj[i].style[x]));
    var intcontent = arr_dj[i].style[x];
    $span.tooltip({
      items: "div",
      tooltipClass: "style_tooltips",
      position: {
        my: "left-25 top",
        at: "right bottom "
      },
      content: (function(intcontent){
        return function(e) {
          var html = getmusicdef(intcontent);
          return html;
        }
      }(intcontent))//IIFE setting intcontent correctly
    });
    $divstyle.append($span);
  }
}


text:
Q: PHP SoapServer and Complex Types I am working on building a web service in PHP using the SoapServer class, but I'm running into an issue with casting of complex types.
The WSDL is completely valid, and the PHP SoapClient handles it flawlessly, but there seems to be an issue with the complex types that are returned not being cast properly. This came to light when consuming the service in .Net, as I was getting exceptions that indicated the type was not present in the given namespace.
I mangled my function numerous times, changing the namespace on the element, but .Net continues to give me errors, regardless of what namespace I use.
Consider the following abbreviation of the script:
function getCommands() {
    $output = array();
    // ...
    foreach($result as $row) {
        $output[] = new SoapVar($row, SOAP_ENC_OBJECT, 'ns1:command');
    }

    return $output;
}

The abbreviated response:
<?xml version="1.0" encoding="utf-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ns1="urn:MyWebService"
    xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Body>
    <ns1:getCommandsResponse>
      <return SOAP-ENC:arrayType="ns1:command[12]" xsi:type="ns1:ArrayOfCommand">
        <item xsi:type="ns1:command">
            <!-- ... -->
        </item>
      <!-- ... -->
      </return>
    </ns1:getCommandsResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

What I've noticed is that xmlns:ns1 is defined by way of the WSDL, and it does match the namespace in the WSDL. However, the .Net SOAP client doesn't seem to understand that the command element is defined there. It does, however, understand that that's where ArrayOfCommand is defined.
So my question is multipart:

*

*Is this a known bug with the SoapServer?

*If not, am I missing something grievous in my WSDL?

*Am I not encoding my objects properly?

*Is this an issue with .Net? If so, what's the work-around?

A: I was able to resolve this issue by working over the <types/> section of my WSDL again, using the Google WSDL for reference. Then, I had to work some magic in my PHP function, casting the elements of the $command appropriate to their respective types in the WSDL, and encoding the entire command as a ns2:command. When aligned with the WSDL, this all fell together nicely and .Net is having zero difficulty with it.
I'm surprised nobody in the development community was willing to answer this, but I hope someone will be able to glean from it at least some direction on how to fix their own instance of this problem.


text:
Q: Found hex characters (\xHH) in access_log on Apache2 In my RHEL 3 after installing Apache2 with CGI module is logging special hex chars in his logs/acces_log. Why Appear that?
[18/May/2015:16:35:11 +0200] "\xac\xc4>\x90X\x7f\xdb\x18\x85\xf7\xcb\xd8FN\x1b\x1e\\\x89i\x13\xdf A\xae\x80\xa3\xee\xbaA\xa3\x1f\xc9orQi\xbd?\x1eD\x94\x87\xe7\x94HA\x83\xa0\x8b\xad\x14\x13tl|2M<\xdf\xf8\xe9\xb7\x04\xe5\xb0\x85\xd1\xf8\x07\xd9~\xca#-\t\x8e\xd3\x13!I\x82;\xe0\x97zX\x01\xc4\x03\xda\xcb10\x8b\x9b\xd0\xe1\xb2\xd6\xd7\x02\xfd\x01\xc5D\xc6\x06" 400 226
[18/May/2015:16:35:11 +0200] "POST /cgi-bin/upload.pl HTTP/1.1" 200 -
[18/May/2015:16:35:15 +0200] "GET /cgi-bin/md5.pl HTTP/1.1" 500 528
[18/May/2015:16:38:21 +0200] "\xac\xc4>\x90X\x7f\xdb\x18\x85\xf7\xcb\xd8FN\x1b\x1e\\\x89i\x13\xdf A\xae\x80\xa3\xee\xbaA\xa3\x1f\xc9orQi\xbd?\x1eD\x94\x87\xe7\x94HA\x83\xa0\x8b\xad\x14\x13tl|2M<\xdf\xf8\xe9\xb7\x04\xe5\xb0\x85\xd1\xf8\x07\xd9~\xca#-\t\x8e\xd3\x13!I\x82;\xe0\x97zX\x01\xc4\x03\xda\xcb10\x8b\x9b\xd0\xe1\xb2\xd6\xd7\x02\xfd\x01\xc5D\xc6\x06" 400 226
[18/May/2015:16:38:21 +0200] "POST /cgi-bin/upload.pl HTTP/1.1" 200 24

A: The problem is with ilegal client petition. Server is OK. It sends an incorrect Content-Lenght header, and this causes overbuffer on log. For example, in this header petition, Content-Length is 1000, but correct Content-Length is 500.
Date: Thu, 28 May 2015 06:25:43 GMT
Server: Apache/2.0.52 (Red Hat)
Last-Modified: Mon, 26 Jan 2015 16:18:38 GMT
ETag: "115446-e4e1c0-7da57380"
Accept-Ranges: bytes
Content-Length: 1000
Connection: close
Content-Type: text/plain; charset=UTF-8

This provoke that Apache2 server read buffer bytes and his acces_log appear hexadecimal characters \xHH.


text:
Q: JQuery - Using $(document).ready() after window.location I'm trying execute js function after redirection to the page e.g "example.com" when DOM is ready to work with him but it doesn't work.
$(document).ready() is running before "example.com" is loaded. What is wrong? Here is my code:
window.location = "http://example.com";
$(document).ready(function(){
    //DO SOMETHING WHEN PAGE 'example.com' IS LOADED
});

I would be grateful for your help!

A: You simply can't do what you're trying to do.  When the page is changed to "http://example.com", this sets in motion a series of events which will eventually result in your entire Javascript context being stopped.  You can't run Javascript from this page in the new page.
When you assign:
window.location = "http://example.com";

This begins a process which will stop the execution of the Javascript in the current page.  The current page is unloaded and all memory associated with it is freed.  Then, a new page is loaded, a new Javascript context is created and the Javascript in that new page is then loaded and run.

The usual way to communicate with a new page is to put the Javascript that wants to run in that new page and then send some parameters to that new page that its Javascript can detect and react accordingly.
For example, you might do this:
window.location = "http://example.com?doSomething=whatever";

And, then when the new page is loaded, the Javascript in THAT page can check the query string to see if any special arguments were passed to it.  If they were, then that Javascript can parse them and decide what behavior to carry out based on those query string parameters.

Another possibility is to not use window.location.  You can, instead, fetch new HTML via Ajax and then use Javascript in the current page to insert that new content into the current page (or replace existing content with new content).   With jQuery, you can use jQuery's .load() to load content from a URL directly into an element in the current page like this:
$("#myDiv").load(someURL);

Since this is Ajax, it has all the normal cross-origin restrictions that any Ajax call might have so you can't freely load pages from other websites (unless they permit cross origin access).

A: A JavaScript program embedded in a page only runs while that page is open.
If you leave the page, by loading a new one (which is what you are doing), then it stops running.
You can't inject JavaScript on to the next page using just features of the browser. You have to have some mechanism to pass it through the server.

A: I wanted to have some JavaScript inserting values from www.mypage.com to www.example.com and then submit button is clicked.
Thank you for your clarification but I decide to use Selenium with Python and PHP. Or maybe is there any way to do this with JavaScript?
run_search.py
import sys
from selenium import webdriver

def insertContent(myElement):
    driver = webdriver.Firefox()
    driver.get("http://www.google.com")
    elem = driver.find_element_by_id("lst-ib")
    elem.send_keys(myElement)
    BUTTON_XPATH = '//button[@type="submit" @name="btnI"]'
    button = driver.find_element_by_xpath(BUTTON_XPATH)
    button.click()

if __name__ == '__main__':
    insertContent(sys.argv[1])

mypage.php
<?php
    $my_value = "Python";
    $exec_py = shell_exec('python run_search.py '.$my_value);
?>


text:
Q: Flutter - Riverpod 2.0 - .select() function is not preventing unnecessary rebuilds at all, .select() is not working i'm using state notifier and state notifier provider with select to only apply rebuild to specific field in the object. but the whole widget rebuild whether i selected or not.
i have the following example code to simplify my problem:
final counterProvider =
    StateNotifierProvider<CounterState, Counter>((ref) => CounterState());

class Counter {
  int count1;
  int count2;

  Counter(this.count1, this.count2);
}

class CounterState extends StateNotifier<Counter> {
  CounterState() : super(Counter(0, 0));

  void inc1() => state = Counter(state.count1 + 1, state.count2);

  void inc2() => state = Counter(state.count1, state.count2 + 1);
}

and the following consumer widget:
class TestWidget extends ConsumerWidget {

  const TestWidget({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) => Scaffold(
      body: Column(
        children: [
      Text(ref.watch(counterProvider.select((value) {
        print("rebuilt counter 1 Text with val: ${value.count1}");
        return value.count1.toString();
      }))),
      Text(ref.watch(counterProvider.select((value) {
        print("rebuilt Counter 2 Text with val: ${value.count2}");
        return value.count2.toString();
      }))),
      ElevatedButton(
          onPressed: () => ref.read(counterProvider.notifier).inc1(),
          child: const Text("Inc 1")),
      ElevatedButton(
          onPressed: () => ref.read(counterProvider.notifier).inc2(),
          child: const Text("Inc 2"))
        ],
      ));
}

i'm excpecting when pressing the inc1() button to not rebuild the second text. only the first.
but the output in the console when i press inc1 for 3 times is the following:
I/flutter (19394): rebuilt counter 1 Text with val: 0
I/flutter (19394): rebuilt Counter 2 Text with val: 0
D/EGL_emulation(19394): app_time_stats: avg=417.64ms min=8.70ms max=4924.00ms count=13
I/flutter (19394): rebuilt counter 1 Text with val: 1
I/flutter (19394): rebuilt Counter 2 Text with val: 0
I/flutter (19394): rebuilt counter 1 Text with val: 1
I/flutter (19394): rebuilt Counter 2 Text with val: 0
D/EGL_emulation(19394): app_time_stats: avg=78.42ms min=2.63ms max=1171.43ms count=18
I/flutter (19394): rebuilt counter 1 Text with val: 2
I/flutter (19394): rebuilt Counter 2 Text with val: 0
I/flutter (19394): rebuilt counter 1 Text with val: 2
I/flutter (19394): rebuilt Counter 2 Text with val: 0
D/EGL_emulation(19394): app_time_stats: avg=34.74ms min=2.47ms max=721.10ms count=25
I/flutter (19394): rebuilt counter 1 Text with val: 3
I/flutter (19394): rebuilt Counter 2 Text with val: 0
I/flutter (19394): rebuilt counter 1 Text with val: 3
I/flutter (19394): rebuilt Counter 2 Text with val: 0

and i'm expecting in the console:
I/flutter (19394): rebuilt counter 1 Text with val: 0
I/flutter (19394): rebuilt Counter 2 Text with val: 0
D/EGL_emulation(19394): app_time_stats: avg=417.64ms min=8.70ms max=4924.00ms count=13
I/flutter (19394): rebuilt counter 1 Text with val: 1
D/EGL_emulation(19394): app_time_stats: avg=78.42ms min=2.63ms max=1171.43ms count=18
I/flutter (19394): rebuilt counter 1 Text with val: 2
D/EGL_emulation(19394): app_time_stats: avg=34.74ms min=2.47ms max=721.10ms count=25
I/flutter (19394): rebuilt counter 1 Text with val: 3

so what am i not understanding correctly about select() function?
and why the first text is rebuilt twice although the change occur once?

A: The select function is unrelated to the problem described.
select is for skipping some updates which you don't care about. In your care about the update, but want to rebuild fewer widgets.
To do that the solution is to either:

*

*Extract your individual texts as a separate ConnsumerWidget

*wrap your texts into a Consumer
Like:
Column(
  children: [
    Consumer(builder: (context, ref, _) {
      return Text(ref.watch(fooProvider));
    }),
    Consumer(builder: (context, ref, _) {
      return Text(ref.watch(barProvider));
    }),
  ],
)

This way, an update on fooProvider will not rebuild the text which listens to barProvider

A: try like this:
class TestWidget extends ConsumerWidget {

  const TestWidget({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) => Scaffold(
      body: Column(
        children: [
     Consumer(builder: (context, ref, _) { // added this
      Text(ref.watch(counterProvider.select((value) {
        print("rebuilt counter 1 Text with val: ${value.count1}");
        return value.count1.toString();
      }))),
     }),
     Consumer(builder: (context, ref, _) { // added this
      Text(ref.watch(counterProvider.select((value) {
        print("rebuilt Counter 2 Text with val: ${value.count2}");
        return value.count2.toString();
      }))),
     }),
      ElevatedButton(
          onPressed: () => ref.read(counterProvider.notifier).inc1(),
          child: const Text("Inc 1")),
      ElevatedButton(
          onPressed: () => ref.read(counterProvider.notifier).inc2(),
          child: const Text("Inc 2"))
        ],
      ));
}

This is because you are using ref, which is in the scope of TestWidget. You must use a separate widget or use the Consumer wrapper. This was described by @Rémi Rousselet

A: Thank you @Ruble, @Rémi Rousselet
i did this solution before and it worked as i said.. but a problem occurs when i have a situation like this:
class Counter {
  int count1;
  int count2;
  Color count1Color;
  Counter(this.count1, this.count2,this.count1Color);
}

and i can change the color the same way i did with inc1() and inc2(), through a procedure..
Consumer(builder: (context, ref, _) =>
                    Text(ref.watch(counterProvider.select((value) =>
                        value.count1.toString()))
                      , style: TextStyle(color: ref.watch(counterProvider.select((value) => value
                          .count1Color))),)),
                // a color for count1 editable through a button for example.
                // if i change the state of the color the the text
                // will be rebuild too! so back to the same problem!

                Consumer(builder: (context, ref, _) =>
                    Text(ref.watch(counterProvider.select((value) =>
                        value.count2.toString())))),

so where is the problem? there is still some situations for example where i want to watch a decoration of an object through a composite state notifier like this example above. the solution of nested consumer widgets doesn't always work, because in the situation above the style property doesn't accept a value of type consumer because it is not a widget.
what can i do in situations like this?
i need change the text of the counter and it's color using state notifier provider, without any redundant rebuilts.


text:
Q: authenticate_or_request_with_http_token returning html instead of json I've created a rails-api application and proceeded to secure it using token authentication.
I've set a before_filter that is calling a method which uses authenticate_or_request_with_http_token. Everything is working fine but, when the authentication is incorrect i'm getting an html response.
How can I define what format the response should be?
before_filter :restrict_access

private

def restrict_access
  authenticate_or_request_with_http_token do |token, options|
    check_token token
  end
end

def check_token(token)
  Session.exists?(access_token: token)
end

A: By including ActionController::HttpAuthentication::Token::ControllerMethods you include several methods, amongst others request_http_token_authentication which is simply a wrapper around Token.authentication_request. That #authentication_request-method is the culprit and sends the plain text (not HTML as your question suggests) as follows:
def authentication_request(controller, realm)
  controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
  controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
end

The trick is to override request_http_token_authentication in your ApplicationController to not call Token.authentication_request but to set the correct status and headers and then render JSON instead. Add this to your ApplicationController:
protected
def request_http_token_authentication(realm = "Application")
  self.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
  render :json => {:error => "HTTP Token: Access denied."}, :status => :unauthorized
end

A: From Rails 5, the authenticate_or_request_with_http_token method allows a second parameter with a custom message, so you could just do:
  authenticate_or_request_with_http_token('realm', json_error) do |token, options|
    check_token token
  end


text:
Q: changed object after storage or object-state used Example:
class UserStorage {
    public function addUser(User $user) { //saves to db }
}

class User {
    public function setName($name);
}

What if I add a user to the user storage and later change that user object? In this case you might argue that user objects only should be stored on __destruct. But sometimes this isn't an option (eg imagine the user is displayed and updated afterwards).

A: Implicit writes to the database are probably a bad idea.  That should be an explicit, controlled operation.
Your pattern is a little weird to me, but I think this how you'd want to do it
class UserStorage
{
    const ACTION_INSERT = 'INSERT';
    const ACTION_UPDATE = 'UDPATE';

    public function addUser(User $user)
    {
        $this->saveUser($user, self::ACTION_INSERT);
    }

    public function updateUser(User $user)
    {
        $this->saveUser($user, self::ACTION_UPDATE);
    }

    protected function saveUser(User $user, $action)
    {
        switch ($action) {
            case self::ACTION_INSERT:
                //  INSERT query
                break;
            case self::ACTION_UPDATE:
                //  UPDATE query
                break;
            default:
                throw new Exception('Unsupported action');
        }
    }
}

class User
{
    public function setName($name)
    {
        // whatever
    }
}

$userStorage = new UserStorage();
$user = new User();

$userStorage->addUser($user);

$user->setName('Peter');

try {
    $userStorage->updateUser($user);
} catch (Exception $e) {
    echo "There was an error saving this user: " . $e->getMessage();
}

But Personally I'm not crazy about this class design.  There are some well-established patterns for this that are less confusing, such as ActiveRecord.

A: I agree with Peter, the above model seems a little quirky to me and I would recommend against implicit save to the datastore.
Additionally, a pattern to use is something like:
class UserStorage {
   $_user;

   function addUser(User user, commit = true) {
      if (commit) {
        // save to db
      } else {
        // populate your internal instance
        $_user = user;
      }
   }
}

So if you have multiple updates of a User object in the execution of your PHP application, you can use
addUser(user,false)

all the way until the very last call to
addUser(user)

This will alleviate the need for multiple inserts/updates to the DB.
However, your problem of where in the application to decide to finally save to db remains, and is more about logical flow than object representation. It may be helpful to have a end() function in the script that persists all your objects to the db.


text:
Q: How to remove paragraph spacing in output using the Microsoft.Office.Interop.Word Library In my C# Desktop app i am using the Microsoft.Office.Interop.Word library to write to a word file. But whenever its done exporting there's huge spaces between paragraphs. Using the paragraph1.Range.ParagraphFormat.SpaceAfter = 0; parameter doesn't affect the result as well.
My desired result is the "No Spacing" preset in Word but after some research i found out it is not an option this library.
Is there any way to remove or set the spacing between paragraphs.
This is my code:
 Microsoft.Office.Interop.Word.Application word = new Application();
 word.Visible = false;
 var doc = word.Documents.Add();
 var paragraph1 = doc.Content.Paragraphs.Add();

 paragraph1.Range.Font.Name = "Calibri";
 paragraph1.Range.Font.Size = 11;

 paragraph1.Range.ParagraphFormat.SpaceBefore = 0;
 paragraph1.Range.ParagraphFormat.SpaceAfter = 0;

 paragraph1.Range.Text = story;
 paragraph1.Range.InsertParagraphAfter();

 doc.SaveAs2(@"F:\Documents\Visual Studio Projects\LITPC\LITPC\bin\Debug\"+title+".docx");

 word.Quit();

A: First of all the SpaceBefore and SpaceAfter properties take floats so you need to suffix your values with an f.
Try: paragraph1.SpaceBefore = 0.0f;, that worked for me.
Also, be careful to reset the spacing when you insert a new paragraph because subsequent paragraphs will inherit the new spacing.
Or avoid Interop Word altogether if you can, it's a deep, dark, rabbit hole I've been down for several days.

A: I solved this problem by changing the Word.Paragraph.SpaceAfter parameter on previous paragraph. For example.
// First Paragraph
Word.Paragraph mainTitle = document.Paragraphs.Add();
mainTitle.Range.Text = "para1";
mainTitle.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
mainTitle.Range.InsertParagraphAfter();
mainTitle.SpaceAfter = 0.0f;

// Second Paragraph
Word.Paragraph semiTitle = document.Paragraphs.Add();
semiTitle.Range.Text = "para2";
semiTitle.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
semiTitle.Range.InsertParagraphAfter();
semiTitle.SpaceAfter = 10.0f;

So, the SpaceAfter of semiTitle will be 0. Similarly, the SpaceAfter of the next paragraph after semiTitle will be 10.


text:
Q: Move Object in its own X - axis to and from, on mouse drag
I want to:

*

*move a particular object in its own X- axis to and from, by using mouse.

*Clamp the movement between that box gap

Code i tried but not working for me:
    void Update()
    {
    point = Camera.main.ScreenToWorldPoint(
    new Vector3(Input.mousePosition.x,
            (transform.position.y-Camera.main.transform.position.y),
            (transform.position.z-Camera.main.transform.position.z)));

    point.y = transform.position.y;
    point.z = transform.position.z;
    transform.position = point;
  }

A: To clamp a value you can use the Mathf.Clamp() method.
The full solution could look something like this:
Add a script to your lever object:
using UnityEngine;
using UnityEngine.EventSystems;

public class MoveOnMouseDrag : MonoBehaviour {

    public float halfDistance;

    void Start()
    {
        EventTrigger trigger = GetComponent<EventTrigger>();
        EventTrigger.Entry entry = new EventTrigger.Entry();
        entry.eventID = EventTriggerType.Drag;
        entry.callback.AddListener((data) => { OnDragDelegate((PointerEventData)data); });
        trigger.triggers.Add(entry);
    }

    public void OnDragDelegate(PointerEventData data)
    {
        float distanceFromCamera = Vector3.Distance(Camera.main.transform.position, transform.position);
        var newPos = Camera.main.ScreenToWorldPoint(new Vector3(data.position.x, data.position.y, distanceFromCamera));

        transform.position = new Vector3(Mathf.Clamp(newPos.x, -halfDistance, halfDistance),
                                         transform.position.y,
                                         transform.position.z);
    }
}

In order for the script to work you have to add EventTrigger component to the same object, EventSystem to the scene and PhysicsRaycaster component to the camera.


text:
Q: How to prove that $W=Y$, where $Y=\bigcap\{U:U \text{ is a subspace of }V, \text{dim } U=n-1, W\subset U\}$. Let $V$ be a $n$-dimensional vector space. Let there be a $r$-dimensional subspace $W\subset V$, whereby $r<n$. How to prove that $W=Y$, where $Y=\bigcap\{U:U \text{ is a subspace of }V, \text{dim } U=n-1, W\subset U\}$.

A: The inclusion $W\subseteq Y$ is immediate.
Let $z\in V$ such that $z\not\in W$. Fix a basis $(e_1,\ldots,e_r)$ of $W$. Hence the family $(e_1,\ldots,e_r,z)$ is free, so we can compete it to a basis of $V$, say $(e_1,\ldots,e_r,z,e_{r+2},\ldots,e_n)$.
No let $U$ be the subspace of $V$ generated by $e_1,\ldots,e_r,e_{r+1},\ldots,e_n$, it a subspace of dimension $n-1$ and $z\notin U$, hence $z\notin Y$.
Conclusion $z\notin W\Rightarrow z\notin Y$: that is $Y\subseteq W$.


text:
Q: How to check other user's CRUD permission for an object (APEX) I want to find out, if another user has READ permission on a specific object (I don't care about record access/sharing). Is there a way to accomplish this via APEX?
I do NOT want to find out if the running user has access to the object, since that is rather straight forward.
My use case is: I want to assign ownership of custom object records to users based on their properties. Unfortunately a user can only own a record if he has at least read access to the object. If I try to assign the owner regardless, I'll get an exception.
Also this must be applicable in a non-test context, so. runAs() won't do.
My question is: How can I check read (or CRUD in general) access to objects for other users?
Any help is appreciated.

A: You can try like below
String desireUserId = UserInfo.getUserId(); // or pass any other user id.
User u = [select profileId from user where id =: desireUserId];
String profileId = u.profileId;

List<ObjectPermissions> 0bjPermissionList = [SELECT Id, SObjectType,
PermissionsRead FROM ObjectPermissions WHERE parentid in (select id from
permissionset where PermissionSet.Profile.Id=: profileId)];

Before assigning, chedk if that user has PermissoinsRead field is true.


text:
Q: How to Read/ Parse Data of Signed_Request from Registration Script in Php 5.1.6 I'm trying to implement the Facebook registration script.
The form is getting submitted fine and the server is receiving the signed request. However, it is not able to read/parse the signed request.
I used the script recommended on the registration page https://developers.facebook.com/docs/plugins/registration/ (code below) and all I see for output is:
signed_request contents:
I have verified that the signed_Request is being received. If I pass it to: http://developers.facebook.com/tools/echo?signed_request=  I see data.
However on my server with the script below nothing.
The server is http NOT https and using php 5.1.6 (which doesn't have some of the JSON support) Do I need PHP SDK installed? Or the jsonwrapper? I've tried the jsonwrapper but not PHP SDK.
Any help on why the signed_request can not be read would be appreciated.
Code below from facebook
    <?php
    include ('jsonwrapper/jsonwrapper.php');

    define('FACEBOOK_APP_ID', 'XXX');
    define('FACEBOOK_SECRET', 'XXX');

    function parse_signed_request($signed_request, $secret) {
    list($encoded_sig, $payload) = explode('.', $signed_request, 2);

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
}

if ($_REQUEST) {
  echo '
signed_request contents:
';

  $response = parse_signed_request($_REQUEST['signed_request'],
                                   FACEBOOK_SECRET);
  echo '
';
  print_r($response);
  echo '
';

} else {
  echo '$_REQUEST is empty';
}
?>

output is
"signed_request contents:"
If I add:
 print_r($_REQUEST); to the script I do see the  request but can't parse it

A: I had something similar with the signed request coming back blank. On your application make sure you first download and inlude the php sdk from http://developers.facebook.com/docs/reference/php/. Next add
 require_once("facebook.php");

to your script at the top, or to where you uploaded it to. Now in your application settings for the application, in Facebook, make sure your url to the application has the www in it or not. For example: In the application you have it pointing to example.com/index.php?tab=test but when you put it in the browser it always comes up www,example.com/index.php?tab=test. Not including the www can mess it up.
EDIT - WORKED FOR ME
    <?php
    #error_reporting(E_ALL);

        include ('{{PATH TO facebook.php}}');

        $appapikey = 'xxxx';
        $appsecret = 'xxxx';
        $facebook = new Facebook($appapikey, $appsecret);

    function parsePageSignedRequest() {
        if (isset($_REQUEST['signed_request'])) {
          $encoded_sig = null;
          $payload = null;
          list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
          $sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
          $data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
          return $data;
        }
        return false;
      }
      function parse_signed_request($signed_request, $secret) {
          list($encoded_sig, $payload) = explode('.', $signed_request, 2);

          // decode the data
          $sig = base64_url_decode($encoded_sig);
          $data = json_decode(base64_url_decode($payload), true);

          if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
            error_log('Unknown algorithm. Expected HMAC-SHA256');
            return null;
          }

          // check sig
          $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
          if ($sig !== $expected_sig) {
            error_log('Bad Signed JSON signature!');
            return null;
          }

          return $data;
        }
        function base64_url_decode($input) {
          return base64_decode(strtr($input, '-_', '+/'));
        }

    if (isset($_REQUEST['signed_request'])) {
      echo '
signed_request contents:
';

      $response = parse_signed_request($_REQUEST['signed_request'],
                                       $appsecret);
      echo '
';
      print_r($response);
      echo '
';

    } else {
      echo '$_REQUEST is empty';
    }
    ?>

      function getDefinedVars($varList, $excludeList)
      {
          $temp1 = array_values(array_diff(array_keys($varList), $excludeList));
          $temp2 = array();
          while (list($key, $value) = each($temp1)) {
              global $$value;
              $temp2[$value] = $$value;
          }
          return $temp2;
      }

To view All SYSTEM Variables (except globals/files/cookies/post/get) to make sure Signed Request is passed you can use this snippet of code
      /**
       * @desc   holds the variable that are to be excluded from the list.
       *         Add or drop new elements as per your preference.
       * @var    array
       */
      $excludeList = array('GLOBALS', '_FILES', '_COOKIE', '_POST', '_GET', 'excludeList');

      //some dummy variables; add your own or include a file.
      $firstName = 'kailash';
      $lastName = 'Badu';
      $test = array('Pratistha', 'sanu', 'fuchhi');

      //get all variables defined in current scope
      $varList = get_defined_vars();

      //Time to call the function
      print "
";
      print_r(getDefinedVars($varList, $excludeList));
      print "
";

A: You don't need the PHP SDK for this. It may make it easier to do this and various other things, but it is not necessary if you want to do the decode yourself.
Are you sure you actually have a json_decode function? I don't think it's usually part of jsonwrapper.php, so I suspect your script is crashing on that function call.  You can use the following function as a substitute, just change the call to usr_json_decode and include the following at the bottom of your script:
function usr_json_decode($json, $assoc=FALSE, $limit=512, $n=0, $state=0, $waitfor=0)
{
  $val=NULL;
  static $lang_eq = array("true" => TRUE, "false" => FALSE, "null" => NULL);
  static $str_eq = array("n"=>"\012", "r"=>"\015", "\\"=>"\\", '"'=>'"', "f"=>"\f", "b"=>"\b", "t"=>"\t", "/"=>"/");
  for (; $n<strlen($json); /*n*/)
    {
    $c=$json[$n];
    if ($state==='"')
      {
      if ($c=='\\')
        {
        $c=$json[++$n];
        if (isset($str_eq[$c]))
          $val.=$str_eq[$c];
        else if ($c=='u')
          {
          $hex=hexdec(substr($json, $n+1, 4));
          $n+=4;
          if ($hex<0x80) $val .= chr($hex);
          else if ($hex<0x800) $val.=chr(0xC0+$hex>>6).chr(0x80+$hex&63);
          else if ($hex<=0xFFFF) $val.=chr(0xE0+$hex>>12).chr(0x80+($hex>>6)&63).chr(0x80+$hex&63);
          }
        else
          $val.="\\".$c;
        }
      else if ($c=='"') $state=0;
      else $val.=$c;
      }
    else if ($waitfor && (strpos($waitfor, $c)!==false))
      return array($val, $n);
    else if ($state===']')
      {
      list($v, $n)=usr_json_decode($json, $assoc, $limit, $n, 0, ",]");
      $val[]=$v;
      if ($json[$n]=="]") return array($val, $n);
      }
    else
      {
      if (preg_match("/\s/", $c)) { }
      else if ($c=='"') $state='"';
      else if ($c=="{")
        {
        list($val, $n)=usr_json_decode($json, $assoc, $limit-1, $n+1, '}', "}");
        if ($val && $n) $val=$assoc?(array)$val:(object)$val;
        }
      else if ($c=="[")
        list($val, $n)=usr_json_decode($json, $assoc, $limit-1, $n+1, ']', "]");
      elseif (($c=="/") && ($json[$n+1]=="*"))
        ($n=strpos($json, "*/", $n+1)) or ($n=strlen($json));
      elseif (preg_match("#^(-?\d+(?:\.\d+)?)(?:[eE]([-+]?\d+))?#", substr($json, $n), $uu))
        {
        $val = $uu[1];
        $n+=strlen($uu[0])-1;
        if (strpos($val, ".")) $val=(float)$val;
        else if ($val[0]=="0") $val=octdec($val);
        else $val=(int)$val;
        if (isset($uu[2])) $val*=pow(10, (int)$uu[2]);
        }
      else if (preg_match("#^(true|false|null)\b#", substr($json, $n), $uu))
        {
        $val=$lang_eq[$uu[1]];
        $n+=strlen($uu[1])-1;
        }
      else
        {
        return $waitfor ? array(NULL, 1<<30) : NULL;
        }
      }
    if ($n===NULL) return NULL;
    $n++;
    }
  return ($val);
}

BTW though, this should be very easy to track down using your error log, turning on extra debugging and adding some echo or var_dump statements as necessary.


text:
Q: Amazon & HTML AgiltiyPack It seems almost all of my request are being hit with an 500 SERVICE ERROR.
Yet I am able to access the site through a web browser just fine.I am sending UserAgent through HAP as well.
Is there anyone with experince on this matter know how Amazon is detecting that the HAP request is a robot?
  Dim aHtml As New HtmlWeb
    Dim UserAgent1 As String = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"
    Dim iPadAgent As String = "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10"
    Dim AndroidAgent As String = "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13"
    Dim iPhoneAgent As String = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5"
    Dim ChromeAgent As String = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"
    aHtml.UserAgent = iPadAgent

    Dim Credentials As New System.Net.NetworkCredential("", "", "")

    Dim proxy As New System.Net.WebProxy

    Dim proxyAddress As New Uri("http://11.11.11.11")
    proxy.Address = proxyAddress

    Dim aDoc As HtmlDocument = aHtml.Load(AmazonURL, "GET")

    Dim aNode As HtmlAgilityPack.HtmlNode
    aNode = aDoc.DocumentNode.SelectSingleNode("//div[@id='olpDivId']/span[2]")

    If aNode.InnerText Is Nothing Then

    End If

    Dim UsedPrice1 As String = aNode.InnerText
    Dim i As Integer = UsedPrice1.IndexOf("$")
    Dim UsedPrice As Integer = UsedPrice1.Substring(i + 1)

    System.Threading.Thread.Sleep(Delay)

    Return UsedPrice

'
WebClient Method(Retunrs 503):
 Dim filename As String = "amzContent.html"
    Client.Headers("User-Agent") = ChromeAgent
    Client.Proxy = proxy
    Client.Credentials = Credentials
    Client.DownloadFile(AmazonURL, (Server.MapPath("amz//") & _
                  filename))
    Dim aDoc As HtmlDocument = aHtml.Load(Server.MapPath("amz//") & _
                  filename)

A: Using the WebClient Method above, and sending language,charset,and accept headers seems to work for now


text:
Q: Good off-site backup solution for database and files I was searching for a tool that would make remote backups/restores easier for both database and files, but I couldn't find any, so I started thinking about creating my own online service that deals with this problem. I would like to share this idea with you to see if it's needed, or maybe I'm wrong and there are already some good tools which I don't know about.
Here is how I see this service. It will be very easy to use, you will just have to fill information about your server on a website (hostname, login, public and privatekey or password), set the backup rate and it will take care of the rest for you. It will also alert you in case something goes wrong. You will be able to download files when you need them, or use built-in tools that will handle server restores for you. What do you think?
And I'm sorry that it isn't a normal question.

A: We are looking into better backup solutions, including online backup, for our organization.  Mozy offers an online backup service, and I use it for my laptop.  At work we are currently evaluating a solution from Barracuda.  You buy their hardware appliance and install it at your site.  Their software backs up your servers to the appliance.  Then at night the appliance transfers the data to their data center.  Their software has a great user interface.  You can throttle the bandwidth usage by time of day.  It understands SQL Server and Exchange backups.  You can even restore one deleted email.  In a lot of respects, it looks great.
Online backup is oh so seductive, but there are two big gotchas.
1)  It can take a LONG time to get your data up into the cloud -- weeks, or months, depending on the amount of data, and your pipe to the Internet.  Once the original upload is done, then good backup software will just copy up what's changed, nightly.  So theoretically it should work.  But what if so much gets changed during the day that you can't shove it up to the cloud overnight?  I would like all data to be located off-site every night, in case of a fire or something.
2)  If your place burns to the ground, how quickly can you get your data back from the cloud?  It may take a month to download it, again depending on the amount of data and your bandwidth.  Barracuda and Mozy both say they will copy your data onto some kind of media and ship it to you.  They are vague on how quickly they will get this to you.
Although our evaluation with Barracuda isn't quite over, my hunch is we will return our evaluation unit and invest in LTO4 tape.  We found a local courier service that will come by every day and pick up our latest backup tape and return the older one for less than $400 per month.
By the way, Iron Mountain also offers courier services, and a very sophisticated online backup solution.  Both services were a lot more money than we could afford.


text:
Q: ¿Cómo puedo enviar una notificación push (firebase) sin la consola, cuando cambio un dato de la base de datos? Estoy tratando de hacer un Chat de 2 personas y guardo los mensajes en la Base de datos de FireBase, quiero que cuando un usuario escriba el mensaje se le envíe una notificación al otro.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
DatabaseReference mensajeRef= ref.child("mensaje");

Ahí guardo los mensajes, tengo hecha la clase 'FirebaseMessagingService' pero solo puedo enviar notificaciones desde la consola de Firebase.

A: Hasta donde tengo entendido si quieres envíar notificaciones desde un lugar ajeno a la consola de Firebase debes tener un servidor que se encargue de enviar una solicitud a Firebase para enviar el mensaje.
Indagando por la web encontré este enlace que explica cómo hacer una llamada a Firebase desde un dispositivo Android con Node.js

A: Acá encontré un tutorial muy útil https://www.coursera.org/learn/aplicaciones-android/lecture/Se1Fb/notificaciones-en-android

A:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.enviarNotificacion = functions.database.ref('LA RUTUA DE TU BASE DE DATO')
.onWrite(async (change, context) => {

 const myId = context.params.keyid;
  const id_hora = context.params.RefTelB;
  const id_nombre = context.params.keynombre;

  if (!change.after.val()) {
    return console.log('nose', myId, 'un-followed user', id_nombre);
  }
  console.log('tines un nuevo siguidor:', 'otroMas', 'for user:', id_nombre);

  const getDeviceTokensPromise = admin.database()
      .ref('RUTA DE LOS TOKEN').once('value'); ////tabla donde

  let tokensSnapshot;
  let tokens;

  const results = await Promise.all([getDeviceTokensPromise]);
  tokensSnapshot = results[0];
  if (!tokensSnapshot.hasChildren()) {
    return console.log('No hay tokens de notificación para enviar.');
  }
  console.log('existen', tokensSnapshot.numChildren(), 'este token te a enviado una notificacion.');
  const payload = {
    notification: {
      title: `Nuevo msj!  ${id_hora}`,
      body: `${id_nombre} esta solicitando tu ayuda.`,
     // icon: follower.photoURL
    }
  };

  tokens = Object.keys(tokensSnapshot.val());
  const response = await admin.messaging().sendToDevice(tokens, payload);
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('error a enviar la notificacion a', tokens[index], error);

      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {

      }
    }
  });

});


text:
Q: Trying to understand Delphi mov ebx, eax in a binary file I'm trying to reverse engineer some code that was used to read a hex file and a football roster file for xbox 360.
Can you someone who is familiar with Delphi help me understand what the below code is doing exactly?  I believe it's grabbing offsets from a hex file and then creating pointers of some sort to pull the first and last name.
I've pasted the entire procedure in here, but I'm primarily focusing on the FirstName and LastName sections.
Thanks in advance for any help!
Javo
procedure TEditPlayerMain._PROC_00697780(Sender : TObject);
begin
(*
00697780   53                     push    ebx
00697781   8BD8                   mov     ebx, eax
00697783   33D2                   xor     edx, edx

* Reference to control TEditPlayerMain.FirstNameTxt : TcxTextEdit
|
00697785   8B83AC030000           mov     eax, [ebx+$03AC]
0069778B   8B08                   mov     ecx, [eax]

* Possible reference to virtual method TcxTextEdit.OFFS_64
|
0069778D   FF5164                 call    dword ptr [ecx+$64]

* Possible String Reference to: 'Multi'
|
00697790   BA40786900             mov     edx, $00697840

* Reference to control TEditPlayerMain.FirstNameTxt : TcxTextEdit
|
00697795   8B83AC030000           mov     eax, [ebx+$03AC]

* Reference to: Controls.TControl.SetText(TControl;TCaption);
|
0069779B   E874CEDDFF             call    00474614
006977A0   33D2                   xor     edx, edx

* Reference to control TEditPlayerMain.LastNameTxt : TcxTextEdit
|
006977A2   8B83A8030000           mov     eax, [ebx+$03A8]
006977A8   8B08                   mov     ecx, [eax]

* Possible reference to virtual method TcxTextEdit.OFFS_64
|
006977AA   FF5164                 call    dword ptr [ecx+$64]

* Possible String Reference to: 'Player'
|
006977AD   BA50786900             mov     edx, $00697850

* Reference to control TEditPlayerMain.LastNameTxt : TcxTextEdit
|
006977B2   8B83A8030000           mov     eax, [ebx+$03A8]

* Reference to: Controls.TControl.SetText(TControl;TCaption);
|
006977B8   E857CEDDFF             call    00474614

* Possible String Reference to: 'Multi Player'
|
006977BD   BA60786900             mov     edx, $00697860

* Reference to control TEditPlayerMain.lblPlayerName : TLabel
|
006977C2   8B8300030000           mov     eax, [ebx+$0300]

* Reference to: Controls.TControl.SetText(TControl;TCaption);
|
006977C8   E847CEDDFF             call    00474614
006977CD   33D2                   xor     edx, edx

* Reference to control TEditPlayerMain.cbJersey : TcxComboBox
|
006977CF   8B83A4030000           mov     eax, [ebx+$03A4]
006977D5   8B08                   mov     ecx, [eax]

* Possible reference to virtual method TcxComboBox.OFFS_64
|
006977D7   FF5164                 call    dword ptr [ecx+$64]
006977DA   33D2                   xor     edx, edx

* Reference to control TEditPlayerMain.numLabel : TLabel
|
006977DC   8B8388030000           mov     eax, [ebx+$0388]
006977E2   8B08                   mov     ecx, [eax]

* Reference to method TLabel.SetEnabled(Boolean)
|
006977E4   FF5164                 call    dword ptr [ecx+$64]
006977E7   33D2                   xor     edx, edx

* Reference to control TEditPlayerMain.lblJersey : TLabel
|
006977E9   8B8328030000           mov     eax, [ebx+$0328]

* Reference to: Controls.TControl.SetText(TControl;TCaption);
|
006977EF   E820CEDDFF             call    00474614
006977F4   33D2                   xor     edx, edx

* Reference to control TEditPlayerMain.lblPosition : TLabel
|
006977F6   8B8324030000           mov     eax, [ebx+$0324]

* Reference to: Controls.TControl.SetText(TControl;TCaption);
|
006977FC   E813CEDDFF             call    00474614
00697801   33D2                   xor     edx, edx

* Reference to control TEditPlayerMain.lblWeight : TLabel
|
00697803   8B8350030000           mov     eax, [ebx+$0350]

* Reference to: Controls.TControl.SetText(TControl;TCaption);
|
00697809   E806CEDDFF             call    00474614
0069780E   33D2                   xor     edx, edx

* Reference to control TEditPlayerMain.lblHeight : TLabel
|
00697810   8B834C030000           mov     eax, [ebx+$034C]

* Reference to: Controls.TControl.SetText(TControl;TCaption);
|
00697816   E8F9CDDDFF             call    00474614
0069781B   33D2                   xor     edx, edx

* Reference to control TEditPlayerMain.tsAttributes : TcxTabSheet
|
0069781D   8B8360030000           mov     eax, [ebx+$0360]

* Reference to: ComCtrls.TCustomHeaderControl.SetHotTrack(TCustomHeaderControl;Boolean);
|
00697823   E83C48F0FF             call    0059C064
00697828   33D2                   xor     edx, edx

* Reference to control TEditPlayerMain.tsAbilities : TcxTabSheet
|
0069782A   8B8368030000           mov     eax, [ebx+$0368]

* Reference to: ComCtrls.TCustomHeaderControl.SetHotTrack(TCustomHeaderControl;Boolean);
|
00697830   E82F48F0FF             call    0059C064
00697835   5B                     pop     ebx
00697836   C3                     ret

*)
end;

A: Disclaimer: I'm not particularly "familiar with Delphi". But I understand quite well what's happening, so do read on.

I believe it's (1) grabbing offsets from a hex file and then (2) creating pointers of some sort to (3) pull the first and last name.

That is entirely, completely, and utterly the wrong way to look at it. None of your 3 assumptions appear to be correct. Sorry.
There is only one occurrence of mov ebx, eax, and it's right at the top. Its purpose is to safeguard the initial value of eax, which is important in Delphi-assembly, as it holds a pointer to an instance of the class that calls this code.
Since eax gets used in other ways as well (typically, it will hold a return value from calling another function), the compiler stores this right away into another register -- here ebx, although the compiler is free to pick any free one, or even store it temporarily on a local stack.
Your class is called TEditPlayerMain, and this decompiler¹ recognizes ebx gets used as a Class in a couple of lines -- the ones with comments "Reference to control TEditPlayerMain.xxx". Those are class member variables that are referenced by name, and stored in the positions pointed to by ebx: [ebx+$034C], for instance, points to TEditPlayerMain.lblHeight.
Another typical use, which does not appear in this fragment, is that the initial value allows access to the Virtual Method Table of the class, the full list of functions that were defined for it. This table is pointed to by the first value, [ebx], and so code to 'call' the second method in the VMT would be something like
mov eax, [ebx]
call dword ptr [eax+4]

You can see variants of this code in your lines
006977A0   33D2                   1. xor     edx, edx
006977A2   8B83A8030000           2. mov     eax, [ebx+$03A8]
006977A8   8B08                   3. mov     ecx, [eax]
006977AA   FF5164                 4. call    dword ptr [ecx+$64]

*

*Zero out edx -- this is the argument of the following function call.

*Load eax with a pointer to a class object inside your class.

*Load ecx with the VMT pointer for that object.

*Call function #$64 of that object.

Now where do you see references to "first and last names"? Only as class member variables:
Reference to control TEditPlayerMain.FirstNameTxt : TcxTextEdit
and
Reference to control TEditPlayerMain.LastNameTxt : TcxTextEdit
These are controls inside the window or dialog that happen to bear the names 'FirstNameTxt' and 'LastNameTxt'. Both are (apparently) TcxTextEdit fields, and are called first with some  function_X(0), then
TControl.SetText(FirstNameTxt, 'Multi')
...
TControl.SetText(LastNameTxt,'Player')

I don't know what this dialog looks like, but I think it's two text edit fields with a header, and the headers are set to 'Multi' and 'Player'. The function_X(0) might very well be to clear the contents of the text field.
So this code does not 'grab offsets from a hex file' (all of that "hex" stuff is actually something defined inside this single class), it does not create pointers (it merely fetches some, to class member objects inside this single class), and it doesn't handle "first and last name", other than there happen to be some member variables named as such.

¹ But it's nicely commented output anyway. This doesn't seem native asm code created by Delphi itself, so which decompiler did you use?


text:
Q: React object rendering to fontawesome how do i render an object to a font awesome component. i have an object with different properties and i am rendering them dynamically into my cards component so i have many cards with different contents. below is my code.
import React from "react";
import "../Styles/card.css";
import "bootstrap/dist/css/bootstrap.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCar, faTruck, faHome } from "@fortawesome/free-solid-svg-icons";

const Card = () => {
 const Cards = [
    {
      _uid: "BUY6Drn9e1",
      Icon: "faHome",
      head: "Free and Fast",
      text: "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquam
tempora illum magni minima dolor id sequi quibusdam omnis.",
},
{
  _uid: "BUY6Drn9e1",
  Icon: "faTruck",
  head: "Post Transportation",
  text: "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquam tempora illum magni minima dolor id sequi quibusdam omnis.",
},
{
  _uid: "BUY6Drn9e1",
  Icon: "faCar",
  head: "Free and Fast",
  text: "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquam tempora illum magni minima dolor id sequi quibusdam omnis.",
},
  ];

  const renderCard = (Card, index) => {
const shape = Card.Icon;
console.log(shape);
return (

        {/*  */}

        <FontAwesomeIcon
          icon={faCar}
          className="pic"
          style={{ fontSize: 25, color: "#66b2e9" }}
        />

{Card.head}

{Card.text}

);
};

  return
{Cards.map(renderCard)}
;
};
export default Card;

i am trying to replace  the faCar with {Card.Icon}

A: You have made a mistake,

*

*Link the font awesome icon to each item using the import name, not as strings.

  const Cards = [
    {
      _uid: "BUY6Drn9e1",
      Icon: faHome,
      head: "Free and Fast",
      text:
        "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquam tempora illum magni minima dolor id sequi quibusdam omnis."
    },
    {
      _uid: "BUY6Drn9e1",
      Icon: faTruck,
      head: "Post Transportation",
      text:
        "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquam tempora illum magni minima dolor id sequi quibusdam omnis."
    },
    {
      _uid: "BUY6Drn9e1",
      Icon: faCar,
      head: "Free and Fast",
      text:
        "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aliquam tempora illum magni minima dolor id sequi quibusdam omnis."
    }
  ];

*Access it when iterating as you have done for the text

...
           <FontAwesomeIcon
              icon={Card.Icon}
              className="pic"
              style={{ fontSize: 25, color: "#66b2e9" }}
            />
...


text:
Q: FB Chat Extensions: Setting different home urls for test versions of an app We're creating a bot and messenger exentension on Messenger. We have multiple test apps on fb developer. Setting different webhooks (via ngrok) allows us to trigger our app for every developer so that each can test his feature. So every time I talk with my bot, it replies four times. Useful for testing replies independently.
Is this sort of workflow avaiable for the chat extensions? Currently we set the home Url using the curl command below. But all the devs will get that home URL - they each want to set their own somehow.
curl -X POST -H "Content-Type: application/json" -d ' {
"home_url" : {
 "url": "https://xxxx.ngrok.io/extension/welcome",
 "webview_height_ratio": "tall",
 "webview_share_button": "hide",
 "in_test":true
}
}' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=xxxxxD"

any ideas, greaty appreciated
Guy


text:
Q: Incorrect NSStringEncoding value 0x8000100 detected when converting NSAttributedString to html I'm getting a warning in the debugger in XCode: Incorrect NSStringEncoding value 0x8000100 detected when converting an NSAttributedString to html data. Not sure what is causing this or how to fix it. Here is my code:
let testString = NSAttributedString(string: "test")
    let documentAttributes: [NSAttributedString.DocumentAttributeKey: Any] = [.documentType: NSAttributedString.DocumentType.html]
    let htmlData = try? testString.data(from: NSRange(location: 0, length: testString.length), documentAttributes: documentAttributes)

The data does get created, but not sure why I'm getting the warning.

A: I finally figured out what was causing this. It seems that the string to data function wants some idea of what text encoding to use. Here is the fixed code which removes the debugger warning:
let testString = NSAttributedString(string: "test")
    let documentAttributes: [NSAttributedString.DocumentAttributeKey: Any] = [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue]
    let htmlData = try? testString.data(from: NSRange(location: 0, length: testString.length), documentAttributes: documentAttributes)


text:
Q: How to remove an item from a redis geohash? Redis 3.2 feature the geohash type.
GEOADD is used to add keys:
> GEOADD restaurants 32.0 34.0 Falafel
(integer) 1
> GEOADD restaurants 32.1 34.1 Pizza
(integer) 1

GEORADIUS is used to make a geo query:
> GEORADIUS restaurants 32.05 34.05 100 km WITHDIST
1) 1) "Falafel"
   2) "7.2230"
2) 1) "Pizza"
   2) "7.2213"

However, HDEL does not seem to work:
> HDEL restaurants Falafel
(error) WRONGTYPE Operation against a key holding the wrong kind of value

How do I delete, or set a TTL, to a key within a geo hash?

A: Geohashes are sorted sets, so the right command is ZREM:
> ZREM restaurants Falafel
(integer) 1

> GEORADIUS restaurants 32.05 34.05 100 km WITHDIST
1) 1) "Pizza"
   2) "7.2213"


text:
Q: Println null argument in java One interviewer asked me this below question what is the output of the program.
But I try it in my end the line one compile but line two not compile what is the reason behind it.
Anyone can tell me please.
package swain.javainterviewhub.blogspot.in;

import java.util.Scanner;

public class JavaInterviewHub {

    public static void main(String[] args) {

        String str=null;
        System.out.println(str);//Line 1 Compile
        System.out.println(null);/Line 2 Not compile
    }

}

What is null in real.Its string or charecter or integer.My question is what is null type.
Thanks
Sitansu

A: Line two doesn't compile because System.out is a PrintStream instance, and PrintStream has more than one println method that take a reference type argument (println(String x) and println(char x[])). When you pass a null, the compiler can't decide which of the overloaded methods to choose.
System.out.println(str) passes compilation since the type of the argument (String) matches only one of the overloaded versions of println - println(String x).

A: you can cast it to make it work
System.out.println((String)null);

A: i Don't Why you are printing Null . you can Null As s String on Print Statement .
You Can Use Like That :
String str=null;
System.out.println(str);//Line 1 Compile
System.out.println("null");Print Null


text:
Q: Java - Hidden import folders in Intellij I'm trying to work off of an existing code base, and one of the files has an import statement accessing the path game.format.noFlash.*. However the format folder only has files for the other classes; the noFlash file folder is nowhere to be found.
I know it must be there because when I begin to type in the import statement in intelliJ, one of the autofill options is the noFlash folder. Is there a way to access it, and if so how?

A: The auto-fill options are display packages and also class names
I suspect the noFlash is a class and not a folder and Intellij is suggestion that you can import it, for example:

Classes can be specified explicitly on import instead of using the wildcard character.
  import javax.swing.JOptionPane;  // Make a single class visible.


text:
Q: How can I use handle change event on text box to update react array state?
Below is the code, where on preload all items gets bind inside text box and with the help of same text box I want to update the value of state in react.
items state get's updated but it throws an error as soon as the handlechange method execution gets over.
items.map is not a function. How can I use handle change function on text box to update array state?

import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import {getItems} from "./helper/adminapicall";

const ManageItems = () => {
  const [items, setItems] = useState([]);

  const preload = () => {
    getItems().then((data) => {
      if (data.error) {
        console.log(data.error);
      } else {
        setItems(data);
      }
    });
  };

  const handleChange = (index, name) => (event) => {
    setItems({
      ...items[index].name,
      error: false,
      [name]: event.target.value,
    });

    console.log(items);
  };

  useEffect(() => {
    preload();
  }, []);

  return (
    <Base title="Welcome admin" description="Manage items here">

All items:

      <Link className="btn btn-info" to={`/admin/dashboard`}>
        Admin Home
      </Link>

Total 3
           products

          {items &&
            items.map((item, index) => {
              return (

                    <input
                      type="text"
                      className="form-control"
                      value={item.name}
                    onChange={handleChange(index, "name")}
                    />

              );
            })}

    </Base>
  );``
};

export default ManageItems;

A: onchange={e=> setItems(e.target.value)}
I hope this is what you mean from what you asked in your question.


text:
Q: Why is my font not working in form text field? I'm trying to add a vag font inside my form. i placed the "VAG Rounded Std-Black.otf" font in a folder outside name "fonts" to link it. but i still cant get it to work in a form text field?
any help to the solution would be helpful. thx yummi

<style type="text/css" href="/fonts">

   @font-face {
   font-family: vag;
   src: url(fonts/VAG Rounded Std-Black.otf);
}
    body {
    background-color: dimgrey;
    font-family: Arial;
    color: white;
    font-size: 20px;
    margin: 50px;
}
    /*... input message ...*/

    input[type=text] {
    width: 300px;
    height: 40px;
    border: none;
    outline: none;
    padding-left: 37px;
    font-family: vag;
    font-size: 14px;
    color: white;
    font-weight: bold;
    letter-spacing: .5px;
    background-color:grey;
}
<!-- input message -->
<form><input style="color:white;font-family: vag;" type="text" id="fname" name="fname" value="Type Your Message" onFocus="this.value=''"></form>

A: You can check This Code
I've Used Google fonts

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=M+PLUS+Rounded+1c:wght@700&display=swap" rel="stylesheet">
    <title>Document</title>
</head>
<body>
    <form><input style="color:black; font-family: 'M PLUS Rounded 1c', sans-serif;" type="text" id="fname" name="fname" value="Type Your Message" onFocus="this.value=''"></form>
</body>
</html>


text:
Q: LocSvc error messages in logcat After various Google searches, I've come up short for an answer, so:
I've written a delivery tracking application that our drivers take with them on LG G2 devices. It uses XMPP to converse with HQ and upload information, as well as tracks our vehicles by use of GPS. Today, all of a sudden all tracking stopped. Each of our devices thought they were at base all day... Bit odd, I thought, no new software pushed into production for a month or so. So I get given a device from one of our drivers and plug it in to Eclipse to see what its doing and LogCat is FULL of this:
08-27 16:31:24.944: E/LocSvc_api_v02(955): V/locClientSendReq:2413] qmi_client_send_msg_sync returned 0
08-27 16:31:24.944: E/LocSvc_api_v02(955): V/convertQmiResponseToLocStatus:681]: result = 0, error = -6564, status = 0
08-27 16:31:24.944: E/LocSvc_api_v02(955): V/loc_sync_send_req:512]: select_id = 0,locClientSendReq returned 0
08-27 16:31:24.944: E/LocSvc_api_v02(955): D/loc_free_slot:299]: freeing slot 0
08-27 16:31:24.944: E/LocSvc_api_v02(955): V/loc_sync_send_req:539]: success (select id 0)
08-27 16:31:24.944: E/LocSvc_ApiV02(955): D/Got Zpp fix location validity (lat:1, lon:1, timestamp:1 accuracy:1)
08-27 16:31:24.944: E/LocSvc_ApiV02(955): D/(50.9496151, -2.6051965), timestamp 1409153485700, accuracy 3168.393066
08-27 16:31:24.944: E/LocSvc_ulp_log(955): V/creating msg ULP_MSG_REPORT_POSITION
08-27 16:31:24.944: E/LocSvc_ulp_log(955): V/creating msg ox60b
08-27 16:31:24.944: E/LocSvc_ulp_log(955): V/flags: 63
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   source: 4
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   latitude: 50.949615
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   longitude: -2.605197
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   altitude: 94.844193
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   speed: 6.000000
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   bearing: 0.712935
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   accuracy: 3168.393066
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   timestamp: 1409153485700
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   rawDataSize: 0
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   rawData: 0x0
08-27 16:31:24.944: E/LocSvc_ulp_log(955):   Session status: 0
08-27 16:31:24.944: E/LocSvc_ulp_log(955):  Technology mask: 1
08-27 16:31:24.944: E/LocSvc_utils_q(955): D/msg_q_snd: Sending message with handle = 0x735B4310
08-27 16:31:24.944: E/LocSvc_utils_ll(955): D/linked_list_add: Adding to list data_obj = 0x735B4310
08-27 16:31:24.944: E/LocSvc_utils_q(955): D/msg_q_snd: Finished Sending message with handle = 0x735B4310
08-27 16:31:24.944: E/LocSvc_eng(955): V/Exiting int loc_eng_get_zpp_handler(loc_eng_data_s_type&) line 2044 0
08-27 16:31:24.944: E/LocSvc_MsgTask(955): D/MsgTask::loop() 701679 listening ...
08-27 16:31:24.944: E/LocSvc_utils_q(955): D/msg_q_rcv: Waiting on message
08-27 16:31:24.944: E/LocSvc_libulp(955): I/===> int ulp_msg_process_start_req() line 414
08-27 16:31:24.944: E/LocSvc_libulp(955): I/int ulp_msg_process_start_req(), at ulp state = 1
08-27 16:31:24.944: E/LocSvc_libulp(955): V/Exiting int ulp_msg_process_start_req() line 459 -1
08-27 16:31:24.944: E/LocSvc_libulp(955): V/Exiting int ulp_msg_process_system_update(UlpSystemEvent) line 1398 0
08-27 16:31:24.944: E/LocSvc_ulp_log(955): V/deleting msg UNKNOWN (0x60e)
08-27 16:31:24.944: E/LocSvc_utils_q(955): D/msg_q_rcv: Waiting on message
08-27 16:31:24.944: E/LocSvc_utils_ll(955): D/linked_list_remove: Removing from list
08-27 16:31:24.944: E/LocSvc_utils_q(955): D/msg_q_rcv: Received message 0x735B4310 rv = 0
08-27 16:31:24.944: E/LocSvc_libulp(955): D/void ulp_msg_main(void*) received msg of type: 0x60b
08-27 16:31:24.944: E/LocSvc_libulp(955): I/===> int ulp_brain_process_zpp_position_report(loc_sess_status, LocPosTechMask, const UlpLocation*) line 1427
08-27 16:31:24.944: E/LocSvc_libulp(955): I/int ulp_brain_process_zpp_position_report(loc_sess_status, LocPosTechMask, const UlpLocation*), zpp session status = 0, source: 4, flags = 0x3f, lat = 50.949615, lon = -2.605197, uncertainty = 3168.393066, tech_mask = 0x1
08-27 16:31:24.944: E/LocSvc_libulp(955): I/===> bool ulp_zpp_engine_running() line 62
08-27 16:31:24.944: E/LocSvc_libulp(955): V/Exiting bool ulp_zpp_engine_running() line 73 1
08-27 16:31:24.944: E/LocSvc_libulp(955): I/int ulp_brain_process_zpp_position_report(loc_sess_status, LocPosTechMask, const UlpLocation*), first_fix_pending 1, request active = 1,zpp running 1, zpp state 1
08-27 16:31:24.944: E/LocSvc_libulp(955): I/===> int ulp_msg_send_generic_position_report(loc_sess_status, LocPosTechMask, const UlpLocation*, const GpsLocationExtended*, const void*) line 942
08-27 16:31:24.944: D/Ulp_jni(955): Location CB invoked

Is this anything to worry about? I'm particularly interested in "error = -6564" here:
08-27 16:31:24.944: E/LocSvc_api_v02(955): V/convertQmiResponseToLocStatus:681]: result = 0, error = -6564, status = 0

Which I've tried to search google for, but to no avail. Any help is very much appreciated thanks.

A: They marked as obsolete https://code.google.com/p/android/issues/detail?id=62285
I don't know why. The issue is still happening on my gs4.
With that ton of messages is really hard to debug my applications, since the logcat overflow quickly. I'm very concerned about battery drain.

A: This seems an obvious misclassification of a debug as an error
message.
I asked today for a clarification in which version of Android
the bug was fixed, will post here as soon as I get a reply.
I'm seeing the same problem with hundreds of these per second
on Android 4.4.2.  Battery drain is certainly a concern here.


text:
Q: Snowflake PARSE_JSON Failure on Apparently Valid JSON I have the JSON below, which is (allegedly) from a JSON payload.
I have verified it against several different JSON parsers. But Snowflake TRY_PARSE_JSON returns NULL and PARSE_JSON returns "Error parsing JSON: missing comma, line 2, pos 28".
STRICT_JSON_OUTPUT is false.
{

"Target_Payload__c": "[{"BillingState":"OH","LastModifiedById":"0053R000000KbvFQAS","Id":"0013R000002kqE4QAI","ShippingState":"CA","CreatedDate":"2021-06-09T22:39:11.000+0000","ShippingPostalCode":"94509","BillingStreet":"231 West 4th Street","BillingCountry":"United States","Type":"Analyst","ShippingStreet":"231 West 4th Street","SystemModstamp":"2021-06-09T22:39:11.000+0000","IsDeleted":false,"ParentId":"0013R000002kJfPQAU","BillingPostalCode":"45202","ShippingCity":"Antioch","ShippingCountry":"United States","Phone":"4082393817","CreatedById":"0053R000000KbvFQAS","OwnerId":"0053R000000KbvFQAS","Industry":"Agriculture","Name":"Nibeditatest","NumberOfEmployees":23,"Website":"ww.nibi.com","IsActive":false,"BillingCity":"Cincinnati","Description":"test123","LastModifiedDate":"2021-06-09T22:39:11.000+0000","attributes":{"url":"/services/data/v51.0/sobjects/Account/0013R000002kqE4QAI","type":"Account"}}]"
}

A: It passed two online parsers.
The problem is quotes surrounding the array, i.e. it should be "Target_Payload__c": [
not
"Target_Payload__c": "
and the trailing quote also needs to be removed.

A: so the JSON is valid, in so mush is it is really
{ "Target_Payload__c": "long string" }

the question then becomes is Snowflake trying to parse the Stringfied embedded JSON, as JSON and getting upset, OR seeing the escape token \ but getting upset that it is not itself escaped, because it is parsing it.
If you were testing this like
SELECT '{ "Target_Payload__c": "long string with embedded \"double quotes\"" }' as json_str,
    PARSE_JSON(json_str) as json;

then yes, the escape tokens will need to be escaped, and the above will error, thus it should be:
SELECT '{ "Target_Payload__c": "long string with embedded \\"double quotes\\"" }' as json_str,
    PARSE_JSON(json_str) as json;

If your SQL is in a Stored Procedure, then as it parses SQL it also will want the escapes doubled.
But that doesn't sound the case if you are selecting the SQL from a table, and just parsing it. But you could test via
SELECT PARSE_JSON( REPLACE(json_str, '\\', '\\\\') ) as json
FROM table;

this would show if it's double slash based.

A: After i remove double quotes before and after Value from Key:Value Json string , it got parsed. Js look at this json string
{
"Target_Payload__c": [{"BillingState":"OH","LastModifiedById":"0053R000000KbvFQAS","Id":"0013R000002kqE4QAI","ShippingState":"CA","CreatedDate":"2021-06-09T22:39:11.000+0000","ShippingPostalCode":"94509","BillingStreet":"231 West 4th Street","BillingCountry":"United States","Type":"Analyst","ShippingStreet":"231 West 4th Street","SystemModstamp":"2021-06-09T22:39:11.000+0000","IsDeleted":false,"ParentId":"0013R000002kJfPQAU","BillingPostalCode":"45202","ShippingCity":"Antioch","ShippingCountry":"United States","Phone":"4082393817","CreatedById":"0053R000000KbvFQAS","OwnerId":"0053R000000KbvFQAS","Industry":"Agriculture","Name":"Nibeditatest","NumberOfEmployees":23,"Website":"ww.nibi.com","IsActive":false,"BillingCity":"Cincinnati","Description":"test123","LastModifiedDate":"2021-06-09T22:39:11.000+0000","attributes":{"url":"/services/data/v51.0/sobjects/Account/0013R000002kqE4QAI","type":"Account"}}] }


text:
Q: Data to pre-populate a database kept in text files Many web application require a seed file -- a file, written in the same language as a web application, where I have data to pre-populate a database. This makes sense.
Nonetheless, I sometimes see that some parts of that data  is extracted into separate, text files to be read from the main seed.{rb, py, php} file and inserted into a database.
It can be a list of countries with languages and locales. Or a list of products for an internet-shop with descriptions, prices, etc. Or a list of articles for a blog. Whatever.
I wonder, why are kept in separate, text files which then read from the main seed.{rb, py, php} file and inserted into a database instead of keeping that in a seed file itself? What are the benefits of this approach? And when is this approach necessary?

A: There are virtually dozens of reasons why separating text files from the program which reads and processes them can be beneficial, even if the program is written in a scripting language (so in a text file itself) and both are always deployed together. By separating the text file, you can

*

*hand it over to another person who has no knowledge of the scripting language or programming at all and let the person create or maintain the file

*use a completely different editor (for example, a spreadsheet application), to maintain the text file

*give the data a version number different from the program

*let the same, untouched program process different variants of the text file (for example, for testing purposes, or for different, customized instances of the database)

*reuse the same script to populate different tables in your database easily from different text files, without the need to create a large, unmaintainable BLOB of a >10000 lines script
I guess if you think twice about the question, you can extend this list by a lot of further points by yourself.
Of course, if the task is just to fill one or two tables with two or three columns and rows, and the data virtually never changes, putting everything into one single script maybe sufficient and anything else unnecessary overhead. But if the task gets larger, separation of concerns becomes important.


text:
Q: Get WordPress metabox value before header is output I'm writing a sort of 301 redirecting plugin for WordPress, which adds a metabox for each page, where you can enter a URL you want to redirect that page to. The value of this field has to be obtained before the header is output or else it's too late to redirect. Is it possible to get a metabox value before the header is output? How?

A: The ideal place to do this is with a hook into the template_redirect action. The WP object is already set up, and no output has been generated yet.


text:
Q: Count all row in union with pagination (OFFSET,FETCH) Here is my query.
 SELECT
         S.Id,
         S.[Order],
         COUNT(*) OVER () AS Total_Count --Return 4
FROM Subscriptions S
UNION
SELECT
         S1.Id,
         S1.[Order],
         COUNT(*) OVER () AS Total_Count --return 5
FROM Subscriptions1 S1
ORDER BY [Order] DESC
            OFFSET 0 ROWS
    FETCH NEXT 2 ROWS ONLY

What I want is count 9 (4+5) in every row.

A: Use a subquery:
SELECT id, [Order], COUNT(*) OVER () AS Total_Count
FROM ((SELECT S.Id, S.[Order],
       FROM Subscriptions S
      ) UNION
      (SELECT S1.Id, S1.[Order]
       FROM Subscriptions1 S1
      )
     ) s
ORDER BY [Order] DESC
OFFSET 0 ROWS
FETCH NEXT 2 ROWS ONLY;

Note:  Only use UNION if you want to incur the overhead of removing duplicates.  Otherwise, use UNION ALL.