text:
Q: How to upgrade libstdc++ I have the same question as How do I get my DEB to install libstdc++.so.6.0.20?. (more or less).  The developer of the binary I downloaded used a later version libstdc++ than is present on my 14.04LTS.  Can I manually upgrade to libstdc++.so.6.0.20?  Would I need to upgrade the compiler, too?  Would that mess up other parts of my system?
He promised to recompile using the previous compiler version, thereby working with my library but never followed through.
(I don't have his source.)
https://github.com/FoldingAtHome/fah-client-pub/issues/1147


text:
Q: Contribution to/towards/for According to OALD contribution to/towards is correct usage, but in the following sentence

The country's highest film honour, the Dadasaheb Phalke award, conferred for "outstanding contribution for the growth and development of Indian cinema" will be presented this year to Amitabh Bachchan.

Contribution for is used. Is that correct?

A: The form "contribution to X" or "contribution towards X" is certainly the usual form in US or UK English. "contribution for" could be used to indicate the purpose of the contribution, rather than the thing contributed to, such as:

Jones made a large contribution for feeding the hungry.

But this is not the construction in the question.
It may be that a phrase such as "outstanding contribution for the growth and development of Indian cinema" would be usual in Indian English, I don't know. It is certainly not natural in US English, nor, I think, in UK or Canadian English. But I expect that most fluent speakers of any variety of English would understand it correctly, and I hesitate to label it as "wrong". But I advise learners not to imitate this example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Question on primitive ring I wanted to show that the ring $R=M_{2}(\mathbb{Z})$ is a not primitive.
Here is what I did.
Suppose for contradiction it is primitive. Then there is a faithful and irreducible  $R-$ module $M$.
Let $$0\neq x\in M$$
Then from the irreduciblity of $M$, $$Rx=M$$
Define a module homomorphism $$\phi:R\rightarrow M, r\mapsto rx$$
Then  $$ker(\phi)=ann_{R}(M)={0}$$
(here is one of my doubt) by the faithfulness of the module. Moreover $\phi$ is subjective. Therefore $\phi$ is an isomorphism. But we know that $R$ is not simple module as an $R$ module.Let its the non trivial sub module be given by $V$. Therefore contradiction( as $\phi(V)$ is a non trivial sub module of $M$, which was claimed as irreducible).
Is my argument correct. Or is there another approach?

A: Suppose that $M_2(\mathbb Z)$ is primitive. Being right primitive is a Morita invariant property, so $\mathbb Z$ is also primitive. But a commutative primitive ring is a field, so $\mathbb Z$ is not primitive, a contradiction.

A: No, it doesn't work, because you could apply the same argument to any ring.
The kernel of $\phi$ is the annihilator of $x$, which is not generally the same as the annihilator of $Rx$ when $R$ is not commutative.
For commutative rings the argument works to prove that primitive is the same as simple, that is, a commutative ring is primitive if and only if it is a field.


text:
Q: AngularJS not updating view I'm quite new to Angular, and I feel that the more nesting there needs to be, the more complex the code. I feel that I'm missing some fundamentals here.
Problem: In the chapter.html I see everything correctly, however, when clicking the next hyperlink, the URL gets updated, the view does not.
What am I missing, guys?
Here's my code:
ChapterController.js
app.controller('ChapterController', ['$scope', 'books', '$routeParams', function($scope, books, $routeParams) {
  books.success(function(data) {

    // Your code here
    $scope.book = data[$routeParams.bookId];
    $scope.chapter = data[$routeParams.chapterId];

    // If there no more chapters left, go back to the bookshelf view
    if($routeParams.chapterId >= $scope.book.chapters.length - 1) {
      $scope.nextChapterIndex = "#";
    }
  });

  // Using these properties to create the URLs in line 1 and line 11 of view/chapter.html
  $scope.currentBookIndex = parseInt($routeParams.bookId);
  $scope.currentChapterIndex = parseInt($routeParams.chapterId);
  $scope.nextChapterIndex = $scope.currentChapterIndex + 1;

}]);

chapter.html
Back

 {{book.title}}   {{book.author}}

 {{chapter.title}}

{{ paragraph }}

  Next

Route
.when('/books/:bookId/chapters/:chapterId', {
    controller: 'ChapterController',
    templateUrl: 'views/chapter.html'
  })


text:
Q: How can i do that in gmail adress cannot be two or more "."(points)? I have to write something in my if clause, but I don't know how to write it. For example "hello..hello@gmail.com" or "hello.hello.hello@gmail.com" should be invalid inputs, but "hello.hello@gmail.com" should be valid.
read -p  "enter email " email;

if [[ "$email" =~ ^[A-Za-z]+[A-Za-z0-9_%+-]+[A-Za-z]+@[A-Za-z]+[A-Za-$
echo "Email address $email is valid."//my if clause, which checks if there is correct gmail

else

echo "Email address $email is invalid."

fi

A: You can use this expression:
^[A-Za-z][A-Za-z0-9_%+-]+(\.[A-Za-z0-9_%+-]+)?@[A-Za-z]+(\.[A-Za-z]+)+$

Key ideas:

*

*\. allows one dot

*(...)? says that group with the dot is optional, so no dots is also OK

*minimize the number of different ways the same string can get parsed, for efficiency

*I assume the domain can have multiple dots, but you can also use `...@[A-Za-z]+.[A-Za-z]+$ to allow exactly one dot in the domain.


text:
Q: How to compute the area or number of pixels for selected region in R? I am drawing a region over a raster files but I need to know how many pixels are covered in this box (by means the area):
        the raster file is 1440 pixels*720 lines``(25km*25km).
example:
   saf <- stack(system.file("external/rlogo.grd", package="raster"))
    plotRGB( saf )
    e <- drawExtent()

So after this I drew e as a box but how many pixels/how much is the area?
Thanks

A: Try using raster::crop...
crop(saf , e )
#class       : RasterBrick
#dimensions  : 40, 50, 2000, 3  (nrow, ncol, ncell, nlayers)
#resolution  : 1, 1  (x, y)
#extent      : 23, 73, 26, 66  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=merc
#data source : in memory
#names       : red, green, blue
#min values  :   0,     0,    0
#max values  : 255,   255,  255

And if you just want the number of cells...
ncell( crop(saf , e ) )
#[1] 2000

And to eliminate NA....
x <- crop( saf , e )
ncell( ! is.na(x[]) )


text:
Q: Can I run PHP 5.3 and PHP 5.2 on the same server with Apache? I just curious if there's a way I can set up my development box so that I can have some sites running PHP 5.3 and some with PHP 5.2, and that I can switch between them fairly painlessly.

A: Check out: https://stackoverflow.com/questions/524508/how-can-one-run-multiple-versions-of-php-5-x-on-a-development-lamp-server

A: Looking at the solutions offered in that link, I vastly prefer using the same Apache instance on the same port and just overriding the handler. For details, see my blog post.

A: suPHP is another way to run multiple versions on the same webserver. We do it and map .php/.php5 to PHP5, then .php4 to PHP4.
Overrides are also allowed by users on a per-directory basis by changing the handler in their php.ini file.

A: Yes you can! In the past I've install PHP 5.x from my distribution packages, then downloaded and compiled PHP 5.y from source. Then in Apache you load both modules and just overwrite the file handlers when you want to switch versions - which can even be done in .htaccess files.


text:
Q: Adding additional information when rendering a form in Play! 2.0.2 I'm adding more information to a user model through a LinkedIn API, and all this code is handled in a controller. When the information is added to the model, I re-render the form (of User class) in a new view. Is there any way to attach additional information to this form (built into Play!), to display which fields have been updated by the API-call?
Use case:

*

*User enters view/edit profile page

*User clicks "import information from LinkedIn"

*An API-call is made to the LinkedIn API - the user is then returned to a specific controller (called Social) which handles the JSON to JAVA conversion of data, and binds the new data to the user model, and stores the updated model in the database.

*The controller then redirects the user to the index() controller which renders the view/edit profile view again. (now I'd like to add the functionality that the user can see which of the fields on his profile were modified due to the API-call).
For instance, something similar to form.errrors() (called form.info() or something). If this isn't possible, then is it any way to gain access to the FieldElements, and maybe add something to them?
Cheers!

A: I don't clearly see the problem.
When the controller redirects the user to its profile page, you just have to populate the form with the data from the database.
Something like that:
public static Result profile(String userId) {
    Form<User> userForm = form(User.class);

    User user = User.findById(userId); // data have been set in the database
    if (user != null) {
         userForm = userForm.fill(user);
    }

    return redirect(your.view.render(userForm));
}


text:
Q: What is the Docker Engine? When people talk about the 'Docker Engine' do they mean both the Client and the Daemon? Or is it something else entirely?
As I see it there is a Docker Client, a Docker Daemon. The Client runs locally and connects to the Daemon which does the actual running of the containers. The Client can connect to a remote Daemon. Are these both together the Engine? thanks

A: The Docker Engine is the Docker Daemon running on a single host, installed with the Docker Client CLI. Here are the docs that answer this specific question.
On top of that, you can have a Swarm running that joins multiple hosts to horizontally scale and provide fault tolerance. And there are numerous other projects from Docker, like their Registry, Docker Cloud, and Universal Control Plane, that are each separate from the engine.

A: Docker engine is a client-server application which comprises of 3 components.
1. Client: Docker CLI or the command line window that helps us to interact.
2. REST API: Client communicate with the server with REST API, the commands issued by the client is sent to the server in the form of REST API, it is this reason our server can either be in the local or remote machine.
3. Server: Server here is either the local or remote machine or host machine which has a daemon process running in it which receives the commands and creates, manages and destroys the docker objects like images, containers, volumes etc.


text:
Q: Delta Function Representation in Statistical Mechanics Enumeration Problem With $\rho_{0}>0$, take the power law density function $P(q)=\rho_{0}q^{-\gamma}$. If I have
$$
{\cal N}_L=\frac{L!}{2 L} \sum_{\{n_q\}}  \prod_q \frac{N_q!}{n_q! (N_q-n_q)!}\left(\frac{q^2}{Nc}\right)^{n_q}
$$
which is an expression for a number of loops of length $L$, I can use a delta function representation for the condition $\sum_{q}n_{q}=L$ to obtain
$$
{\cal N}_L=\frac{L!}{2 L}
\int_{-\infty}^\infty \frac{dx}{2\pi} \exp\left(iLx+N\left\langle \log\left[1+q^2e^{-ix}/(Nc)\right]\right\rangle\right)
$$
given $N \to \infty$, and where the angled brackets are the expected value over $q$. Also, there is a condition which reads $\Delta q \to 0$.
This is a common rearrangement in statistical mechanics. But I cannot see how its done, only sources of similar manipulations. Can someone give me the trick?
I think it comes down to how the condition in the sum in the first equation is written as a delta function. The second term in the exponent of the second equation then cancels the first via the complex exponential, after taking some approximation for large $N$?
See this paper, Eqs. 6 and 7.

A: They should have had a Kronecker $ \delta $; a Dirac delta makes no sense in that context since it is a sum over $ n$ and not an integral. Based on my skim on the next page, this does not seem to affect those results much.
The correct derivation is as follows. The first equation is
$$
{\cal N}_L=\frac{L!}{2 L} \sum_{(n_q)_{q \in \mathbb{N}}} \delta(\Sigma_q n_q, L)  \prod_q \frac{N_q!}{n_q! (N_q-n_q)!}\left(\frac{q^2}{Nc}\right)^{n_q}$$
where $ \delta(m,n) $ is the Kronecker delta:
$$
\delta(m,n) = \frac{1}{2 \pi } \int_{-\pi}^{\pi} e^{ i x ( m - n) } dx
$$
Putting this into the formula gives
$$
{\cal N}_L=\frac{L!}{2 L} \frac{1}{2 \pi }  \sum_{(n_q)_{q \in \mathbb{N}}} \int_{-\pi}^{\pi} e^{ i x L - \sum_q i x n_q}  \prod_q \frac{N_q!}{n_q! (N_q-n_q)!}\left(\frac{q^2}{Nc}\right)^{n_q} dx \\ =\frac{L!}{2 L} \frac{1}{2 \pi }  \sum_{(n_q)_{q \in \mathbb{N}}} \int_{-\pi}^{\pi} e^{ i x L}  \prod_q \frac{N_q!}{n_q! (N_q-n_q)!}\left(\frac{q^2 e^{-i x}}{Nc}\right)^{n_q} dx \\ =\frac{L!}{2 L} \frac{1}{2 \pi } \int_{-\pi}^{\pi} e^{ i x L}  \prod_q \left(1 - \left(\frac{q^2 e^{-i x}}{Nc}\right)\right)^{N_q} dx. $$
In the last line, I used the binomial theorem to do the sums over $ (n_q)_{q \in \mathbb{N} } $. Moving on, rewriting the product over $ q $ as a sum in the exponent,
$$
\frac{L!}{2 L} \frac{1}{2 \pi } \int_{-\pi}^{\pi} e^{ i x L}  \exp \left( \sum_q \log \left(1 - \left(\frac{q^2 e^{-i x}}{Nc}\right)\right) N_q \right) dx
$$
and recognizing that $$ \frac{1}{N} \sum_q \log \left(1 - \left(\frac{q^2 e^{-i x}}{Nc}\right)\right) N_q = \left\langle \log \left(1 - \left(\frac{q^2 e^{-i x}}{Nc}\right)\right) \right\rangle$$
gives the final answer.
In their analysis, it looks like the saddle points are in the interval $ (- \pi , \pi ) $, so that the asymptotics are not affected by the incorrect bounds of the integral.


text:
Q: onKeyDown() functionality issue I was trying to override the back button functionality where I wanted to call the default functionality in case a boolean is set false
public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean temp = false;
        if (event.KEYCODE_BACK == keyCode) {
            System.out.println("Back pressed");
            if (isTrue) {
                //Do something
                return true;
            }
            else return false;
        }
        return false;
    }

Now this doesn't exactly work how the documentation states. the //Do Something part is executed well, but when isTrue is false i want the default back functionality which is not happening. Im using SDK 1.5
Now,

*

*How do I fix this?

*Is this issue fixed in later SDK updates? If not can someone raise a bug for the same?

A: *

*If you want the default behavior, chain to the superclass:
return(super.onKeyDown(keyCode, event));

*The bug is in your code. Also, for Android 1.6 and newer, you are better served overriding the dedicated onBackPressed() method (where, again, if you want the default behavior, chain to the superclass).


text:
Q: remove the highlight for the current parenthesis but keep it for the matching pair When I work in a fast paced with vim, one of the recurring annoyance is highlighting of {} or {} or []. When the parenthesis or brackets are adjacent to each other, it takes me a second (yes a whole second!) to figure out where the focus is. I do not like having to rely on the blinking and I still want the matching paren/bracket to be highlighted. So how can I remove just the highlighting for the current paren/bracket?

A: :hi MatchParen ctermbg=black guibg=black

show match is ok, but the highlight was driving me nutz.  The above turns the highight black so you don't see it when editor has a black background

A: :NoMatchParen
type :help matchparen for more help on this .
this functionnality is really useful for me, so maybe you can look at the doc a little and find a way to hightlight the matching pair in a different color (or just underline it for example)

A: What you are looking is
set noshowmatch
to be set in vimrc


text:
Q: Manually editing point coordinates in QGIS Is there a tool for shapefiles or a QGIS Plugin available, which will enable me to edit the coords of a point manually ?
("tool" -f1 "Tsunami Gauge"-move x1.abcdef -to x2.ghijkl)

I do have approximate points of which I the later receive highly preceice data and there I would lie to update my so far data, instead of creating new files.

A: If you want to interactivelly change your points coordinates, one by one, I believe you can do what you want by using the Numerical Vertex Edit Plugin. I can install it in Plugins > Fetch Python Plugins and search it by its name.
After installing you will notice a new icon on you digitalizing toolbar like this . To make it active you must be editing a layer.
Click the plugin button, then click on the desired vertex (in your case the point feature). A dialog show the current coordinates of the vertex, and you can edit them.

Doing this to too many points can be quite boring.
UPDATE to QGIS 3.10
In more recent versions of QGIS, there are more options to edit a point or a vertex coordinate.
Using the vertex editor tool

*

*While editing, click the vertex tool
2.then right-click the feature you want to edit

*The vertex editor opens, you can change the coordinates of the vertexes

Using the advanced digitizing panel
If your layer is in a planimetric SRC, you can use the advanced digitizing panel.

*

*While editing, open the advanced digitizing panel (View > Panels > advanced digitizing panel)

*Enable advanced digitizing

*Click the vertex tool

*Click the vertex you want to move

*In the advanced digitizing panel, fill in the x and y coordinates and lock them. You can use the X and Y keys as shortcuts to fill the values and the Enter key to lock the values

*click the map canvas near the pink cross and the feature map and the node should move to the desired coordinates


text:
Q: Visual studio setting or plugin to "hide" region directives in the IDE In our team we have people that love and hate the "#region" directive. I am looking for a way to make both sides happy. We use VS2010.
I know that you can go to tools > options > text editor > C# > Advanced > Uncheck "Enter outlining mode when files open", as explained in this question:
How to permanently disable region-folding in Visual Studio 2008
However, this is not what I am loking for as it disables all collapsing and the #region text still appears on the screen.
The ideal solution would just hide on the fly the region directives (as if they weren't in the file). It should be just an IDE trick.
If nothing exists a pointer to a similar VS extension sample that could be used as a baseline would be great.

A: This guy wrote an Visual Studio extension that disable the region.
https://stackoverflow.com/a/6179771


text:
Q: create json from a property definition in a class I have a class that every now and then adds a new property, I am looking for a way to create an automatic task that at the time of creating a new property is also saved a json file with its description in Spanish. what is expected is:
class MyEmployee{
constructor(
  name: string, //@ Nombre
  apell: string,//@ Apellido
  segApell: string, @ Segundo Apellido
){}
}

automatic output
{
 "name": "Nombre",
 "apell": "Apellido",
 "segApell": "Segundo Apellido"

}


text:
Q: Adding onclick to input I have been trying add an onclick event for a set of checkboxes I create via JS but it isn't doing what I expect.
At the end of the script, after it builds the checkboxes within the "checkboxes" div, I expect each box to call the handler with a different argument i.  It appears the handlers are all using the current value of i, actually incremented from where it was being used.
What am I missing here ???
    function initialize() {
        console.log("enter initialize");
        console.log("create checkboxes");
        for ( i=0; i<4; i++){

            var span1 = document.createElement('span');
            span1.innerHTML = i;

            var cb = document.createElement('input');
            cb.type = "checkbox";
            cb.name = i.toString();
            cb.onclick = function(){myFunction(i);}
            console.log(i, cb.name, cb.onclick);

            var checkboxes = document.getElementById("checkboxes");
            checkboxes.appendChild(span1);
            checkboxes.appendChild(cb);
            console.log("cb="+cb.toString());
        }
    }
    function myFunction(b){
        alert(b);

A: This is a pretty common scope problem people have. The issue is that the 'i' value at the time you create the function isn't the same 'i' value that's set when you call the function, so the 'i' every time it gets called will always be 3.
The simplest way around this is to simply grab the value from your 'this' for the element, e.g.:
cb.onclick = function(){myFunction(this.name);}

If you don't want it to be the string name, just set it earlier like so:
cb.counter = i;
cb.onclick = function(){myFunction(this.counter);}

A: There are still several attributes that cannot be applied by the way you are trying to. So, you will have to use the older .setAttribute method. For example on your cb object. Try instead of .onClick, try this:
cb.setAttribute('onClick','function(){myFunction(i);}');
Hope this helps!


text:
Q: call custom Java method from jrxml passing the parent object reference Can I invoke a some Java method from expression element in jrxml that can pass a "reference" to this element (from which it was called)?
Some pseudo code:
<textField>
    <reportElement x="0" y="3" width="74" height="16">
        <printWhenExpression><![CDATA[UtilCheck.getval(_this)==true]]></printWhenExpression>
    </reportElement>
    <textFieldExpression><![CDATA["Primary value"]]></textFieldExpression>
</textField>

In Java the the signature of such method will be like this:
class UtilCheck{
  public static boolean getval(JRDesignTextField texfield) {
   //here i need change the value of some of the text field attributes.
    //or get accesss to it parent node
    //or modify its parent attribute
  }
}

I want to modify this element's attributes on the fly or access parent elements and so on.


text:
Q: cann't create task to user using login name I'm building my workflow for sharepoint 2013 on sharepoint designer and I try to create a task to user using his login and I got this error :

System.ApplicationException: HTTP 404 {"error": {"code": "- 1, Microsoft.SharePoint.Client.ResourceNotFoundException", "message": {"lang": "fr-FR" Resource can not be found for sp.utilities.utility.ExpandGroupsToPrincipals. "," Innererror ": {" message ":" The resource can not be found for sp.utilities.utility.ExpandGroupsToPrincipals. " .SharePoint.Client.ResourceNotFoundException "," stacktrace ":" to Microsoft.SharePoint.Client.Rest.RestRequestProcessor.GetObjectFromPathRoot (Boolean mainRequestPath, EdmParserNode node, Boolean resourceEndpoint, MethodInformation & METHODINFO) \ u000d \ u000a to Microsoft.SharePoint.Client.Rest .RestRequestProcessor.GetObjectFromPath (Boolean mainRequestPath, String path, String pathForErrorMessage) \ u000d \ u000a to Microsoft.SharePoint.Client.Rest.RestRequestProcessor.Process () \ u000d \ u000a to Microsoft.SharePoint.Client.Rest.RestRequestProcessor.ProcessRequest () \ u000d \ u000a to Microsoft.SharePoint.Client.Rest.RestService.ProcessQuery (Stream inputStream, IList`1 pendingDisposableContainer) "}}} {" X-SharePointHealthScore ": [" 0 "]," SPClientServiceRequestDuration ": [" 47 " ] "SPRequestGuid": [ "8dc91359-318d-46c6-ba01-46f66ea5630d"], "request-id": [ "8dc91359-318d-46c6-ba01-46f66ea5630d"], "X-FRAME-OPTIONS": [ " Sameorigin "," MicrosoftSharePointTeamServices ": [" 15.0.0.4569 "]," X-Content-Type-Options ": [" nosniff "]," X-MS-InvokeApp ": [" 1; RequiredReadOnly "]," Cache-Control ": [" max-age = 0, private "]," Date ": [" Mon, 27 Feb 2017 13:44:23 GMT " IIS \ /8.5 "]," X-AspNet-Version ": [" 4.0.30319 "]," X-Powered-By ": [" ASP.NET "]} to Microsoft.Activities.Hosting.Runtime.Subroutine. SubroutineChild.Execute (CodeActivityContext context) to System.Activities.CodeActivity.InternalExecute (activityInstance instance, ActivityExecutor executor, BookmarkManager BookmarkManager) to System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody (ActivityExecutor executor, BookmarkManager BookmarkManager, resultLocation Location)

Can you help me to fix this.
thank you

A: please check all language settings. There seems to be an object or browser instance requesting "en-fr" resource. But this culture does not exist - normally it's "fr-FR" or "en-US" / "en-GB".


text:
Q: Avoiding retain cycles in tree-like data structure in Objective C (ARC) I have a data structure in Objective C with retain cycles, and I'm trying to figure out a reasonable way to break them. None of the usual rules seem to help here (e.g. "use weak for parent relationships") due to the requirements I have for the data structure.
The data structure is essentially a tree. However, I want to ensure that, if any of the nodes in the tree is retained, then the entire tree is retained. For example, in this very simple tree:
  A
 / \
B   C

If someone retains A, B, or C, then the entire tree should be retained and available to walk up/down from any node. The nodes in the tree should only be released when no one is retaining any of the nodes.
The only two solutions I have come up with are not very pretty. Does anyone know of a more elegant solution?
For reference, here are the two solutions I've thought of (both of which mess with retainCount, which is gross):

*

*Create a TreeHelper object that holds onto all nodes in the tree strongly. All nodes use weak pointers to refer to all other nodes. All nodes in the tree hold onto TreeHelper strongly when their retainCount > 1 and weakly when retainCount == 1. This should work, but requires that we use non-ARC code so we can override retain/release and change the ownership of TreeHelper.

*Create a TreeHelper object that holds onto all objects in the tree strongly. All nodes use weak pointers to refer to all other nodes and strongly hold TreeHelper. Periodically, it will execute a garbage collection and check the retainCount of all objects. If they are all == 1, then it nils all objects to release them. This should also work, but the garbage collection is not pretty and has some serious thread safety issues.

A: There is nothing to stop you from using ARC for your "treehelper" scheme.
First, make your tree opaque. Any accesses to the nodes (which have weak references to their parents to avoid retain cycles) go through methods of the treehelper (maybe call it a TreeWrapper or TreeRef instead).
Whenever any third-party accesses a node, you return a new data structure NodeWrapper, which has a strong reference to both the specific node you want, and the root node. The third party establishes a strong reference to this object, not the node itself.
The result is that when the last of these objects is deallocated, the whole tree is deallocated, and as long as one NodeWrapper lives, your tree lives, meeting your requirements.
Never use retainCount for anything, even if you aren't using ARC.


text:
Q: Search for index.php and index.html and replace string I recently had some sort of Malware on my computer that added to all index.php and index.html ON THE WEBSERVER! the following string(s):
echo "";

echo "";

So the parameter after "click=" always changes. These two were only examples.
Is there a way to do that quick and fast?
.
.
EDIT: It is on my webserver, so no use of find...

A: one easy way to do this is by using find and grep, plus perl to do the edits.
first, construct a list of filenames that have been compromised:

find /path/to/web/site -name 'index.htm*' -o -name 'index.php' -print0 | \
  xargs -0 grep -l 'iframe src.*fabujob\.com' > /tmp/compromised-files.txt

next, use perl to edit the files and remove the exploit:

cat /tmp/compromised-files.txt | \
  xargs -d '\n' perl -n -i.BAK -e 'print unless m/fabujob\.com/i'

(yes, for the UUOC pedants out there, that is a Useless Use of Cat, but it makes the example easier to read and understand)
that will delete every line containing the string "fabujob.com" from each of the compromised files.  It will also keep a backup of each file as filename.BAK so you can easily restore them if something goes wrong.  you should delete them when you no longer need them.
this perl script is based on the sample you gave which appears to indicated that the attack added an entire line containing the exploit, so this script prints every line EXCEPT those containg the exploit's URL.  if that's not actually the case, then you'll have to come up with a more appropriate script :)
this is a generic technique that you can use to make any automated edits to a batch of files.  you can use any perl code to do the job, and perl has a huge swag of text manipulation capabilities.
BTW, when doing this kind of work, ALWAYS make a copy of the entire directory tree involved and work on that first.  that way it doesn't matter if you screw up the perl editing script...just rsync the original back over the working dir.  once you've got the script exactly right, you can then run it on the real files.

A: sed and find should help you, but sed take some time to learn (enough that I can't come up with a possible command from my mind right now).
Also, there are gui editors that are capable of find and replace in a whole directory tree (i.e. Textmate on the Mac). You would then use a regex to cover the variable part.

A: Try regexxer or rpl type tools. Their whole purpose is project wide replacements. They support recursive directories and let you choose file types to which replacement should be applied.

A: Assuming that the domain is always the same and shouldn't legitimately exist anywhere:
find <documentroot> -name 'index.html' -or -name 'index.php' \
    -exec sed -i'.bak' '/fabujob\.com/d' {} \;

Originals will be saved with the extension '.bak'. You can just use -i if you don't want backups.

A: If you know you have no  tags in your documents, you can simply do
perl -i -n -e'print unless //' $(find . -name index.html)

If you do have iframes, then you'll need to make your regex more exact.
Perl's -i flag is far-too-often overlooked.  It means "edit in place".  See http://petdance.com/perl/command-line-options.pdf for more examples of magic to be done in Perl from the command line.


text:
Q: Why does 'git merge' add files ending with tilde? I'm in the process of merging two git branches that are fairly diverged.
After the automatic merge is complete, I ended up having multiple files having two versions:
file.cc~HEAD
file.cc~branchA

While the original file.cc was gone.
Since both files are identical, I'm slightly puzzled. Why does it happen? Which kind of conflict does it represent?

A: As you mention that you are trying to merge two git branches that are fairly diverged. So in this situation, automatic merge fail.
Ideally, this situation occurs when your local file let say file.cc and file in the other branch in which you are merging are fairly diverged or lack any common ancestor so they cannot be merged. And then, we must keep both files in the working directory but as a conflict. So  file.cc~HEAD and file.cc~branchA files created and original file file.cc deleted.
For more information on git merge read this article.


text:
Q: How can I use Shiny as an upload form for an R Script? I have an R script that loops through a folder of csv files, transforms them, and then writes several csv files once completed.
I want users to be able to use an input form to select various files before the R script runs.  I have never used Shiny before, and I cannot figure out the best way to do this.  Here is what I have come up with so far:
UI
library(shiny)
library(shinyjs)
fieldsMandatory <- c("calDataImport")
appCSS <- ".mandatory_star { color: red; }"
    labelMandatory <- function(label) {
        tagList(
            label,
            span("*", class = "mandatory_star")
        )
    }

ui <- fluidPage(
    shinyjs::useShinyjs(),
    shinyjs::inlineCSS(appCSS),
    options(shiny.maxRequestSize = 30 * 1024^2),

    titlePanel("Setup"),
        sidebarLayout(
        sidebarPanel(

            fileInput("calDataImport", labelMandatory("Choose CSV File for Calibration Data"),
                      multiple = FALSE,
                      accept = c("text/csv",
                                 "text/comma-separated-values,text/plain",
                                 ".csv")),
            tags$hr(),

            shinyDirButton("ticLoc", "Choose Sample Folder", "Upload"),
            tags$hr(),

           # Output: Go and Download----
           downloadButton('submit', 'Select Save Location and Go', class= "action"),

           # CSS style for the download button ----
           tags$style(type='text/css', "#downloadFile { width:100%; margin-top: 35px;}")

       ),

       mainPanel()

    )
)

Server
server <- function(input, output) {
    observe({
        # check if all mandatory fields have a value
        mandatoryFilled <-
            vapply(fieldsMandatory,
                   function(x) {
                       !is.null(input[[x]]) && input[[x]] != ""
                   },
                   logical(1))
        mandatoryFilled <- all(mandatoryFilled)

        # enable/disable the submit button
        shinyjs::toggleState(id = "submit", condition = mandatoryFilled)
    })

    # dir
    shinyDirChoose(input, 'ticLoc', roots = c(home = '~'), filetypes = c('xlsx', 'csv'))
    ticLoc <- reactive(input$ticLoc)
    output$ticLoc <- renderPrint(ticLoc())

    # path
    path <- reactive({
        home <- normalizePath("~")
        file.path(home, paste(unlist(ticLoc()$path[-1]), collapse = .Platform$file.sep))
    })

    # files
    calDataImport <- reactive({
        inFile <- input$calDataImport
        if (is.null(inFile)) return(NULL)
        calDataImport <- read.csv(inFile$datapath, header = TRUE)
        calDataImport
    })

    # Download handler in Server
    output$submit <- downloadHandler(
        filename = function() {
            paste('RAPTOR_Output', Sys.Date(), '.zip', sep='')
        },
        content = function(con) {
            owd <- setwd(tempdir())
            on.exit(setwd(owd))
            outputFiles <- NULL;

################ INSERTING STANDARD R SCRIPT HERE ##########
           # [necessary libraries here]
           # [functions defined here]

           if("CAS#" %in% colnames(calDataImport)){names(calDataImport)[names(calDataImport) == 'CAS#']<-"CAS Number"}
           if("Component RT" %in% colnames(calDataImport)){names(calDataImport)[names(calDataImport) == 'Component RT']<-"Ret. Time"}

           outputFileName <- paste("calDataImport", "csv", sep = ".")
           write.csv(calDataImport, outputFileName, row.names = FALSE)
           outputFiles <- c(outputFileName,outputFiles)

           setwd(ticLoc)
           files <- list.files(pattern = "csv")
           filesFull <- list.files(pattern = "csv", full.names = TRUE)
           for (i in 1:length(files)) {
             fileName <- str_split(files[i], "\\.", n=2)[[1]][1]
             rawData <- read.csv(paste(fileName, str_split(files[i], "\\.", n=2)[[1]][2], sep="."), check.names=FALSE)

           # [more transforming script here]

             outputFileName <- paste(fileName, "_Annotated",".csv", sep = "")
             write.csv(annotatedData, outputFileName, row.names = FALSE)
             outputFiles <- c(outputFileName,outputFiles)
           }
################### END ############

            #create the zip file
            zip(con,outputFiles)
                        })
        }

# Create Shiny app ----
shinyApp(ui, server)

What I have here doesn't seem to work. I get the following error:

Warning: Error in UseMethod: no applicable method for 'filter' applied to an object of class "c('reactiveExpr', 'reactive', 'function')"
[No stack trace available]

So my question is, how can I make this work? My standard R script that I am inserting is nearly 2000 lines, so I would rather not have to go through and adjust the script if possible.
Thank you so much for any insight you can provide!

A: This is a shiny app letting the user to upload multiple csv files. Then, the app reads each csv file and then calculates some properties, which will be displayed on the app. Please note the option multiple = TRUE in fileInput:
library(tidyverse)
library(shiny)

ui <- fluidPage(
  fileInput(
    inputId = "files",
    label = "Upload tables",
    placeholder = "No files selected.",
    multiple = TRUE,
    accept = c(
      "text/csv",
      "text/comma-separated-values,text/plain",
      ".csv"
    )
  ),
  tableOutput("table")
)

server <- function(input, output, session) {
  output$table <- renderTable({
    req(input$files %>% nrow() > 0)

    input$files %>%
      as_tibble() %>%
      mutate(data = datapath %>% map(read_csv)) %>%
      transmute(
        datapath,
        nrow = data %>% map_int(nrow),
        colnames = data %>% map_chr(~ .x %>%
          colnames() %>%
          paste0(collapse = ", "))
      )
  })
}

shinyApp(ui, server)

Here I uploaded 2 csv files with the content of the R objects iris and mpg:

I do not know how your script is structured, but the uploaded files are in the directory dirname(input$files$datapath[[1]]).


text:
Q: How to retrieve trips from historical data? I have the following table mytable in Hive:
id    radar_id     car_id     datetime
1     A21          123        2017-03-08 17:31:19.0
2     A21          555        2017-03-08 17:32:00.0
3     A21          777        2017-03-08 17:33:00.0
4     B15          123        2017-03-08 17:35:22.0
5     B15          555        2017-03-08 17:34:05.0
5     B15          777        2017-03-08 20:50:12.0
6     A21          123        2017-03-09 11:00:00.0
7     C11          123        2017-03-09 11:10:00.0
8     A21          123        2017-03-09 11:12:00.0
9     A21          555        2017-03-09 11:12:10.0
10    B15          123        2017-03-09 11:14:00.0
11    C11          555        2017-03-09 11:20:00.0

I want to get the routes of cars passing through radars A21 and B15 within the same trip. For example, if the date is different for the same car_id, then it is not the same trip. Basically, I want to consider that the maximum time difference between radars A21 and B15 for the same vehicle should be 30 minutes. If it's bigger, then the trip is not the same, like for example for the car_id 777.
My final goal is to count the average number of trips per day (non-unique, so if the same car passed 2 times by the same route, then it should be calculated 2 times).
The expected result is the following one:
radar_start   radar_end       avg_tripscount_per_day
A21           B15             1.5

On the date 2017-03-08 there are 2 trips between radars A21 and B15 (car 777 is not considered due to 30 minutes limit), while on the date 2017-03-09 there is only 1 trip. The average is 2+1=1.5 trips per day.
How can I get this result? Basically, I do not know how to introduce 30 minutes limit in the query and how to group rides by radar_start and radar_end.
Thanks.
Update:

*

*The trip is registered at the date it started.

*If the car was triggered by radar A21 at 2017-03-08 23:55 and by radar B15 at 2017-03-09 00:15, then it should be considered as the same trip registered for the date 2017-03-08.

*In case of ids 6 and 8 the same car 123 passed by A21 two times, and then it turned to B15 (id 10). The last ride with id 8 should be considered. So, 8-10. Thus, the closest previous to B15. The interpretation is that a car passed by A21 two times and the second time is turned to B15.

A: I missed that you're using Hive so started writing query for SQL-Server, but maybe it will help for you. Try something like this:
QUERY
select radar_start,
       radar_end,
       convert(decimal(6,3), count(*)) / convert(decimal(6,3), count(distinct dt)) as avg_tripscount_per_day
from (
    select
        t1.radar_id as radar_start,
        t2.radar_id as radar_end,
        convert(date, t1.[datetime]) dt,
        row_number() over (partition by t1.radar_id, t1.car_id, convert(date, t1.[datetime]) order by t1.[datetime] desc) rn1,
        row_number() over (partition by t2.radar_id, t2.car_id, convert(date, t2.[datetime]) order by t2.[datetime] desc) rn2
    from trips as t1
    join trips as t2 on t1.car_id = t2.car_id
        and datediff(minute,t1.[datetime], t2.[datetime]) between 0 and 30
        and t1.radar_id = 'A21'
        and t2.radar_id = 'B15'
)x
where rn1 = 1 and rn2 = 1
group by radar_start, radar_end

OUPUT
radar_start radar_end   avg_tripscount_per_day
A21         B15         1.5000000000

SAMPLE DATA
create table trips
(
    id int,
    radar_id char(3),
    car_id int,
    [datetime] datetime
)
insert into trips values
(1,'A21',123,'2017-03-08 17:31:19.0'),
(2,'A21',555,'2017-03-08 17:32:00.0'),
(3,'A21',777,'2017-03-08 17:33:00.0'),
(4,'B15',123,'2017-03-08 17:35:22.0'),
(5,'B15',555,'2017-03-08 17:34:05.0'),
(5,'B15',777,'2017-03-08 20:50:12.0'),

(6,'A21',123,'2017-03-09 11:00:00.0'),
(7,'C11',123,'2017-03-09 11:10:00.0'),
(8,'A21',123,'2017-03-09 11:12:00.0'),

(9,'A21',555,'2017-03-09 11:12:10.0'),
(8,'B15',123,'2017-03-09 11:14:00.0'),
(9,'C11',555,'2017-03-09 11:20:00.0')

A: select  count(*) / count(distinct to_date(datetime))    as trips_per_day

from   (select  radar_id
               ,datetime
               ,lead(radar_id) over w  as next_radar_id
               ,lead(datetime) over w  as next_datetime

        from    mytable

        where   radar_id in ('A21','B15')

        window  w as
                (
                    partition by  car_id
                    order by      datetime
                )
        ) t

where   radar_id        = 'A21'
    and next_radar_id   = 'B15'
    and datetime + interval '30' minutes >= next_datetime
;

+----------------+
| trips_per_day  |
+----------------+
| 1.5            |
+----------------+

P.s.
If your version does not support intervals, the last code record could be replaced by -
and to_unix_timestamp(datetime) + 30*60 > to_unix_timestamp(next_datetime)


text:
Q: How to reference app in .kv? Any reference ends with AttributeError I want to use attribute from app but any reference ends up with:
AttributeError: 'NoneType' object has no attribute 'bind'
Here is part of my code:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import StringProperty
from kivy.lang import Builder

class FightScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

# design constructor
kv = Builder.load_file('AppDesign.kv')

class Design(App):
    def __init__(self, **kwargs):
        super(Design, self).__init__(**kwargs)
        self.main_hero = MainHero() # Tried main_hero = MainHero() too
        self.val = self.main_hero.nick  # string

    # Construct app
    def build(self):
        return kv

if __name__ == "__main__":
    Design().run()

# Using kv 2.0
ScreenManagement:
    id: screen_manager
    FightScreen:
        name: 'FightScreen'
        manager: screen_manager
        id: fight_screen

<FightScreen>

FloatLayout:
     BasicBackground
     Label:
          text: app.val
          pos_hint: {'center_x': .5, 'center_y': .35}

Any attempt for reference app in .kv will lead to error.
I tried using

StringProperty;
apply_property(**kwargs);
reference through ScreenManagement/ FightScreen

Problems to access app attributes too

A: The app attribute is None until the App is created. Just move the loading of the kv into the build() method of the App, so that it is not executed until the App is created:
class Design(App):
    val = StringProperty('default')

    def __init__(self, **kwargs):
        super(Design, self).__init__(**kwargs)
        self.main_hero = MainHero() # Tried main_hero = MainHero() too

    # Construct app
    def build(self):
        # design constructor
        kv = Builder.load_file('AppDesign.kv')
        return kv


text:
Q: Lemma 10.8 - Rudin's Functional Analysis, simple inequality. From a question asked by myself long ago apparently:
All the notation is in that question.
There's the inequality
$$
|g(\lambda)| \leq |2r - g(\lambda)|
$$
Which I am not sure where it comes from. Here $g$ is an entire function with the following properties: $g(0) = g'(0) = 0$ and $Re\left[ g(\lambda) \right] \leq |\lambda|$. This last inequality should imply the one I am asking.
Can you help to figure out?

A: Suppose $g(\lambda)=a+ib$. In the argument in the posting you quote it is established that  $g(\lambda)$ is in the region $A_\lambda:=\{x+iy: x\leq |\lambda|\}$. If $|\lambda|\leq r$ then $a\leq|\lambda|\leq r$
Then

*

*$|g(\lambda)|^2=a^2+b^2$

*$|2r-g(\lambda)|^2=(2r-a)^2+b^2=4r^2-4ra+a^2+b^2=4r^2-4ra+|g(\lambda)|^2$

*$4r^2-4ra=4r(r-a)\geq0$
Putting things together, you obtain the desired conclusion.


text:
Q: Removing values from one array and moving to another Array I have an array $scope.multiRoles , I need to remove the values inside it by clicking remove button. And the removed value should moved to another array $scope.role. I am able to remove the array by calling removeRole() but couldn't move the removed values into another array. Need assistance.
Html:

    {{data}}

JS:
$scope.removeRoles = function(index){
  if(($scope.multiRoles!== null ) && ($scope.multiRoles.length>1)) {
    $scope.multiRoles.splice(index,1);
  }

  $scope.rolesAdded = true;
};

A: You are not adding it anywhere. And since you are using the index for your logic you need to add it in the other array before removing it. Consider this
$scope.removeRoles = function(index){
    if($scope.multiRoles !== null && $scope.multiRoles.length > 1) {
        $scope.role.push($scope.multiRoles[index]);
        $scope.multiRoles.splice(index,1);
    }
    $scope.rolesAdded = true;
};

Also $scope.role should be an existing array

A: $scope.role = [];
$scope.removeRoles = function (index) {
if (($scope.multiRoles !== null) && ($scope.multiRoles.length > 1)) {
    $scope.role.push($scope.multiRoles[index])
    $scope.multiRoles.splice(index, 1);
}
$scope.rolesAdded = true;
};

A: I think pushing the value before splicing the array can work.
Try this:
 $scope.removeRoles = function(index){
            if(($scope.multiRoles!== null ) && ($scope.multiRoles.length>1)) {
          $scope.role.push($scope.multiRoles[index])
          $scope.multiRoles.splice(index,1);

            }

            $scope.rolesAdded = true;
        };

A: I got a solution :
JS :
  $scope.removeRoles = function(index,data){

        if(($scope.multiRoles!== null ) && ($scope.multiRoles.length>1)) {
               var index = $scope.multiRoles.indexOf(data);
      $scope.multiRoles.splice(index,1);
             $scope.role.push(data);


text:
Q: How can I send an email using SharePoint Web Service Access? I'm developing an external ASP.NET app that will sit inside a SharePoint site. Can I use SharePoint services to send an email? The app will specify the email content (subject, to, from, and body). I just want to call a method on the SharePoint service to have it send the email.
I'm using WSS 3.0 (not MOSS). Is this possible? If not, what are possible alternatives?

A: You can use SPUtility.SendEmail method to send email. Add reference to SharePoint DLL and then you can use this method. This way you wil be using your WS site's email configuration.


text:
Q: Loading partial view using ajax the submit button is fired When I am loading a partial view with ajax the submit button is fired.
If I remove/delete the submit button the partial view is rendered properly.
This is my javascript code:
$(".searchclientssendsms").keypress(function (event) {

    var keycode = (event.keycode ? event.keycode : event.which);
    if (keycode == '13') { //enter key

             var value = $(this).val();

             $.get("/smstemplate/SearchClients/" + value,

             function (data) {
                $('#searchClientsResult').html(data);
             });

    }
});

The line from RouteConfig regarding my search :
routes.MapRoute(name: "SearchClientsSendSMS",
                  url: "smstemplate/searchclients/{search}",
             defaults: new { controller = "smstemplate",
                                 action = "searchclients" });

And the functions from controller:
    public ActionResult SendSMS()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SendSMS(SMSTemplate sms, string[] clients)
    {

        foreach (string client in clients)
        {
            int idclient = Convert.ToInt32(client);
            Customer customer=db.Customers.Find(idclient);
           // SendSMS(customer.Phone, sms.Text);
        }

        return View();
    }

    public ActionResult SearchClients(string search)
    {
        List<Customer> clients = db.Customers.Where(c => c.Deleted == true && (c.Email.Contains(search) || c.Name.Contains(search) || c.Phone.Contains(search))).ToList();

        return PartialView(clients);
    }

If I execute the javascript function from firebug the partial view is rendered corrected. The submit button is not fired any more.
 $.get("/smstemplate/SearchClients/poir",

        function (data) {

            $('#searchClientsResult').html(data);

        });

I noticed this behaviour only at enter key.
So, what can cause that?

A: It seems to me that the Enter key is also submitting the button, so it is calling the AJAX and pressing button at the same time.
Try this:
$(".searchclientssendsms").keypress(function (event) {

var keycode = (event.keycode ? event.keycode : event.which);
    if (keycode == '13') { //enter key

         var value = $(this).val();

         $.get("/smstemplate/SearchClients/" + value,

         function (data) {
            $('#searchClientsResult').html(data);
         });

         event.preventDefault(); //Inside the if so only is prevented for Enter Key.

    }
});

And to disable it in all the page you could try this:
$(document).ready(function() {
  $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
   });
});


text:
Q: Split string to numpy array I am trying to split this element:
'(353.0206847485174, 351.209306627799, 357.05459767397815, 351.53131418867196, 350.8487161820783, 356.76859139989006)'

to a numpy array. I tried the following:
'(353.0206847485174, 351.209306627799, 357.05459767397815, 351.53131418867196, 350.8487161820783, 356.76859139989006)'.split(', ')

but then I have the following:
['(353.0206847485174',
 '351.209306627799',
 '357.05459767397815',
 '351.53131418867196',
 '350.8487161820783',
 '356.76859139989006)']

So the first and last element still has the columns, any idea how to fix that? thanks

A: I assume you really want an array of numbers, not an array of strings.
>>>import ast
>>>import numpy as np
>>>s = '(353.0206847485174, 351.209306627799, 357.05459767397815, 351.53131418867196, 350.8487161820783, 356.76859139989006)'
>>> np.array(ast.literal_eval(s))
array([353.02068475, 351.20930663, 357.05459767, 351.53131419,
       350.84871618, 356.7685914 ])
>>>

A: You can do it without any additional dependencies
s = '(353.0206847485174, 351.209306627799, 357.05459767397815, 351.53131418867196, 350.8487161820783, 356.76859139989006)'
nums = s.strip('(').strip(')').split(',')
numbers = [float(n.strip()) for n in nums]

This gives you the values as a list and if you want it as a numpy array replace the last line with
import numpy as np
numbers = np.array([float(n.strip()) for n in nums])


text:
Q: Calling phone number in flutter application without re-directing to default phone dailler with permission request I am developing an application using flutter one of my application features is calling phone numbers directly without re-directing to phone dailler and this feature is very fundamental to the app.
Thanks in advance

A: Try using :- flutter_phone_direct_caller plugin
https://pub.dev/packages/flutter_phone_direct_caller


text:
Q: How to get working directory in node-webkit I've got a simple program that can be run from command line.
This program is for live preview of markdown files.
When i'm packaging the app with
cat $NW/nw marknow.nw > marknow

and running from different location:
./build/marknow ../relative/path/to/file.md

I can't get current working directory.
process.cwd()

is returning /tmp/something???
How can I get working directory in node-webkit? Directory from which ./build/marknow ../relative/path/to/file.md was called.

A: I think cwd is getting 2 different meanings:

*

*directory where the app lives

*directory where the user launch the app from

In shell scripting I can see the 2nd meaning applied, but the node-webkit community
seems to be using the 1st
Correct me if I'm wrong, but I think you are looking for the 2nd: the path where the user was when calling to your app.
After some tests I finally found a way that works for me:

process.env.PWD

A: Another option you could try if the cwd doesn't seem to work is getting the execution directory with something like this:
var path = require('path');
var execPath = path.dirname( process.execPath );

This should get you the execution directory of the exe. cwd gets the temp directory because of how node-webkit handles opening the files from a temp directory on each run.

A: As is pointed out in other answers, node-webkit starts up the node process with the wrong 'current working directory' (from a command line perspective anyway).
As is pointed out elsewhere, process.env.PWD in fact contains what we want (when the app is started from the command line). A simple workaround could then be to do the following in your index.html (or some other place that gets executed early):
<script type="text/javascript">
  if(process.env.PWD) {
    process.chdir(process.env.PWD);
  }
</script>

Presto! Now process.cwd() returns the right thing.
Apparently, this trick only really works for apps that are started from the command line - but then again, it is probably only necessary when the app is launched from the command line.
There is a ticket for this issue, but it is old and dusty

A: If all answer were failed, try this.

*

*Create file "main.js" and copy this code.
// get child_process module.
var childproc = require('child_process');

// start process using child_process
//  with current path string
// '__dirname' would be not only path
//  of 'main.js' but also one of 'app.zip'
//  because 'main.js' and 'app.zip' have same directory
childproc.exec('nw app.zip ' + __dirname);

*Add this code which you want to get current path
// get 'nw.gui' module
var gui = require('nw.gui');

// get arguments that we passed
var arr = gui.App.argv;

// nw app.zip __dirname
//            ^ argv[0]
alert('current path: [' + arr[0] + ']');

*Run "main.js" with node.js
I posted "How to get current directory(current path) using node-webkit".
http://hdnua.tistory.com/16
It gets executing zip file's directory.


text:
Q: Laravel Database Query returns collection of objects - how do I get the values to display? I guess there is a simple solution to my problem, I'm just a beginner :D
On one of my controllers I have a fairly complex DB request (see below) that returns a collection of objects and not an array (and I think I cannot perform the request with Eloquent?). Now I don't know how I get these values to actually display inside my blade page? Do I have to somehow convert it to an array to do that?
Thank you very much!

Part of TagsController.php:
$tags = DB::table('tags AS ta')
        ->select('ta.name')
        ->join('tag_thread AS tt', 'tt.tag_id', '=', 'ta.id')
        ->join(DB::raw('(select * from threads order by id desc limit 2000) th'), 'tt.thread_id', '=', 'th.id')
        ->groupBy('ta.name')
        ->orderBy(DB::raw('count(ta.name)'), 'DESC')
        ->limit(5)
        ->get();

return $tags:
[
    {
        "name": "javascript"
    },
    {
        "name": "jquery"
    },
    {
        "name": "php"
    }
]

A: Use pluck() to get specific columns in array.
$tags = DB::table('tags AS ta')
        ->select('ta.name')
        ->join('tag_thread AS tt', 'tt.tag_id', '=', 'ta.id')
        ->join(DB::raw('(select * from threads order by id desc limit 2000) th'), 'tt.thread_id', '=', 'th.id')
        ->groupBy('ta.name')
        ->orderBy(DB::raw('count(ta.name)'), 'DESC')
        ->limit(5)
        ->pluck('name');

This will output like below and simply use @foreach () in blade
[
    "name1",
    "name2",
    "name3",
]

A: use json_encode() first to get the json from your result data, and then use json_decode() to convert the json data into array. so your final result will be a multidimensional array.
$tags=json_decode(json_encode($tags,true),true);

Then you can print the data in your blade as
@foreach ($tags as $tag)

{{ $tag['name'] }}

@endforeach

A: Inside your blade template, you can just loop through them with:
@foreach ($tags as $tag)

{{ $tag->name }}

@endforeach

A: You can use @foreach statement in your views to iterate the Collection
@foreach($tags as $tag)

{{ $tag->name }}

@endforeach

A: you can do with two ways with the collection object get value like below-:
  @foreach($tags as $value)

{{$value->name}}

@endforeach

or you can do with toArray function. just put the toArray function after the query like so
     get()->toArray();

and then use
    @foreach($tags as $value)

  {{$value['name']}}

     @endforeach


text:
Q: Matlab rat function in Python Is there a Python version of Matlab's rat function? I've tried looking and the seemingly closest I've found is Python's fractions.Fraction.from_float method within the fractions module. However, it doesn't seem to be implementing the same algorithm.
It doesn't seem to be too difficult to implement a function by hand following this Matlab reference page, but I was wondering if there was a built-in function or a standard library version for it.

A: If you want to stay inside of the standard library, you might want to look at the fractions.Fraction.limit_denominator() method:
>>> fractions.Fraction.from_float(0.8)
Fraction(3602879701896397, 4503599627370496)

>>> fractions.Fraction.from_float(0.8).limit_denominator()
Fraction(4, 5)

If you're migrating from Matlab you probably want some outside help from numpy, scipy and sympy. Sympy has a nice .nsimplify method which also does "the right thing" for fraction approximation:
>>> import sympy
>>> sympy.nsimplify(0.8)
4/5


text:
Q: autofac Resolve all types of open generic type? I'm guessing there is no way to do something like the following with Autofac, to ctor inject an enumerable collection of open generic types? The various Handle types have dependencies, otherwise I would just dynamically build those up.
    class EventOne : IEvent {...}
    class EventTwo : IEvent {...}
    class EventThree : IEvent {...}
    interface IHandleEvent<T> where T : IEvent {...}
    class HandleEventOne : IHandleEvent<EventOne> {...}
    class HandleEventTwo : IHandleEvent<EventTwo> {...}
    class HandleEventThree : IHandleEvent<EventThree> {...}

    builder.RegisterAssemblyTypes(myAssembies).AsClosedTypesOf(typeof(IHandleEvent<>));
    builder.RegisterType<AService>().As<IAService>();

    class AService : IAService
    {
      public AService(IEnumerable<IHandleEvent<IEvent>> handles)
      {...}
    }

A: As explained in the comments, what you want is impossible to achieve in C# and with good reason. If you were able to cast an IHandleEvent<EventOne> to an IHandleEvent<IEvent> it would allow an EventTwo to be passed in as well, which would fail at runtime.
So what you need is an mediator abstraction that allow getting all the compatible event handlers and call them. Such mediator is often called IEventPublisher and might look like this:
public interface IEventPublisher {
    void Publish(IEvent e);
}

You can now create a container specific implementation. For instance, for Autofac this would look as follows:
public class AutofacEventPublisher : IEventPublisher {
    private readonly IComponentContext container;

    public AutofacBusinessRuleValidator(IComponentContext container) {
        this.container = container;
    }

    public void Publish(IEvent e) {
        foreach (dynamic handler in this.GetHandlers(e.GetType())) {
            handler.Handle((dynamic)e);
        }
    }

    private IEnumerable GetHandlers(Type eventType) =>
        (IEnumerable)this.container.Resolve(
            typeof(IEnumerable<>).MakeGenericType(
                typeof(IHandleEvent<>).MakeGenericType(eventType)));
}

Consumers can now depend on this new abstraction:
class AService : IAService
{
    public AService(IEventPublisher publisher) {...}
}

A: You won't be able to cast IHandleEvent<EventThree> to IHandleEvent<IEvent> because IHandleEvent<T> is not a covariant you can add it by adding the out modifier.
public interface IHandleEvent<out TEvent>
    where TEvent : IEvent
{ }

Unfortunately Autofac doesn't support covariant type but only contravariant type.
By the way you can create a custom IRegistrationSource implementation to have the requested behavior. Something like this :
public class CovariantHandleEventRegistrationSource : IRegistrationSource
{
  public bool IsAdapterForIndividualComponents
  {
    get
    {
      return false;
    }
  }

  public IEnumerable<IComponentRegistration> RegistrationsFor(Service service,
                                Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
  {
    IServiceWithType typedService = service as IServiceWithType;
    if (typedService == null)
    {
      yield break;
    }

    if (typedService.ServiceType.IsGenericType && typedService.ServiceType.GetGenericTypeDefinition() == typeof(IHandleEvent<>))
    {
      IEnumerable<IComponentRegistration> eventRegistrations = registrationAccessor(new TypedService(typeof(IEvent)));

      foreach (IComponentRegistration eventRegistration in eventRegistrations)
      {
        Type handleEventType = typeof(IHandleEvent<>).MakeGenericType(eventRegistration.Activator.LimitType);
        IComponentRegistration handleEventRegistration = RegistrationBuilder.ForDelegate((c, p) => c.Resolve(handleEventType, p))
                                          .As(service)
                                          .CreateRegistration();

        yield return handleEventRegistration;
      }
    }
  }
}

With this IRegistrationSource you can have this :
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<EventOne>().As<IEvent>();
builder.RegisterType<EventTwo>().As<IEvent>();
builder.RegisterType<EventThree>().As<IEvent>();
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
        .AsClosedTypesOf(typeof(IHandleEvent<>));

builder.RegisterSource(new CovariantHandleEventRegistrationSource());

IContainer container = builder.Build();

var x = container.Resolve<IEnumerable<IHandleEvent<IEvent>>>();


text:
Q: Passing a std::vector from native C++ to managed array in C++/CLI and/or C# I have been trying to find a way to pass a std::vector from native C++ code into a static method in a C++/CLI managed class. I am new to C++ (non-managed) and so it is not surprising I have had no luck with this. What I would like is some pointers as to how a std:vector (of any type, but preferably double or int) can be converted to managed C++/CLI arrays and/or C# arrays. Perhaps this cannot be done since I only see examples to do the opposite (i.e. C# to native C++), for example see "convert System::array to std::vector". Below I summarise my abortive attempts.
I can pass a double vector such as
   vector<vector<double> > dblvec

into a method defined in a native C++ class (where the class is in a C++/CLI project), but not into a method defined in a ref class (also in a C++/CLI project). The comiler complains that the method (in the ref class) does not exist (candidate function not accessible). I think this is something to do with vector > being foced to be a private variable (see for example C++ CLI error C3767: candidate function(s) not accessible).
Any help would be greatly appreciated.

A: Yes, you are essentially correct about the cause (native types are not public outside the assembly).  And you can't easily fix it since templated types cannot be made public (even by using the make_public pragma).
You'll want to read the following for a workaround:
Best workaround for compiler error C2158: make_public does not support native template types
Good luck!


text:
Q: How to make iFrame not have the scrolling bar I am working on making a widget like this one here:
http://www.comehike.com/outdoors/widget.php?hike_id=176&height=400&width=700
And for some reason I can't seem to make scrolling bar go away.  Does anyone know how to do that?
Thanks!

A: The CSS property that deals with the document being larger than the viewable area is overflow.
This is commonly used to make scrollable divs as seen in this example.
The value you're looking for is: hidden which will clip the area outside of the visible range. Something like:
<iframe style="overflow:hidden;" src="URL" />

Should look nice a a widget
So for CSS properties you might want:
overflow:hidden;
border:none;
width:100px;
height:25px;"

And for iframe properties you probably want:
scrolling="no"
frameborder="0"
allowTransparency="true"

Read up on these to understand what they do, but they are the ones common to widgets like what you describe in your question. Together they should produce a good looking widget.

A: iframe { overflow: hidden; }

ought to do it. However, do you really want to do that? Any content that is not immediately viewable will then not be available (without the user jumping through hoops to scroll it via the keyboard).

A: Like this:
<iframe ... scrolling="no"></iframe>

Edit: Also frameborder="0" is handy to hide the border.

A: Just add the scrolling="no" attribute to your iframe.

Note: this will not work in HTML5.

A: Although
overflow:hidden;
may work with Firefox, it doesn't work with IE or Chrome. If you are NOT using HTML5, then you can use scrollable=no.


text:
Q: AWS SAM local debugging is chargeable? I am using Visual Studio code for debugging a lamda function written in python.
Is the local execution of the lamda function is chargeable ? since at the end of each execution we are getting an entry in the log showing execution time charged.
Please note we are calling some AWS api from within the lamda function, and that is understandably chargable, I have no issues with that.

A: No, you are not charged for debugging it locally. SAM just creates a local environment which is quite similar to the environment your Lambda functions run in.
From the docs:

Local debugging and testing. The AWS SAM CLI lets you locally build,
  test, and debug serverless applications that are defined by AWS SAM
  templates. The CLI provides a Lambda-like execution environment
  locally. It helps you catch issues upfront by providing parity with
  the actual Lambda execution environment.

A: AWS SAM CLI provides a Lambda-like execution environment locally. So it tries to mimic the actual Lambda environment in your local machine. But since the execution is running on your local machine, it won't be charged.
Probably the log would be similar to what you see in the actual Lambda environment because SAM CLI is trying to mimic the actual Lambda output format as well.

In contrast, if you use a Serverless IDE such as SLAppForge Sigma, it will run your debugging code on the actual AWS environment.


text:
Q: Given algorithm, find and solve the recurrence relation Consider the following recurrence relation:
$T(2) = 5$
$T(n) = 2T\left( {\left\lceil {{{2n} \over 3}} \right\rceil } \right) + T\left( {\left\lfloor {{n \over 3}} \right\rfloor } \right) + 3$
I got this recurrence relation by analysing the following algorithm:

I got $T(2) = 5$ as the base case because of 2 comparisons in the if statement plus 3 statements in swap() function.
The question requests to solve it using the characteristic equation. However, I don't know how to proceed with the constant $1$ at the end.
My attempt:
$a_n - a_{2n/3} - a_{n/3} = 3
\\
x^n - x^{2n/3} - x^{n/3} = 3
\\
x^{n/3}(x^3 - 2x^2 - 1) = 3$
Also, if I analysed incorrectly the algorithm, please tell me!
All help is appreciated!
edit: I incorrectly deduced the recurrence equation. I didn't count the cost of first and second if statement.

A: Then you can solve your recurrence by putting
$$
n = 3m + k = 3\left\lfloor {{n \over 3}} \right\rfloor  + n\bmod 3
$$
and split the recurrence into a system three, one for each k.

A: Too long for a comment.
A good way to simulate it in MATHEMATICA
t[n_] := 2 t[Ceiling[2 n/3]] + t[Floor[n/3]] + 1

t[0] = 0;
t[1] = 0;
t[2] = 5;

tk = Table[{k, t[k]}, {k, 3, 200}]

gr1 = ListPlot[tk]
nlm = NonlinearModelFit[tk, a x^b, {a, b}, x]
gr2 = Plot[Normal[nlm], {x, 0, 400}, PlotStyle -> {Red,Dashed}]
Show[gr1, gr2]


text:
Q: Codeigniter: How to capture slashes in route and pass to controller? I'm trying to capture slashes from a url and pass them into my controller. Here's an example of my problem:
Let's say I GET http://localhost/here/is/an/example where my route looks like:
$routes['here/is/(:any)'] = 'my_controller/$1';

and I have the following function definition in my_controller:
public function index($rest_of_the_path) {
...
}

I would like the value of $rest_of_the_path to be 'an/example', but it actually equals 'an'. How can I structure my code so I get what I want?
P.S.: I'm using Codeigniter 2.1.3

A: You can simply do this:
public function index() {
    $rest_of_the_path = implode("/", func_get_args());
    ...
}


text:
Q: Xcode standard editor shows wrong file (with correct location) while assistant editor shows the correct one I have a project folder, and another projectBackup folder next to it.
Yesterday I was working on my project, and by mistake, I opened another Xcode project, directly realized and closed Xcode.
I reopened my project with Xcode and I can see that all my outlets look disconnected in the standard editor.
I check the location of the open file, and it shows the correct one.
When I open the storyboard and the same viewController in assistant editor, I get the correct one (checked the location) - with the connected outlets.
I removed the content of DerivedData folder - but it didn't help.
What is this bug, how can I fix it?

Edit: Just for info, I did a test : created a new project, copied the folder of the project and pasted it next to it, opened the first
  one, then the second. Closed both and Boom, outlet connections
  disapeared (But the application still works)


text:
Q: Does SIP offer a mechanism to initiate a stream and returning an error? Imagine you are browsing to a HTTP URL that does not exists. You'll get a 404 which often contains an explanatory body.
Now imagine you are calling someone using VoIP with SIP and use a non-existent addressee. Is it possible to return an error AND to establish an RTP stream with an explanatory audio message?

A: Yes, if you look at the RFC at https://www.ietf.org/rfc/rfc3261.txt
It explains exactly how to do this.

20.18 Error-Info
The Error-Info header field provides a pointer to additional
    information about the error status response.
  SIP UACs have user interface capabilities ranging from pop-up
  windows and audio on PC softclients to audio-only on "black"
  phones or endpoints connected via gateways.  Rather than forcing a
  server generating an error to choose between sending an error
  status code with a detailed reason phrase and playing an audio
  recording, the Error-Info header field allows both to be sent.
  The UAC then has the choice of which error indicator to render to
  the caller.

A UAC MAY treat a SIP or SIPS URI in an Error-Info header field as if
    it were a Contact in a redirect and generate a new INVITE, resulting
    in a recorded announcement session being established.  A non-SIP URI
    MAY be rendered to the user.
Examples:
 SIP/2.0 404 The number you have dialed is not in service
 Error-Info: <sip:not-in-service-recording@atlanta.com>

The client would therefore receive the 404 in the SIP reply plus it will be told to connect to sip:not-in-service-recording@atlanta.com for a recorded message.


text:
Q: Unable to connect to bitbake server Im trying to setup bitbake tool and trying to follow the tutorial
https://www.yoctoproject.org/docs/1.8/bitbake-user-manual/bitbake-user-manual.html#bitbake-examples
Now when I run the bitbake command I get the following error,
p@p-ubuntu:~/ba/bitbake$ bitbake
NOTE: Retrying server connection... (Traceback (most recent call last):
  File "/home/p/ba/bitbake/lib/bb/main.py", line 428, in setup_bitbake
    topdir, lock = lockBitbake()
  File "/home/p/ba/bitbake/lib/bb/main.py", line 480, in lockBitbake
    lockfile = topdir + "/bitbake.lock"
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
)
NOTE: Retrying server connection... (Traceback (most recent call last):
  File "/home/p/ba/bitbake/lib/bb/main.py", line 428, in setup_bitbake
    topdir, lock = lockBitbake()
  File "/home/p/ba/bitbake/lib/bb/main.py", line 480, in lockBitbake
    lockfile = topdir + "/bitbake.lock"
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

How do I start the bitbake server?

A: I had the same problem after I canceled a bitbake-process harshly (ctrl-c).
After removing the file bitbake.lock in the build-folder, bitbake worked again as intended.
rm bitbake.lock

A: I was following the Yocto tutorial too and had the exact same error. I am running Ubuntu 16.04 in a Virtual Box 6.0 environment on my Windows 10 system.
I finally figured out that using BitBake on a shared folder produce that error. For some reason, installing the Yocto project with the Bitbake on a Virtual Box "sf_" shared folder produce that error.
I then created a fresh folder not on a shared folder of my Ubuntu and redone the Yocto tutorial steps there and the Bitbake command ran succesfully ! It's building the tutorial project while I write those lines.
Hope it will help you with your problem !

A: $ sudo apt-get install gawk wget git-core diffstat unzip texinfo gcc-multilib \
 build-essential chrpath socat cpio python python3 python3-pip python3-pexpect \
 xz-utils debianutils iputils-ping python3-git python3-jinja2 libegl1-mesa libsdl1.2-dev \
 xterm

I accidentally skipped this step in the manual - resolved my issue, hopefully yours

A: You have to run bitbake command from build directory. I also had the same issue since i was not running it from build directory.

A: This is because new function findTopdir (Submitted on July 18, 2017) does not handle errors. For example, the lack of BBPATH environment variable and the inability to find conf/bblayers.conf in BBPATH. findTopdir just returns None in case of that errors.

A: Install needed support packages:
install gawk wget git-core diffstat unzip texinfo gcc-multilib \
     build-essential chrpath socat cpio python python3 python3-pip python3-pexpect \
     xz-utils debianutils iputils-ping

A: I received the same error, after I managed to run a bitbake command that deleted my current derictory. (bitbake -c clean <something> while I was in the work directory of <something>).
The solution is then quite simple: change to another directory, e.g. cd $BUILDDIR.

A: In my way, It works fine when I delete the dir build/ and source oe-init.. again.
You can try this if you don't have built the project.

A: install these packages:
sudo apt-get install makeinfo textinfo texi2html


text:
Q: I need to call MediaPlayer in my View Is there any possible way to call MediaPlayer while in youre in a class that extends View?
I have made mediaplayer work successfully on my Activity class.
If it is not possible, is there a way i can call the method to start streaming audio in my Activity class from my View class?
Android.
public class RealPlayView extends View {
// call objects
private Background background;
private Grid grid;
private Box[] box = new Box[30];
private Paint[] paint = new Paint[30];
private UpdateHandler updatehandler;
private Handler invalidatehandler;
private ColorFilter filter;

// sound variables
private RealPlayActivity realplayactivity;

// variables
public int lineNum = 0;
public int boxValue = 3;
public int gameSpeed = 250;
public int controlMove = 1;
public int controlSet = 1;
public boolean goRight;

// other variables regarding plain function
public int setX1 = 100;
public int setX2 = 100;
public int setX3 = 100;
public int endGame = 0;

// variables regarding to checker
public int X1;
public int X2;
public int X3;
public int X4;
public int X5;
public int X6;
public int X4D;
public int X5D;
public int X6D;

public RealPlayView(Context context) {
    super(context);

    // call objects
    background = new Background(context, R.drawable.background);
    grid = new Grid(context, R.drawable.grid);
    updatehandler = new UpdateHandler();
    invalidatehandler = new Handler();
    filter = new PorterDuffColorFilter(0xffffcc33, PorterDuff.Mode.SRC_ATOP);
    }

A: try with make base with context
MediaPlayer mp_xmPlayer2 = MediaPlayer.create(context, R.raw.error );
mp_xmPlayer2.start();


text:
Q: GO: Obtain various query results in if else block based on parameters number I am using go-mysql-driver to make queries to my database.
I have a function In which I am passing id and warehouseId.
Now I am modifying my mysql query based on if warehouseId value is 0 or not.
The problem is the parameters that I pass in db.Query().
Following is my mysql query where I am appending additional query if warehouseId is not 0.
query := "select id,description from offers inner join offer_entities on offers.id = offer_entities.offer_id where offer_entities.entity_id = ?"
if warehouseId != 0 {
    query += `and offer_entities.warehouse_id = ? `
}
query += `group by offer_id`

I parse it like this:
if warehouseId != 0 {
    rows, err := db.Query(query, variantId, warehouseId)
} else {
    rows, err := db.Query(query, variantId)
}

However, the problem is when I run it, I get an error undefined: rows. I know that it is because rows should be defined outside the if-else conditions. But I don't understand how to define rows outside if-else or
If there is any other way I could achieve my requirements.
How should I tackle this problem.
Thanks in advance.

A: the problem is because of variables are defined in the scope in which they are declared.
The difference between = and := is that = is just assignment and := is used for assignment and declaration
for example
 rows := 1
//it basically means
 var rows int
 rows = 1

what you want is to declare rows outside the if-else and then use them, will solve the problem.

A: Scope visibility
Each block has itself visibility scope. A general rule is visible from inner, invisible from outer. It means you can see variables from superior scope in subject scope but not vise versa.
I believe you use rows declared in if statement out of the block, so it doesn't exist there.
var err error
var rows string
if warehouseId != 0 {
    rows, err := db.Query(query, variantId, warehouseId)
} else {
    rows, err := db.Query(query, variantId)
}
fmt.Println(rows) // It is now possible to use `rows` outside of the block

Declaration styles
var name <type> is a common declaration way. The variable with typed nil value will be declared.
name := <value of type> is a short declaration form. It will declare a variable of a type and assign a value to it at the same time. Allowed only in functions.


text:
Q: How can I hover over a blank space on a site and make an image fade in and slowly fades out after my mouse leaves that spot? I am able to make the image fade in but it immediately disappears when the cursor is off the image. I want it to slowly fade out. Here is an example of what I am wanting http://byvictoriageorge.studio/

A: Hard to say without code examples, but here is some theory.
You have a transition on your Image with opacity 0, and then it transitions to opacity 1 when hover.
You need to duplicate the same functionality, but vice versa. So what you can do it use the ease-in-out; setting on the transision css property.
So the full transition CSS would be soemthing like: transition: opacity 3s ease-in-out;
Edit: I can see your code transition: opacity .2s ease; so you want to change this to:
transition: opacity .2s ease-in-out;

A: You need a little Javascript

*

*When the mouseenter add class (fade in)

*When the mouseleave  add class (fade out)

or only CSS
What is the opposite of :hover (on mouse leave)?


text:
Q: Chrome Dev Tools - GeoLocation override not working I want to override my GeoLocation using Chrome Dev Tools. I changed my GeoLocation to Moscow as shown in the below screenshot, but still my google search results are generated based on my actual location. I've also tried refreshing the page (Empty Cache and Hard Reload) and it still wont work.

I followed the steps mentioned in this Doc.

A: Please try scrolling to the bottom of google search and clicking on 'Update Location' or 'Use precise location':
Google search screenshot
If that does not work, then you might have issues with permissions in your Chrome settings.
https://support.google.com/chrome/answer/142065?co=GENIE.Platform%3DDesktop&hl=en
I recommend this answer for time zone testing:
Is there a way to change your timezone in Chrome devtools?
(edit) = Also might be worth to check you are using an accepted value for TimezoneID when adding a new custom location:
https://cloud.google.com/dataprep/docs/html/Supported-Time-Zone-Values_66194188


text:
Q: dead.mailer php sinology nas I'm trying to make a registration form where at the end a mail is sent to the person who has just registered, to confirm the mail. I've loaded everything on my Sinology nas(RS10613xs+) but when the php script arrives at the point where it must send the mail this error comes out: Warning: mail(vlume1/web/LOG): failed to open stream: No such file or directory in /volume1/web/email.php on line 13 Mailer
and creates a file called dead.mailer does anyone know how to solve and fix this problem
(I'm still "beginners" with php)


text:
Q: can i define global variables for an email in eloqua I am using eloqua for email marketing and i do not see any way to define global variables in the email. Is there any script that eloqua uses that i can use to define some global variables at the top of the email so i do not have to define values several times in the html?
I am looking to define variables like this:
var mylink = "www.google.com";

<!DOCTYPE html>

Visit Website

A: Eloqua actively blocks java scripting in emails[1].
What you are attempting is bypassing eloqua built in functions.
Either utilize the field merge or dynamic content modules to achieve your desired outcome.
If you have a range of values, picklists can be very powerful.
1 https://docs.oracle.com/en/cloud/saas/marketing/eloqua-user/Help/Emails/HTMLemailCodeRequirements.ht


text:
Q: How to use semicolon(;) as a part of command in shell script I am trying run a tool via gnumake.
$(cksumS19) :
$(MY_TOOL_PATH)/toolname $(cksumS19) /CS14:@0x1FFFA;0x500000-0x70FFEF

semicolon ; in the above command is treated as command separator and throwing command not found error for string (0x500000-0x70FFEF).
Can anybody help me please?
I have tried appending $1 to the above command but script became unresponsive.
I have tried to run this in batch script and was successful, but this batch file is not invoked during make.

A: Wrap argument with quotes: "/CS14:@0x1FFFA;0x500000-0x70FFEF"


text:
Q: Erro ao inserir registro, último valor de indice possível já usado Estou com um erro ao tentar inserir um registro alguém sabe resolver.
Segue a mensagem de erro:
Operation failed: There was an error while applying the SQL script to the database.
Executing:
INSERT INTO `local`.`tab_evento` (`id`) VALUES ('18446744073709551616');

ERROR 1264: 1264: Out of range value for column 'id' at row 1
SQL Statement:
INSERT INTO `local`.`tab_evento` (`id`) VALUES ('18446744073709551616')

Edit:  O id é um tipo BigInt(11) unsigned, já tentei alterar ele para bigint(20) unsigned e continua com o mesmo erro.

A: O valor que você está inserindo é maior do que o valor máximo suportado pelo tipo definido a coluna.
Pode consultar os máximos tamanhos para cada campo: integer-types.
Uma alternativa para seu problema, é mudar o tipo do campo para varchar e definir com um tamanho maior, porém terá de mudar a forma com que acontece o auto-increment.

A: Para se solucionar tal problema será necessário usar uma chave primária composta, e controlar o autoincremento através de uma trigger, portanto não será mais automático no próprio campo.
Com base no script abaixo, você poderá ampliar as regras de mudança dos períodos conforme sua necessidade e assim ajustar o id para 1 a cada novo período, mas veja que a contagem do período está manual, para torna-la automática será necessário ampliar o código do trigger para que se baseie em uma terceira tabela de parametrização.
-- --------------------------------------------------------

--
-- Table structure for table `tab_confere_evento`
--

CREATE TABLE IF NOT EXISTS `tab_confere_evento` (
`id` bigint(11) NOT NULL,
  `evento_id` bigint(11) unsigned DEFAULT NULL,
  `evento_periodo` int(10) unsigned NOT NULL,
  `usuario` varchar(100) DEFAULT NULL,
  `status` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `tab_evento`
--

CREATE TABLE IF NOT EXISTS `tab_evento` (
`id` bigint(20) unsigned NOT NULL,
  `periodo` int(10) unsigned NOT NULL,
  `data` timestamp NULL DEFAULT NULL,
  `evento` varchar(120) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Tabela para guardar os logs de modulos abertos pelo usuário' ;

--
-- Triggers `tab_evento`
--
DELIMITER //
CREATE TRIGGER `prx_periodo_trigger` BEFORE INSERT ON `tab_evento`
 FOR EACH ROW begin
    set new.id=(select ifnull((select max(prx_id)+1 from tab_event where periodo=new.periodo),1));
end
//
DELIMITER ;

--
-- Indexes for table `tab_confere_evento`
--
ALTER TABLE `tab_confere_evento`
 ADD PRIMARY KEY (`id`,`evento_periodo`), ADD KEY `idx_evento_id` (`evento_id`,`evento_periodo`);

--
-- Indexes for table `tab_evento`
--
ALTER TABLE `tab_evento`
 ADD PRIMARY KEY (`id`,`periodo`), ADD KEY `id` (`id`), ADD KEY `periodo` (`periodo`);


text:
Q: How to run multiple parallel spark job in AWS EMR clusters through AWS Data Pipe line I am trying to setup a flow for running spark jobs in EMR clusters using AWS Data PipeLine. And our flow runs on "On Demand" schedule.
As part of this activity, we create an EMR cluster in the begining of the pipe line and then we want to run multiple spark jobs on an emr cluster in parallel.
Is there a we can run parallel jobs on Data Pipe Line with "On Demand" schedule.

A: you can check out this example
https://github.com/ychantit/airflow_aws_utils
basically you will need to submit your jobs connecting to the emr using ssh and watch the execution of the jobs yourself
but it's not using aws datapipeline...


text:
Q: C Structure Segment Overflow I have a program in C that creates a two part singly linked list.
I use structures to generate the list, nodes, and node data.
Where the structures are defined as
struct TList {
    struct LNode* first;
    struct LNode* last_left;
};

struct LNode {
    struct LData* data;
    struct LNode* next;
};

The list looks like [ A B C ][ D E ]
Where,
list->first = "A" and list->last_left = "C"
The following function resets the cursor in the linked list.
void reset_list_cursor(struct TList *list) {

    struct LNode *temp, *temp1, *temp2;
    int i = (list_left_size(list) - 1 );

    for (i; i >= 0; i--) {

        temp = list->last_left;
        temp1 = list->first;

        if (temp != NULL) {

            temp2 = temp1->next;
            while (temp2 != temp) {
                temp1 = temp1->next;
                temp2 = temp2->next;
            }

            list->last_left = temp1;
        }
    }
    list->last_left = NULL;
}

However, I am getting a segmentation fault, and I have narrowed it down tho the following lines...
void reset_list_cursor(struct TList *list) {

    temp1 = temp1->next;
    temp2 = temp2->next;

I understand you can never call a temp = temp->next->next, but when you create a structure in place of the temp->next shouldn't it work?

A: Firstly, there's nothing wrong with temp -> next -> next and it's syntactically right too. What you have to make sure in any case involving loops is that you perform a check as to whether the "next" is null or not when stepping into it. Include a condition where you check if temp -> next == NULL when you step into the loop. This will work wonders for you.
That's something like while(temp1->next!=NULL && temp2->next!=NULL)
Hope this helps.


text:
Q: backgrid paginator is not working after collection filter I am a beginner for backbone and backgrid.paginator . I have tried to make a table and used backgrid paginator for pagination. It works fine at the first time load but after filter, paginator does not work.
Even it shows the required number of pages for the resulted filtered collection but does not switched to the other pages , only shows the first page, on clicking on the other page number only shows the content of the first page.
code samples are :
var Organisation = Backbone.Model.extend({});
var OrganisationCollection = Backbone.PageableCollection.extend({
model: Organisation,
state: {pageSize: 20},
mode: "client",
queryParams: {
    currentPage: "current_page",
    pageSize: "page_size"
},
filterBy: function(filterBy,organisationName) {
    var filteredOrg = this.fullCollection.filter(function(model) {
        if(model.get(filterBy).indexOf(organisationName) !== -1) {
            return true;
        }
        return false;
    });
    return new OrganisationCollection(filteredOrg);
}
}

I created a paginator view for pagination using bacgrid.paginator inside that view as follows :
var PaginationView = Backbone.View.extend({
tagName:"div",
el:"#paginator",
initialize: function(){
    _.bindAll(this,'render','filterRender');
    this.collection.setSorting('name');
    this.collection.on("reset",this.render);
    this.collection.on("filter-by-organisation", this.filterRender);
},

filterRender: function (filterBy,organisationName) {
    var filteredOrg = this.collection.filterBy(filterBy,organisationName);
    var paginator = new Backgrid.Extension.Paginator({
        collection: filteredOrg
    });
    this.$el.html("");
    this.$el.append(paginator.render().el);
    return this;
},
render: function(){
    var paginator = new Backgrid.Extension.Paginator({
        collection: this.collection
    });
    this.$el.html("");
    this.$el.append(paginator.render().$el);
    return this;
}
})

I created my own table

                Organization
                Type
                Country
                pledge
                commitment
                expenditure

and my template is

I excluded other codes for rendering the collection on the table here . I think the problem is in the filterRender function in the Paginator view.
Please give some way to solve this out and what is the mistake here.
Thank you in advance.


text:
Q: ASP.NET Web API retunrs Internal Server 500 error while accessing through xamarin Mobile Application.? I wrote asp.net web api and accessing same from xamarin forms mobile app.But while accessing web api i am getting Internal server error 500.
Web API Code:
[HttpPost]
[Route("getObjectName")]
public ActionResult<List<string>> getObjectName([FromBody]imageData data)
{
Console.WriteLine("base64`enter code here`:" + data.imageBase64);
            var detectionResult= objectDetection.detectImage(data.imageBase64);

            if(detectionResult==null)
            {
                return NotFound();
            }

            return detectionResult;
        }

Xamarin Forms Code:
var url =new Uri( "https://tensorflowapi.azurewebsites.net/api/v1/getObjectName");
           // string url = "https://10.0.3.2:5001/api/v1/getObjectName";
            HttpClient httpClient = new HttpClient();
            imageData data = new imageData { imageBase64 = "values" };
            var content =new StringContent(JsonConvert.SerializeObject(data),Encoding.UTF8, "application/json");
            var apiResult =await httpClient.PostAsync(url, content);

            var result=await apiResult.Content.ReadAsStringAsync();


text:
Q: How to print Trie in tree structure in python? I am still a beginner for programming. I do not know how to print trie in tree structure as I have try for a few methods. Anyone can help?
class TrieNode:

    def __init__(self, data):

        self.data = data
        self.is_end = False
        self.children = {}

class Trie(object):

    def __init__(self):
        self.root = TrieNode("")

    def insert(self, array):
        node = self.root

        for x in array:
            if x in node.children:
                node = node.children[x]
                print(node.data)
            else:
                new_node = TrieNode(x)
                node.children[x] = new_node
                node = new_node
                print(node.data)
        node.is_end = True

Below is the code from the main class :-
tr = Trie()
n = int(input("Enter number of file(s): "))
for x in range (n):
    path = input("Enter your directory path: ")
    tr.insert(path.split("/"))
print(tr.root.data)

A: You could define a __repr__ method on your Trie class so that when you do print(tr), that method will be called, and you'll get the tree printed in the way you want.
Here is possible implementation for such a __repr__ method: it uses a recursive function and an indent variable that will ensure that items are indented:
    def __repr__(self):
        def recur(node, indent):
            return "".join(indent + key + ("$" if child.is_end else "")
                                  + recur(child, indent + "  ")
                for key, child in node.children.items())

        return recur(self.root, "\n")

This string representation will append a $ after each data when the corresponding is_end attribute is True.
A remark about your trie implementation:
You are currently storing the data twice: once as a data attribute, and a second time as a key in the children dictionary. This should not be necessary. At the two places where you use node.data, you could use x instead -- they have the same value.
You can then remove the data attribute from your TrieNode class. The code will then look like this:
class TrieNode:
    def __init__(self):
        self.is_end = False
        self.children = {}

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, array):
        node = self.root

        for x in array:
            if x in node.children:
                node = node.children[x]
            else:
                child = TrieNode()
                node.children[x] = child
                node = child
            print(x)
        node.is_end = True

    def __repr__(self):
        def recur(node, indent):
            return "".join(indent + key + ("$" if child.is_end else "")
                                  + recur(child, indent + "  ")
                for key, child in node.children.items())

        return recur(self.root, "\n")

# Main code
tr = Trie()
n = int(input("Enter number of file(s): "))
for x in range (n):
    path = input("Enter your directory path: ")
    tr.insert(path.split("/"))
print(tr)


text:
Q: How to make firebase addValueEventListener to fire only when the data is added to the firebase? I have created an Intent service, and in it, I have created a listener,
but as addValueEventListener get called three-time

*

*first when declared

*when data is added

*when data is removed

How can I modified it so that I can have events only when the data is added
public class MyIntentServiceForEmploy extends IntentService {

    public MyIntentServiceForEmploy() {
        super("MyIntentServiceForEmploy");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        DatabaseReference reference = firebase.getAllOnlineOrder();
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                Toast.makeText(MyIntentServiceForEmploy.this, "notiifiicatiion", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
}

A: You are describing the expected behavior. The "onDataChange" method will fire, first when you open the app, and then every time something in your database changes. If you want for example to be notified only for one type of operation, then you should use a ChildEventListener, as explained in the following lines of code:
ChildEventListener childEventListener = new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
        //Get the added data out from the dataSnapshot object
    }

    @Override
    public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

    @Override
    public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {}

    @Override
    public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
reference.addChildEventListener(childEventListener);


text:
Q: Get image uri from Source How do I get the image url? My xaml is:
<toolkit:HubTile Name="Demo" Title="Demo" Source="demo\0.png"  Margin="15" Tap="Demo_Tap"/>

and in c# I try to get the url from the sender (because I have a lot of entry's in the same tap)
my c# so far
((Microsoft.Phone.Controls.HubTile)(sender)).Source

and I get errors
what I need rests inside
System.Windows.Media.Imaging.BitmapImage m_string;

but how do I access that?

A: If Source is a BitmapImage you can just cast the sender source as BitmapImage
(((Microsoft.Phone.Controls.HubTile)(sender)).Source as BitmapImage).UriSource.OriginalString

A: Source
Source is a dependency property of type ImageSource. It gets or sets the image source of the HubTile control.
Are you casting to an ImageSource when getting the value?  Also, it would help if you displayed the error message.
Update
Per your update, casting to a BitmapImage and getting the UriSource would probably get you what you want:
(BitmapImage).UriSource


text:
Q: How to view docker logs How to check docker logs for specific time using any sudo user.
like I want to check logs for 2022-02-02 from 00:00 AM EST till 01:00 AM EST.
So, I was trying to access logs using Sudo docker logs -f  but unfortunately it is giving me all the output.

A: Have a look at the official documentation. There are 2 options of interest:

--since
Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
--until
Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)