Find rate of change of implicit function.

Question: There is a function like that : $\frac{y}{x}= a+ bx^2+cy^4$. I want to find rate of change of $\frac{y}{x}$. If I find $\frac{dy}{dx}$ or $\frac{dx}{dy}$ it will give me rate of change of y (or x) respectively to x (or y). But I want to find rate of the change of the $\frac{dy}{dx}$ itself. How can I do it?
Answer: The stages of implicit differentiation may also be handled in this way.  Beginning with
$$ \frac{d}{dx} \ [ \ \frac{y}{x} \ ] \ \  =  \ \ \frac{d}{dx} \ [ \ a+ bx^2+cy^4 \ ] \ \ \Rightarrow \ \ \frac{x·y' \ - \ y}{x^2} \ \ = \ \ 2bx \ + \ 4cy^3 · y' $$
$$ \Rightarrow \ \  x·y' \ - \ y  \ \ = \ \ 2bx^3 \ + \ 4cx^2y^3 · y' \quad \quad \mathbf{[ \ A \ ]} \ \ . $$
We can re-arrange this equation to obtain an expression for the first derivative as
$$ (x   \ - \ 4cx^2y^3) · y'   \ \ = \ \ 2bx^3 \ + \ y \ \ \Rightarrow \ \ y' \ \ = \ \ \frac{2bx^3 \ + \ y}{x \ · \ (1   \ - \ 4cxy^3)} \ \ . $$
We will set this aside for the moment to differentiate implicitly equation $ \ \mathbf{A} \ \ , \ $ producing
$$  \frac{d}{dx} \ [ \ x·y' \ - \ y \ ]  \ \ = \ \ \frac{d}{dx} \ [ \ 2bx^3 \ + \ 4cx^2y^3 · y' \ ] $$
$$ \Rightarrow \ \  ( \ y' \ + \ x·y'' \ ) \ - \ y' \ \ = \ \ 6bx^2 \ + \ 4c·( \ 2xy^3 · y' \ + \ 3·x^2y^2 · y' \ + \ x^2y^3 · y'' \ ) $$
$$ \Rightarrow \ \  x·y'' \ \ = \ \ 6bx^2 \ + \  ( \ 8cxy^3 · y' \ + \ 12cx^2y^2 \ ) · y' \ + \ 4cx^2y^3 · y''   $$
$$ \Rightarrow \ \  x·(1 \ - \ 4cxy^3)·y'' \ \ = \ \ 6bx^2 \ + \  4cxy^2·( \ 2y  \ + \ 3x \ ) · y' \ \ .  $$
In this way, we have avoided needing to apply the Quotient Rule to our ratio for $   \ y' \ . $ Instead, we now insert our result for the first derivative into this latest equation to obtain
$$ y'' \ \ = \ \ \frac{1}{x·(1 \ - \ 4cxy^3)} \ · \ \ \left[ \ 6bx^2 \ + \  4cxy^2·( \ 2y  \ + \ 3x \ ) · \left(\frac{2bx^3 \ + \ y}{x \ · \ (1   \ - \ 4cxy^3)} \right)  \ \right]  $$
$$ = \ \ \frac{6bx^2}{x \ · \ (1   \ - \ 4cxy^3)} \ + \ \frac{4cy^2·( \ 2y  \ + \ 3x \ ) ·  ( 2bx^3 \ + \ y)}{x·(1   \ - \ 4cxy^3)^2} $$ $$ = \ \ \frac{6bx^2 · (1   \ - \ 4cxy^3) \ + \ 4cy^2·( \ 2y  \ + \ 3x \ ) ·  ( 2bx^3 \ + \ y)}{x·(1   \ - \ 4cxy^3)^2}  $$
$$  = \ \  \frac{24bcx^4y^2 \ - \ 8bcx^3y^3 \ + \ 6bx^2 \ + \ 12cxy^3 \ + \ 8cy^4}{x·(1   \ - \ 4cxy^3)^2} \ \ .     $$
Answer: $$y=ax+abx^3+cxy^4$$, you need to find $y'$ and $y''$, so d.w.r. t. $x$,
$$y'=a+3abx^2+cy^4+4cxy^3 y' \implies (1-4cxy^3)y'=a+3abx^2 \implies y'=\frac{a+3abx^2}{1-4cxy^3}.$$
Again d.w.r.t. $x$, to get
$$y''=\frac{(1-4cxy^3)(6abcx)-(a+3abx^2)(-4cy^3-12cxy^2 y')}{(1-4cxy^3)^2}$$
Comment: What do this process is called? Could you give me any supplementary material about it?
Comment: This is called successive differentiation. in the third step I have used $\frac{d}{dx}(u/v)=\frac{v u'-u v'}{v^2}.$ Also when you differentiate $y$ do multiply by $y'$.
Comment: The full name of the topic would be "Successive differentiation of implicit fumctions", you may see https://www.intmath.com/differentiation/8-derivative-implicit-function.php
Comment: It appears that you inserted an extra factor into the middle term of your first equation:  it should read $ \ y \ = \ ax + bx^3 + cxy^4 \ \ . $  The first derivative is then
$$ y' \ \  = \ \ a + 3bx^2+cy^4+4cxy^3 y' \implies y'=\frac{a \ + \ 3bx^2 \ + \  cy^4}{1 \ - \ 4cxy^3} \ \ . $$


Docker CPU Config

Question: I am running 6 containers on a server with 8 CPU each, assigned using run time option —cpuset-cpu
There are times when only a couple of containers have heavy processing to perform and others are sitting idle. Is it possible that at these times containers with Heavy load use CPU of idle containers as well ?
Similar to the concept of limit/reserve resources of VMware.
Answer: The --cpuset-cpus option limits execution to those specific CPUs. It will not use other cores even if they are idle. Use this option only for workloads with extreme sensitivity to the latency of migration to another CPU.
What you actually want is the --cpus  option. Set it to some floating point number, like 6 for high priority containers or 2 for low priority ones. Adjust until host CPU is fully utilized.

Docker CPU Config


How to Move the Nodes Displaying in the Front Page to Another Page? (e.g. domain.com/articles)

Question: I've searched almost everywhere and nothing found, so hopefully someone can help me in here!
Okay, I'm using Drupal 7, I installed it and changed the front page to a basic page as I want to have static page displayed rather than list of articles! So this bit is fine and working perfectly, but the problem is how to display a list of my articles on another page, say I'm posting articles regularly and I want to be displayed on the articles section of the website and not on the front page, so how do I do that?
This can be done easily with WordPress 3, but couldn't find a solution for Drupal 7? Anybody have any idea? If you do then please help!
For example http://mydomain.com/articles/ would display a list of my articles, by the way I want each of my articles to be displayed as http://mydomain.com/article/the-article-name
Any idea?
Thanks
Answer: You need to use the Views module to create a list of recent articles. In fact views come with a predefined view that emulates the core Drupal frontpage. You just need to enable it and just define another path to use (such as site.com/articles). Here is a good series on learning views http://nodeone.se/blogg/learn-views-screencast-series-summed-up (Not affiliated in any way)
Answer: You can use a view as suggested, but as '/node' also contains a list of article teasers as you say, you can create an alias for '/node' called '/articles' using URL Aliases.
Given that you've changed your front page to a standard page, the default '/node' still exists and will receive a teaser from any content that has 'promoted to the front page' checked under 'publishing options' when creating a new piece of content.  You can also use the 'sticky at the top of lists option' if you want an article to remain at the top of your '/articles' page.  Example from Drupal6;

Finally for any new articles you simply assign the URL Alias /articles/article-name when creating a new article.


Downloading images from a server

Question: i wanna download images from a server using python but for e.g the URL is "example.com/photo/1.jpg" i wanna run the script again and again but with different image name
here is my code
import wget
fileurl = 0
url = 'http://example.com/photo/' + str(fileurl) + '.jpg'

while fileurl != 500:
 fileurl += 1
download = wget.download(url)

Comment: You never change `url` and I assume that the download should be part of the loop.
Comment: you could replace your while loop with: `fileurl = 500`. that's probably not what you want...
Answer: If you put the url line in the loop, it will change every iteration. In your current code it never changes.
import wget
fileurl = 0

while fileurl != 500:
    url = 'http://example.com/photo/' + str(fileurl) + '.jpg'
    fileurl += 1
    try:
        download = wget.download(url)
    except Exception as e:
        print(e)

Comment: it is giving me a sytem error Traceback (most recent call last): raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found
Comment: Because the url doesnt exist. If  you change the url to an existing image it wont.
Comment: my bad i forgot to change the url
Comment: hey bro how can i pass a HTTPError 404, for example: on a server only two images exits 1.jpg and 10 .jpg how can i continue it till 10.jpg without stopping on 2.jpg

Downloading images from a server


open menu while clicking on checkbox

Question: hey there i created this checkbox in comobination with a menu:
<input type='checkbox' name='thing' value='valuable' id="thing"/>

Johnny

Julie

Jamie

style :
input[type=checkbox] {
display:none;
}

input[type=checkbox] + label
{
background: #999;
height: 16px;
width: 16px;
display:inline-block;
padding: 0 0 0 0px;
}
input[type=checkbox]:checked + label
{
background: #0080FF;
height: 16px;
width: 16px;
display:inline-block;
padding: 0 0 0 0px;
}
.sub-nav {
    display: none;
}
input[type=checkbox]:checked > .sub-nav {
    display: block;
    position: absolute;
    top: 100px;
    left: 0;
    z-index: 99999;
    width: 100px;
    height: 100px;
    background-color: red;
}

the demo: http://jsfiddle.net/4huzr/71/
i want the sub-menu to open when you click at the grey checkbox(when you click again it should hide), but this sample doesnt work, anybody can help?
Answer: The submenu is not a child of the input so > will not work.
JSFiddle Demo
The CSS should read
input[type=checkbox]:checked ~ .sub-nav {
    display: block;
    position: absolute;
    top: 100px;
    left: 0;
    z-index: 99999;
    width: 100px;
    height: 100px;
    background-color: red;
}

Answer: Change:
input[type=checkbox]:checked > .sub-nav {

to:
input[type=checkbox]:checked ~ .sub-nav {

jsFiddle example
> selects the child (which sub-nav isn't), where ~ is a general sibling selector.
Answer: This should be a good plug and play component for anyone. You can always edit some css for anything else you need.

.menu {
  width: 100%;
}

.menu-checkbox {
  display: none;
}

.menu-label {
  display: block;
  position: relative;
  background: black;
  color: white;
  font-weight: bold;
  height: 2rem;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  cursor: pointer;
}

/*menu-label and menu-text have same padding*/

.menu-label {
  padding: 0 .5rem;
}

.menu-content {
  overflow: hidden;
  word-break: break-all;
  background: black;
  color: white;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
  max-height: 0;
}

.menu-text {
  padding: 0 .5rem;
}

.menu-checkbox:checked~.menu-content {
  max-height: 100vh;
}

.menu-label::after {
  position: absolute;
  right: 1rem;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

/*codes from utf-8 dingbats*/

.menu-checkbox[type=checkbox]+.menu-label::after {
  content: "\2795";
}

.menu-checkbox[type=checkbox]:checked+.menu-label::after {
  content: "\2796";
}

  <input class="menu-checkbox" id="menu-toggle" type="checkbox" name="tabs">
  LABEL NAME

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It itaque.sdfsdfsdfsdfsfsdfsdfsdfsdfsdfsdfsdsdddddddddddddddddddddddddddddddddddddddddd

open menu while clicking on checkbox


In Golf, can you choose to play down the 'wrong' fairway?

Question: I am an occasional (and fairly terrible) golfer. I played a round the other day and was confronted with an odd situation. I sliced a ball through some trees and onto the adjacent fairway. I still had 200-250 metres left to the pin after this shot. When I got to my ball, I noted that the trees between me and hole or the fairway of the hole I was playing were thick and high, whereas about 150 closer to the hole, the trees really thinned out. I therefore played a shot up the 'wrong' fairway to a position where I could relatively easily chip to the green through the sparse area of trees.
This was a social game, so I wasn't too worried, but was what I did legal under the Laws of Golf? Is there any compulsion to play along the 'correct' fairway when possible? Also, aside from any letter of the law considerations, what etiquette issues might doing this present?
Answer:
In Golf, can you choose to play down the 'wrong' fairway?

This depends on local course rules.

Courses define out-of-bounds.
Do fences, lines, and/or stakes mark out-of-bounds boundaries?

Some courses mark boundaries per each hole, which means you cannot chose to play down the "wrong" fairway, or fairway of a different hole. However, some courses mark boundaries only per hazard (a body of water, a swamp, a forest, etc.).
If the course does not mark boundaries per each hole, then that course does not prohibit playing down the "wrong" fairway. If you are playing recreationally, chances are that your playing partners will not mind if you play down the "wrong" fairway. Perhaps the group playing that hole might.
Comment: Tiger has played from the wrong fairway before, so I surmise that the same sentiment applies.
Comment: Thanks. Out of interest, what is the typical situation in major Pro tournaments? Do these define out-of-bounds for each hole? Would you ever see Tiger Woods playing down the wrong fairway?
Answer: There is nothing to stop you playing the 'wrong' fairway if you wish providing it is in bounds.
In an amateur situation this is likely to be a misplaced shot, but there are examples in the pro game where players hit the wrong fairway intentionally. I believe there is a hole at St.Andrews which is a good example of this.
Etiquette wise, it may be frowned upon a little, but I think if you're accurate enough to do this without endangering anyone and perceive there to be an advantage it's not much different from hitting a high shot over a corner to reduce the hole length.
Comment: I like this answer (though it's 2 years late). At my "home course" of sorts, many of the longer holes have a slight dogleg and are adjacent to another hole, so it's common for players in the know to intentionally tee onto the adjacent fairway because that actually provides a better approach shot than playing the intended fairway. Also, it should be noted that on the traditional Scottish style links course, there are only nine fairways, and the teeing ground for, say, hole 3 is a short pitch shot from the green for hole 16, and vice versa.


SELECT in Criteria Queries

Question: I have this class for example:
public class Person {
    private Integer id;
    private String name;
    private Address address;
}

public class Address {
    private Integer id;
    private String street;
    private String number;

    ...
}

I would like a build CriteriaQuery in JPA for this SQL
select p.name, d.street from Person p join Address d on d = p.address;

Do I have to create a Constructor for class Person and class Address for this particular situation?
Thanks.
Answer: Your where condition is invalid:
select p.name, d.street from Person p join Address d on d = p.address;

it should be something like:
select p.name, d.street from Person p join Address d on d.person_id = p.id;

or:
select p.name, d.street from Person p join Address d on d.id = p.address_id;

and an example for constructors for class Person:
//cTor I
public Person(Integer id, String name, Address address){
    this.id = id;
    this.name = name;
    this.address = address;
}

//cTor II
public Person(Integer id, String name, Integer addressId, String street, String number){
    this.id = id;
    this.name = name;
    this.address = new Address(addressId, street, number);
}

Comment: Ok, thanks for the answer. Now how can I make a Criteria with this JPQL?
Answer: from JPQL
select p.name, d.street from Person p join Address d on d = p.address;
TO Criteria
an option with constructor:
first mark the relation in your entity
@OneToOne/@OneToMany or etc..
use @JoinColumn
i.e
    public class Person {
           private Integer id;
           private String name;

           @JoinColumn(name="id", referencedColumnName = "id")
           private Address address;
}

later
create a class for your result type
      public class Result(){
           String name;
            String street;

         /* you must have constructor here for the multi select later */
         public Result(String name,String street) {
            this.name = name;
            thi.street = street
         }
      }

then do (em is the entity manager)
      CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery<PlaceSearch> query = cb.createQuery(PlaceSearch.class);
  Root<Person> personRoot = query.from(Person .class);
  Join<Person, Address> address= personRoot .join(Person_.address);

      / * without meta model
  Join<Person, Address> address= personRoot .join(person.get("address"));
      */
/* we know Result has a construct of (String,String) . this is important for the                        multi select here */

query.multiselect(person.get(Person_.name),address.get(Address_.street);
List<Result> result = em.

createQuery(query).getResultList();

SELECT in Criteria Queries


Example of properties so that "any two properties imply the third"

Question: I realise this is not a mathematics question per se, but it relates to teaching mathematics, and should have simple closed answers - therefore I have decided that MSE is an appropriate platform.
In mathematics, there are many examples of properties $\{P,Q,R\}$ so that any two imply the third. For example

A Kähler manifold: $\{\text{Complex, Riemannian, Symplectic}\}$.
$n$ is prime, $n$ is even, $n^n = n^2$.

My question is, are there any simple (non mathematics) examples of properties satisfying this rule? Like colours, or flavours.
One way to artificially create such a collection of three properties is to start with any two properties $\{P,Q\}$, and then define a third property $R$ to be "$P$ and $Q$". While it is certainly true that any two of $P,Q$, and $R$ will imply the third, $R$ alone will also imply the other two. The properties aren't "symmetric", and it isn't interesting. Therefore, we must add an extra condition: no property implies either of the remaining two properties.
My Question: Give three properties $\{P,Q,R\}$ (which are non-mathematical in nature) so that

Any two properties imply the third.
No single property implies any of the other two.

Thank you!
Comment: Donald is the US President, Melania is the US First Lady, Donald and Melania are married.
Comment: [relevant](https://ncatlab.org/nlab/show/two-out-of-three)
Comment: `non-mathematical in nature` Where is the line drawn? Would the following for example qualify as an answer: **P**  the lake is round, **Q** the lakeshore length is $2 \pi$ km, **R** the lake area is $\,\pi\,$ km$^2$.
Comment: I think this isn't an easy question to answer, if for no other reason than actual implication is difficult to pin down in a non-mathematical setting. The classic implication "If it is raining, I'll get wet" doesn't really work. What if you're inside or under cover? What if you have an umbrella? What if a machine with a thousand high-powered lasers evaporate every droplet before they can hit you? Real life has the potential to be messy and riddled with caveats, even if some of them are absurd!
Comment: If she buys kippers it will not rain, trout live in trees, I do not love her anymore. (I'm using the last opportunity to make a joke [before they ban it](https://meta.stackexchange.com/questions/312850/). If you don't know the sketch, you can Google it.)
Comment: @Rahul Not quite--although the First Lady is usually the president's wife, [she doesn't have to be](https://en.wikipedia.org/wiki/First_Lady_of_the_United_States#Non-spouses_in_the_role).
Comment: @eyeballfrog: Damn it. [Theo was right!](https://math.stackexchange.com/questions/2862902/example-of-properties-so-that-any-two-properties-imply-the-third?noredirect=1#comment5906889_2862902)
Comment: How exact do they have to be?  The phrase "maternal uncle" means the brother or brother in law of my mother so:  "Bob is my maternal uncle"  "Alisha is my mother".  "Bob is my mother's brother or brother in law" ought to do it.  Of course if Theo's point is that is definition and not implication then ... I can't really argue but... well, does the OP *really* need such precise examples. Or we could do:  Sam and Ellen are my biological parents.  Grace is Sam and Ellen's biological daughter.  Grace is my full biological sister. Definition and implication gets pretty blurry in real life.
Answer: (Not nonmathematical)
In an $n$-dimensional vector space consider the statements about a subset $S$:

$S$ is independent.
$S$ spans.
$S$ has cardinality $n$.
Answer:
One dollar is worth $\frac67$ euro.
One euro is worth $\frac78$ pounds.
One pound is worth $\frac43$ dollars.
Comment: Ah nice this is literally: a = b, b = c, a = c. Very simple.
Comment: (Assuming an exactly arbitrage-free market. Forex trading comes pretty close, though).
Answer: First, an example of three predicates such that any two imply the negation of the third:
In a house on the (straight) seashore, you can look out to the distance in three directions at $120°$ angles to each other. Then looking out to sea in two directions implies that you don't in the third.
Now a slightly more contrived example of three predicates such that any two imply the third:
You're trying to break out of a prison. You dug a tunnel, but apparently you miscalculated, and you've emerged in a watchtower. If it's one of the watchtowers on the corners of the prison, you could still escape by going back down and digging a bit further, but if it's the watchtower in the centre of the prison you should go back to your cell and cover your tracks or you'll be caught.
The watchtowers are round, and the outer watchtowers are centred on the corners of the rectangular prison, so that $90°$ of their circumference faces the prison and $270°$ faces the outside. You have time to make three tiny holes in the wall to get your bearings, so you decide to make them at $120°$ angles to get the best possible overview of the situation. But then after looking out onto the prison yard through two of them, you realize that any two such observations imply the third...
Comment: "Any two imply the negation of  the third" would be any three properties that are contradictory.


Send groovy script as a file to the Gremlin Server REST API

Question: Here it is explained how I can interact with a Gremlin Server using its REST API. With the following command I execute the rather simple 100-1 script.
curl -X POST -d "{\"gremlin\":\"100-1\"}" "http://localhost:8182"

What I want is to instead of using an inline script, define it in say, script.groovy.
I can make it work for this case defining a variable with the entire script:
GROOVY_LOAD_DATA_SCRIPT=$(


Powershell - Searching for files with extension using Get-ChildItem and Read-host

Question: Very simple code and I am trying to search for some files with a specific extension using read-host. I then try to pass that to a get-childitem line so search for the said extensions, but its just not working.
 $SelectedFiles = Read-Host "Which type of file(s) do you wish to delete?"

 $TargetedLocation = Read-Host "Which location are the files located?"

 Get-ChildItem -Path $TargetedLocation -Include $SelectedFiles -Recurse

Comment: That code gets me a list of files just fine. What are you using as input, and what is the error?
Answer: I ran this code:
$SelectedFiles = Read-Host "Which type of file(s) do you wish to delete?"

$TargetedLocation = Read-Host "Which location are the files located?"

Get-ChildItem -Path $TargetedLocation -Include $SelectedFiles -Recurse

Giving the following responses to the prompts:

Which type of file(s) do you wish to delete?: txt
Which location are the files located?: C:\temp

This returned no output. However, if I repeated with *.txt, as the first response, then I do get all of the txt files within C:\temp. If you want the end-user to specify the extension without putting *. in front then you can do this:
$SelectedFiles = Read-Host "Which type of file(s) do you wish to delete?"

$TargetedLocation = Read-Host "Which location are the files located?"

Get-ChildItem -Path $TargetedLocation -Include "*.$SelectedFiles" -Recurse

This adds *. to the beginning of the response to question 1.
Here's some more context on using Get-ChildItem with -Include: Difference between -include and -filter in get-childitem


How to get paragraph field values?

Question: I'd like to create a product list in drupal and send it in a webservice.
For this I created an entity type with paragraphs for each product.
How can I load the paragraph and access its fields? Until now I see only the target_id and target_revision_id of the product. Thanks!
$nodestorage = \Drupal::entityManager()->getStorage('node');
$productslist = $nodestorage->loadUnchanged(9)->toArray();
foreach($productslist['field_products'] as $prod) {
  debug($prod);
}

Result:
Array
(
  [target_id] => 1
  [target_revision_id] => 3
)

Answer: You should be able to include the Paragraph entity class, and use Paragraph::load($entity_id) to load it.
Example:
use Drupal\paragraphs\Entity\Paragraph;

$paragraph = Paragraph::load($target_id);
$foo = $paragraph->field_name->value;

Comment: The following change worked for me: `$foo = $paragraph->field_name->getValue();`
Answer: $paragraph = Paragraph::load($target_id);
// Paragraph type could be also useful.
$prgTypeId = $paragraph->getType();
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $prgMediaField */
$prgMediaField = $paragraph->get('field_media');
$prgMediaFieldValue = $prgMediaField->getValue();

Answer: I know this is old, but might be helpful for the future.
To load entities referenced by a Node entity you can use the entity property. For example, consider the following code:
$nodestorage = \Drupal::entityManager()->getStorage('node');
$node = $nodestorage->loadUnchanged(9);

foreach ($node->field_products as $product) {

  /** @var Entity (i.e. Node, Paragraph, Term) $referenced_product **/
  $referenced_product = $product->entity;

  // Use now the entity to get the values you need.
  $field_value = $referenced_product->field_name->value;
}

So no need to load an entity by the entity id, you just simply user ->entity property over a referenced list of entities.
Comment: No, that's not correct, @Dalmaz, that loop will generate every item contained in field_products.
Comment: Good, but This will get you only one entity per field!
Comment: you're right @Adaddinsane
Answer: The quickest way is to use referencedEntities():
$nodestorage = \Drupal::entityManager()->getStorage('node');
$node = $nodestorage->loadUnchanged(9);
$products_list = $node->{'field_products'}->referencedEntities();

How to get paragraph field values?


differential equation with 3 equalities

Question: please if you can help me to solve this differential equation :
$\frac{dx}{x}=\frac{dy}{y}=\frac{dz}{z}$
I tried solving it taking two equalities at a time
Answer: $$\int{dx\over x}=\int{dy\over y}=\int{dz\over z}$$ $$\log x=\log y+C=\log z+D$$ for some constants $C$ and $D$.
Comment: How to find a relation between x y and z ... i mean f(x,y,z)=0 ?
Comment: What makes you think the solution is given by such an $f$? Exponentiating the equation with the logarithms gives $z=Ay=Bx$ for some constants $A$, $B$.

differential equation with 3 equalities


Is there an equivalent of soft pen in GDI+?

Question: I need to draw a soft wide outline for my GDI+ GraphicsPath.
Something like this:

A path edge is shown in red. I'd like to use a wide pen which is smooth. I also need an ability to control smoothness of the pen.
I tried to use a gradient brush with the pen but couldn't find a solution that works.
I can achieve the desired result by drawing an outline with a black solid pen and applying a Gaussian smoothing filter on top of the result image, but I want to avoid this because it's slow when I have to process the whole image which could be quite large.
Is there a way to draw a smooth path outline?
Answer: There is no standard way in GDI+ that provides this functionality so you will have to create it.
You could track the line segments and draw a fuzzy, filled circle along the segments. By drawling the fuzzy circle once to a bitmap it should be fairly easy and fast to blit it continuously. By blending it slowly over time to the canvas you can also create a very nice effect and it would allow the user to control the intensity and maybe the size of the circle.
Comment: Is there a simple way to draw a bitmap at every pixel along a GDI+ shape path? It could be hard to calculate coordinates for pixels along a curve.
Comment: @Lev - The GDI Pen only supports a single color, no texturing. So I am afraid not. For most GDI shapes the formulars are well known so you could calculate them and do the drawing. Perhaps there is a library that already does this.
Comment: @lev - by the way ,are you using C/C++ or C#? (Just in case I have time to create a demo)
Comment: So basically I'll have to render shape path myself. I'll still need to use GDI+ to fill a shape. I wonder if in the end this approach is going to be faster than applying a blur on top of the shape drawn with GDI+ as a post processing.
Comment: Forgot to mention. I'm using C++
Comment: @lev - what will be the fastest way depends on how the drawling is created and how complex it is. To create the desired effect blurring might prove to be more complicated than expected; you only want to blur the edges so you need to find those first.
Comment: All my shapes have solid color fill, with the same color as the edge before smoothing. So I can just blur the whole image.


Como utilizar attr(selected) em um option criado dinamicamente?

Question: Tenho uma tabela criada dinamicamente e dentro dela um select no qual uso um map para criar suas options.
json.map(item => {
 var corpo = '';

 corpo += '';
 corpo += '  <select>';
 arrStatus.map(item => {
   corpo += '  <option value="' + item.freteStatusID + '">' + item.status + '</option>';
 })
 corpo += '  </select>';
 corpo += '	'

 //adiciona esta linha na tabela
 $('#tabela').append(corpo);

 $('option[value=' + item.freteStatusID + ']').attr('selected', 'selected');
}

Quando tento usar o .attr dentro do map recebo este resultado com duas options sendo selecionadas
<select>
  <option value="5">Aceito pelo embarcador</option>
  <option value="2">Agendado</option>
  <option value="3">Declinado</option>
  <option value="1" selected="selected">Recebido</option>
  <option value="6" selected="selected">Rejeitado pelo embarcador</option>
  <option value="4">Removido</option>
</select>
<select>
  <option value="5">Aceito pelo embarcador</option>
  <option value="2">Agendado</option>
  <option value="3">Declinado</option>
  <option value="1" selected="selected">Recebido</option>
  <option value="6" selected="selected">Rejeitado pelo embarcador</option>
  <option value="4">Removido</option>
</select>

Como posso fazer com que apenas uma option por select fique com o atributo "Selected"?
Answer: Parece que o seu problema está no $('option[value=' + item.freteStatusID + ']')
Nessa query você está procurando por todos os elementos option com o valor item.freteStatusID na sua página, não apenas dentro do select que você acabou de criar.
Se no primeiro loop você procurar por um option com o valor 1, e no segundo com valor 6, ele irá atribuir a propriedade selected para todos os option presentes na sua página com esse valor.
Você nem precisa fazer essa query separada para adicionar a propriedade no seu elemento, você pode utilizar uma condição durante a construção do seu HTML para adicionar essa propriedade, exemplo:
json.forEach(item => {
 var itemSelecionado = item.freteStatusID;
 var corpo = '';

 corpo += '';
 corpo += '  <select>';
 arrStatus.forEach(item => {
   var selected = item.freteStatusID === itemSelecionado ? 'selected' : '';
   corpo += '  <option ' + selected + ' value="' + item.freteStatusID + '">' + item.status + '</option>';
 });
 corpo += '  </select>';
 corpo += '	';

 //adiciona esta linha na tabela
 $('#tabela').append(corpo);
}


Cannot display retrieved API data in table view in swift

Question: Goal

My goal is to display the closest restaurants in my area by using Zomato API and swift

Error

When I try to populate an array to display the closest restaurants in my area, code does not enter for loop inside viewDidLoad() to populate the array.

Code
RestaurantTableViewController.swift
import UIKit
import Foundation
import CoreLocation

class RestaurantTableViewController: UITableViewController, CLLocationManagerDelegate {
    let apiKey: String = "e06745d59aa6170842e9760500129d63"
    let cellIdentifier: String = "restaurantCell"
    var restaurantImages: [URL] = []
    var locationManager = CLLocationManager()
    var restInfoVC = RestaurantInfoViewController()
    var nearby_restaurants = [Welcome]()
    // MARK: Lifecycle methods

    override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = """
        https://developers.zomato.com/api/v2.1/geocode?lat=\(38.390625)&lon=\(27.02147911555935)
        """
        let url = URL(string: urlString)

        if url != nil {
            var request = URLRequest(url: url!)
            request.httpMethod = "GET"
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.addValue(apiKey, forHTTPHeaderField: "user-key")

            URLSession.shared.dataTask(with: request) { (data, response, error) in
                guard let data = data, error == nil else { return }
                let httpResponse = response as! HTTPURLResponse

                if httpResponse.statusCode == 200 {
                    do {
                        /*
                        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]
                        guard let array = json!["nearby_restaurants"] else { return }
                        print(array)
                        */
                        let decoder = JSONDecoder()
                        let list = try decoder.decode(Welcome.self, from: data)
                        var welcome = Welcome()
                        // print(list.nearbyRestaurants[1].restaurant.menuURL)

                        for index in 0..<self.nearby_restaurants.count {
                            welcome.nearbyRestaurants[index].restaurant.name = list.nearbyRestaurants[index].restaurant.name
                            welcome.nearbyRestaurants[index].restaurant.url = list.nearbyRestaurants[index].restaurant.url
                            welcome.nearbyRestaurants[index].restaurant.thumb = list.nearbyRestaurants[index].restaurant.thumb
                            welcome.nearbyRestaurants[index].restaurant.userRating.ratingText = list.nearbyRestaurants[index].restaurant.userRating.ratingText
                            self.nearby_restaurants.append(welcome)
                        }
                    } catch {
                        print("Error is: \(error)")
                    }
                }
            }.resume()
        }
    }
}

extension RestaurantTableViewController {
    // MARK: Tableview delegate methods

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nearby_restaurants.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RestaurantTableViewCell
        cell.restaurantName.text = nearby_restaurants[indexPath.row].nearbyRestaurants[indexPath.row].restaurant.name
        cell.restaurantRating.text = nearby_restaurants[indexPath.row].nearbyRestaurants[indexPath.row].restaurant.userRating.ratingText
        do {
            //let data = try Data(contentsOf: URL(string: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSk90on-LRDhhFc7FRyRjR_yuv1OBKXHcJclO07h5zpZOrs-QJH&s")!),
            let data = try Data(contentsOf: URL(string: nearby_restaurants[indexPath.row].nearbyRestaurants[indexPath.row].restaurant.photosURL)!)
            let imageView = UIImageView(image: UIImage(data: data))
            imageView.contentMode = UIView.ContentMode.scaleAspectFit
            DispatchQueue.main.async {
                cell.restaurantImage.image = imageView.image
            }
        } catch _ {

        }
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let url = URL(string: nearby_restaurants[indexPath.row].nearbyRestaurants[indexPath.row].restaurant.url)!
        restInfoVC.restaurantWebView.load(URLRequest(url: url))
        /*
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let destination = storyboard.instantiateViewController(withIdentifier: "RestaurantInfoViewController") as! RestaurantInfoViewController
        navigationController?.pushViewController(destination, animated: true)
        */
    }
}

import Foundation

// MARK: - Welcome
struct Welcome: Decodable {
    var location: WelcomeLocation
    var popularity: Popularity
    var link: String
    var nearbyRestaurants: [NearbyRestaurant]

    enum CodingKeys: String, CodingKey {
        case location, popularity, link
        case nearbyRestaurants = "nearby_restaurants"
    }

    init() {
        location = WelcomeLocation()
        popularity = Popularity()
        link = ""
        nearbyRestaurants = []
    }
}

// MARK: - WelcomeLocation
struct WelcomeLocation: Decodable {
    var entityType: String
    var entityID: Int
    var title, latitude, longitude: String
    var cityID: Int
    var cityName: String
    var countryID: Int
    var countryName: String

    enum CodingKeys: String, CodingKey {
        case entityType = "entity_type"
        case entityID = "entity_id"
        case title, latitude, longitude
        case cityID = "city_id"
        case cityName = "city_name"
        case countryID = "country_id"
        case countryName = "country_name"
    }

    init() {
        entityID = 0
        entityType = ""
        title = ""
        latitude = ""
        longitude = ""
        cityID = 0
        cityName = ""
        countryID = 0
        countryName = ""
    }
}

// MARK: - NearbyRestaurant
struct NearbyRestaurant: Decodable {
    var restaurant: Restaurant
}

// MARK: - Restaurant
struct Restaurant: Decodable {
    var r: R
    var apikey, id, name: String
    var url: String
    var location: RestaurantLocation
    var switchToOrderMenu: Int
    var cuisines: String
    var averageCostForTwo, priceRange: Int
    var currency: String
    var offers: [JSONAny]
    var opentableSupport, isZomatoBookRes: Int
    var mezzoProvider: String
    var isBookFormWebView: Int
    var bookFormWebViewURL, bookAgainURL, thumb: String
    var userRating: UserRating
    var photosURL, menuURL: String
    var featuredImage: String
    var hasOnlineDelivery, isDeliveringNow: Int
    var includeBogoOffers: Bool
    var deeplink: String
    var isTableReservationSupported, hasTableBooking: Int
    var eventsURL: String

    enum CodingKeys: String, CodingKey {
        case r = "R"
        case apikey, id, name, url, location
        case switchToOrderMenu = "switch_to_order_menu"
        case cuisines
        case averageCostForTwo = "average_cost_for_two"
        case priceRange = "price_range"
        case currency, offers
        case opentableSupport = "opentable_support"
        case isZomatoBookRes = "is_zomato_book_res"
        case mezzoProvider = "mezzo_provider"
        case isBookFormWebView = "is_book_form_web_view"
        case bookFormWebViewURL = "book_form_web_view_url"
        case bookAgainURL = "book_again_url"
        case thumb
        case userRating = "user_rating"
        case photosURL = "photos_url"
        case menuURL = "menu_url"
        case featuredImage = "featured_image"
        case hasOnlineDelivery = "has_online_delivery"
        case isDeliveringNow = "is_delivering_now"
        case includeBogoOffers = "include_bogo_offers"
        case deeplink
        case isTableReservationSupported = "is_table_reservation_supported"
        case hasTableBooking = "has_table_booking"
        case eventsURL = "events_url"
    }
}

// MARK: - UserRating
struct UserRating: Decodable {
    var aggregateRating: AggregateRating
    var ratingText, ratingColor: String
    var ratingObj: RatingObj
    var votes: AggregateRating

    enum CodingKeys: String, CodingKey {
        case aggregateRating = "aggregate_rating"
        case ratingText = "rating_text"
        case ratingColor = "rating_color"
        case ratingObj = "rating_obj"
        case votes
    }
}

enum AggregateRating: Decodable {
    case integer(Int)
    case string(String)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let x = try? container.decode(Int.self) {
            self = .integer(x)
            return
        }
        if let x = try? container.decode(String.self) {
            self = .string(x)
            return
        }
        throw DecodingError.typeMismatch(AggregateRating.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for AggregateRating"))
    }
}

Result

I want the closest restaurants in my area to be displayed in a table view

Any help is appreciated
Comment: Where do you set values for `self.nearby_restaurants`? and since `self.nearby_restaurants` is empty. It is not getting into the for loop.
Comment: Did you check count for `self.nearby_restaurants`?
Comment: You are decoding the response to `list` not `nearby_restaurants`, so the array you are trying to loop over is empty!
Comment: @Vicky_Vignesh I declared nearby_restaurants right above viewDidLoad() method
Comment: @ErdalGüzel yes ! You have declared `nearby_restaurants` but didn't assign it
Answer: First of all, your self.nearby_restaurant count in 0 so for loop will never be executed. Also, you need to reload your table view once the data is fetched.
self.tableView.reloadData()

So here is how your viewDidLoad() should look like
var nearby_restaurants : Welcome!

override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = """
        https://developers.zomato.com/api/v2.1/geocode?lat=\(38.390625)&lon=\(27.02147911555935)
        """
        let url = URL(string: urlString)

        if url != nil {
            var request = URLRequest(url: url!)
            request.httpMethod = "GET"
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.addValue(apiKey, forHTTPHeaderField: "user-key")

            URLSession.shared.dataTask(with: request) { (data, response, error) in
                guard let data = data, error == nil else { return }
                let httpResponse = response as! HTTPURLResponse

                if httpResponse.statusCode == 200 {
                    do {
                        let decoder = JSONDecoder()
                        let welcomeData = try decoder.decode(Welcome.self, from: data)
                        self.nearby_restaurants = welcomeData.nearbyRestaurants
                    } catch {
                        print("Error is: \(error)")
                    }
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                }
            }.resume()
        }
    }

Answer: This code makes no sense at all
 let decoder = JSONDecoder()
        let list = try decoder.decode(Welcome.self, from: data)
        var welcome = Welcome()
        // print(list.nearbyRestaurants[1].restaurant.menuURL)

        for index in 0..<self.nearby_restaurants.count {
            welcome.nearbyRestaurants[index].restaurant.name = list.nearbyRestaurants[index].restaurant.name
            welcome.nearbyRestaurants[index].restaurant.url = list.nearbyRestaurants[index].restaurant.url
            welcome.nearbyRestaurants[index].restaurant.thumb = list.nearbyRestaurants[index].restaurant.thumb
            welcome.nearbyRestaurants[index].restaurant.userRating.ratingText = list.nearbyRestaurants[index].restaurant.userRating.ratingText
            self.nearby_restaurants.append(welcome)
        }

First of all the array nearbyRestaurants is empty so the loop will never be executed. Secondly you are creating the new Welcome instance outside of the loop so always the same instance will be used.
Long story short, the entire loop is pointless, just assign the value of welcome.nearbyRestaurants to nearby_restaurants (the variable name list is misleading) and you have to reload the table view on the main thread
 let decoder = JSONDecoder()
 let welcome = try decoder.decode(Welcome.self, from: data)
 self.nearby_restaurants = welcome.nearbyRestaurants
 DispatchQueue.main.async {
     self.tableView.reloadData()
 }


what is the solution with rails in adding something to a table?

Question: I am new to rails
so I am doing a basic application that manage tasks
I have created the create method to add a new task
and a form in the index.html.erb file
but when i insert a task in the form it shows an error
the tasks controller file:
class TasksController < ApplicationController
  def index
    @tasks = Task.all
  end

  def create
    Task.create params[:task]
    redirect_to :back
  end
end

the index.html.erb file:
    "
Tasks

<%= form_for Task.new do |f| %>
<%= f.label :task %>
<%= f.text_field :task %>
<%= f.submit %>
<% end %>

<% for task in @tasks %>

<%= task.task %>

<% end %>

"

and the error is:
undefined method `task' for #<Class:0xbd75770>
Extracted source (around line #7):
6 def create
7 Task.create params[:task]
8 redirect_to :back
9 end

app/controllers/tasks_controller.rb:7:in `create'

what is the problem?
Answer: Your problem in:
t.task = Task.task

Task class has no method task.
Use t = Task.new(task_params) or t.task = task_params['task']
Updated:
Add to your controller:
def create
   @task = Task.new task_params
   @task.save
   ... etc
end

def task_params
  params.require(:task).permit(:task)
end

Comment: About this errors look at http://stackoverflow.com/questions/20815513/rails-typeerror-cant-cast-actioncontrollerparameters-to-text - i think you need use strong parameters


XP Virtual Mode in Windows 7, network access for installed apps?

Question: I have the joy of having to manage a Microsoft Access form that was designed in Access 2003. The MDB is converted to an MDE for security reasons. However, I'm running Windows 7 with Office 2007 (including Access 2007). Access 2007 doesn't allow you to convert an MDB to MDE that is compatible with Access 2003.  Wow, that was a mouthful...
So, to rectify the situation and to keep from having to use a slooooow laptop here, I've just setup XP Virtual Mode in my Windows 7 install. Access 2003 is installed into it and works great... there's just one problem. The Access 2003 install cannot make use of the User DSN's my Win7 install has, and because the XP mode VM uses a generic local user, it cannot access my SQL databases from within the VM.
Any thoughts on how I can get around this? Should I add the XP vm to our company's domain and treat it like any other computer? I'm assuming I'll have to change the networking so that it's got access (doesn't appear to have any now).
I don't need a full walkthrough, but would love some tips/suggestions. At the end of the day, I need my Access 2003 instance to be able to access network resources, preferably using my AD login info (passthru), but I can create a static DB account if needed.
Thanks all!
Answer: You're stuck adding the VM to the domain and using a real login. Virtualized machines, even the "XP Mode" one can be thought of as independent of the host OS (including all it's DSN configurations and Authentication).
Comment: Thanks Chris - that's not a real big deal if I have to go that route, I can work with it. I'll give that a shot when I get into the office tomorrow.


Unable to get graphics context from fxml canvas

Question: I've created a basic FXML layout with a grid and canvas side by side. I have access to the canvas object (drawArea) but after having called getGraphicsContext my gt variable is always null.
Controller Class
public class controls {
    private GraphicsContext gc;
    @FXML private Canvas drawArea;

public void start() {
    gc = drawArea.getGraphicsContext2D();
}

@FXML protected void Step(ActionEvent event) {
    //TODO code to update positions of boids.
    System.out.print("Step triggered ");

    gc.fillOval(100, 100, 10, 10);
}

}
FXML display
<SplitPane dividerPositions="0.29797979797979796"
maxHeight="-Infinity" maxWidth="-Infinity"
minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="controller.controls" >
  <items>

    <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
         <children>
            <GridPane hgap="15.0" prefHeight="90.0" prefWidth="175.0">
              <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
              </columnConstraints>

<rowConstraints>
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          </rowConstraints>
           <children>

              <Button id="buttonStart" mnemonicParsing="false" text="Start" GridPane.columnIndex="1" GridPane.halignment="CENTER" GridPane.rowIndex="2" />
              <Button id="buttonStep" mnemonicParsing="false" onAction="#flockStep" text="Step" GridPane.halignment="CENTER" GridPane.rowIndex="1" />
              <Button mnemonicParsing="false" text="-" GridPane.columnIndex="1" GridPane.halignment="LEFT" />
              <Button mnemonicParsing="false" text="+" GridPane.columnIndex="1" GridPane.halignment="RIGHT" />
              <Button id="buttonStop" mnemonicParsing="false" text="Stop" GridPane.halignment="CENTER" GridPane.rowIndex="2" />
           </children>
        </GridPane>
     </children></AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
     <children>
        <Canvas fx:id="drawArea" height="200.0" width="200.0" />
     </children></AnchorPane>

Answer: In the controller, start() is never called. If you define an initialize() method (or just change start() to initialize()), that method will be called automatically by the FXMLLoader.
Comment: Great thank you. So my context is no longer null but I can't draw anything. Something else I've missed?


Previous Year Sales Calculation, SAMEPERIODLASTYEAR alternatives?

Question: I have a customer dashboard that has 2 years worth of sales, purchases, and inventory data. However, the customer does everything by their Fiscal Calendar rather than calendar year. This caused me to have to make some initial tweaks but I created a fiscal calendar that I use as the master date calendar for the application. Once I created the necessary relationships, this seemed to solve it.
However, after updating the data with the most recent week, now I am getting strange results from my measure for previous year sales. The formula is as follows:
PY Sales $ = CALCULATE(SUM('Weekly Sales by State'[Sales $ - TY]),SAMEPERIODLASTYEAR('Fiscal Calendar'[Date]))
The formula is pulling one week behind from the previous year and the final fiscal week is now 5x larger than it should be.
Fiscal Week Totals
Date Dimension table for reference:
Fiscal Calendar Table used as date dimension
Any thoughts on how I can tweak my PY Sales formula?
I have tried a few variations using EDATE but I still was not able to get the correct results.
Answer: You can try something similar to the following with the understanding that it will have a minimum grain of fiscal week.
PY Sales $ =
  SUMX(
    DISTINCT('Fiscal Calendar'[Fiscal_Yr]),
    (
      var prvYear = CALCULATE(MAX('Fiscal Calendar'[Fiscal_Yr])) - 1
      var fiscalWks = CALCULATETABLE(DISTINCT('Fiscal Calendar'[Fiscal_Wk]))
      return
        CALCULATE(
          SUM('Weekly Sales by State'[Sales $ - TY]),
          REMOVEFILTERS('Fiscal Calendar'),
          'Fiscal Calendar'[Fiscal_Yr] = prvYear &&
          'Fiscal Calendar'[Fiscal_Wk] IN fiscalWks
        )
    )


Apache mod_rewrite adding extra slash at the end of URL

Question: I'm running CentOS 6.0 and am trying to make mod_rewrite remove the www from any URL's prefixed with it. Here's the code I have in my httpd.conf:
NOTE: I am using a VPS with full root access so I am not using .htaccess files or any "per-directory" settings.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.aaronjwood\.com$
RewriteRule ^(.*)$ http://aaronjwood.com/$1 [R=301,L]

This is working fine for all pages except that the URL will be written to http://aaronjwood.com// (notice the two slashes) or http://aaronjwood.com//contact.php. Can anyone help me figure out why this is happening?
Answer: Since it's directly in a vhost, here's the solution: remove the slash here: http://aaronjwood.com$1
Another tip: when alone, ^(.*)$ is the same as (.*).
So here's the solution:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.aaronjwood\.com$
RewriteRule (.*) http://aaronjwood.com$1 [R=301,L]

Please tell me if it worked.
Olivier
Comment: Thanks for your answer Olivier. Even though the above answer solved my problem first, I tried out your syntax to see if it would produce the same result and it worked fine :)
Answer: Since it's in your main config file, and not a per-directory (<Directory> or .htaccess), then the leading slash is not being stripped for context.  It's actually adding (or trying to add - not sure if Apache's removing the extra in most cases, or if the client browser is) the second slash to every rewrite.
Just account for the fact that the leading slash is included in the string that you're matching:
RewriteRule ^/(.*)$ http://aaronjwood.com/$1 [R=301,L]

Comment: Thanks! That did the trick. I never ran into this issue when using Ubuntu Server or Fedora so I was rather stumped why it was happening on CentOS.


Leitura de arquivo texto armazenado na pasta raw através de uma classe de usuário

Question: Eu tenho um código de teste que funciona bem.
A função do teste é ler um arquivo texto que está numa pasta res\raw.
Ele lê o arquivo texto sem problemas e estampa seu conteúdo linha a linha através do Toast.
O código funcional é o seguinte:
package com.example.teste;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //------------------------------------------------
        Button bt = (Button) this.findViewById(R.id.button1);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                InputStream ins = MainActivity.this.getResources().openRawResource(MainActivity.this.getResources().getIdentifier("raw/teste","raw", getPackageName()) );
                InputStreamReader inputreader = new InputStreamReader(ins);
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line;
            try {
                    while (( line = buffreader.readLine()) != null) {
        Toast.makeText(MainActivity.this, line, Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }//onClick
        });//bt.setOnClick
    }//onCreate
    //**********************************************************
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }//onCreateOptions

}//classe

A minha intenção, entretanto, é fazer um reaproveitamento do código, uma vez que em várias partes de uma futura aplicação eu iria aproveitar a leitura de vários arquivos texto.
Então, quis criar uma classe, a fim de que, após instanciada, lesse arquivos diferentes, quando passasse a um método o nome do arquivo desejado.
Só me interessaria, então, a parte de localização, abertura e leitura do arquivo.
Assim, criei a classe da seguinte forma:
 package com.example.teste;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    import android.app.Activity;
    import android.content.Context;
    import android.widget.Toast;

    public class TestaLeituraArquivo extends Activity {
    Context gblContext;
//--------------------------construtor-----------------
    public TestaLeituraArquivo(Context context){
        this.gblContext=context;
    }//construtor
//---------------------------------método de leitura---------------------------
        public void leArquivo(String strCaminhoNomeArquivo){
                InputStream ins = gblContext.getResources().openRawResource(gblContext.getResources().getIdentifier(strCaminhoNomeArquivo,"raw", getPackageName()) );
            InputStreamReader inputreader = new InputStreamReader(ins);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line;
        try {
                while (( line = buffreader.readLine()) != null) {
    Toast.makeText(gblContext, line, Toast.LENGTH_SHORT).show();
                }
            } catch (IOException e) {
                Toast.makeText(gblContext, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }//leArquivo
    }//Classe

Uma vez que tenho esta classe dentro do mesmo pacote, vou modificar o código inicial, o primeiro lá de cima, a fim de que eu possa aproveitar o benefício da classe criada:
 package com.example.teste;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    public class MainActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //------------------------------------------------
            Button bt = (Button) this.findViewById(R.id.button1);
            bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    TestaLeituraArquivo tl = new TestaLeituraArquivo(MainActivity.this);
tl.leArquivo("raw/teste");
                }//onClick
            });//bt.setOnClick
        }//onCreate
        //**********************************************************
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }//onCreateOptions

    }//classe

Ou seja, apenas retirei da MainActivity, no click do botão, todo o código que funcionava na leitura do arquivo e passei para o método da classe criada, levando em consideração a passagem do Context que chamava.
O problema que enfrento é que a aplicação 'crasha' e o Try/catch não me avisa nada.
O log de erros mostra alguns erros, mas nada que indique o método em si. Fala de ausência de comunicação com o site da google, problemas com a parte de telefonia, etc.
Onde estou cometendo um erro?
O log de erros é
02-13 10:44:19.512: E/PowerManagerService(2486): CurLock p:3 mPS:1
02-13 10:45:36.953: E/PowerManagerService(2486): CurLock p:3 mPS:1
02-13 10:51:17.559: E/SensorManager(2583): unregisterListener: com.android.phone.AccelerometerListener$1@47bcf058
02-13 10:51:17.750: E/LogsProvider(19112): onCreate()
02-13 10:51:18.109: E/RingtoneManager(2583): getRingtone : content://settings/system/ringtone, streamType : -1
02-13 10:51:18.121: E/RingtoneManager(2583): getActualDefaultRingtoneUri : content://media/internal/audio/media/13
02-13 10:51:18.121: E/RingtoneManager(2583): Uri.parse(uriString) : content://media/internal/audio/media/13
02-13 10:51:18.195: E/SettingsProvider(2486): openAssetFile uri: content://settings/system/ringtone, mode=r
02-13 10:51:18.195: E/SettingsProvider(2486): ringtoneType : 1
02-13 10:51:18.195: E/RingtoneManager(2486): getActualDefaultRingtoneUri : content://media/internal/audio/media/13
02-13 10:51:18.195: E/RingtoneManager(2486): Uri.parse(uriString) : content://media/internal/audio/media/13
02-13 10:51:18.195: E/SettingsProvider(2486): soundUri : content://media/internal/audio/media/13
02-13 10:51:18.481: E/RingtoneManager(2583): getActualDefaultRingtoneUri : content://media/internal/audio/media/13
02-13 10:51:18.481: E/RingtoneManager(2583): Uri.parse(uriString) : content://media/internal/audio/media/13
02-13 10:51:18.492: E/AudioService(2486): sendVolumeUpdate   VOLUME_CHANGED_ACTION  streamType =  2
02-13 10:51:19.277: E/PowerManagerService(2486): reset countdown Timer for PhoneAPP
02-13 10:51:20.500: E/AudioService(2486): sendVolumeUpdate   VOLUME_CHANGED_ACTION  streamType =  2
02-13 10:51:21.731: E/SensorManager(2486): registerListener 7:gp2a Proximity Sensor delay:240
02-13 10:51:21.734: E/SensorManager(2583): registerListener 0:SMB380 delay:240
02-13 10:51:21.738: E/SensorManager(2583): =======>>>Sensor Thread RUNNING <<<========
02-13 10:51:22.398: E/SensorManager(2486): unregisterListener: com.android.server.PowerManagerService$11@47b904c0
02-13 10:51:22.582: E/SensorManager(2486): registerListener 7:gp2a Proximity Sensor delay:240
02-13 10:51:23.477: E/SensorManager(2486): unregisterListener: com.android.server.PowerManagerService$12@47b90578
02-13 10:51:23.512: E/SensorManager(2486): unregisterListener: android.view.WindowOrientationListener$SensorEventListenerImpl@47da0520
02-13 10:51:23.922: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:51:36.535: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:51:36.535: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:51:55.660: E/SensorManager(2486): registerListener 4:gp2a Light Sensor delay:240
02-13 10:51:55.934: E/SensorManager(2486): registerListener 0:SMB380 delay:60
02-13 10:51:56.559: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:51:56.559: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:51:59.219: E/SensorManager(2486): unregisterListener: com.android.server.PowerManagerService$12@47b90578
02-13 10:51:59.246: E/SensorManager(2486): unregisterListener: android.view.WindowOrientationListener$SensorEventListenerImpl@47da0520
02-13 10:51:59.434: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:52:40.289: E/SensorManager(2486): registerListener 4:gp2a Light Sensor delay:240
02-13 10:52:40.555: E/SensorManager(2486): registerListener 0:SMB380 delay:60
02-13 10:52:41.090: E/SensorManager(2486): unregisterListener: com.android.server.PowerManagerService$11@47b904c0
02-13 10:52:41.723: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:41.762: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:41.816: E/PowerManagerService(2486): reset countdown Timer for PhoneAPP
02-13 10:52:41.848: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:41.918: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.020: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.020: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.180: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.243: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.352: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.392: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:44.856: E/SensorManager(2583): unregisterListener: com.android.phone.AccelerometerListener$1@47bcf058
02-13 10:52:57.398: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 10:53:19.419: E/PowerManagerService(2486): CurLock p:3 mPS:1
02-13 10:53:48.957: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 10:55:23.664: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 10:56:23.383: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 10:57:05.449: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 10:58:05.168: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:01:55.379: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:03:32.785: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:03:55.887: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:05:33.266: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:06:00.133: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:08:18.781: E/libnetutils(2486): dhcp start cmd 11 : [dhcpcd:-ABK]
02-13 11:08:19.012: E/HierarchicalStateMachine(2486): TetherMaster - unhandledMessage: msg.what=3
02-13 11:08:19.844: E/dalvikvm(19408): Could not find class 'android.database.sqlite.SQLiteCantOpenDatabaseException', referenced from method com.google.android.gms.plus.provider.PlusProvider.a
02-13 11:08:22.609: E/SPPClientService(19480): ============PushLog. commonIsShipBuild. stop!
02-13 11:08:22.625: E/SPPClientService(19480): [PushClientApplication] Push log off : This is Ship build version
02-13 11:08:23.332: E/dalvikvm(19491): Could not find class 'android.os.UserManager', referenced from method xg.b
02-13 11:08:23.332: E/dalvikvm(19491): Could not find class 'android.os.UserManager', referenced from method xg.c
02-13 11:08:27.352: E/dalvikvm(19514): Could not find class 'android.os.StrictMode$ThreadPolicy$Builder', referenced from method J.a.g
02-13 11:18:59.789: E/TalkProvider(2627): replaceContactWithContactId: contactId==0!!! firstname.lastname@example.com, acct=1
02-13 11:18:59.805: E/TalkProvider(2627): insert presence failed for account=1 email@example.com client_type=2 status= priority=0 mode=3
02-13 11:19:58.402: E/dalvikvm(19408): Could not find class 'android.os.UserManager', referenced from method xg.b
02-13 11:19:58.406: E/dalvikvm(19408): Could not find class 'android.os.UserManager', referenced from method xg.c
02-13 11:20:01.215: E/dalvikvm(19727): Could not find class 'android.os.StrictMode$ThreadPolicy$Builder', referenced from method J.a.g
02-13 11:20:36.645: E/PowerManagerService(2486): CurLock p:3 mPS:1
02-13 11:22:34.746: E/Mms/SmsReceiverService(19762): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:23:08.363: E/Mms/SmsReceiverService(19762): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:27:38.953: E/Mms/SmsReceiverService(19762): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:28:24.680: E/Mms/SmsReceiverService(19762): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:35:14.977: E/PowerManagerService(2486): CurLock p:3 mPS:1
02-13 11:36:57.973: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.051: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.121: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.215: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.277: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.289: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.439: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.516: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.582: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.664: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.739: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.808: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.902: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.966: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:59.056: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:59.056: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:59.201: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:59.290: E/imdg81(2486): IsShutDownStarted()
02-13 11:37:01.778: E/imdg81(2486): IsShutDownStarted()
02-13 11:37:03.735: E/imdg81(2486): IsShutDownStarted()
02-13 11:37:12.348: E/HierarchicalStateMachine(2486): TetherMaster - unhandledMessage: msg.what=3
02-13 11:37:13.613: E/WifiHW(2486): [WIFI] Unload Driver
02-13 11:37:13.918: E/LogsProvider(19971): onCreate()
02-13 11:37:15.387: E/FlurryAgent(19914): Post to http://ads.flurry.com/v4/getAds.do caught IOException: java.net.UnknownHostException: ads.flurry.com
02-13 11:37:16.805: E/GoogleConversionPing(19950): Error sending ping
02-13 11:37:16.805: E/GoogleConversionPing(19950): java.net.UnknownHostException: Host is unresolved: www.googleadservices.com:80
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at java.net.Socket.connect(Socket.java:1057)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:62)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:88)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHTTPConnection(HttpURLConnectionImpl.java:927)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:909)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:1373)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at com.google.ads.conversiontracking.a.run(SourceFile:168)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at java.lang.Thread.run(Thread.java:1096)
: E/(): Device disconnected

Comment: Amigos, acabei de postar, mas acho que já resolvi o problema. Está na classe _TestaLeituraArquivo_, no método _leArquivo()_. Especificamente na linha dos dois _Toast_: quando troquei o contexto _gblContext_ para _this_ funcionou.
Comment: Desculpem-me, as não achei a solução, não. Eu cometi um engano. Eu continuo com o problema.
Comment: Provavelmente seu problema é com o `Context` tente implementa-lo de uma maneira diferente.
Comment: Por favor, poste o log de erro mesmo não tendo encontrado a linha exata.
Comment: Pus o log de erros após os códigos apresentados. Grato.
Comment: Caro Paulo Roberto, já tentei de alguns jeitos, mas dá sempre o mesmo erro, que não sei qual é. Este é o maior problema, não saber qual o erro exato.
Answer: Pesquisando bastante, descobri um jeito de fazer funcionar e tudo tem a ver com o que sugeriu o Paulo Roberto: é um problema de Context.
Não sei se é a melhor técnica, mas ponho aqui apenas para aqueles que porventura venham a ter este tipo de problema e pelo menos provocar uma discussão boa para todos.
A mudança principal é que alterei o construtor da classe do usuário, o daquela que criei.
Neste código, ele passa a receber o contexto da classe inicial e esta variável-contexto passa a ser usada em todas as linhas de código que exigiam essa referência.
O código inicial com uma ligeira modificação é:
[...]
//------------------------------------------------
        Button bt = (Button) this.findViewById(R.id.button1);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//Veja abaixo dois parâmetros no construtor: o caminho-nome do arquivo e o Context desta activity que instancia a classe
//---------
                Teste t = new Teste("raw/teste",MainActivity.this);//construção
//--------
            t.leArquivo();//método que executa a leitura do arquivo texto no objeto 't'
//---------
            }//onClick
        });//bt.setOnClick
[...]

Agora, vamos à classe do usuário:
public class Teste extends Activity {
    String strGblCaminhoNomeArquivo="";//variável 'global' do caminho-nome do arquivo
    Context gblContext;//variável 'global' do contexto recebido
//----------construtor
    public Teste(String strCaminhoNomeArquivo, Context context){
        this.strGblCaminhoNomeArquivo=strCaminhoNomeArquivo;
        this.gblContext=context;

    }//construtor
    //---------------------------

/*aqui no método é que o cuidado precisa ser tomado: gblContext teve de ser posto...
*..antes de getResources e de getPackageName().
*Do mesmo mesmo modo, teve de ser posto no Toast também.
*/
public void leArquivo(){
             InputStream ins = gblContext.getResources().openRawResource(gblContext.getResources().getIdentifier(this.strGblCaminhoNomeArquivo,"raw", gblContext.getPackageName()) );
                 InputStreamReader inputreader = new InputStreamReader(ins);
         BufferedReader buffreader = new BufferedReader(inputreader);
         String line;
     try {
             while (( line = buffreader.readLine()) != null) {
 Toast.makeText(gblContext, line, Toast.LENGTH_SHORT).show();
                    }

          } catch (Exception e) {
             Toast.makeText(gblContext, e.getMessage(), Toast.LENGTH_SHORT).show();
         }
    }//leArquivo
}//class

Feito isto, tive sucesso em exibir cada linha do arquivo sem erro algum.
Comment: Eu ia te sugerir isso, porém eu odeio variáveis globais, e aposto que muita gente aqui também odeia, e não vi nenhuma outra maneira de fazer, por isso nem respondi ;P mas foi boa a tua sacada, a mesma que a minha haha :) - e sobre responder a sua propria pergunta, sim! você tanto pode como deve fazer isto sempre que achar a resposta para o seu problema.
Comment: Se eu tivesse posto _private String strGblCaminhoArquivo;_ e _private Context gblContext;_ talvez ficasse melhor, não?
Comment: É que na verdade não vai mudar muita coisa. Todas as variáveis que você declarar lá em cima na `Activity` você vai poder acessar de qualquer lugar da sua `Activity` que você estiver, por isso não é necessario nem o `this.` na frente :p
Comment: Sim, uso o _this_ para ficar bem claro a 'força' da variável. Mas dentro da mesma classe esse pseudo escopo 'global' não faz muito mal, não acha? Ou tem alguma implicação que eu deveria saber?
Comment: Variáveis globais só não são utilizadas pelo fato que elas podem gerar conflitos, ou você pode alterar o valor delas não intencionalmente causando diversos problemas, variáveis locais são sempre melhor recomendadas pelo fato que elas são forçadas a serem utilizadas apenas para uma funcionalidade e impedindo o uso para outra funcionalidade. Mas no seu caso acredito que não vá ter problema, a não ser que você eventualmente venha a adicionar mais variáveis a sua `Activity` aí talvez possa gerar uma confusão.
Answer: Quando há a necessidade de utilizar a pasta \res\raw em algum dos meu projetos eu utilizo da seguinte forma.
 InputStream ins = getResources().openRawResource(R.raw.teste);

Toda vez que você coloca um arquivo na pasta raw automaticamente o sistema cria um ID na classe R para esse arquivo, logo, quando você utiliza desta forma fica bem mais difícil acontecer erro de I/O
Sugiro que mude as assinaturas do metodo para trabalho com o IDs do aruqivo raw como por exemplo
public void lerArquivo(int idResources){...}

Com essa alteração a chamada do método deve ser:
obj.lerArquivo(R.raw.teste);

Ao meu ver fica mais fácil de trabalhar.
Mais informações Android - Provinding Reources
Comment: Caro Clebao, isto me causa uma economia de código, conforme você disse, por um lado, mas me obriga a fazer mais código para descobrir, a partir do nome na pasta raw, o id do arquivo. Não ficaria a mesma coisa?
Comment: Mas os arquivos da sua pasta raw não são fixos? ou você faz download de arquivos por demanda?
Comment: Por demanda, Clebao. Eu quero ler o conteúdo da pasta, que poderá ser móvel na quantidade de arquivos. Não quero engessar os tais, uma vez que a aplicação, em si, terá vários 'sabores' em apks independentes, com quantidade de arquivos textos diferentes.
Comment: Nesse caso eu recomendo você trabalhar com getResources().getIdentifier("raw/teste","raw", getPackageName()), logo ficaria basicamente InputStream ins = getResources().openRawResource( getResources().getIdentifier("raw/teste","raw", getPackageName()) );
Comment: Agradeço a ajuda, Clebao, mas não adiantou. Continuando tendo a 'exceção', sem nada de novo no log de erros.
Comment: Pelo sue logcat que você colou na pergunta não consegui identificar o erro, coloque o try cat o e.printStackTrace() e cole novamente o logcat.


Pandas - Filter Dataframe on Multiple Criteria

Question: I have a dataframe df:
type    rec_1   rec_2   rec_3   rec_4   rec_1_outlier   rec_2_outlier   rec_3_outlier   rec_4_outlier
yellow  1          7       3       1       FALSE        TRUE                  TRUE          TRUE
red     3         11       2       5       FALSE        TRUE                 FALSE          FALSE
blue    5         2        1       6        TRUE        FALSE                FALSE          FALSE
green   2         9       13       9        FALSE       FALSE                TRUE           FALSE

I want to get separate dataframes per type where the _outlier columns are only false, but the rec columns are independent of each other and one column may be true and the other false.
So theoretically if I were to try
df_blue = df['type']=='blue' & df['rec_1_outlier']=='False' & df['rec_2_outlier']=='False' & df['rec_3_outlier']=='False' & df['rec_4_outlier']=='False'

This would might never select any rows because the _outlier columns might never all be false.
I have also thought about doing it one column at a time like this.
df_blue_rec_1 = df['type']=='blue' & df['rec_1_outlier']=='False'
df_blue_rec_2 = df['type']=='blue' & df['rec_2_outlier']=='False'

Then just appending the separate dataframes into one.
I have this feeling like there is a better way to accomplish this.
Answer: You are on the right path. What you did was create a boolean mask. like so:
mask_blue =((df['type']=='blue') &
            (df['rec_1_outlier']=='False') &
            (df['rec_2_outlier']=='False') &
            (df['rec_3_outlier']=='False') &
            (df['rec_4_outlier']=='False')

This mask gives a list of true/false that corresponds to the indexes of your original df.
df_blue = df.loc[mask_blue,:]

Now you choose which column to transfer to df_blue by changing the (:) above. for example:
df_blue = df.loc[mask_blue,['type','rec_1']]

This would give a df with the column: type and rec_1
Update
To do this for every individual rec_1, try creating on mask for each rec_x. This will give nan values for True outliers. The following code is an example for rec_1 and rec_2.
df_blue = pd.Datafram()
mask_blue1 =((df['type']=='blue') & (df['rec_1_outlier']=='False'))
df_blue.loc[:,'rec_1'] = df.loc[mask_blue1,'rec_1']
mask_blue2 =((df['type']=='blue') & (df['rec_2_outlier']=='False'))
df_blue.loc[:,'rec_2'] = df.loc[mask_blue2,'rec_2']

Comment: Thanks Kosmos. Question for you, would your mask above only find rows where all the _outlier columns = False? Sometimes the row would have rec_1_outlier == False but rec_2_outlier == True. In that row I would want to take the value for rec_1_outlier but reject rec_2_outlier. Does that make sense?
Comment: No problem. Hope it works for you. I've updated the post to match your question. This solution will give nan values when the mask gives False.


What are the current rules for modern pentathlon?

Question: The rules for a modern pentathlon competition have changed several times since it was created in 1912, such as combining running and shooting, and an announcement in 2021 that equestrian would be replaced with a different event. Recently, there was the "UIPM 2022 Pentathlon World Cup" in Cairo and there are several more upcoming "UIPM 2022 Pentathlon World Cups" this year. Apparently these are being run on a "new format", and it appears this is the format that will be used at the 2024 Olympics.
What are the rules for modern pentathlon in this series of 2022 world cups? Is the format for the 2024 Olympics set yet, and is it the same?
Answer: As of May 2022, the plan is:

The 2024 Olympics will use the existing rules (i.e. with show jumping)
The 2028 Olympics will use a different format - although modern pentathlon has been omitted from the provisional list of sports for the 2028 Olympics due to the uncertainty.

The UIPM (the governing body for modern pentathlon) are due to vote on 2nd May 2022 to agree the new format. However, there is significant push-back on the changes from a number of leading athletes so it is by no means clear what is actually going to happen.
Source: Modern pentathlon: Athletes demand investigation by International Olympic Committee, BBC News


Javascript redirect to html

Question: I've been trying to let javascript redirect to another html file using window.location but it keeps reloading. Here is the Javascript

var myStorage = window.localStorage;
let accounts = [{
  username: 'admin',
  pass: 'admin123!',
  email: 'email@example.com'
}];
myStorage.setItem("account", accounts);

//check login account
var checkLogin = function() {
  let uname = document.getElementById("Uname").value;
  let pass = document.getElementById("Pass").value;
  if (uname == "admin" && pass == "admin123!") {
    myStorage.setItem("user", {
      username: 'admin',
      pass: 'admin123!',
      email: 'firstname.lastname@example.com'
    });
    alert("Login admin");
    window.location = "../account/myaccount.html";
    alert("redirect");
  } else {
    myStorage.setItem("user", undefined);
    document.getElementById("incorrectAccount").style.color = "red";
    document.getElementById("incorrectAccount").innerHTML = "Incorrect Username or Password";
  }
};
<form id="login" method="post" onsubmit="return checkLogin();">

    Username:

    <input type="text" name="Uname" id="Uname" placeholder="admin">

    Password:
    <input type="Password" name="Pass" id="Pass" placeholder="admin123!">

    <input type="submit" name="log" id="log" value="Log In">

    <input type="checkbox" id="check">
    Remember me

    Forgot Password?

    Register

</form>

After typing the same username and the password, the first alert works and then it skips the redirect link and goes straight for the 2nd alert message
Comment: @BOZ — That won't make a difference.
Comment: `window.location.href = "../account/myaccount.html";` try this.
Comment: Please, use JSON.stringify to stringify the data you save to localStorage.
Comment: You should [learn how to use the label element properly](http://www.456bereastreet.com/archive/200711/use_the_label_element_to_make_your_html_forms_accessible/). Without a for attribute or a form control inside it, a label is useless. (And use them consistently, you have a span instead of a label for "Remember me")
Comment: Use CSS. Don't use `` or simulate margins using multiple line breaks.
Answer: Submitting a form will cause the page to load the URL specified in the action attribute, which defaults to the current URL, which gives that effect though.
You must be trigging the JS when you submit the form. The JS runs, then the form submits, and the URL being navigated to changes.
You need to prevent the default behaviour of the form submission event.
e.g.
var checkLogin = function(event){
    event.preventDefault();

and
document.querySelector('form').addEventListener('submit', checkLogin);

Re edit.
This is the problem. However, you are using event binding methods from before they introduced addEventListener (which became a standard in November 2000).
If you want to use intrinsic event attributes (I don't recommend them, they have some confusing gotchas) then you need to return false from the event handler.

onsubmit="return checkLogin();"

You are currently returning the return value of checkLogin, but that doesn't have a return statement so it returns undefined. You need to return false and not any falsy value.
Answer:

function myRedirect() {
  location.replace("https://stackoverflow.com")
}
<button onclick="myRedirect()">Replace document</button>
Comment: I have tried this but it did not really work
Comment: I don't understand how you think this code-only-explanation-free answer solves the problem.

Javascript redirect to html


Getting error in PL/SQL Oracle

Question: I'm newbie in PL/SQL and I have problem with the following code:
ALTER TRIGGER secure_employees DISABLE;

ALTER TABLE employees ( ADD (exceed_avgsal VARCHAR2(3) DEFAULT 'NO'
 CONSTRAINT employees_exceed_avgsal_ck CHECK (exceed_avgsal IN ('YES', 'NO')));

CREATE OR REPLACE PROCEDURE check_avgsal IS
  avgsal_exceeded employees.exceed_avgsal%type;
  CURSOR emp_csr IS
    SELECT employee_id, job_id, salary FROM employees FOR UPDATE;
  e_resource_busy EXCEPTION;
  PRAGMA EXCEPTION_INIT(e_resource_busy, -54);

  FUNCTION get_job_avgsal(jobid VARCHAR2) RETURN NUMBER IS
    avg_sal employees.salary%type;
  BEGIN
    SELECT (max_salary + min_salary) / 2
      INTO avg_sal
      FROM jobs
     WHERE job_id = jobid;
    RETURN avg_sal;
  END;
BEGIN
  FOR emprec IN emp_csr LOOP
    avgsal_exceeded := 'NO';
    IF emprec.salary >= get_job_avgsal(emprec.job_id) THEN
      avgsal_exceeded := 'YES';
    END IF;
    UPDATE employees
       SET exceed_avgsal = avgsal_exceeded
     WHERE CURRENT OF emp_csr;
  END LOOP;
EXCEPTION
  WHEN e_resource_busy THEN
    ROLLBACK;
    RAISE_APPLICATION_ERROR(-20001, 'Record is busy, try later.');
END check_avgsal;

EXECUTE check_avgsal

SELECT e.employee_id, e.job_id, (j.max_salary-j.min_salary/2) job_avgsal, e.salary, e.exceed_avgsal avg_exceeded
 FROM employees e, jobs j WHERE e.job_id = j.job_id and e.exceed_avgsal = 'YES';
COMMIT;

I get the error message

PROCEDURE CHECK_AVGSAL compiled
  Errors: check compiler log

If anyone can help me I will be thankful
Comment: How are you running this? All as one script? Looks like it's treating the `execute` line as part of the procedure. If it's all executed together then you need a `/` on a line on its own after the `end chk_avgsal`, but it's not entirely clear.
Comment: And what does the **compiler log** say?
Comment: The error you are getting is just a compiler message saying that there are errors. You have to do a `SELECT * FROM user_errors WHERE name='CHECK_AVGSAL'` to see the actual errors. Please post those ones here.
Comment: Error(36,1): PLS-00103: Encountered the symbol "EXECUTE"
Comment: Again the same problem Error(36,1): PLS-00103: Encountered the symbol "EXECUTE"
Comment: Also have that : Error(39,1): PLS-00103: Encountered the symbol "EXECUTE" when expecting one of the following:     * & - + ; / at for mod remainder rem  and    or group having intersect minus order start union where    connect || multiset
Comment: yes , all as one script
Comment: Where is `'/'` ?? it pushes ur queries into DB actually..
Comment: i repair it , but getting :
get Error(2,17): PL/SQL: Item ignored Error(2,27): PLS-00302: component 'EXCEED_AVGSAL' must be declared Error(21,1): PLS-00320: the declaration of the type of this expression is incomplete or malformed : PL/SQL: Statement ignored Error(23,1): PLS-00320: the declaration of the type of this expression is incomplete or malformed : PL/SQL: Statement ignored : PL/SQL: SQL Statement ignored : PLS-00320: the declaration of the type of this expression is incomplete or malformed PL/SQL: ORA-00904: "AVGSAL_EXCEEDED": invalid identifier PLS-00103: Encountered the symbol "/"
Comment: Also you don't need a `COMMIT` after your last `SELECT` statement as long as `SELECT` doesn't start a transaction.
Comment: If this is not just a learning exercise then you should note that this procedure could easily be replaced by a view which just lists the employee id's that exceed the median salary, or which returns employee id's and the ratio of their salary to the median.
Answer: You need a / on a line on its own, between the end chk_avgsal; and the next statement, to run the PL/SQL block:
...
END LOOP;
EXCEPTION WHEN e_resource_busy THEN ROLLBACK;
RAISE_APPLICATION_ERROR (-20001, 'Record is busy, try later.');
END check_avgsal;
/

EXECUTE check_avgsal
...

Your alter table syntax is wrong too:
ALTER TABLE employees ADD (exceed_avgsal VARCHAR2(3) DEFAULT 'NO',
  CONSTRAINT employees_exceed_avgsal_ck CHECK (exceed_avgsal IN ('YES', 'NO')));

SQL Fiddle demo.
Comment: and get Error(2,17): PL/SQL: Item ignored
Error(2,27): PLS-00302: component 'EXCEED_AVGSAL' must be declared
Error(21,1): PLS-00320: the declaration of the type of this expression is incomplete or malformed
Error(21,1): PL/SQL: Statement ignored
Error(23,1): PLS-00320: the declaration of the type of this expression is incomplete or malformed
: PL/SQL: Statement ignored
: PL/SQL: SQL Statement ignored
: PLS-00320: the declaration of the type of this expression is incomplete or malformed
 PL/SQL: ORA-00904: "AVGSAL_EXCEEDED": invalid identifier
 PLS-00103: Encountered the symbol "/"
Comment: Your `alter table` is failing - that will shown as you execute the script! - so the new column doesn't exist when the procedure is compiled. If this is a one-off you could do this as an anonymous block rather than creating a stored proc; or as Wenfried says, with a simole update statement - no PL/SQL needed.
Answer: You forgot the semicolon:
EXECUTE check_avgsal;

But you could do it in a simple UPDATE:
UPDATE employees e
    SET avgsal_exceeded = (
WITH avg_salaries AS
    (SELECT (max_salary + min_salary)/2 AS avg_sal, job_id FROM jobs)
SELECT CASE
    WHEN employee_id >= avg_sal THEN 'YES'
    ELSE 'NO'
    END
FROM avg_salaries
    WHERE a.job_id = e.job_id);

Comment: I've repaired the semicolon but have that : SQL Error: ORA-00904: "E"."EXCEED_AVGSAL": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:
commited
Comment: You did not add column EXCEED_AVGSAL to employees table.

Getting error in PL/SQL Oracle


Jquery click only works with double click

Question: I am so close to getting this.  Here's my code that is returning the correct url, but only when button is double-clicked.  I only need one click to retrieve the image.
<code> var origin = 'COMP';
 var area = 'US';
 var type = 'typeA';
 var level = 'Xnay';
 var time = '0';
 var btn1 = document.getElementById("redbutton").winControl;

function change_area(new_area) {
     area = new_area;
}

function change_type(new_type) {
     type = new_type;
}

$(btn1).click(function () {
  var src = "http://somesite.net/folder/WEB_" + origin + "_" + area + "_" + level + "_" + type + "_" + time + "HR.png";
         change_area('GB');
         change_type('typeB')
         $('#mainmap').attr('src', src), false;
});
</code>
Comment: did you find what happens in console when u clik the first time
Comment: How do I view this?  I have the javascript console visible during debug but I cannot see each process/click.
Answer: You try by adding
<code>$(document).ready(function() { });</code> block
before the following line
<code>$(btn1).click(function () {
</code>
Finally as,
<code>$(document).ready(function() {
       $(btn1).click(function () {
         var src = "http://somesite.net/folder/WEB_" + origin + "_" + area + "_" + level + "_" + type + "_" + time + "HR.png";
         change_area('GB');
         change_type('typeB')
         $('#mainmap').attr('src', src), false;
    });
});
</code>


Implementing LoadMore functionality with paging library 2

Question: i have implemented paging library in my application which is working pretty fine , now the functionality that i want to add is to simply show load more as progress bar in the bottom , so when there isn't data , simply show progress bar , now i'm getting confused on what to use either normal pagination with recycler view where i need to check for last position in the layout manager or simply use view item type with recycler , your help is appreciated and thank you in advance
Answer: The concept of load state isn't build into Paging v2 APIs - you need to track this yourself via posting updates from your implementation of DataSource and the easiest way to show another load state based item in RecyclerView is with ConcatAdapter.
However if you are inclined to upgrade to the v3 beta, the good news is that this is supported out of the box with the v3 APIs - see:
https://developer.android.com/reference/kotlin/androidx/paging/PagingDataAdapter#loadStateFlow:kotlinx.coroutines.flow.Flow
and:
https://developer.android.com/reference/kotlin/androidx/paging/LoadStateAdapter


How do I find the mean in statistical surveys?

Question: I have this question on my math homework and I would really like to understand how to solve a problem like this.
In a statistics survey, several measurements were taken and the mean of the measurements was 10.2. In a new survey, twice as many measurements were taken and the mean of these measurements was 10.8. What is the average of all the measurements?
What I don't understand is how to solve it, since I know that the mean is all the values added together and then divided on the number of values I use. But I am not told how many values or which values are used in these surveys. Or am I missing something?
Comment: Welcome to Math SE. Note that if you use something like $n$ for the number of initial measurements and do the calculations, you'll find that $n$ cancels out when determining the overall average, so it doesn't affect the final result.
Answer: Hint:

Suppose there were $n$ measurements in the first survey
What was the sum of the measurements in the first survey?
How many measurements were there in the second survey?
What was the sum of the measurements in the second survey?
How many measurements were there altogether?
What was the sum of the measurements altogether?
What was the average of the measurements altogether?


different 'click' callbacks in different scripts: can I control order of execution?

Question: I have one script that manages playlist clips.  It includes a callback that specifies what to do with the playlist when the user clicks on a clip:
<code>$('div.clip').bind("click.playlist", function() {
  ...
});
</code>
I am now planning to add jquery-tabs, and would like to create a second script with a second callback, that specifies what to do with the tab content when the user clicks on a clip:
<code>$('div.clip').bind("click.tabs", function() {
  ...
});
</code>
Here is my question:
When the user clicks on a clip, I want the "click.tabs" callback to execute before the "click.playlist" callback.  Does anyone know how to do this?
Answer: imho i would do that in an other way:
<code>$('div.clip').bind("clip.playlist", function() {
  ...
});
</code>
and
<code>$('div.clip').bind("clip.tabs", function() {
  ...
});
</code>
and then fire it up with:
<code>$('div.clip').click(function(){
    $(this).trigger('clip.playlist').trigger('clip.tabs');
});
</code>
to get the FULL control of event-chaining.
Comment: +1 This is the same as my answer, except you're triggering two custom events instead of calling the functions directly, a matter of choice. The important thing is that you cannot rely on order. If you need two things to happen in order, you do it from a single handler
Comment: your solution is 100% synchonous (which is not exactly claimed)..

my solution is asynchonous, but will fire up the first handler and directly after that the second without waiting for each other.
the difference between that and the original approach is, that the "clip.playlist"-handler will be triggered BEFORE "clip.tabs" instead of it's randomly chosen, which handler will be fired first...

synchronous-code can lead to not very responsive websites -- don't know what he want to do, but this should work as requested. - your solution is right, altough, but synchronous.
Comment: Can you point me to some place that says that jquery events are asynchronous? As far as I understand, they're not, because they're not true browser events.  http://stackoverflow.com/questions/6620010/are-handlers-always-called-synchronously-during-jquery-click. Even in browsers, if you do fire a browser event synthetically, that event gets handled synchronously, it's a problem with IE since the event object is a global, and the nested events can really screw with you (as they have me in the past)
Comment: @JuanMendes oh! you're right (*totallyWeird*) jQuery-triggering is completely synchronous (read about that in a bug report, but this is *expected behavior*), sorry for my wrong statement!
but -- this won't change anything ;)
this solution is then exactly the same like your's, except, that you're handler-code has to be wrapped in public functions and mine in anonymous ones ;)
Answer: The order that events handlers on the same element run is not guaranteed. Don't rely on it, this is true in most event systems, they are designed to be decoupled. If you really need it, you need to set a single handler that calls both functions you need in order.
Instead of
<code>$('div.clip').bind("click.playlist", function() {
  doSomething();
});

$('div.clip').bind("click.tabs", function() {
  doSomethingElse();
});
</code>
Do
<code>$('div.clip').bind("click", function() {
  doSomething();
  doSomethingElse();
});
</code>
Answer: What if you used
<code>$('div.clip').click(function()
{
    func1().func2()
});
</code>