Call to a member function revoke() on null exception

Question: I am trying to create a logout function in laravel Passport.
public function logout(Request $request) {
        $user = Auth::user()->token();
        $user->revoke();
        $tokens =  $user->tokens->pluck('id');
        Token::whereIn('id', $tokens)
            ->update(['revoked'=> true]);

        RefreshToken::whereIn('access_token_id', $tokens)->update(['revoked' => true]);
    }

I got this exception on postman. Is there someone who can help me for this? How can I solve this

Call to a member function revoke() on null

problem
"message": "Call to a member function revoke() on null",
"exception": "Error",
"file": "/Users/123/Desktop/Projeler/Passaport Api/App/app/Http/Controllers/ApiAuth.php",
"line": 52,

Comment: It is because no user is logged in and you are trying to log "him" out
Answer: You need to include the route inner the passport Auth middleware like below:
Route::group(['middleware' => ['auth:api']], function() {
 Route::post('logout',   [YourNameController::class, 'logout']);
});

hopefully that is help you
Comment: 'CSRF token mismatch' I got a alert like that
Comment: Add the following line to the head tag. ` // Add in
`
Add the following line to the head tag.

 // Add in
Then get you can get this content attribute in Laravel. Also, in your script tag, add the following code (this is to make sure when you submit the form, you get the correct  `csrf_token`    `$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});`
Comment: I get this problem on postman. how can I solve it?


Update Ubuntu from 13.04 to 13.10

Question: If i update ubuntu from 13.04 to 13.10,
It will delete all the installed softwares..?
It will delete any of my data..?
I'm totally new to ubuntu.
Answer: All of your settings, files in your /home directory and personal software will be preserved.
It is recommended, however, to make a backup beforehand in case the update renders your operating system inoperable. The chance of this happening shouldn't be big.
Comment: Thanks man, so i'm good to go. Any tips..?
Comment: If this answered your question, please mark it as accepted by clicking the checkmark under the vote counter.
Comment: As for tips, don't touch your computer while its updating. It could mess things up.

Update Ubuntu from 13.04 to 13.10


Can a Virtual Host on Apache access the files of another Virtual Host?

Question: I'm looking to set up a few virtual hosts for different domains for a few friends, and want to know if one virtual host can access files from another host, whether it be via PHP or any other option or if it's totally isolated, so any scripts they can run would only affect their area.
Answer: An Apache "virtual host" is just a mapping of a hostname (or ip address or port) to a particular set of configuration directives.  There is no "containment" or isolation implied by this; everything is still running on the same host.
If you want to actually isolate applications, consider investigating container technology like Docker (or a virtual machine solution), with a front-end proxy directing traffic as necessary to the appropriate backend.
Comment: So even if the hosts each have their own www folder they'd be able to access the other folders via scripts?
Comment: That's correct.  If a script were to be compromised, an attacker would have full access to the system (presumably with the UID of whatever process the web server is running as).


add custom params to fullcalendar request

Question: I'm want to add a parameter named foo to the request that fullcalendar submits when retrieving event data. According to the docs this can be achieved using:
var getFoo() = function() {
    // implementation omitted
};

$('#calendar').fullCalendar({

    loading: function(isLoading) {
        // CAN I SOMEHOW UPDATE foo FROM HERE?
    },
    events: {
        url: '/myfeed.php',
        type: 'POST',
        data: {
            foo: getFoo()
        }
    }

});

I want the value of the foo parameter to be calculated each time the calendar event data is requested, but it seems that fullcalendar only calls getFoo() the first time it loads, then re-uses that value for each subsequent request.
I've tried using this the loading event that is triggered immediately before the data is loaded, but I can't figure out how to update the foo paramter from within this function.
Update
I followed the advice below and got it working with this:
        $('#calendar').fullCalendar({
            events: function(start, end, callback) {
                $.ajax({
                    url: 'getCalendarEvents',
                    dataType: 'json',
                    data: {

                        start: Math.round(start.getTime() / 1000),
                        end: Math.round(end.getTime() / 1000),
                        foo: getFoo()
                    },
                    success: function(doc) {
                        var events = eval(doc);
                        callback(events);
                    }
                });
            },
        });

Answer: Maybe you could use the events as function to create your own ajax request.
var getFoo() = function() {
    // implementation omitted
};

$('#calendar').fullCalendar({
    events: function(start, end, callback) {
        var myFoo = getFoo();
        $.ajax({
            url: 'myxmlfeed.php',
            dataType: 'xml',
            data: {
                // our hypothetical feed requires UNIX timestamps
                start: Math.round(start.getTime() / 1000),
                end: Math.round(end.getTime() / 1000),
                foo: myFoo
            },
            success: function(doc) {
                var events = [];
                $(doc).find('event').each(function() {
                    events.push({
                        title: $(this).attr('title'),
                        start: $(this).attr('start') // will be parsed
                    });
                });
                callback(events);
            }
        });
    }
});

Answer: Try setting lazyFetching to false. I'm guessing you're having this problem because fullCalendar tries to save you from unnecessary ajax requests.
Fullcalendar doc on lazyFetching


Number of ways 6 things can be selected from a group of identical things

Question:
In how many ways can a party of 6 men be selected out of 10 Hindus, 8 Muslims, and 6 Christians if the party consists of at least one person of each religion( Consider only the religion of the person?

Now, I know this problem can be solved by finding the non-negative integral solution to the given equation,
$$x+y+z=6$$
Which the answer turns out to be $\binom{6-1}{3-1}$
But I want to know is there any other method of solving this problem?
Any help would be appreciated.
Comment: You can apply the method I used in the addendum to my answer to [this question](https://math.stackexchange.com/questions/2687609/the-number-of-ways-in-which-10-identical-apples-can-be-distributed-to-six-childr) you posed.  This is not a permutation problem since we are not arranging objects, just selecting them.  The general class of problems you are solving fall under the topic combinatorics.
Comment: Sorry, I forgot to permute them... That gives me 10.
Comment: No of possibilities I could find is $(1,1,4), (1,2,3), (2,2,2)$ with the pattern following (Hindu, Muslim, Christian). However, that only gives me 3 solutions. But the answer is $\binom{5}{2}=10$ solutions.
Comment: Since you figured it out, I suggest you write an answer to your own question.
Answer: No.of possibilities according to the given condition is as follows,
$$(1,1,4), (1,2,3), (2,2,2)$$
Now we find the no.of ways we can select the persons of different religion corresponding to the possibilities.
1) For $(1,1,4)$,
No.of ways of selecting the persons = $3!$.
But since there are 2 1's, each selection will have two copies.
And since we only need to consider their religion (that means persons in a particular religion are identical), we need to divide the result by 2. That gives us,
$\frac{3!}{2} = 3$ ways
For $(1,2,3)$
No.of ways of selecting the persons = $3!$.
(Notice there aren't any repeating numbers in this case!)
2) For $(2,2,2)$
No.of ways of selecting the persons = $3!$.
Now, there are 3 repeating numbers.
That means there are $3!$ copies for each selection. Applying the same logic, we divide the result by $3!$.
$\frac{3!}{3!} = 1$
Adding all the result gives us,
$3+3!+1 = 10$
Answer: Stars and Bars
Once we pre-select one of each religion, this is the same as asking "how many ways we can choose $3$ men from $9$ Hindus, $7$ Muslims, and $5$ Christians?" This is the same as asking how many ways to solve
$$
x+y+z=3
$$
with $x,y,z\ge0$. Stars and Bars say $\binom{5}{2}=10$.

Generating Functions
$$
\begin{align}
&\left[x^n\right]
\overbrace{\left(x+\cdots+x^{10}\right)}^{1\dots10\text{ Hindus}}
\overbrace{\left(x+\cdots+x^8\right)}^{1\dots8\text{ Muslims}}
\overbrace{\left(x+\cdots+x^6\right)}^{1\dots6\text{ Christians}}\\
&=\left[x^n\right]x^3\frac{1-x^{10}}{1-x}\frac{1-x^8}{1-x}\frac{1-x^6}{1-x}\\
&=\left[x^{n-3}\right]\frac{1-x^6-x^8-x^{10}+x^{14}+x^{16}+x^{18}-x^{24}}{(1-x)^3}\\
&=\left(\left[x^{n-3}\right]-\left[x^{n-9}\right]-\left[x^{n-11}\right]-\left[x^{n-13}\right]+\left[x^{n-17}\right]+\left[x^{n-19}\right]+\left[x^{n-21}\right]-\left[x^{n-27}\right]\right)\frac1{(1-x)^3}\\
&=\textstyle(-1)^{n-3}\left[\binom{-3}{n-3}-\binom{-3}{n-9}-\binom{-3}{n-11}-\binom{-3}{n-13}+\binom{-3}{n-17}+\binom{-3}{n-19}+\binom{-3}{n-21}-\binom{-3}{n-27}\right]\\[6pt]
&=\bbox[5px,border:2px solid #C0A000]{\textstyle\binom{n-1}{n-3}-\binom{n-7}{n-9}-\binom{n-9}{n-11}-\binom{n-11}{n-13}+\binom{n-15}{n-17}+\binom{n-17}{n-19}+\binom{n-19}{n-21}-\binom{n-25}{n-27}}
\end{align}
$$
This is the number of ways to pick a group of $n$ people from a pool of $10$ Hindus, $8$ Muslims, and $6$ Christians, where there is at least $1$ of each.
The only one of these that is not $0$ for $n=6$ is $\binom{n-1}{n-3}=\binom{5}{3}$.
Note that we could reduce the last line to
$$
\textstyle\binom{n-1}{2}-\binom{n-7}{2}-\binom{n-9}{2}-\binom{n-11}{2}+\binom{n-15}{2}+\binom{n-17}{2}+\binom{n-19}{2}-\binom{n-25}{2}
$$
except that the equation $\binom{n}{k}=\binom{n}{n-k}$ only holds when $k$ and $n-k$ are non-negative integers.
Comment: This is the number of *positive* integer solutions to $x+y+z=6$. This is different than the number of non-negative integral solutions to $x+y+z=6$, which is $\binom{8}{2}=28$. Perhaps this is what you meant when you said you wanted methods other than counting the number of *non-negative* integral solutions to $x+y+z=6$.
Answer: The number of ways arranging this would be 10 .
And the possibilities are :
( 1 , 1 , 4)
( 1 , 2 , 3)
( 1 , 3 , 2)
( 2 , 2 , 2)
( 2 , 3 , 1)
( 2 , 1 , 3)
( 3 , 2 , 1)
( 3 , 1 , 2)
( 4 , 1 , 1)
( 1, 4 , 1)
following the pattern ( Hindu, Muslim , Christian )
Comment: The question seems to be asking about other *methods* for solving the problem.  What is your *method* here?  To simply list them all out and hope that you don't miss any?  I don't see how this answers the question...


An issue with SLComposeViewController sharing text appear blank ios9

Question: i am using SLComposeViewController for sharing on facebook and twitter.
when i perform action then open dialog box but there are no any text is appear in dialog box.
Comment: Maybe fb forbids to prefill it now.  Read the Facebook Policy at https://developers.facebook.com/policy 2.3
Answer: Since Facebook update their policy it always blank.
Possible solution: create your own alert view (push me), integrate FacebookSDK (push me) and implement sharing (push me).
The easiest way to integrate sdk is through CocoaPods.


Show a set is a closed set larger than open set

Question: let $(\mathbb{R}^n, \tau)$ where $\tau$ is the std topology. Show that the set $U = D_{\delta}(x) = \{y\in \mathbb{R}^n: ||y-x||\leq \delta \}$ is a closed set.
so under these conditions it means I have to show that $\mathbb{R}^n \setminus U$ is open
So the first thing to consider is what does an open set look like:
$\mathbb{R}^n \setminus U$ = $D_{\delta}(x) = \{y\in \mathbb{R}^n: ||y-x||> \delta \}$
proof:
let $\varepsilon = ||x-y|| - \delta$,  let $z\in D_{\epsilon}(x)$,
want to show: $D_{\delta}(x) \subset D_{\epsilon}(x)$
$||z-x|| = ||z - y + y - x|| \leq ||z-y|| + ||y-x|| < \epsilon + \epsilon + \delta$
Problems: Now I know that I have to manipulate my inequality to some how get $\delta < ||z-x||$ but I can't figure out how to get it to work out.  Suggestions?
Answer: You are right in that you have to show the complement is open. To do this, you select an arbitrary point in the complement and show that there is an $\varepsilon$-neighborhood of the point so that the neighborhood is contained entirely within the complement. Here, the choice of $\varepsilon$ can be dependent on your point, unlike how you have chosen your $\varepsilon$ (I can tell you were getting at that point, however!).
Now we can begin the proof. The intuition behind my choice of $\varepsilon$ is the fact that the point is not in the neighborhood, i.e. there is some 'wiggle-room' around the point where we can move and still be in the complement. This 'wiggle-room' will be our $\varepsilon$. More precisely, let $z \in \mathbb{R}^n \setminus U$. Since $z \notin U$, $||z - x|| > \delta$. Set $\varepsilon = ||z - x|| - \delta > 0$. Now we show $N_\varepsilon(z) \subset (\mathbb{R}^n \setminus U)$. Let $w \in N_\varepsilon(z)$. We need to show $w \in (\mathbb{R}^n \setminus U)$, i.e. $||x - w|| > \delta$. To this end, we will use the triangle inequality.
$$||x - z|| = ||x - w + w - z|| \leq ||x - w|| + ||w - z||$$
$$||x - w|| \geq ||x - z|| - ||w - z|| > ||x - z|| - \varepsilon = ||x - z|| - ||z - x|| - \delta = \delta,$$
where we heavily use the fact that $||w - z|| < \varepsilon$.
I hope the motivation for the choice of $\varepsilon$ was clear -- traditionally, this is done by drawing a picture for basic facts of point-set topology.
Comment: yea I had the picture drawn, just couldn't phrase it right. I also negelceted to use the other form of the triangle inequality
Answer: You're getting a bit mixed up on the notation, I think. You want $z\in D_{\varepsilon}(y)$, then by the triangle inequality, $$\|x-y\| \leqslant \|y-z\| + \|z-x\|. $$Since $\|x-y\|=\delta+\varepsilon$ and $\|y-z\|\leqslant\varepsilon$, we have $$\|z-x\| \geqslant \|x-y\|-\|y-z\| \geqslant\delta+\varepsilon - \varepsilon = \delta,  $$
so that $z\in\mathbb R^n\setminus U$.
Comment: I also didn't use the othe form  of the triangle inequality.


Unexpected behaviour of R "library" function with function args as parameters

Question: What I'm trying to do is plain straight forward:
required_pkgs <- c("A", "B", "C")

for (pkg in required_pkgs) {
   library(pkg)
}

At runtime, the R interpreter tries to lookup (3 times) a package called "pkg" (and of course it fails at the first try), when I do expect it to be either "A", "B", "C".
Of course My ignorance of the language makes me miss the point, but why it behaves like that? Does R expects me to write the following code:
library(A)
library(B)
library(C)

I do need to iterate over each package loading to handle missing packages and fallback to installing it or pick an alternative.
BASICALLY I was whining for not being able to iterate over the array of packages names and each call to library with the for parameter (pkg) resulted in R trying to load a non-existent pkg library. This is solved by adding the character.only=TRUE argument a the invocation of library.
EDIT: more infos, sorry for being so vague...
Comment: Found the answer by myself here: http://stat.ethz.ch/R-manual/R-devel/library/base/html/library.html and the param `character.only` will solve my issue.
Comment: See http://stackoverflow.com/questions/8175912/load-multiple-packages-at-once
Comment: Thank you @zx8754! That's a good one. Probably the answer to this question/doubt would be my own previous comment.
Answer: You saved A,B and C in required_pkgs then modify your code as: library(required_pkgs[pkg]) in for loop instead of library(pkg)
Comment: I don't think this is the correct answer; some thing like : `required_pkgs=c("A","B","C"); for(pkg in required_pkgs) library(required_pkgs[pkg])` doesn't do what I was looking after (loading "A", "B", "C")
Answer: Or, if you wanna install three packages at a time, you can use following code of R:
install.packages(c("A", "B", "C")),
still if its not gonna work elaborate your question properly.
Comment: My first comment resolves my question. I fell in panic before reading accurately the docs, even though is counter intuitive. I should have forgotten `for` and go straight to `library(required_pkgs)`.


Monaco custom language validation

Question: Monaco editor
Is there any example how to write validation for custom language ?
For example i need to write error for unused words (words is dynamic)
Comment: See my answer to this question at https://stackoverflow.com/a/66070565/3160967
Answer: Your question is rather vague but here is an example that shows how to validate if typescript is all written in lowercase instead of TypeScript.
Comment: This is for VSCode. For Monaco which is browser based, the problem is there is no standard language server/client api?
Comment: If you're trying to use a language server, you can try looking into TypeFox's monaco-languageclient project.
https://github.com/TypeFox/monaco-languageclient

Monaco custom language validation


Is there a way to see a list of every game I have ever owned on Steam?

Question: Is there a way to see a list of every game I have ever owned on Steam? This includes games I have refunded, free games I've removed the license for, and free weekend games that I didn't end up buying.
If I edit an achievement showcase, I can see almost such a list, but it only shows games I have earned at least one achievement for. There is no way to know if, for example, a game I refunded a year ago and promptly forgot about recently added achievements.
Comment: I think this is sort of related: https://gaming.stackexchange.com/questions/300761/is-there-a-way-to-list-my-removed-games-on-steam/301100#301100
Comment: Give it a shot - I'd be curious to see your solution if you can come up with one.  It seems the person who tried to use the API didn't get very far, but they were looking for achievement information so perhaps it may be possible to do what you want.  Good Luck!
Comment: Do you consider every free weekend game to be "owned", since you could technically install and play any of them at some point?
Comment: @Batophobia no. If I didn't download it, then it's not associated with my account, so it's none of my concern
Comment: @TimmyJim thanks for the link, the answer about the steam api may be useful. I'm a programmer, so I'm perfectly willing to get my hands dirty with json api requests (as long as there is adequate documentation). I don't need to see the achievement list, as there are other ways I can check that (store page, showcase edit)
Answer: Although it doesn't seem to show weekend games that weren't purchased, you could use the purchase history page (https://store.steampowered.com/account/history/).
On that page, you will see every game you have purchased, including ones that have been refunded.
Comment: The purchase history shows monetary transactions you've made, which even includes buys and sales in the community market. There is also a separate list of the licenses you own which includes free games etc, but the licenses in that list disappear if you remove the free game from your account IIRC. It used to be that uninstalling a free game would remove it from your library, but it has since changed: you have to explicitly remove the game now.


In C++ does returning a string created from a local char array cause a memory leak or undefined behavior?

Question: I am wondering if this would cause a memory leak or an undefined outcome in C++?
string foo()
{
    char tempArray[30];
    strcpy(tempArray, "This is a test");
    return string(tempArray);
}

I know this is a bad thing in C but I haven't found a definite answer for C++.
So everyone is saying no, but I am still confused as to when the memory is deallocated?
Lets say I have this method that calls the above method
void bar()
{
    string testString = foo();
}

At what point in the above code does the string object returned from foo() call its destructor? Is it immediately after getting copied into the object testString?
Comment: It would just seem incredibly unnecessary compared to the much more obvious `return "This is a test";`...
Comment: As an aside, your comments on answers here strongly give the impression that you think C++ is or resembles C -- it isn't. ;-]
Comment: Ya i know. Still trying to wrap my head around stuff.
Comment: Does this compile, or is it a typo: `string testString =  string foo();`?
Comment: It was a typo, its now fixed
Answer: No, there is no memory leak, and you don't need to do all that, here is equivalent to your code
string foo()
{
 return "This is a test";
}

Comment: You should be aware that there is an implicit constructor call in that code. The C string "This is a test" is implicitly converted to a `std::string` because the constructor isn't declared `explicit`.
Comment: @BeenCoding2Long: No, your code does not return the temporary array, it copies its contents into a string. In both cases what's returned is a `string` object whose value is a copy of something else, but it makes no difference to the string object what it was a copy of.
Comment: In your example you have a static string stored... In mine I have a temporary array, when it returns the pointer to the array would no longer contain the temp array just stack popped garbage
Comment: Ah ok I see thanks! I have been coding in C so long it hard for me to get used to the object stuff.
Comment: @JørgenFogh: For what it's worth, `return string(tempArray);` also contains an implicit constructor call -- to the copy constructor of `string` in C++03, the move constructor in C++11.
Comment: @Steve Jessop: Are you sure? I thought that it might be called but I was unsure about the exact semantics here, since we are returning the new object directly. The compiler is definitely not required to call the copy constructor and any half decent compiler will only emit one constructor call.
Comment: @JørgenFogh: yes, it's eligible for copy elision because it's an object (the return value) constructed by copying a temporary object of the same type (the expression in the return statement). Try it with a class that has no copy ctor (or private in C++03): `class F() { F(); }; F f() { return F(); }`. Result `error: F::F() is private`.
Answer: What happens in your example is that the constructor with the signature
string ( const char * s );
is called. The constructor allocates new memory for a copy of the string and copies it to that new memory. The string object is then responsible for freeing its own memory when its destructor is called.
When you make a copy of a string, the copy constructor also allocates memory and makes a copy.
You should also take a look at the RAII pattern. This is how string's memory management works.
Answer: In this code:
char tempArray[30];

tempArray is a variable with automatic storage duration.  When tempArray "falls out of scope" it is automatically destroyed.  You copy the contents of this array (somewhat clumsily) in to a std::string and then return that string by value.  Then tempArray is destroyed.  It;s important to note here that tempArray is the array.  It is not a pointer to the first element of the array (as is commonly mis-perceived), but the array itself.  Since tempArray is destroyed, the array is destroyed.
There would be a leak if you used a variable with dynamic storage duration, such as with:
  char* tempArray = new char[30];
  strcpy(tempArray, "This is a test");
  return string(tempArray);

Note the new[] with no matching delete[].  Here, tempArray is still a variable with automatic storage duration, but this time it is a pointer, and the thing that it points to has dynamic storage duration.  In other words, tempArray gets destroyed when it falls out of scope, but it's just a pointer.  The thing that it points to -- the char array itself, is not destroyed because you don't delete[] it.
Answer: Not particularly efficient, but no, no leak.
Comment: Thanks.. Do you know why not? Where is the string stored if not in the registers of the return value?  And how is it cleaned up later?
Comment: It's stored by the string object, and is implementation dependent.  Most likely, it's on the heap, and it will be freed from the heap when the string variable goes out of scope.  In your case, when the caller of `foo()` goes out of its scope.
Answer: No, it wouldn't cause any leaks as you never allocate memory on the heap. If you used malloc, calloc or new.. and you never free/delete it. Then yes, memory leak!
The array is statically allocated, so it is created on the stack. strcpy doesn't return a dynamically allocated object, it fills the existing array, it knows how to do this because of the pointer you passed in - again, not allocated on the heap. A copy of the string object is made when you return the string.
Comment: Ah okay, so an entire string object is created and returned.  The same as if I returned a local structure and the object keeps track of how big the string is and where it is allocated?
Comment: A new string object is created and all the characters are copied into your that string object. But when you return that string, it returns another copy of the string object. That object knows its length and all that.
Answer: You can always return local automatic variable from function by value. For any type this should be safe (unless copy constructor is not safe):
T foo()
{
   return T(...);
}

or:
T foo()
{
   T t
   return t;
}

Your example matches my first case.
What is not safe is returning pointer/reference to local automatic variable:
T& foo()
{
   T t
   return t;
}

T* foo()
{
   T t
   return &t;
}


Apple Watch "No such module 'Alamofire'"

Question: Alamofire has been working fine for an iPhone only project.
I DID THE MANUAL INSTALL OF ALAMOFIRE - NOT COCOA PODS
Now I have added a watch app target following these steps - https://developer.apple.com/library/content/documentation/General/Conceptual/WatchKitProgrammingGuide/ConfiguringYourXcodeProject.html#//apple_ref/doc/uid/TP40014969-CH2-SW1IIm
"import Alamofire" works fine on the iPhone's view controller but when I try to add it to one of the code files in the " Extension" Folder the following error occurs...
<code>No such module "Alamofire"
</code>
Comment: Perhaps you shouldn't use http requests from WatchKit extension at all. Take a look at a similar question: http://stackoverflow.com/a/28931587/1689376
Comment: How would I link parsed JSON data in the view controller for the iOS app onto the watch?
Comment: How would I put a variable from the iPhone onto the Watches UI???
Comment: I don't think my project would function with that method...
Comment: Could I do it without Alamofire???
Answer: Below 2 steps  have resolved above issue  :

i) Check the target name in the Podfile it should match with extension
  that you are adding Library to it. "AppleWatchApp Extension" instead
  of "AppleWatchApp" in my case .
ii) Change the framework search Path in BUILD SETTINGS in the target
  as mention below.


Order nested boxplot groups along a continuous x-axis and across facets [R]

Question: I'd like to get the same order of boxplot fills among temporal groups and across facets using ggplot2 in R. Boxes should be drawn along a continuous x-axis, and box.width should scale with number of values within each group as it is provided by position_dodge2().

Note here, that sometimes the first box within a temporal group (marked by vertical lines) is blue, sometimes red.
Making the variable used for coloring to a factor, does not help. Also it does not seem like the first coloring value within a temporal group, nor the its frequency are responsible for which "color" comes first. Otherwise position_dodge2() does a very good job here, producing the boxes exactly like I want.
Minimal example:
library(ggplot2)
time_data = data.frame( time = c(1:100),
                        y.var = rep(seq(0,1,.02),2)[1:100],
                        f.var = rep(c("A","B","C","D"),25),
                        time.group = c ( rep(c("q"),10),
                                         rep(c("r"),35),
                                         rep(c("s"),5),
                                         rep(c("t"),30),
                                         rep(c("u"),20)
                                         ),
                        col.group = rep(c(T,F,T),40)[1:100]
                        )

break.time = time_data$time[ which( time_data$time.group != lead(time_data$time.group) )]

ggplot()+
  facet_grid(f.var ~.)+
  geom_boxplot(data = time_data, aes( x = time, y = y.var,
                    fill = col.group,
                    group = paste(time.group, col.group)))+
  geom_vline(xintercept = break.time)

Thanks for any help.
Answer: The issue is that the position for your box plots it determined by the time values for each boxplot, i.e. only in the cases where mean(time) is the same for both col.groups in a time.group will dodging have an effect. Otherwise the position is determined by mean(time).
To make this visible I added a stat_boxplot using a geom="text". From this you can see that "order" of the box plots is determined by mean(time):
ggplot() +
  facet_grid(f.var ~ .) +
  geom_boxplot(data = time_data, aes(
    x = time, y = y.var,
    fill = col.group,
    group = paste(time.group, col.group)
  )) +
  stat_boxplot(
    data = time_data, geom = "text",
    aes(
      label = after_stat(x),
      x = time,
      y = stage(y.var, after_stat = 0),
      group = paste(time.group, col.group)
    ),
    vjust = 0,
    position = position_dodge2(.75)
  ) +
  geom_vline(xintercept = break.time)

This said, one option to achieve your desired result would be to make the x positions the same for both col.groups per time.group which could be achieved using stage() and an after_stat= calculation using e.g. ave(). As a first step we could get the order right per time group by computing the position per group.
library(ggplot2)

ggplot() +
  facet_grid(f.var ~ .) +
  geom_boxplot(data = time_data, aes(
    x = stage(time, after_stat = ave(x, group, FUN = mean)),
    y = y.var,
    fill = col.group,
    group = paste(col.group, time.group)
  )) +
  geom_vline(xintercept = break.time) +
  scale_color_manual(values = "black", guide = "none")

However, getting the same order of the col.groups for all time groups requires even more effort. The issue is that we need to ensure that the information on the time group is part of the dataset after the stat has been applied. The only way I figured out to achieve that was once again using stage to map the time group on the color aes, then setting color to a constant value and replacing with the default "black" and getting rid of the color legend using scale_color_manual:
ggplot() +
  facet_grid(f.var ~ .) +
  geom_boxplot(data = time_data, aes(
    x = stage(time, after_stat = ave(x, color, FUN = mean)),
    y = y.var,
    fill = col.group,
    color = stage(time.group, after_stat = "1"),
    group = paste(col.group, time.group)
  )) +
  geom_vline(xintercept = break.time) +
  scale_color_manual(values = "black", guide = "none")

Comment: Thanks a lot Stefan. Only thing is, I needed to make x as POSIXct again by `ave(as.POSIXct( x ), color, FUN = mean)` since the orginal x data is of type POSIXct. Very good answer, now I see how things are done for the positioning.


Using cmd module: how to have sub-commands documented in `help` and integrated with autocomplete?

Question: I'm using the cmd module and have a command called server (method do_server()) which has autocomplete out of the box (I'm on macOS). That's all fine and works like expected. But if i want to additionally also use a sub-command on the server command, things don't work out like i need it.
I would need the following:
- sub-commands should also be integrated with the help command (shouldn't be shown when entering help since they are not first level commands but should be shown when entering help server)
- sub-commands should also integrate with auto-complete
Currently i don't see a way to define sub-commands out-of-the-box. I need to implement them as arguments for a command which isn't ideal.
My question would be, how can i achieve automatic documentation of the sub-commands with help and have autocomplete so that it integrates as good as possible with cmd?
For this example, i'd like to better integrate connect as a sub-command:
from cmd import Cmd

class Tansanit(Cmd):

    def do_server(self, args):
        """ Show server info """
        print("Some server details")

        if args and args == "connect":
            print("Connect to the server")

    def do_quit(self, args):
        """ Quit CLI """
        raise SystemExit

if __name__ == '__main__':
    t = Tansanit()
    t.prompt = "> "
    t.cmdloop()

I would prefer to have something like this:
from cmd import Cmd

class Tansanit(Cmd):

    def do_server(self, args):
        """ Show server info """
        print("Some server details")

    def do_server_connect(self, args):
        """ Connect to server """
        print("Connect to the server")

    def do_quit(self, args):
        """ Quit CLI """
        raise SystemExit

if __name__ == '__main__':
    t = Tansanit()
    t.prompt = "> "
    t.cmdloop()

Unfortunately that's not possible.
Answer: Relavant infos can be found here
Autocomplete for sub-commands

The interpreter is able to process completion for commands names, but for commands arguments you will have to help it. For the command xxx, this is done by defining a complete_xxx method. For example, if you have defined a color command, the completion method for this command could be:

_AVAILABLE_COLORS = ('blue', 'green', 'yellow', 'red', 'black')
def complete_color(self, text, line, begidx, endidx):
    return [i for i in _AVAILABLE_COLORS if i.startswith(text)]

The complete_xxx method takes four arguments:
text is the string we are matching against, all returned matches must begin with it
  line is is the current input line
  begidx is the beginning index in the line of the text being matched
  endidx is the end index in the line of the text being matched
  It should return a list (possibly empty) of strings representing the possible completions. The arguments begidx and endidx are useful when completion depends on the position of the argument.

help for sub-commands

You can also define help for topics that are not related to commands:

def help_introduction(self):
    print 'introduction'
    print 'a good place for a tutorial'

This isn't perfect since the help will be categorized as undocumented commands but it's for an argument. But maybe still better then nothing.


Routing Table: Why do some websites still work after removing the default entry?

Question: i have a question regarding routing tables. By default the ip route command gives me the following result:
default via 192.168.178.1 dev wlp6s0  proto static  metric 600
169.254.0.0/16 dev wlp6s0  scope link  metric 1000
192.168.178.0/24 dev wlp6s0  proto kernel  scope link  src 192.168.178.62  metric 600

192.168.178.1 is the adress of my router. Now, when i delete the default entry the routing table looks like this.
169.254.0.0/16 dev wlp6s0  scope link  metric 1000
192.168.178.0/24 dev wlp6s0  proto kernel  scope link  src 192.168.178.62  metric 600

If i understand it correctly this means that i should only be able to send packets to devices inside the local network because there is no route defined for other destinations right?
When i try to open a website in firefox now it usually tells me that it is unable to connect as expected but there are some websites like google.com which still work in firefox. However, i can't ping google.com because i get the error connect: Network is unreachable
To sum it up, i want to know why some websites still work after i removed the default entry in the routing table while others don't.
Comment: You sure they worked?  Did you close your browser entirely, wipe your browser cache, and try again?  Web browsers are *notorious* for caching things, and usually caching is to blame in these instances.
Comment: Yes im sure. Youtube works as well and i can watch videos that i haven't watched before and using vlc to stream youtube videos works too
Comment: and you are sure you only have v4 routes, and no IPv6 routes? `ip -6 route list`
Comment: Yes you are right it is the IPv6 routes. I feel so stupid now but thank you very much!
Comment: Glad it helped.  I posted my comment as an answer, feel free to accept it since it helped to identify the issue you ran into, and how to resolve it (delete the v6 route)
Answer: There can be the case where you have two IP routes - one for IPv4 which you removed and the other for IPv6.
Check ip -6 route list to find any IPv6 routes, and if there is a default v6 route, delete it.  Then you will get the behavior you expect.


What are the benefits of procreation?

Question: According to the wikia's page on Marriage and Genes, reproducing and making a gene allow you to create a new character with "your current character's inventory and some bonuses." The page does not, however, mention what these bonuses are.
What are these bonuses, and other than having an easier start with a new race/class, is there any benefit to making a  gene?
Comment: Another title for the collection!
Comment: I tweaked the title. Feel free to change it back if you prefer the original.
Comment: Other questions about elone 200 views. This one 3x as much. The benefits of a good title.
Answer: It does absolutely nothing for your current character, at least not more than sleeping during the night normally does. If you make more than one gene, the later genes will replace the existing gene file for that character. Really, the primary benefit of baby-making is the inheritance of inventory. A very commonly recommended strategy for a new player is to start with an "easy" class like Warrior, that can plow through the early game and stock up stuff to pass on to a child who is of a much harder class. One interested in playing classes like a Wizard or Pianist or Tourist might consider this strategy to make it not as much of a punch-to-the-face for a first play.
There are limits, as explained in the article:

No Kitty Banks, so no passing on gobs of ludicrous early game fortune
No Deeds, so no inheriting very nice properties
No Figurines/Cards, these aren't baseball cards you can just pass on to your kid
No small medals/music tickets, as these are basically alternatives to cashmonies
No precious items. This is the big one, as it includes all pre-generated artifacts, diaries, most goods from Miral and Garokk's Workshop, Statues, fusion-made high potions, and about any kind of quest prize consumable that directly improves your stats (as well as hermes blood).

That is a fair much, but then what can you pass on? Your only limit is your weight capacity and your inventory limit (which is about 12 pages). Here's some advice on what to think on.

Almost any item you can wish for. Seven league boots, vindale cloaks, astral light pens, secret experience of Kumiromi... basically you can save your new game a lot of wish usage by having this stuff already prepared.
For that matter, rods of wishing can be passed on if you choose to save them up. Rods of domination can also be handy to pass on.
Piles of useful potions: holy water, unholy water, cure corruption, evolution, descent, speed upper, acidproof and fireproof liquids, antiseptic, soda. As well, useful scrolls: vanish curse, growth, gain attribute, faith, (greater) enchant weapon/armor, flying, wonder. Having just such a major supply of these goods to start a new game can make a lot of the early game dangers much softer.
Multi-use tools like a leash, stethoscope, tamer whip, fishing rod, and pot for fusion which, while moderately easy to find, can be nice to get guaranteed early. Disguise kits may also be handy, but scrolls of incognito are much lighter to stack even if they're single use.
Extra copies of the Rachel books for the one quest. As well, unicorn horns for a later quest are also helpful.
Whatever ridiculous non-pregen artifacts you may have scrounged up in your journey is fair game. Plan not just for yourself, but your future allies as well!
The six different evolution hearts can all be passed on. Guaranteed sources of God, King, Machine, and Magic Hearts are pretty late game typically, so if you save one or two up as a parent, your child can play with the results.
Monster Balls with anything inside can be passed on to allow your progeny to have friends. High powered friends that are tens if not hundreds of levels above the starting enemy challenge. Unlike the method I'll detail next, there are essentially no penalties to these other than the 10.0s they weigh.
For a different approach, a carpenter can also make what is known as a Soul Spindle. It allows one to essentially transfer a copy of an ally. The process to use one, and the penalties to a transferred ally, are detailed in this article. While the penalties look a bit steep, this is the only way to transfer unique allies that can't be caught in monster balls, and they do retain all of their special abilities and gene-engineering results. Stat penalties can be fixed with effort, in the long run.
If you spent a good amount of time nabbing an altar of your own, you can also pass that on as well to save your descendent from having to figure how to haul their own.

Do keep in mind that inheritance items use the same colors as they were in the parent game. The same items in the new game will possibly be of a different color, so not only do these not auto-identify the versions for the new game, but they also will not stack with items of the same type in the new game. To this point, it's pretty helpful to do all your blessings and such ahead of time before you sleep with your mate that night.
Aside from inheriting inventory, the only other "bonus" I can think of from having actual parents is that, if your parent used the Secret Treasure of Lomias (which is randomly dropped by Lomias the Messenger from Vindale, the jerk who kills a beggar and tries to feed you it in the game's beginning), then you will have the Beggar's Pendant artifact in your inventory to start. Thievery protection and the Charisma boost are actually pretty nice to start, and unlike the inherited goods you do not need to use a Deed of Heirship to acquire the pendant.

What are the benefits of procreation?


How to create a `.desktop` launcher for the latest FreeCAD AppImage in Ubuntu 20.04?

Question: I can't seem to create a .desktop launcher for the latest FreeCAD AppImage.
I first tried answer by @UriHerrera but it did not work. Then I included the answer by @vanadium but it did not work too. When I press Super+A keys, I can't see the FreeCAD icon there. Neither does FreeCad icon appears when I pressed the Super key and typed Freecad in search bar. I also tried refreshing gnome-shell by pressing Alt+F2followed by pressing r and Enter but this action did not help either.
Can you tell me my mistake?
Summarising my actions:

I downloaded FreeCAD-0.20  from https://www.freecadweb.org/index.php into ~/.local/bin.

Executed:
 $ chmod +x ~/.local/bin/FreeCAD-0.20.0-Linux-x86_64.AppImage
 $ ~/.local/bin/FreeCAD-0.20.0-Linux-x86_64.AppImage --appimage-extract
 $ cp ~/.local/bin/squashfs-root/freecad_weekly.desktop ~/.local/share/applications/freecad_weekly.desktop
 $ mkdir ~/.local/share/icons/FreeCAD/
 $ cp ~/.local/bin/squashfs-root/freecad_weekly.svg ~/.local/share/icons/FreeCAD/freecad_weekly.svg
 $ xprop | grep WM_CLASS
 WM_CLASS(STRING) = "gnome-terminal-server", "Gnome-terminal"
 $ gedit ~/.local/share/applications/freecad_weekly.desktop

Changed
 [Desktop Entry]
 Version=1.0
 Name=FreeCAD Weekly
 Exec=AppRun
 Icon=freecad_weekly
 Type=Application
 Categories=Engineering;
 Comment=Feature based Parametric Modeler
 Terminal=false
 StartupNotify=true
 NoDisplay=false
 MimeType=application/x-extension-fcstd;

to
 [Desktop Entry]
 Version=1.0
 Name=FreeCAD Weekly
 Exec=$HOME/.local/bin/FreeCAD-0.20.0-Linux-x86_64.AppImage
 Icon=$HOME/.local/share/icons/FreeCAD/freecad_weekly.svg
 StartupWMClass="gnome-terminal-server","Gnome-terminal"
 Type=Application
 Categories=Engineering;
 Comment=Feature based Parametric Modeler
 Terminal=false
 StartupNotify=true
 NoDisplay=false
 MimeType=application/x-extension-fcstd;

Also tried StartupWMClass=gnome-terminal-server Gnome-terminal but this did not work too.
Update: Why does the Freecad icon not show properly?

Outcome from updating ~/.local/share/applications/freecad_weekly.desktop to:
[Desktop Entry]
Version=1.0
Name=FreeCAD Weekly
Exec=freecad
Icon=freecad_weekly
Type=Application
Categories=Engineering;
Comment=Feature based Parametric Modeler
Terminal=false
StartupNotify=true
NoDisplay=false
MimeType=application/x-extension-fcstd;

Answer: Almost there. Replace $HOME by the actual pathname. .desktop files do not know about bash variables.
Tips:

You can leave out the path names. Since ~/.local/bin is in your path, and .local/share/icons is a location where icons are searched, it is sufficient to just mention the file name of the executable, i.e., Exec=FreeCAD-0.20.0-Linux-x86_64.AppImage and the file name of the icon without the extension, i.e.,  Icon=freecad_weekly.

Personally, I would rather place the AppImage file in a directory "~/.apps" and create a symlink to it in ~/.local/bin, e.g. ln -s ~/.apps/FreeCAD-0.20.0-Linux-x86_64.AppImage ~/.local/bin/freecad. The line now becomes Exec=freecad. That way you can

Run the program conveniently from the terminal using the command freecad.
When you later download an updated appimage, it will be sufficient to recreate the link to have it point to the new version.
Comment: Thanks. I have attached to my question an imaged of the freecad icon which is not showing correctly. Why is this so?
Comment: Also, with or without `StartupWMClass="gnome-terminal-server","Gnome-terminal"`, the "freecad" icon appears. Is this statement still needed?
Comment: Since I am not on your system, I cannot verify whether the icon is a valid graphics file and whether it effectively is in a correct location. Perhaps the icon file needs to be right under ~/.local/share/icons/ for it to work with the name alone (although systemwide once certainly can have subdirs).
Comment: You are right. The icon file needs to be right inside `~/.local/share/icons/` and not inside a subdir. I should have done `$ cp ~/.app/squashfs-root/freecad_weekly.svg ~/.local/share/icons/freecad_weekly.svg`.


android no applications can perform this action error

Question: So I'm having a problem when trying to choose a file from the storage in my android app. I'm using the Emulator to try this out but when pressing the button I get No app can perfrom this action. I have no idea why so I need some help.
Code:
So please help me out guys! Thanks!
Comment: I changed the MIME type to * / * and now it works fine. :)
Comment: You don't have an app which accepts that intent. Make your own file opener.
Comment: What makes you think that `file/*` is a valid MIME type?
Answer: file/* is not a valid MIME type so android cannot find a suitable application to handle your Intent. Use a proper MIME type for the file you'd like to open.


Ember Routing with renderTemplate and setupController

Question: I am building an Ember app to show a simple Twitter-like tagging system. When a user visits /items, he or she will see a list of all items. When the user visits /tags, the user will see a list of tags as links. When the user clicks one of these links, the user should be directed to /tags/:id and will see all items tagged with that specific tag. Then the user will be able to search/sort/manipulate the items as he/she would be able to from the ItemsRoute.
How can I make TagRoute use ItemsController and render the items template, using the tag's associated items as the model?
I have tried different combinations of the hooks in TagRoute, and I'm not able to find a recipe that works. There seems to be a fundamental misunderstanding on my part.
Here is my relevant code:
router.js.coffee
App.Router.map ()->
  @resource 'items'
  @resource 'tags', ->
    @resource 'tag', path: ':tag_id'

routes/tag.js.coffee
App.TagRoute = Ember.Route.extend
  model: (params)->
    @get('store').find 'tag', params.tag_id
  controllerName: 'items'
  setupController: (controller, model)->
    @controllerFor('items').set('model', model.items)
  renderTemplate: ->
    @render 'items', ->
      into: 'tags'
      controller: 'items'

templates/tags.hbs

  {{#each tag in model}}

    {{#link-to 'tag' tag}}
      {{tag.name}}
    {{/link-to}}

  {{/each}}

{{outlet}}

models/items.js.coffee
App.Item = DS.Model.extend(
  body:       DS.attr('string')
  checked:    DS.attr('boolean')
  tags:       DS.hasMany('tag')
)

models/tags.js.coffee
App.Tag = DS.Model.extend(
  name:             DS.attr('string')
  taggings_count:   DS.attr('number')
  items:            DS.hasMany('item')
)

Currently, this give me an error:
Error while processing route: tag Cannot assign to read only property 'name' of function () {
        return {
          into: 'tags',
          controller: 'items'
        };
      } TypeError: Cannot assign to read only property 'name' of function () {
        return {
          into: 'tags',
          controller: 'items'
        };
      }

Looking at the Ember Routes Inspector in Chrome, the controllerName property is the only one which overrides Ember's defaults, and Ember still tries to render a generated tag template.
Comment: Bidirectional has many mappings are always making things more complicated. How about linking back to items with a query param?tag. Then you could pass it to the model and show only items with that tag. No need for a tags/:id route. Just link to items with query param {tag;tagname}
Comment: Its transparent if your backend can process /items?tag={tag} or /items?tagId={tag.id}. This would be a filter, not an associated model. Im doing the same thing for a different case and it works like a charm. Just make tag or tagId a queryParam in your itemsController.
queryParams: {
  page: {
   refreshModel: true
  },
Pass the tag/tagId as a queryParams in your links/ transitionTo calls and thats it. I dont think there is any drawback using a filter a like that.
Comment: Could you put this code into a JSBin?
Comment: @Gaurav I'm not sure how to do routing in a JSBin, but here is the link: [link](http://emberjs.jsbin.com/zeyodabise/1/edit?html,js,output). I hope what is there is helpful. My latest idea was to have the `TagRoute` redirect to a `TagItemsRoute`, but I'm having similar problems there. For example, ember generates a `'tag/items'` template instead of using my specified `'items'` template.
Comment: @ahmed.hoban Is it possible to filter a model by an associated model, using queryParams set in the controller? I'm trying it out. My understanding was that queryParams were best used for things like filtering and sorting on a model's attributes, and that routing was best for finding models by associations.
Comment: @ahmed.hoban Thanks! I tried it out and it works!
Answer: As ahmed.hoban suggested, I have solved this using query params. This helps me avoid duplicating routes and having a tangled router. It hits the database, which is not preferable, but I'm not sure at this point if I'll make that a requirement. I have control over the full-stack, so I was able to make adjustments on the back-end to support the request.
router.js.coffee
App.Router.map ()->
  @resource 'tags', path: '/', ->
    @resource 'items'

routes/tag.js.coffee - deleted
templates/tags.hbs

  {{#each tag in model}}

    {{#link-to 'items' (query-params tag=tag.id)}}
      {{tag.name}}
    {{/link-to}}

  {{/each}}

{{outlet}}

controllers/items.js.coffee
App.ItemsController = Ember.ArrayController.extend(
  needs: 'tags'

  queryParams: ['tag']
  tag: null

  items: (->
    tag = @get 'tag'
    if tag
      @store.find 'item', tag: tag
    else
      @get 'model'
  ).property('tag', 'model')
)

Comment: nice. But why dont you just pass the tag to your route? It will be available in params:
model: function(params) { this.store.find('item', params)} no need for "if tag" in your controller. If no tag is set, no tag query param is passed to the server. Then you dont need the items computed property but just the model. You can, in your route, declare queryParams and add the "refreshModel" property. Whenever a queryparam on the controller is changed, the model will be refetched automatically. Magic of ember.
Comment: So in your route:
App.ItemsRoute = Ember.Route.extend({
  queryParams: {
    tag: {
      refreshModel: true
    }
  },
model : function(params) {
  this.store.find('item',params);
}


How do I season wood on my own?

Question: Just what the title asks. Earlier today a tree on our premises split in two in heavy winds. The tree is of a variety referenced 'सागवन' in the vernacular, and Central Provinces Teak else-wise - that it topped itself is extremely surprising, and uncommon!
After trimming the foliage, and off-shoots I hope to season it. After taking a quick gander at the various notes on seasoning posted online, here's what I find myself wondering

Is wood seasoned with, or without the bark?
Should I simply leave the log lying on the ground? It is a fairly hard kind, and the fallen length (approx. 50 ft) far too heavy to lift.
Need I take any precautions against warp/split?

p.s. I'm told grand-dad seasoned wood letting it lie up-to 10 years thus!
Comment: You want it for making stuff with or for firewood?
Comment: If it's teak, I sure hope it's not for firewood! :)
Comment: Had to ask... you never know, but I should have read more carefully
Comment: @Jack - Sad fact, we burnt Luan Mahogany out of Southeast Asia for several decades. The plywood plant where my father worked imported the veneer and the stickers used to bundle it were reject leftovers either given away to the employees or burnt in the boiler furnace. We got it by the truckload, used what we could and burnt the rest. I have some of another type that's a kind of dense Ironwood like material that I use as a kindling chopping block.
Comment: @Jack Not fire-wood (+: If it ever becomes fire-wood, let it be my pyre
Answer: From my experience with Walnut, etc.
You slab it with the bark on, oversize so there is excess stock to work with when planed to final dimension and stack the flitches with stickers between them to keep them separated. The base they're stacked on needs to be flat, the storage sheltered from rain and extremes of weather.
Paint the end grain to slow down moisture movement in aid of reducing checking and minimizing splitting.
When properly dried out, the flitches get resawn and then sent to the planer for finished dimension or sent to the veneer mill to be sliced down into sheets.
A local business, Wagner Electronics, produces moisture meters that are used to determine when wood is seasoned to the proper moisture content. Slow is good. Note: not an affiliate of any kind with the company, just relating how the professionals determine seasoning speed and finish.
Flitch: a piece of wood that is to be resawn or sliced for veneer.
Sticker: thin pieces of wood used to separate flitches or veneer stacks.
Comment: Anything that plugs the pores. Thick white exterior latex. You want to prevent water transport in and out of the wood via the way it normally flows so the ends don't dry out faster than the middle.
Comment: Any recommendations on what to paint the end with?
Answer: सागवन in Marathi translates to Sāgavana which is a Hindi word for teak.  This is a common wood in the tropics, uncommon in the subtropics, and rare to nonexistent in temperate and colder areas.
If it is dried (which is what seasoning means) slowly, it is less likely to warp and split.  This would be ideal for woodworking uses such as making decking, furniture, etc.  Cut the log into suitable lengths (3–5 meters), raise them off the ground and leave the bark intact.  In a warm, dry climate, they should season in less than two years; for humid climates, it could take 2–5 years.
If the wood is to be used as firewood, cut it up and split it into convenient burnable pieces and stack them off wet ground.  Protecting the stacks from moisture—rain, condensation, etc.—is usually enough for them to burn cleanly in 9 to 12 months, even if there is frequent high humidity.
Comment: I'm curious. Any particular reason to reduce it's length before seasoning (other than the fact that 50ft is plain unwieldly)?
Comment: @Everyone:  more exposed surfaces help speed up drying, besides making it easier to move and better for stacking and storage.

How do I season wood on my own?


Cleaning up tweets before sentiment analysis on cryptocurrencies

Question: I am trying to analyse twitter sentiment and right now I have a code which scrapes tweets from twitter with API and puts them in an excel file followed by their sentiment score, however I want to try and clean these tweets before they are put into the excel file and before they are analysed through the google cloud NLP.
below is the code that scrapes the tweets
    while tweetCount < maxTweets:
    if(maxId <= 0):
            newTweets = api.search_tweets(q=hashtag, count=tweetsPerQry, lang="en",
    result_type="recent", tweet_mode="extended")
    else:
                newTweets =  api.search_tweets(q=hashtag, count=tweetsPerQry, lang="en",
    max_id=str(maxId -1), result_type="recent", tweet_mode="extended")

    if not newTweets:
            print("Tweet habis")
            break

    for tweet in newTweets:
            d={}
            d["text"] = tweet.full_text.encode('utf-8')
            print (d["text"])
            listposts.append(d)

    tweetCount += len(newTweets)
    maxId = newTweets[-1].id
    print (listposts)

and below is the code that cleans tweets
def clean_tweet(tweet):
if type(tweet) == np.float:
    return ""
temp = tweet.lower()
temp = re.sub("'", "", temp) # to avoid removing contractions in english
temp = re.sub("@[A-Za-z0-9_]+","", temp)
temp = re.sub("#[A-Za-z0-9_]+","", temp)
temp = re.sub(r'http\S+', '', temp)
temp = re.sub('[()!?]', ' ', temp)
temp = re.sub('\[.*?\]',' ', temp)
temp = re.sub("[^a-z0-9]"," ", temp)
temp = temp.split()
temp = [w for w in temp if not w in stopwords]
temp = " ".join(word for word in temp)
return temp

tweets = [""]

results = [clean_tweet(tw) for tw in tweets]
results

somehow I want to combine these two pieces of code so that the tweets go into the clean_tweet function before being put into the excel file and thus also being analysed on sentiment.
Comment: Are you asking how to write them to an excel file? Or how to call your `clean_tweet` function from your scraping code?
Comment: how to call my clean_tweet function from scraping the code
Answer: Suppose you have the following function to clean tweets (this is just your function with indentation fixed):
def clean_tweet(tweet):
    if type(tweet) == np.float:
        return ""
    temp = tweet.lower()
    temp = re.sub("'", "", temp) # to avoid removing contractions in english
    temp = re.sub("@[A-Za-z0-9_]+","", temp)
    temp = re.sub("#[A-Za-z0-9_]+","", temp)
    temp = re.sub(r'http\S+', '', temp)
    temp = re.sub('[()!?]', ' ', temp)
    temp = re.sub('\[.*?\]',' ', temp)
    temp = re.sub("[^a-z0-9]"," ", temp)
    temp = temp.split()
    temp = [w for w in temp if not w in stopwords]
    temp = " ".join(word for word in temp)
    return temp

Your other block of code has some problems that I'm not fixing here; for example, listposts is never defined, before you try to append to it. You also might have some indentation issues. With that in mind, you can call the function as follows:
tweetCount = 0

while tweetCount < maxTweets:
    if(maxId <= 0):
            newTweets = api.search_tweets(q=hashtag, count=tweetsPerQry, lang="en",
    result_type="recent", tweet_mode="extended")
    else:
            newTweets =  api.search_tweets(q=hashtag, count=tweetsPerQry, lang="en",
    max_id=str(maxId -1), result_type="recent", tweet_mode="extended")

    if not newTweets:
            print("Tweet habis")
            break

    for tweet in newTweets:
            print("Tweet before cleaning:", tweet, sep="\n")
            tweet = clean_tweet(tweet)
            print("Tweet after cleaning:", tweet, sep="\n")
            listposts.append(d)

    tweetCount += len(newTweets)
    maxId = newTweets[-1].id
    # Instead of just printing listposts, this is where I would
    # write each entry of it to a line in a csv file


How does retrieving the Poke balls actually work?

Question: So, when you throw a ball and you miss, the ball rolls around. You can click on it to get it back and not waste 20 balls on a Pidgey. Well, this works sometimes, and the ball is just laying there, behind the pokemon, but most of the time, the ball disappears almost immediately without me clicking on the screen or anything and its not back in my inventory ? SO what's going on, am I retrieving my balls wrongly or are they disappearing by design ?
Comment: it only works when AR mode on.
and its just skipping miss animation, not retrieving missed pokeballs
Answer: It doesn't work.
You cannot retrieve thrown balls. Once you a throw a ball it is gone from your inventory regardless of if you miss, you hit and catch it or you hit and it escapes.
Comment: @DeMize IGN is wrong, it's a rumor that people keep spreading but is incorrect
Comment: According to IGN, you can get thrown pokeballs back by clicking on them.
Comment: @DeMize prove it.
Comment: @DeMize Yeah I tried, doesn't work, the count still goes down ...


When are language-specific questions allowed?

Question: This post pertains only to questions that ask only about and engage one language.
I already read this and the following reason which has been alleged of many of my own questions:

"Language-specific grammar and usage questions are off-topic unless primarily concerned with linguistics rather than usage. There are many language-specific sites where such questions are welcomed; see: http://stackexchange.com/sites"

I comprehend that prescriptive questions (eg: of usage) are off-topic, but what of  questions necessitating linguistics knowledge about a specific language?
For example, though language-specific sites feature native speakers, they may not be linguists and so would be unable to answer a question as helpfully or meaningfully as here. For example, this question presupposes knowledge of the linguistic definition of 'tone' and 'intonation', and so would necessitate a linguist's attention, not simply anyone who knows Latin. The same problem exists for questions of Historical Linguistics for one language X; for example, most native speakers of X cannot connect an English or French Word to Proto-X as only a linguist can.

Example Question as a Test:
Title: How else might the Latin 'torrere' have drifted semantically to mean 'rushing, roaring (of streams)'?
Question:

[Etymonline] [...] from Latin torrentem (nominative torrens) "rushing, roaring" (of streams), also "a rushing stream," originally as an adjective "roaring, boiling, burning, parching, hot, inflamed," present participle of torrere "to parch" (see terrain).

Google revealed only one conjecture:

So, what could be the connection between a rushing stream and something which is dried out, thirsting for some water?
Supposedly, the contrasting meanings are linked by the image of a mountain creek or river which may be a raging current in spring, but dries out in summer.

Somehow the above is unpersuasive, probably because:

most raging streams do not dry;
it is factually false to refer to a dried raging stream still as a `raging stream``; one would have said 'dried raging stream'. 'dry' and 'rushing, roaring' are polar opposites;

I know that etymology is subjective and speculative, but are there any other conjectures that might possess more conviction?
Comment: cf. http://latin.stackexchange.com/q/19/37
Answer: In my mind, if a question is about some aspect of a language which is essentially arbitrary, then it's off topic. Meaning, usage, semantic drift of particular words, etc should all be off topic.
If a question is about a system, then it's on topic. Systems could cover phonetics, morphology, syntax, semantics, sociology, or any other field of linguistics, and questions about them can be synchronic or diachronic. You may only ask about one language, and the specific system may only be known to exist in one language, that's fine.
Answer: I take my chance to answer here because I've seen many questions asked by the OP, and, to my opinion, many of these questions are language-specific.
Closing questions as "Language-specific" has pretty straightforward reasons. This reason is, whether or not this question is answerable in this very site.
In order to answer questions that only apply one language, this requires having someone who's also familiar with this very language. Which is not given for granted.
In addition, these narrow questions seem to be hardly useful for further visitors who come here in the future.

So, to avoid our questions being closed as "language-specific", we maybe should ask ourselves:

Is there anyone in Linguistics.SE who may answer this question?
How possible it is that this very question would also serve future visitors to the site?

P.S. As I mentioned in another answer, we the users shape this community. If you can find several prominent people who would be able to answer your questions, the community may turn much more loyal to this kind of questions.
Comment: 1. You wrote `Closing questions as "Language-specific" has pretty straightforward reasons.` but the reasons do not appear straightforward at all, given the number of questions particular to French here. 2. `In addition, these narrow questions seem to be hardly useful for further visitors who come here in the future.` : This appears biased, subjective, and even false. Why are the other questions specific to French open permitted and open?
Answer: You should read this thread. As you can see, I believe that the characterization of what is "language specific" needs to be sharpened up. There is some disagreement among participants as to the extension of "not language-specific". I propose that the present question will not yield any new information. However, if you propose a statement of the language-specific criterion and ask for commentary on the proposal, you might move the discussion forward. The previous discussion should help you to avoid beating your head on the wall.
[Edit]
Anyhow, a question should be about facts or theories and not what is proper or similar normative questions. It should be generalizable, so for example "What is the accusative singular of 'chicken' in Russian?" would be off-topic, but "How is the accusative singular formed in Russian?" would be appropriate (though it reveals a false presupposition). Asking such questions about two or three languages doesn't avoid the problem.
Comment: Thanks, but I think that I already read that article, which I already cited in my OP?
Answer: Every question should have a place to ask it.  If there is a better place to ask a language specific question than here, then ask it there.  Otherwise, come here.


Trouble in Setting Java Environment Path on Ubuntu (libjvm.so: cannot open shared object file: No such file or directory)

Question: Found the solution!
Ubuntu by default ignore the command "RD_LIBRARY_PATH" therefore I need to add those codes in ".bashrc" instead of "/etc/environment" or .profile.
it now work perfectly fine!

I am trying to run a program that reads Java method from C/C++ code. (I made it on Windows successfully, now, I am working on Linux)
I made it successfully compiled and run on Ubuntu, however, the problem is..
Whenever I try to run the program, I have to type following commands on terminal..
source /etc/environment
./invoke #program name is invoke

If I do not type "source /etc/environment" every time I boot my PC, the error message I get is...
error while loading shared libraries: libjvm.so: cannot open shared object file: No such file or directory

Ok. Here is what I added in /etc/environment
export PATH="$PATH:/usr/lib/jvm/jdk1.7.0_25_x64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"
export JAVA_HOME=/usr/lib/jvm/jdk1.7.0_25_x64
export LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/amd64:$JAVA_HOME/jre/lib/amd64/server

What I want is that, as you know, I want to run the program without typing "source /etc/environment".
I also tried typing those PATHs on /etc/profile, but result was same... I should type "source /etc/profile" every time I reboot my PC..
How to make it permanently applied to whole range of System without typing "source /etc/environment" stuffs everytime I boot?
if you need to see source code of the program, here is downloadable address:
http://cfile237.uf.daum.net/attach/247819495212DF1C07B9EB
Comment: This is off-topic for SO, but that's *not* how `/etc/environment` woks on Ubuntu. It's not a script file to be sourced which is why what you have in there doesn't work on boot / login.
Answer: This worked for me:
For x86:
export LD_LIBRARY_PATH=/usr/lib/jvm/default-java/jre/lib/i386:/usr/lib/jvm/default-java/jre/lib/i386/server

For x86_64
export LD_LIBRARY_PATH=/usr/lib/jvm/default-java/jre/lib/amd64:/usr/lib/jvm/default-java/jre/lib/amd64/server

Answer: I had the same problem of setting the path(permanently) however I was using Red Hat, If you look change PATH permanently on Ubuntu it might help you. There was a file on Red Hat .profile that once you add your exports statements, they will get loaded when the computer starts. :) There should be the kind of file for ubuntu
export     PATH="$PATH:/usr/lib/jvm/jdk1.7.0_25_x64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"

export JAVA_HOME=/usr/lib/jvm/jdk1.7.0_25_x64
Comment: Ok. tried to write things in "~/.profile" However it was same. I had to type ". ~/.profile" everytime I reboot to make it work, otherwise it does not work.. well the problem is if I do not type ". ~/.profile"  and then type "echo $LD_LIBRARY_PATH", it shows nothing. however, if I type ". ~/.profile" then it shows PATH written in "~/.profile"
Comment: I suppose that you edited .profile or .bash_profile depending on which one you have, this would give you an idea.vi .bash_profile
add: export [VARIABLE]=/variable/path/
        export PATH=${VARIABLE}/bin:$PATH
Then esc :wq Enter
Answer: Put "-Djava.library.path=FULL_PATH_HERE/jre/lib/amd64" as a JVM option in your C code.
Edit the full_path_here part.
The path is allowed to be relative, but I don't think you can use $JAVA_HOME as a placeholder for the environment variable.
Comment: Xabster > I am sorry It didn't work. I changed corresponding C code to options[0].optionString = "-Djava.library.path=/usr/lib/jvm/jdk1.7.0_25_x64/jre/lib/amd64/server"; but it did not work.
Comment: Xabster > it also did not work after I changed /etc/environment to "export PATH="$PATH:/usr/lib/jvm/jdk1.7.0_25_x64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"
export JAVA_HOME=/usr/lib/jvm/jdk1.7.0_25_x64
export LD_LIBRARY_PATH=/usr/lib/jvm/jdk1.7.0_25_x64/jre/lib/amd64:/usr/lib/jvm/jdk1.7.0_25_x64/jre/lib/amd64/server"
Comment: Please confirm that the libjvm.so file is in the amd64/server folder. I didn't expect it to be there, but I could be wrong. I don't understand the last thing you tell me. What did you change in etc/environment that made it stop working? I'm trying to give you C-code that will allow the JVM to find the libjvm.so file without you changing global environment variables. Please also confirm that you're getting the same error since you removed the java.class.path VM option.
Comment: Yes, libjvm.so file is in amd64/server folder. yes, same error occured.
Answer: Found the solution!
Ubuntu by default ignore the command "RD_LIBRARY_PATH" therefore I need to add those codes in ".bashrc" instead of "/etc/environment" or .profile.
it now work perfectly fine!
Answer:
add the path of the missing libraries in the file /etc/ld.so.conf
execute the following command: ldconfig
this way, you'll add the new libraries to the default ones.
To check whether the new libraries have been linked,
execute the following command: ldconfig -p
to have the list of libraries currently linked by default.


Can the whole prologue be skipped with other method than using saves?

Question: Every time I restarted the game, I had to go through the whole "walking cinematic" with Dr. Reed, where the game doesn't prompt any means to skip it.
The reason why I'm asking about not using a save method, is because of the use of mods: he game crashes when loading an unmodded game or one that won't coincide with game's mechanics.
I was wondering if devs made about some deep mechanism about it (maybe a hidden console thing, starting the game with parameters, etc) though I haven't found any so far.
Game has some modding potential, but it seems that nobody made a mod to skip the whole prologue (starting at Sarif, augmented, 6 months later).
Answer: It does not seem so. However, by using a glitch, you can skip most of it.
Answer: An alternative, though not ideal, is to install the Map Selector mod. After all, debug menus are dev/cheat tools.
If never played before, the player would have the power to be auto-spoiled by the places the player would go through canonically. Also, once inside the menu, the player cannot exit the menu until choosing a map!
Lucky for me, I finished this game a long time ago, and judging by the start of the map selector's menu, it's in canon-chronological order. Also has an unused, more tutorial-oriented version of the prologue-escape map.
Comment: Do be careful of choosing to install the Debug Menu mod (displayed in the linked post). Personally I got tempted trying some stuff from the get go as soon as I opened it, and ended up with Steam rewarding me the [Transhumanist](https://steamcommunity.com/stats/DXHR/achievements/) achievement (getting all upgrades of an aug) by accident, when all I wanted was to try removing the Infolink augment to see how the game would respond.


PHP use static function to create new instance w/ Inheritance

Question: So I got this idea from Laravel. With Laravel you can do something like the following.
$user = new User;
$user->where('name', 'george')->get();

// which is the same as...

User::where('name', 'george')->get();

So I'm guessing the User class has a __callStatic setup so it makes a new instance as a fallback. I was able to replicate that using the following code.
class Driver
{
  protected static $instance = null;

  public static function __callStatic($name, $args) {
    $classname = get_called_class();
    if (empty(static::$instance)) static::$instance = new $classname;
    return static::$instance->$name(...$args);
  }
}

But a problem occurs when I try to inherit the class more than once. I want all classes to be able to inherit the __callStatic and be able to call any of their ancestor's public functions statically.
class A extends Driver
{

  public function hello() {
    echo "hello";
    return $this;
  }

  public function world() {
    echo " world";
    return $this;
  }

}

class B extends A
{
  public function name() {
    echo "\nMy Name is George";
    return $this;
  }
}

class C extends B
{
  // class can be empty
}

C::hello()->world()->name();

// returns: hello world
// My name is George

Comment: And the problem is?
Answer: The problem you face is due to the $instance property being static, and declared on the parent class. There is only one instance property in your project, it's a class property of Driver.
There are several ways around this. You could define $instance on the subclasses, make Driver::$instance a map (array) as [className => instance], or better yet, get rid of that piece of global state entirely ;)
The whole concept of having a "singleton-like" $instance structure is probably going to cause more problems later on, anyway. Consider the following example:
class Foo extends Driver
{
  private $name;
  public function named(string $name) : self
  {
    $this->name = $name;
    return $this;
  }
  public function name() : string
  {
    return $this->name;
  }
}

$alice = Foo::named('Alice');
$bob = Foo::named('Bob');

echo $alice->name(); // Outputs "Bob"!

$alice still points to the original instance, but since Foo::named('bob') assigns the name bob to that very same instance, you accidentally renamed Alice into Bob.
What you're probably looking for is more like:
abstract class Driver
{
  public static function __callStatic(string $name, array $arguments)
  {
    $instance = new static;
    $instance->$name(...$arguments);
    return $instance;
  }
}

That way, you'll create new instances every time.
Comment: PS: Laravel, or I should say Eloquent, is an Active Record ORM. IMHO, that's a Bad Thing and ought to be avoided as much as possible. Just deserialise your objects with something decent, like a Data Mapper ORM :D


Image storage as byte code locally from XML parsing & display if it is stored Otherwise go for parsing.

Question: I am having an app in which at the time of launcing the app XML parsing is giving Main category from URL like hp, dell, etc...I am displaying it in the Tableview.
Then on click of particular cell i can get the detail of main category means its subcategory like http://www.dealsbell.com/findcoupon.php?store=hp
Here also i am getting data properly after parsing.
But my concern over here is, in ( http://www.dealsbell.com/findcoupon.php?store=hp ) this link i am getting images.
Each particular subcategory will have a same image. So i want to do something like that the image if first time loaded from the URL then it will display image from parsing otherwise i would like to store that image as its byte code in folder / file / in any way in my device on first parsing.
If once the image is stored to the particular way in my device next time when i will go to see the subcategory it will first check this image is stored locally to my device or not.
If yes then it should go to the particular location to fetch this local image & display it to each cell otherwise will parse & display image.
I hope you are getting, what i want to ask.
Please guide me, how can this be possible & what is the way to get result.
If any example or link you can suggest, then it will be more efficient to me.
Thanks in advance.
Answer: There are probably two ways to achive this.

Get NSData out of Image and hold that in UserDefaults or database.
Dump image in application folder and pick image from that place.

So whenever you try to load image for subcatogory check at one of place and if present use that. IF in case you have stored image and if any updated image comes,then remove previous copy and store new one.
<code>-(void) SaveImageinDocumentWithName:(UIImage*) aUIImage Name:(NSString*) aName
{
    if(aUIImage)
    {
        NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSMutableString* str = [[NSMutableString alloc] initWithCapacity:300];
        [str appendString:documentsDirectory];
        [str appendString:@"/"];
        [str appendString:aName];

        NSFileManager *fileManager = [NSFileManager defaultManager];
        [UIImagePNGRepresentation(aUIImage) writeToFile:str atomically:YES];

        if(str)
        {
            [str release];
            str = nil;

        }
        if(fileManager)
        {
            [fileManager release];
            fileManager = nil;
        }

        [pool release];
    }

}
</code>
-- Getting saved image
<code> -(UIImage*)GetSavedImageWithName:(NSString*) aFileName
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSMutableString* str = [[NSMutableString alloc] initWithCapacity:300];
        [str appendString:documentsDirectory];
        [str appendString:@"/"];
        [str appendString:aFileName];

        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL success = [fileManager fileExistsAtPath:str];

        NSData *dataToWrite = nil;

        UIImage* image = nil;

        if(!success)
        {

        }
        else
        {
            image = [[UIImage alloc] initWithContentsOfFile:str];
        }
        if(dataToWrite)
        {
            [dataToWrite release];
            dataToWrite = nil;
        }

        if(str)
        {
            [str release];
            str = nil;
        }

        if(fileManager)
        {
            [fileManager release];
            fileManager = nil;
        }
        return image;
    }
</code>
Comment: using this code any document will be generated....?

if yes then where it will be located...?

i am not getting this in finder...
Comment: yes it will generate file. if you are running on 5.0 simulator it will be under /Library/Application Support/iPhone Simulator/5.0/Applications / Ur application
Comment: i am calling this methods from

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

}
Comment: Then u will have to call GetSavedImageWithName:(imagename)
Comment: i am using XCode 4.1 and iOS 4.3
Comment: i am calling both methods from cellForRowAtIndexPath method....

        UIImage *imageView;
            NSString *strImage = [NSString stringWithFormat:@"%@",aBook.image];
            NSURL *url4Image = [NSURL URLWithString:strImage];
            NSData *data = [NSData dataWithContentsOfURL:url4Image];
        if(data != NULL) {
            imageView =[[UIImage alloc] initWithData:data];
        }
        else{
            imageView =[UIImage imageNamed:@"icon.png"];
        }
        [self SaveImageinDocumentWithName:imageView Name:strImage];
        [self GetSavedImageWithName:strImage];
Comment: This is the NSLog at the time of saving image

Printing description of paths:
(
    "/Users/apple/Library/Application Support/iPhone Simulator/4.3.2/Applications/121FD761-207F-4B94-B45B-146226ECAE04/Documents"
)
Printing description of str:
/Users/apple/Library/Application Support/iPhone Simulator/4.3.2/Applications/121FD761-207F-4B94-B45B-146226ECAE04/Documents/http://www.dealsbell.com/wp-content/uploads/mobile/hp.gif
Comment: aBook.image is:--> http://www.dealsbell.com/wp-content/uploads/mobile/hp.gif

"...Here in place of hp.gif the dynamic category name can be..."
Answer: Parse dealsbell.com/wp-content/uploads/mobile/hp.gif  and take only hp.gif
<code>NSString *strImage = [NSString stringWithFormat:@"%@",aBook.image];

UIImage* image = [self GetSavedImageWithName:strImage];

if(image) // This means Image exists
{
  // Do what you want
}
else
{
    NSURL *url4Image = [NSURL URLWithString:strImage];

    NSData *data = [NSData dataWithContentsOfURL:url4Image];

    if(data != NULL)
    {
       image =[[UIImage alloc] initWithData:data];
       [self SaveImageinDocumentWithName:image Name:strImage]; // save for future ref.
    }
    else
    {
      image =[UIImage imageNamed:@"icon.png"];
    }
 }
</code>
Comment: http://www.dealsbell.com/wp-content/uploads/mobile/hp.gif

...this is a value of XML tag, you can find this on...  http://www.dealsbell.com/findcoupon.php?store=hp....


NoSuchElementFound Exception while trying to run my code - what's wrong?

Question: I wrote a program to simulate the logic gates operations. My code is as follows,
import java.io.*;
import java.util.Scanner;

// This program simulates the logic gates operations for the given input
class GatesSimulator
{
    int input1, input2, output;
    boolean boolInput1, boolInput2, boolOutput, validate = true;

    void simulateAndGate()
    {
        getInput();
        boolOutput = boolInput1 & boolInput2;
        showOutput("AND");
    }

    void simulateOrGate()
    {
        getInput();
        boolOutput = boolInput1 | boolInput2;
        showOutput("OR");
    }

    void simulateNotGate()
    {
        System.out.println("Under Development");
    }

    void simulateXorGate()
    {
        getInput();
        boolOutput = boolInput1 ^ boolInput2;
        showOutput("XOR");
    }

    void simulateNandGate()
    {
        getInput();
        boolOutput = !(boolInput1 & boolInput2);
        showOutput("NAND");
    }

    void simulateNorGate()
    {
        getInput();
        boolOutput = !(boolInput1 | boolInput2);
        showOutput("NOR");
    }

    void getInput()
    {

        Scanner simInput = new Scanner(System.in);

        while (validate)
        {

            // Scanner simInput = new Scanner(System.in);
            System.out.println("First Input:  ");
            input1 = simInput.nextInt();

            System.out.println("Second Input:  ");
            input2 = simInput.nextInt();
            // simInput.close();
            if ((input1 == 1 || input1 == 0) && (input2 == 1 || input2 == 0))
            {
                boolInput1 = (input1 == 1) ? true : false;
                boolInput2 = (input2 == 1) ? true : false;
                validate = false;
            }
            else
            {
                System.out.println("Enter a Valid Input(1/0)");
            }
        }
        simInput.close();
    }

    void showOutput(String gate)
    {

        output = (boolOutput == true) ? 1 : 0;
        System.out.println(input1 + " " + gate + " " + input2 + " = " + output);

    }
}

class Operations
{
    int choice;
    GatesSimulator simulator = new GatesSimulator();
    boolean contd = true;

    void chooseOperation()
    {

        Scanner input = new Scanner(System.in);

        while (contd)
        {
            System.out
                .println("Enter Your Choice of Simulation\n\t1 -> AND         Gate\n\t2 -> OR Gate\n\t3 -> NOT Gate\n\t4 -> XOR Gate\n\t5 -> NAND Gate\n\t6 -> NOR Gate\n\t7 -> Exit");
            // Scanner input = new Scanner(System.in);
            choice = input.nextInt();
            // input.close();
            switch (choice)
            {
            case 1:
                simulator.simulateAndGate();
                break;
            case 2:
                simulator.simulateOrGate();
                break;
            case 3:
                simulator.simulateNotGate();
                break;
            case 4:
                simulator.simulateXorGate();
                break;
            case 5:
                simulator.simulateNandGate();
                break;
            case 6:
                simulator.simulateNorGate();
                break;
            case 7:
                contd = false;
                break;
            default:
                System.out.println("\tEnter A valid Choice(1 to 7)\t");
            }
        }
        input.close();
    }
}

public class LogicGatesSimulator
{
    public static void main(String args[])
    {
        Operations gates = new Operations();
        System.out.println("\t\t\tLogic gate Simulator\t\t\t");
        gates.chooseOperation();
    }
}

I'm getting an Output like:
Exception in thread "main" java.util.NoSuchElementException
     at java.util.Scanner.throwFor(Scanner.java:855)
     at java.util.Scanner.next(Scanner.java:1478)
     at java.util.Scanner.next(Scanner.java:1478)
     at java.util.Scanner.nextInt(Scanner.java:2067)
     at Operations.chooseOperation(LogicGatesSimulator.java:103)
     at LogicGatesSimulator.main(LogicGatesSimulator.java:132)

what's the problem with my code.
Comment: what's the actual problem with my code??
Comment: Isn't this while loop, `while (contd)` just gonna run forever? Maybe `nextInt()` runs out of "next ints" in the for `while(true)` loop.
Answer: You need to use hasNext() before calling nextInt()
    if(scanner.hasNextInt())
        scanner.nextInt();


getting problem on using useContext in react?

Question: I have a simple react app in which i have to use useContext.
(btw im using vite + react)
here is my code for Context.jsx
import React, {useContext} from 'react';

const emailContext = React.createContext();

export const useEmail = () => useContext(emailContext);

export const emailProvider = ({children}) => {
  const currentUser = "None";

  const value = {
    currentUser
  }

  return(
    <emailContext.Provider value={value}>
      {children}
      </emailContext.Provider>
  )
}

and heres how i am using the context
import "./styles.css";
import { useEmail } from "./Context/Context"

export default function App() {

  const {currentUser} = useEmail();

  return (

Hello CodeSandbox {currentUser}

Start editing to see some magic happen!

  );
}

I am sure why I am getting error in this code.
some of the errors that I am getting

_useEmail is undefined (latest)
currentUser user is undefined

thing i have tried

Initialized createContext with some initial value (only intial value is visible).
using useContext() directy in the App.js (useContext(emailContext) return undefined)
instead of {children} used <children/>.
used useState instead of const currentUser in emailProvider

I am getting same problem even when I use typescript.
but none of the above helped.
Comment: I think it's a [vite issue](https://github.com/vitejs/vite/issues/3301).
Comment: I have read some implemetation on the same for global state management with `context api` you can check it out. Provides a detailed look on the global state. Here is the link [Similar implementation](https://stackoverflow.com/questions/69870459/how-manage-global-state-using-context-api-in-react-js)
Answer: You should wrapping app with <emailProvider></emailProvider> to using data in value={value}. Now it gets undefined from const emailContext = React.createContext();
Comment: ```export default function App() {
  var value  = useEmail();
  console.log(value)

  return (

Hello CodeSandbox
Start editing to see some magic happen!

  );
}``` Even after this the code is not working, If place ```value.currentUser``` in the inside the ```EmailProvider``` component it will throw an error
Answer: Below code may help you analyse the flow , also check link for more details  https://medium.com/technofunnel/usecontext-in-react-hooks-aa9a60b8a461
use useContext in receiving end
 import React, { useState } from "react";

var userDetailContext = React.createContext(null);

export default function UserDetailsComponent() {
  var [userDetails] = useState({
    name: "Mayank",
    age: 30
  });

  return (
    <userDetailContext.Provider value={userDetails}>

This is the Parent Component

      <ChildComponent userDetails={userDetails} />
    </userDetailContext.Provider>
  );
}

function ChildComponent(props) {
  return (

This is Child Component

      <SubChildComponent />

  );
}

function SubChildComponent(props) {
  var contextData = React.useContext(userDetailContext);
  return (

This is Sub Child Component

User Name: {contextData.name}

User Age: {contextData.age}

  );
}

Comment: On same file it working, but if the files are different it is not working. Also, I have to pass components dynamically. For the medium page, I cannot view it because it requires subscription.
Answer: in index.js/main.js file
<emailProvider/> <App/> <emailProvider>
this helped me
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


PixelJunk Monsters - Best Stage for the "Construction Expert" Achievement?

Question: In Pixeljunk Monsters, you can get the Construction Expert steam achievement for building 10 towers in less than 30 seconds upon entering any stage.
But even if you buy the cheapest tower, the Arrow Tower, that means you'll need to start out with at least 1,000 gold pieces.  And you need to have the tower positions close enough.
What's the best map to try for this?
Answer: The "easy 3" stage, as seen in this Youtube video:

I remember following it to get that achievement. IIRC, you'll need some of those extra coins that drop from some random trees, but it's doable.


ccpd starting problem in ubuntu 11.10

Question: How can add the following command to start up ?
Now I manually enter this command in each time the computer start up for using Canon LBP 2900 printer
sudo /etc/init.d/ccpd start
Answer: Hare's a complete guide to get Canon's official CAPT drivers installed and automatically starting.
CanonCaptDrv190

ccpd starting problem in ubuntu 11.10


Is there a way to get the behavior pack out of a MCworld file?

Question: I want to get just the behavior pack out of a world but I don't know how. Is this even possible?
I want to be able to put the behavior pack onto a realm and the world that it belongs to but when the behavior pack is on it refuses to upload the map to the realm.
I got it from MCPEDL so it is not from the marketplace.
Answer: Extracting
Just open the .mcworld file with an archiver e.g. WinRAR.  Then go to the behavior_packs folder and extract your behavior pack.  If the behavior pack requires a resource pack, then you will need to extract that too.  You can find it in the resource_packs folder.
Installing
To install your behavior pack and/or resource pack, you will need to go to the Minecraft Bedrock directory.  Normally, you can find it here
C:\Users\(username)\AppData\Local\Packages\Microsoft.MinecraftUWP_(a bunch of letters)\LocalState\games\com.mojang\

Inside that directory, there will be two folders, one called behavior_packs and the other called resource_packs.  Put your behavior pack(s) and resource pack(s) in their corresponding folders.  Then open/restart Minecraft and now you can use the packs in other worlds.
Comment: Thank you I was able to extract it but how do I exactly put it onto the game? I'm on PC and using windows
Comment: @Khaios check my answer
Comment: @Khaios copy it to your `behavior_packs` folder.  in the Minecraft Bedrock directory.  Normally, the Minecraft Bedrock directory is in `C:\Users\(username)\AppData\Local\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\games\com.mojang` If the behavior pack requires a resource pack, then you will need to extract that and put it in the `resource_pack` folder in the Minecraft Bedrock directory.
Answer: Go to the world you want and then go to behavior_packs/. In there will be the behavior pack folders, just copy the folders in there to your resource_packs folder in your Minecraft Appdata.


How is Alexa programmed to sing?

Question: If you say "Alexa, sing for me", she will choose one of several songs that have been created with her voice. The voice(s) for each of these songs must have been created somehow.
At first, I thought that SSML would provide the tools necessary to do this, especially the <prosody> tag which has parameters for pitch and rate (duration).
I thought perhaps each syllable of singing could have its pronunciation specified with <phoneme> and its pitch and duration specified with <prosody>, with <break> tags in between:
<speak>
  <prosody rate="20%">
    <phoneme alphabet="x-sampa" ph="U">oo</phoneme>
    <break strength="none" />
  </prosody>
  <prosody rate="20%" pitch="+50%">
    <phoneme alphabet="x-sampa" ph="U">oo</phoneme>
    <break strength="none" />
  </prosody>
  <prosody rate="20%">
    <phoneme alphabet="x-sampa" ph="U">oo</phoneme>
  </prosody>
</speak>

However, when executed, Alexa applies her built-in inflection (to sound like a real human), and so the tone is not flat. These "ooh" sounds (above), for example, each have a falling tone. (They also have a noticeable break between phonemes even tho "no break" was explicitly specified.)
So then, how did the Alexa voice which is heard singing all of those songs get programmed? Was it via tools currently only available to Amazon developers?
It's also perplexing to me that I am apparently the only person on the internet even asking this question (based on zero results in stackoverflow, google, etc), especially this late in the game. Aren't there loads of musicians out there who would love to be able to make Alexa sing whatever they want?
Edit: Guys, I thought it was common knowledge, but there is no human voice actor behind Alexa. Her voice is completely computer-generated.
Answer: Alexa's voice is completely computer generated and so are the songs. Research is on-going into generating a singing synthesizer model (#1 and #2).
Here's a video by Popgun Labs regarding how they make their AI sing. Although I am unable to find how Amazon and Google do this, my guess it will be something similar.
EDIT: My earlier answer was based on an extension page and drew incorrect inconclusions.
Comment: My first statement is probably misdirected since it comes from a page run by an extension provided by a third party. Let me try to find more about it and then answer this back.
Comment: @jdunk Updated the answer to reflect my latest research.
Comment: But considering that Alexa's voice is computer-generated / doesn't come from any particular human, how can these songs be "recorded"?
Comment: @jdunk Yes, it is completely computerised, however, research has not advanced enough that Alexa can sing songs so those are pre-recorded. It's similar to how you can pay extra to get a celebrity's voice on your Alexa.
Comment: It would be impossible to get a human to record every known word and their combination.
Comment: Those celebrity voices are 1) from real humans and 2) don't sing, right? Are you saying that a real human is hired, is recorded singing, and then the recording of this real human voice is somehow changed to sound like Alexa's voice?
Answer: My prediction would be either something really fancy like Natural Language Processing or something around that lines, AI/ML or they just had the voice actor sing out something or sing particular tones and just cut them together, i don't own an Alexa but i do have a HomePod mini and an iPhone and the way it pronounces our local singer names like "sidhu moosewala" or "amrit maan" (off topic but still related) i believe they just cut and put together words in a "clean" and 'flowing" way.
Answer: Perhaps her voice is simply autotuned.
Certainly, pitch-shifting tools can force any desired pitch from any audio source, and I presume such tools can force duration changes as well.

How is Alexa programmed to sing?