remove second question mark from query string

Question: I made a mistake in creating links. I corrected it but now still there are links floating around that might look like this:
http://www.domain.com/?page=1?date=29062015&id=778
I would like to correct this using the rewriteEngine to redirect my users to:
http://www.domain.com/?page=1&date=29062015&id=778
I searched around and tried the following, but it doesn't work:
<code> RewriteEngine On
 RewriteCond %{QUERY_STRING} ^(.*)\?(.*)$
 RewriteRule ^\/ ^\/$1\&$2 [L,R=301]
</code>
What should I change here?
Answer: I've slightly corrected your rule,hope it will help to resolve the issue:
<code>RewriteEngine On
RewriteCond %{QUERY_STRING} ^(.*)\?(.*)$
RewriteRule (.*) $1?%1&%2 [L,R=301]
</code>
Note that %1 and %2 are back-references to the matched part of the regular expression in the previous RewriteCond (Query string condition).
Good article about rewriting query string here: https://wiki.apache.org/httpd/RewriteQueryString


ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

Question: I am getting a RuntimeException on Android 2.3.5 but I am using Theme.AppCompat (res/values/themes.xml). This is the phone: http://www.gsmarena.com/samsung_galaxy_y_s5360-4117.php

 <?xml version="1.0" encoding="utf-8"?>
 <resources>

 </resources>

Here is the file for values-v11.

 <?xml version="1.0" encoding="utf-8"?>
 <resources>

 </resources>

Here is the error.
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.txt2lrn.www/com.txt2lrn.www.LandingActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
 at android.app.ActivityThread.access$1500(ActivityThread.java:117)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
 at android.os.Handler.dispatchMessage(Handler.java:99)
 at android.os.Looper.loop(Looper.java:130)
 at android.app.ActivityThread.main(ActivityThread.java:3687)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:507)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
 at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
 at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:102)
 at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:98)
 at com.txt2lrn.www.LandingActivity.onCreate(LandingActivity.java:95)
 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
 ... 11 more

Sorry folks, I also do have android:theme="@style/Theme.Styled" defined in AndroidManifest.xml.
Comment: do you have another values folder that references Theme.Styled but does not use the AppCompat theme?
Comment: Does your manifest reference `Theme.Styled`?
Comment: @tyczj I have added the res/values-v11/themes.xml file and it does not reference Theme.Styled
Comment: @tyczj You can use use your comment as an answer since it can be a common issue (me too)
Comment: Possible duplicate of [You need to use a Theme.AppCompat theme (or descendant) with this activity](http://stackoverflow.com/questions/21814825/you-need-to-use-a-theme-appcompat-theme-or-descendant-with-this-activity)
Comment: For a very simple thing to try first, see http://stackoverflow.com/a/32426664/897007
Comment: Visit this [ link](https://stackoverflow.com/a/45940291/4832664) for solving the problem!
Answer: If you are extending ActionBarActivity in your MainActivity, you will have to change the parent theme in values-v11 also.
So the style.xml in values-v11 will be -

 <?xml version="1.0" encoding="utf-8"?>
 <resources>

 </resources>

EDIT: I would recommend you stop using ActionBar and start using the AppBar layout included in the Android Design Support Library
Comment: Excellent, I missed this. Don't forget all the other -vXX folders as well, or it'll work fine in your test env, only to bite you once someone uses one of those versions.
Comment: Thanks! Just changed ActionBarActivity to Activity! :)
Answer: To simply add ActionBar Compat your activity or application should use @style/Theme.AppCompat theme in AndroidManifest.xml like this:
   <activity
        ...
        android:theme="@style/Theme.AppCompat" />

This will add actionbar in activty(or all activities if you added this theme to application)

But usually you need to customize you actionbar. To do this you need to create two styles with Theme.AppCompat parent, for example, "@style/Theme.AppCompat.Light". First one will be for api 11>= (versions of android with build in android actionbar), second one for api 7-10 (no build in actionbar).
Let's look at first style. It will be located in res/values-v11/styles.xml . It will look like this:

And you need to have same style for api 7-10. It will be located in res/values/styles.xml, BUT because that api levels don't yet know about original android actionbar style items, we should use one, provided by support library. ActionBar Compat items are defined just like original android, but without "android:" part in the front:

Please mark that, even if api levels higher than 10 already have actionbar you should still use AppCompat styles. If you don't, you will have this error on launch of Acitvity on devices with android 3.0 and higher:

java.lang.IllegalStateException: You need to use a Theme.AppCompat
theme (or descendant) with this activity.

Here is link this original article http://android-developers.blogspot.com/2013/08/actionbarcompat-and-io-2013-app-source.html written by Chris Banes.
Answer: Check and make sure that you do not have another values folder that references theme.styled and does not use AppCompat theme
ie values-v11 folder
Comment: This was my problem too. I had a library project and had to import the appcompat-v7 library and make all the themes extend AppCompat themes. The thing is, my main project has the tools:replace="android:icon,android:theme" option added to the  and should leave out styles from other projects. For some reason that wasn't working.
Answer: Try this...
styles.xml
<resources>

</resources>

AndroidManifest.xml
   <activity
        android:name="com.example.Home"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Answer: Your Activity is extending ActionBarActivity which requires the AppCompat.theme to be applied.
Change from ActionBarActivity to Activity or FragmentActivity, it will solve the problem.
Answer: Just do it Build -> Clean Project. I think this will solve your problem.
Answer:
My manifest does not reference any themes... it should not have to AFAIK

Sure it does. Nothing is going to magically apply Theme.Styled to an activity. You need to declare your activities -- or your whole application -- is using Theme.Styled, e.g., :
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.Styled">

Comment: I was incorrect, I do have android:theme="@style/Theme.Styled" in my AndroidManifest.xml (I didn't see it the first time).
Answer: I had such crash on Samsung devices even though the activity did use Theme.AppCompat.
The root cause was related to weird optimizations on Samsung side:
- if one activity of your app has theme not inherited from Theme.AppCompat
- and it has also `android:launchMode="singleTask"`
- then all the activities that are launched from it will share the same Theme

My solution was just removing android:launchMode="singleTask"
Comment: Do you have a source for this? I've been tracking down a similar bug in my app for a while, and this sounds like a promising lead.
Comment: Same here! Would love to more about this! I've been tracking down a similar bug in my app too. Unfortunately, I do not use `android:launchMode="singleTask"`.
Comment: I observe the same issue. It's happening for Galaxy Tab A 10.1 (Android 7.0, not rooted and SM-A320FL (Android 7.0, not rooted). I don't use `android:launchMode="singleTask"` and all my activities use AppCompat theme :/
Answer: I encountered this error when I was trying to create a DialogBox when some action is taken inside the CustomAdapter class.
This was not an Activity but an Adapter class.
After 36 hrs of efforts and looking up for solutions, I came up with this.
Send the Activity as a parameter while calling the CustomAdapter.
CustomAdapter ca = new CustomAdapter(MyActivity.this,getApplicationContext(),records);

Define the variables in the custom Adapter.
Activity parentActivity;
Context context;

Call the constructor like this.
public CustomAdapter(Activity parentActivity,Context context,List<Record> records){
    this.parentActivity=parentActivity;
    this.context=context;
    this.records=records;
}

And finally when creating the dialog box inside the adapter class, do it like this.
AlertDialog ad = new AlertDialog.Builder(parentActivity).setTitle("Your title");

and so on..

I hope this helps you
Answer: I just get my application move from ActionBarSherlock to ActionBarCompat.
Try declare your old theme like this:


Inserir ScrollView em toda Activity

Question: Olá, preciso inserir uma ScrollView em todo layout.  Mas não estou conseguindo. Segue o meu código.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.gerdaumanagement.gerdaumanagement.MenuDrawer"
    tools:showIn="@layout/app_bar_menu_drawer"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/button1"
            android:layout_width="156dp"
            android:layout_height="156dp"
            android:text="Button" />

        <Button
            android:id="@+id/button2"
            android:layout_width="156dp"
            android:layout_height="156dp"
            android:text="Button" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/button3"
            android:layout_width="156dp"
            android:layout_height="156dp"
            android:text="Button" />

        <Button
            android:id="@+id/button4"
            android:layout_width="156dp"
            android:layout_height="156dp"
            android:text="Button" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/button5"
            android:layout_width="156dp"
            android:layout_height="156dp"
            android:text="Button" />

        <Button
            android:id="@+id/button6"
            android:layout_width="156dp"
            android:layout_height="156dp"
            android:text="Button" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/button"
            android:layout_width="156dp"
            android:layout_height="156dp"
            android:text="Button" />

        <Button
            android:id="@+id/button8"
            android:layout_width="156dp"
            android:layout_height="156dp"
            android:text="Button" />

    </LinearLayout>

</LinearLayout>

Answer: Fala Lucas,
Dentro do seu ScrollView, você só pode ter um Layout, por exemplo:
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent">

       <LinearLayout
          android:layout_width="wrap_content"
           android:layout_height="wrap_content">

           <Button
               android:id="@+id/button1"
               android:layout_width="156dp"
               android:layout_height="156dp"
               android:text="Button" />

           <Button
               android:id="@+id/button2"
               android:layout_width="156dp"
               android:layout_height="156dp"
               android:text="Button" />

       </LinearLayout>
       <LinearLayout
           android:layout_width="wrap_content"
           android:layout_height="wrap_content">

           <Button
               android:id="@+id/button3"
               android:layout_width="156dp"
               android:layout_height="156dp"
               android:text="Button" />

           <Button
               android:id="@+id/button4"
               android:layout_width="156dp"
               android:layout_height="156dp"
               android:text="Button" />

       </LinearLayout>
       <LinearLayout
           android:layout_width="wrap_content"
           android:layout_height="wrap_content">

           <Button
               android:id="@+id/button5"
               android:layout_width="156dp"
               android:layout_height="156dp"
               android:text="Button" />

           <Button
               android:id="@+id/button6"
               android:layout_width="156dp"
               android:layout_height="156dp"
               android:text="Button" />

       </LinearLayout>

       <LinearLayout
           android:layout_width="wrap_content"
           android:layout_height="wrap_content">

           <Button
               android:id="@+id/button"
               android:layout_width="156dp"
               android:layout_height="156dp"
               android:text="Button" />

           <Button
               android:id="@+id/button8"
               android:layout_width="156dp"
               android:layout_height="156dp"
               android:text="Button" />

       </LinearLayout>
   </LinearLayout>
</ScrollView>

Veja que dentro do ScrollView, tem um LinearLayout, e dentro do LinearLayout tem o restante dos componentes.
O ScrollView só pode ter um filho.
Comment: Muito obrigado Leonardo

Inserir ScrollView em toda Activity


how to check simple paths exist in bipartite graphs

Question: I have an outgoing neighborhood structure of a directed graph:
a{f}=[d e];
a{d}=[c];
a{e}=[c h];
a{h}=[b];
a{c}=[a b];

where a{f}=[d e] means that nodes d and e are the outgoing neighborhood of node f.
Now, my goal is to determine whether there exist two paths, one is from f to a, the other is from f to b, whose nodes are not allowed to be intersected each other?
For this example, the answer is affirmative, because we can find the two paths:
p1: f->d->c->a
p2: f->e->h->b

But when we delete the edge h->b in the graph, the answer is NO, because even if there are two paths:
p1: f->d->c->a
p3: f->e->c->b

however, the path p3 has a node c intersected with path p1.
  f
 / \
d   e
 \ / \
  c   h
 / \ /
a   b

My question is: is there any algorithms to check the existence of the two paths?
Comment: The Hopcroft-Karp algorithm checks for node-disjoint shortest augmenting paths to compute a maximum matching in bipartite graphs; using a similar technique to the one used in that algorithm, you might get what you want in time O(|V|^0.5 * |E|) which is the time complexity of Hopcroft-Karp. That's what I'd have a look at, apart from the suggestions in the answers that were already posted. Note one thing though, Hopcroft-Karp out of the box only finds node-disjoint paths of equal length. You'd also have to adapt it so the "source" f doesn't mess it up.
Answer: What you are looking for are the dominators of A and B in a flowgraph with starting point F. V dominates A if every path from F to A passes through V. So, for your particular problem, you can:

Compute and go through all the dominators of A, mark those vertices except F
Compute and go through all the dominators of B, and if any of those vertices are marked:
-> A and B have at least one common dominator D, so no two vertex-disjoint (apart from both containing F) paths F->A and F->B can exist, because every path F->A and every path F->B passes through D.

See http://en.wikipedia.org/wiki/Dominator_(graph_theory)#Algorithms
Answer: You could solve this with a max-flow algorithm by:

Construct a directed graph by splitting each of your vertices into an entry vertex and exit vertex
Add an edge from entry(i) to exit(i) with capacity 1 for each pair based on vertex i
Add an edge from exit(i) to entry(j) with capacity 1 for each edge i->j in your original graph
Add an extra terminal vertex e
Add an edge from the exit vertex for every destination (in your case exit(a) and exit(b)) to vertex e with capacity 1
Compute the maximum flow from exit(f) to e

If and only if the max flow is 2, then there are two vertex-disjoint paths from f to a/b.
Example Python code
import networkx as nx
G=nx.DiGraph()
a={'f':'de','d':'c','e':'ch','h':'b','c':'ab','a':'','b':''}
for v in a:
    i='entry_'+v
    j='exit_'+v
    G.add_edge(i,j,capacity=1)
    for dest in a[v]:
        G.add_edge(j,'entry_'+dest,capacity=1)
for dest in 'ab':
    G.add_edge('exit_'+dest,'e',capacity=1)
print nx.max_flow(G,'exit_f','e')

G.remove_edge('exit_h','entry_b')
print nx.max_flow(G,'exit_f','e')

This prints
2 (meaning that in the original graph there are 2 vertex disjoint paths)
1 (meaning that once we remove h->b, there is only 1 vertex disjoint path)


Recuperar dados do DB a partir de uma determinada data

Question: Estou criando uma api em node.js, utilizando express e Sequelize como ORM. Gostaria de saber, qual expressão devo utilizar para recuperar os dados do DB a partir de uma determinada data. Estou utilizando o date-fns para determinar qual data exata seria o início dessa semana e armazenando o valor em uma variável, chamada thisWeek, que retorna:
2019-12-29T03:00:00.000Z

Como utilizo essa variável - thisWeek - para retornar apenas os resultados no banco de dados a partir dessa data? Abaixo está o trecho de código que estou utilizando para recuperar os dados do DB.
const checkQtt = await Checkin.findAll({
      where: { student_id: id }
    });

Answer: Encontrei uma solução que resolveu meu problema:
Utilizei os Operadores do Sequelize. Para isso, importei-o:
import { Op } from "sequelize";

E no trecho de código onde recupero os dados do db e armazeno na variável, utilizei a seguinte expressão - [Op.gt] -, na qual me retorna apenas as linhas no qual o created_at sejam superiores à data da minha variável thisWeek:
const checkQtt = await Checkin.findAll({
      where: {
        student_id: id,
        created_at: {
          [Op.gt]: thisWeek
        }
      }
    });

Qualquer dúvida sobre trabalhar com os operadores no Sequelize, podem ser sanadas a partir da documentação: https://sequelize.org/master/manual/querying.html


Prove or disprove each of the follow function has limits $x \to a$ by the definition $\lim_{(x, y) \to (0, 0)} \frac{x^2y}{x^2 + y^2}$

Question: Prove or disprove each of the follow function has limits $x \to a$ by the definition
$\lim_{(x, y) \to (0, 0)} \frac{x^2y}{x^2 + y^2}$
Let $y = x^2$
$\frac{x^2 y}{x^2 + y^2} = \frac{x^4}{2x^4} = \frac{1}{2}$
If we let $x = 0$, then
$\lim_{(x, y) \to (0,0)} \frac{x^2y}{x^2+y^2} = \frac{0^2 \cdot 0}{0^2 + 0^2} = 0$
Therefore $\lim_{(x, y) \to (0, 0)} \frac{x^2y}{x^2 + y^2} = 0 \neq 1/2$
Therefore the limit does not exist because two different values.
Would this be correct?
Comment: No. $y=x^2$ gives limit $0$.
Comment: $0/0 \neq 0$...
Comment: You have asked a similar question at [here](https://math.stackexchange.com/q/2960120/514490). These two limits are identical since $x,y$ are symmetric here, so the answer should be the same as well. Then why did you conclude differently for these two?
Answer: Note that
$$
\left|\frac{x^{2}y}{x^{2}+y^{2}}\right|=\frac{x^{2}|y|}{x^{2}+y^{2}}=\frac{x^{2}\sqrt{y^{2}}}{x^{2}+y^{2}}\leq\frac{(x^{2}+y^{2})\sqrt{y^{2}}}{x^{2}+y^{2}}=\sqrt{y^{2}}\leq\sqrt{x^{2}+y^{2}}=\|(x,y)\|\to 0.
$$
Comment: So, the limit does exist ?
Comment: Yes, it's zero.
Answer: Note that if $y=x^2$, we have
$$\lim_{x \to 0}\frac{x^2 \cdot x^2}{x^2+x^4}=\lim_{x \to 0}\frac{x^2 }{1+x^2}=0$$
If we let $x=0$, we havae
$$\lim_{y \to 0}\frac{0^2 \cdot y}{0^2+y^2}=\lim_{y \to 0}0=0$$
In fact, the limit is $0$ since
$$\left|\frac{x^2y}{x^2+y^2} \right| =|y|\left| \frac{x^2}{x^2+y^2}\right|\le |y|\le \sqrt{x^2+y^2}$$


Spring Security, Apache 2 fronting Tomcat6. Can't login / immediatly logs out

Question: I deployed my GWT app, that uses SpringSecurity, and have a problem.
After feeding the credentials it logs out immediately. If I put in the wrong credentials, it says 'wrong credentials', but when I give correct ones it just goes back to the login screen.  (So mysql connection works)
My set up is like this:
Apache 2 fronting Tomcat6 on Ubuntu 10.04.2 LTS. I use mod_jk in between.
I've never used this mod_jk thing before, normally I have a standalone Tomcat, but requirements oblige me to use this now.
Q: Can it be that the Tomcat Session doesn't remember that a user is logged in, due to some mod_jk config stuff that I am missing? The requests are forwarded, so mod_jk seems to work fine.
Please provide me some hints where to look! Or should it be working already? Just wanting to know if there are standard procedures to take to make SpringSecurity work in a setup like this.
I followed the following tutorial to install mod_jk, and have the configuration exactly as discussed in that tutorial: http://www.howtoforge.com/how-to-install-tomcat6-with-sun-java-and-apache2-integration-on-ubuntu-10.04-lucid-lynx-with-virtual-hosts
Comment: If you enable HTTP in Tomcat and hit Tomcat directly does the problem persist?  If so, this is likely a coding problem and belongs on Stack Overflow.
Comment: You mean hitting it from the normal connector on port 8080, as configured in server.xml? (ie. ``)
Comment: That also gives the error, so you reckon it is a code problem...? Because it does run on stand-alone tomcat5.5...
Comment: (which is a different server of mine). So it could also be a Tomcat6 problem? Or something has changed on T6 vs T5.5?
Comment: Cancel that! Hitting the url directly using port 8080, it does work!
Comment: What the. Now it just seems to work, and I didn't change a thing. This one is beyond me.
Answer: I dealt with this same issue for a bit myself in the past.  Had some configurations work in 1 browser and not another.  However, I found the fix to be that you should not be using http and port 8080 in your apache httpd configuration.  You should be using ajp and port 8009 (which tomcat has on by default).  The required parts of the configuration I have outlined below:
<code>LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_module modules/mod_proxy.so

...

## App Configuration
ProxyPass    /app1                           ajp://localhost:8009/app1
ProxyPass    /app1/j_spring_security_check   ajp://localhost:8009/app1/j_spring_security_check
ProxyPass    /app1/j_spring_security_logout  ajp://localhost:8009/app1/j_spring_security_logout
</code>
Note: I didn't include obviously the references to virtual host and what not because that will really be specific to your configuration.  Also as long as you haven't modified your tomcat servers AJP connector port you shouldn't have to do anything to your tomcat instance.


Lossless Compression Of Data Tables Leveraging Exploratory Analysis?

Question: Lossless compression of data tables seems a natural application of automated modeling based on exploratory data analysis methods.  While such automatically generated models are not reliable for statistical inference, they are able to predict the contents of the data table better than general file compression techniques.
The quick and dirty model's information content plus that of residual errors requires far fewer bits than the data tables in their, say, gzipped form.
Are there such utilities available for statistical databases?
Comment: I strongly suggest that you read Hadley Wickham's [Tidy Data manuscript](http://vita.had.co.nz/papers/tidy-data.html). One could also argue that you should use a relational database. I'm sure there are suitable frameworks for such databases that enable a good compression.
Answer: My experience lies in sparse matrices for optimization.  Hopefully somebody more knowledgeable will come along to replace my answer.
I took a quick look at sparse matrices in R and found this:  http://www.johnmyleswhite.com/notebook/2011/10/31/using-sparse-matrices-in-r/
Potential for 1000-fold storage reduction - depending upon proportion of zeros.
As to approach, I would store the data for each metric in its own sparse matrix.
Each matrix then consists of a series of entries:  (country, year): observation.
Your data file would consist of a stack of sparse matrices, one for each metric you are storing.
Comment: By "zeros" I presume you mean missing data which, in "R" is represented as "NA" (or "NULL"?).  Right?  So you're saying each matrix would use the GeoCode (which is a positive integer) to index one matrix dimension and the other matrix dimension's index would be the year.  Then the `stack` function composes these 2D matrices into a single "stack" object, indexed by the name of the measure.  This object can then be written out to a single .Rdata file with a call to `save`.  Is that correct?
Answer: The answer is "Semantic Compression" of relation tables.  The most recent work in this area is the 2018 PhD thesis "EXTRACTING AND UTILIZING HIDDEN STRUCTURES IN LARGE DATASETS".


Is there a list of recommended problems to do in each chapter of Spivak's Calculus anywhere?

Question: I've recently been self-studying Spivak's Calculus, and since I don't have the time to do every problem from every chapter at a and finish at reasonable rate, I've looked for a course syllabus or something similar that would have assignments for each section. Unfortunately, I haven't found anything that isn't a dead link.
I know this has been answered here, but it only has dead links.
Answer: I found the assignments from the dead link previously posted.
Here is the list in case the link dies again.
HOMEWORK
Assignment 1: Due in class, Thursday August 25, 2011
required: Chapter 1: 1, 2, 5, 6, 10, 11, 13, 14, 15, 20, 25
extra: Chapter 1: 16, 17, 22
Assignment 2: Due 4 pm, Friday September 2, 2011
required: Chapter 2: 1,2, 3 parts a through d, 5, 6 parts (i) and (ii), 8, 9, 12, 13, 14, 16, 19, 26
extra: Chapter 2: 3 part e, 4, 6 parts (iii) and (iv), 17, 18, 20, 27, 28
Extra Extra Problem 1 (Division Theorem):
a) Let a and b be positive integers. Show that there exists natural numbers q and r such that a = qb + r and 0 <= r < b.
b) Show that the q,r of part a) are unique: i.e., if there is any other pair (q',r') of natural numbers satisfying the same property, then q = q' and r = r'.
c) Extend the results of parts a) and b) to the case where a is any integer.
Assignment 3: Due in class, Friday September 9, 2011
required: Chapter 3: 1-4, 6, 8; Chapter 4: 1-4, 6, 11
Assignment 4: Due in class, Friday September 16, 2011
required: Chapter 3: 9, 12, 13, 26; Chapter 4: 11, 12, 14, 17 parts (i) and (ii)
Hint for Problem 3.13: For any function f, f(x) + f(-x) is even
Assignment 5: Due in class, Friday September 23, 2011
All of the following problems are required. Please read the instructions carefully.
Chapter 9: For these problems, you may (for now!) treat limits intuitively, as we did in Week 4 of class. Exercises: 1,2,3,7,9
Chapter 6: For these problems, you need not prove your answers (for now!) using the epsilon-delta defintion of continuity. Exercises 1,4,5
Chapter 5: Exercise 1
Required Problem V.1:
a) Write down the formal, epsilon-delta definition of continuity of a function f at a point x = c. Draw a picture to accompany your definition.
b) Write down the formal definition of a continuous function.
c) Show that for any real numbers m,b, the function y(x) = mx+b is continuous.
d) Give an example -- with proof! -- of a function which is not continuous at some point x = c of its domain.
Assignment 6: Due in class, Thursday October 6, 2011
required: Chapter 5: 7, 8, 10, 15, 16, 18, 20, 21; Chapter 6: 3, 13, 14
extra: Chapter 6: 7
Assignment 7: Due in class, Friday October 14, 2011
required: Chapter 9: 5, 13, 16, 19, 23; Chapter 10: 1, 2 [feel free to ignore the somewhat obnoxious comment about not taking too much longer than 20 minutes: take as long as you want and need!], 3, 4, 5
extra: Chapter 9: 28
Assignment 8: Due in class, Friday October 21, 2011
required: Chapter 10: 7, 9, 11, 16, 20, 23, 24; Chapter 11: 1, 2, 6
extra: Chapter 10: 31, 33, 34
Assignment 9: Due by 5pm, Monday October 31, 2011
required: Chapter 11: 7 through 14; Chapter 12: 1, 4, 5, 7, 15
extra: Let J be a nonempty interval which is not of the form [a,b]. Let J be any nonempty interval. Show that there is a continuous function f: I --> R with image f(I) = J.
Assignment 10: Due in class, Wednesday November 9 Thursday, November 10, 2011
required: Chapter 11: 23, 25, 27, 29, 30, 33, 38, 62; Chapter 12: 14, 20
extra: Chapter 11: 26, 31
Extra Extra Problem 2: Prove the Lambda-Vee Lemma. (See page 24 of the lecture notes on differentiation.)
Assignment 11: Due in class Friday, November 18, 2011
Please read Chapters 7 and 13 of Spivak's text.
Required: Chapter 7: 2, 5, 7, 10, 14, 16
Extra: Chapter 7: 12, 13, 17, 21
Assignment 12: Due in class Monday, November 28, 2011
Please read Chapter 8 of Spivak's text. (Extra: take a look at my lecture notes on integration.) Also, please solve and turn in Exercise 1.2 on page 4 from my lecture notes on completeness.
Assignment 13: Due by office hours on Wednesday, December 7, 2011
Comments on the homework: Let's agree not to use extended real numbers in your solutions to this problem set: e.g., if a subset is unbounded above, you should say that it does not have a least upper bound, not that its least upper bound is infinity. Also you may use real induction if you want, but the problems are not designed for this to be necessary (or even, it seems to me, especially helpful).
Required: Chapter 8: 1, 3, 4a), 5, 6, 7, 10, 14, 17, 20
Extra: Chapter 8: 11, 15, 16
Extra Extra: Looking through the exercises in Chapter 8 I found several that I could not assign because we have covered them in class, or they are in the lecture notes, or they have been covered in solutions to review / exam problems on the course webpage. For one point of extra credit each, find such problems and document your claim by giving a reference to the appropriate course materials.
Spring Semester Homework Assignments:
Assignment 1: Due in class Friday, January 27, 2012
Please read Chatpter 13 of Spivak's text and solve problems 1, 5, 7 from that chapter. Also please solve the following:
Extra 1.1: Use Newton's method to find a rational number x which approximates the square root of 2012 to at least 20 decimal digits of accuracy.
Extra 1.2: Let a > 0, and let f(x) = x2 - a. We showed in class that there exists delta > 0 such that for all x1 in [a-delta,a+delta], the Newton's method sequence converges to the square root of a. Show that this actually holds for all x1 > 0. (Hint: try to find the largest set on which the amelioration function T(x) is contractive.)
Added: This problem turned out to be harder than I expected. So I am making this problem extra credit. Let me ask you instead to show that there exists C < sqrt{a} such that for all x1 greater than or equal to C, the Newton's method sequence converges.
Extra 1.3: In class I said that a convex function defined on an interval I is continuous. In fact this holds only when I is an open interval: i.e., does not contain any endpoints.
a) Find a convex function with domain [0,1] which is not continuous at 0.
b) Let f be a continuous convex function with domain [0,1]. Find all real numbers L such that if we redefine f at 0 to be equal to L, then the resulting function remains convex.
Extra 1.4: For a continuous function f defined on an interval I, show that the epigraph of f is convex iff every secant line lies on or above the graph of f.
Extra 1.5: Prove Jensen's Inequality.
Extra 1.6: Use Jensen's Inequality to prove the Weighted Arithmetic-Geometric Mean Inequality.
Assignment 2: Due in class Friday, February 3, 2012
Required: From Chapter 13 of Spivak's text: 3, 10, 11a),b),c), 19, 20, 23, 26 [Hint for part c): Thomae's Function], 30a),b), 33
Extra Credit: From Chapter 13: 11d), 15
Assignment 3: Due in class Friday, February 10, 2012
Please read Chapter 14 of Spivak's text and do the following problems: 1 (do any four parts), 2, 3 (beware: part b) is tricky!), 4 (hint: you are trying to show the functions are constant: what's the differential calculus approach to this?), 6, 15, 19, 21, 25, 26 (hint: do not use the fundamental theorem!).
Extra Credit 3.1: Prove by Real Induction that if g is continuous and f is integrable, then the composite function g o f is integrable.
Assignment 4: Due in class Wednesday, February 22, 2012
Please read (or at least skim) Chapters 18 and 19 of Spivak's text and do the following problems:
Chapter 18: 1 (do any four parts), 2, 3, 6, 7, 10 (extra credit: this function, the logarithmic integral, is extremely important in mathematics: why??),
Chapter 19: 1 (do any four parts), 2 (do any five parts), 3 (do any five parts).
Assignment 5: Please turn in any ten of the following problems by Friday, March 9, 2012. Then, please turn in eight more of them by Monday, March 19, 2012.
Chapter 22: 1 (any four parts), 2 (any four parts), 3, 4, 5, 6, 7 (parts a and b only), 8, 9, 11, 12, 13, 16, 17, 18, 19, 20, 21 (part a only), 22, 23, 24, 25, 27, 28, 30, 31.
Assignment 6: due in class Monday, April 2, 2012.
Chapter 23: 1 (any ten parts), 4, 5, 7.
Assignment 7: due in class Monday, April 16, 2012.
Rquired: Chapter 23: 1 (please do six more parts disjoint from the ten you did last time), 3, 6, 7, 8, 13, 24, 25.
Chapter 20: 1,2,3
Also do the following
Problem 7.1: For which positive integers p,q,r does the series sumn 1/(np (log n)q (log log n)r) converge?
Extra Credit: The title of Chapter 12 in my lecture notes is Taylor Taylor Taylor Taylor. Ostensibly this holds because the chapter has four sections: Taylor's Theorem Without Remainder, Taylor Polynomials, Taylor's Theorem With Remainder, Taylor Series. But more than this I am trying to make an allusion to the character Major Major Major Major from Joseph Heller's great novel Catch 22. I am looking for a passage from the novel concerning this character, containing text that either has some mathematical significance or could be misinterpreted as such. Please help!
Assignment 8>: due in class Monday, April 29, 2012.
Required: Chapter 20: 1, 3, 5, 8, 14, 18
Chaper 24: 1, 3, 5, 8, 14
Extra Credit: Chapter 24: 16, 19, 20
Comment: to prevent problems when liks go dead you can write the assignments here in this post instead of providing just the link
Comment: these were made by our very own @PeteL.Clark [link](https://math.stackexchange.com/users/299/pete-l-clark)
Comment: "due in class", "required", etc has nothing to do with the Spivak book.
Comment: I just copy pasted the homework from the website.
Comment: The last but not the least, you give to yourself the green chevron. Is it a joke ?
Comment: When I asked I did not know the answer. Is it wrong to answer my own question? Apparently 4 years ago, a link containing that exact content for this answer was satisfactory.


Messy system with Langrange multipliers

Question:
$f(x,y) = (3-x)(3-y)(x+y-3)$

I'm trying to find and classify the critical points of the former function. I have that
$$\displaystyle\frac{\partial f}{\partial x} = (3-y)(-x^2-xy+2x+3) \\\displaystyle\frac{\partial f}{\partial y} = (3-x)(-y^2-xy+2y+3)$$
Then both partial derivatives are zero for $(0,0)$ because of the first term of each one.
Now, if we add up the second term of both partial derivatives and multiply the result by $-1$ we have
$$x^2+y^2-2x-2y=0 \equiv (x-1)^2+(y-1)^2-2=0$$
To find extrema in the last circumference I'm using Lagrange multipliers.
Let $g(x,y)=(x-1)^2+(y-1)^2-2=0$. Then taking $L(x,y)=f(x,y)-\lambda g(x,y)$ and its partial derivatives within the system
$$\begin{cases} \displaystyle\frac{\partial L}{\partial x} = 0\\ \displaystyle\frac{\partial L}{\partial y}=0 \\ \displaystyle\frac{\partial L}{\partial \lambda} =0\end{cases}$$
I have
$$\begin{cases} x^2+xy^2-5xy-3x^2+6x-3y+9=2x\lambda+2\lambda\\ x^2+xy^2-5xy-3y^2+6x-3x+9=2y\lambda+2\lambda \\ (x-1)^2+(y-1)^2-2=0\end{cases}$$
Here is where I'm stuck. I'm not sure how to solve this system. Since the first and second equation are alike, if I subtract them I get $3(y^2-x^2)+3(y-x)+2\lambda(y-x)=0$, but I don't see how this helps me to get a solution.
Answer: This was a hard question
A common technique is to find the x,y restrictions for equations 1 and 2 to be equal to later be used in equation 3 to find actual values of x and y. A great way to do this is by manipulating dg(x) and dg(y) so that dg(x) = dg(y) and so then df(x) = df(y) and from there find restrictions.
$$dg(x) = 2\lambda x+2\lambda$$ $$df(x) = dg(x)$$
Knowing:
$$ df(x) = \lambda 2(x+1) $$ $$df(y) = \lambda 2(y+1)$$
You multiply dg(x) by what dg(y) has that dg(x) doesn't and vise versa to make them equal.
thus.. $$ dg(x)(y+1) = dg(y)(x+1)$$ $$ \lambda 2(x+1)(y+1) = \lambda 2(y+1)(x+1)$$
and $$\lambda (y+1)df(x) = \lambda (x+1)df(y)$$ (multiply by lambda to include lambdas effect on the restriction)
$$\lambda (y+1)(x^2+xy^2-5xy-3x^2+6x-3y+9) = \lambda (x+1)(x^2+xy^2-5xy-3y^2+6x-3x+9)$$
Now after lots of painful algebra:
$$\lambda ((33y-13y^2+y^3+2xy^2)-(33x-13x^2+x^3+2x^2y)) = 0$$ $$ \lambda \not= 0 $$ $$ 33y-13y^2+y^3+2xy^2 == 33x-13x^2+x^3+2x^2y $$
from this $$ y = x $$
now into equation 3 $$ (x-1)^2+(x-1)^2 = 2 $$ $$ 2(x-1)^2 = 2 $$
$$ (x-1)^2 = 1 = x^2-2x+1 $$ $$ x(x-2) = 0$$
From this, critical points at x = 0 y = 0 and x = 2 y = 2
Max f(2, 2) = 1
Min f(0, 0) = -27
Confirmed by wolfram alpha

Messy system with Langrange multipliers


Por que ao acessar a propriedade de uma classe só preciso usar um cifrão ("$this->propriedade" em vez de "$this->$propriedade")?

Question: Por que não precisa colocar $ na variável nameHolder no retorno do método showHolder() e quando coloca $nameHolder no retorno diz que a variável não está definida?
class Account
{
    private string $cpfHolder;
    private string $nameHolder;
    private float $balance = 0;

    public function showHolder(): string
    {
        return $this->$nameHolder; // não funciona.
        return $this->nameHolder; // funciona.
    }

}

Answer: PHP nunca foi muito bem pensada. Quando criaram as variáveis inventaram que elas deveriam ser precedidas por $ na sua sintaxe. Embora isso seja um facilitador para algumas situações, não é para todas, e dificulta a maioria dos usos. Isso nunca deveria ter sido criado assim.
Quando criaram uma variável dentro de outra variável acharam que podiam consertar isso, ou mesmo que não era necessário duplicar esse esforço errado que já fazia, então acharam melhor não colocar assim tornando a linguagem inconsistente e estranha porque a mesma variável usa o símbolo ou não dependendo de onde é usada.
O símbolo na verdade era para indicar uma expressão a ser tratada de forma diferente, então ele deveria ser usado só em contexto que isso faz sentido. Ao mesmo tempo deveria ser usado para casos que não é uma variável, por isso jamais deveria estar atrelado ao nome.
Se já tem o $ na variável principal não deve usar de novo. Então ficou uma regra de exceção que você tem que saber e usar.
Porém tem uma outra questão. Não existem classes no PHP. Sim, o que você está vendo é uma ilusão, assim como é em PHP e quase todas linguagens de tipagem dinâmica. Elas usam protótipos, ou seja, usam objetos (geralmente alguma forma de array associativo que já podem até existir na linguagem) para armazenar os membros que o objeto teria. A sintaxe de classe é apenas sugar para ficar mais fácil para as pessoas que não gostam ou não entendem os protótipos.
Então o seu código na verdade é isto:
$this['nameHolder']

Está vendo o $ no segundo nome? E abaixo?
$this[$nameHolder]

São coisas diferentes, não? E são válidas, certo? Mesmo que não saiba, é valido sim, você está substituindo um valor por uma variável, como deveria poder em todos lugares (em PHP teve uma época que não podia, e eles arrumaram isso com o tempo, não sei se ainda tem algum lugar que não dá).
O código acima faz sentido, mas quando quer usa a classe quer outro tipo de sintaxe, e quer usar algo que foi consagrado em linguagens de tipagem estática. Mais ainda, segue a tendência de PHP de dar contratos fortes para tudo, portanto uma classe deveria ser vista como algo que não pode ser alterada ou acessado de forma dinâmica, que é isso que está fazendo.
Claro que isso tiraria a flexibilidade que eles preferiram manter, mas tornam a linguagem sem identidade e no fim não dá vantagem que pretendem ter dos contratos fortes.
Então eles mantiveram a possibilidade se usar a variável no lugar do nome literal da membro do objeto e dar a flexibilidade. Eu discordo da decisão até por ficar esquisito, mas principalmente por quebrar o contrato forte que espera de uma classe.
Então por que não deu certo se isso é aceito? O "não funciona" significa apenas que não tem um membro sem nome. E porque está referenciando um membro sem nome? Porque $nameHolder, que não tem qualquer valor, é uma variável que não existe, e PHP aceita uma variável que não existe como se existisse, pegando um valor não existente.
Note que precisaria criar uma variável local para funcionar. Até poderia usar o campo, mas aí ele precisaria ser referenciado com o $this, o que fica mais confuso.
Coloquei no GitHub para referência futura.
Comment: A pessoa que votou negativo pode dizer qual é o erro na resposta. Pode comentar ou dar uma resposta. Caso contrário saberemos que é só desgosto mesmo.
Answer: $this->$nameHolder não funciona da forma que você espera por causa das variable variables (que em português foi traduzido como "variáveis variáveis").
Basicamente, você pode usar uma variável que contém o nome de outra variável, e obter o valor desta diretamente. Por exemplo:
$nome = 'Fulano';

$x = 'nome';
echo $$x; // Fulano

O código acima imprime "Fulano". Isso porque a expressão $$x é avaliada como "a variável cujo nome é o valor de $x". Como o valor de $x é a string "nome", então $$x é o mesmo que $nome, por isso o resultado é a string "Fulano".

Isso também ocorre se usar o $ para acessar a propriedade de uma classe.
Ou seja, $this->$nameHolder irá procurar pela propriedade cujo nome é o valor da variável $nameHolder. Exemplo:
class Account {
    private $nameHolder = 'Fulano';
    private $balance = 0;

    public function test() {
        $nameHolder = 'balance';
        echo "Balance:". $this->$nameHolder. "\n";
        echo "Holder:". $this->nameHolder. "\n";
    }
}

$c = new Account();
$c->test();

No primeiro echo, a expressão $this->$nameHolder pegará o valor da variável $nameHolder (que apesar de ter o mesmo nome da propriedade da classe, não é a mesma variável). O valor é a string "balance", então a expressão pega o valor da propriedade que tem esse nome (ou seja, é o mesmo que $this->balance).
Já no segundo echo estou pegando a propriedade nameHolder. A saída do código acima é:
Balance:0
Holder:Fulano

O que acontece no seu código é que não há nenhuma variável $nameHolder definida, portanto ele não consegue avaliar a expressão $this->$nameHolder (ele tenta pegar o valor de $nameHolder, mas como essa variável não existe, dá erro).
Comment: @AugustoVasques Acho que se a pergunta fosse sobre como funcionam as *variable variables*, aí faria sentido falar de todos os casos. Mas aqui é sobre um caso particular apenas, não sei se precisa se aprofundar tanto...
Comment: Não tinha visto.... :D. Não sei se está dentro do escopo da resposta mas as "variáveis variáveis" tem dois dois casos especiais que não podem ser referenciados o `$this` e as variáveis superglobais.
Answer: O $this já faz isso! Ela diz, variável essa, poderia ser, essa variável, só que no lugar de variável é informado $, grosso modo e "entedível" pra leigos é isso!


WMI Security issue

Question: When I am trying to access WMI from a remote domain controller using WMIMGMT.MSC, I keep getting "Failed to connect to \(remote server) because 'Win32: Access is denied.'.  Does anyone have any ideas on what could be causing this?
I have tried many of the different howtos I found through google and none of them worked. I renamed the logs and repository folder under C:\system32\wbem and rebuilt the repository. After this didn't work, I went into the security tab under WMI Control and allowed 'Everyone' all rights. This did not fix the problem. I believe it has something to do with impersonation, but when I tried a few google searches for this, it brought up scripting and programming help.
I can access WMI locally on the remote computer with no issues
Comment: Something else to add. I can access WMI locally on the remote computer with no issues.
Comment: When you write "remote domain controller", are you talking about a domain controller in the same domain, or in a "remote" domain (one that doesn't trust your domain)
Comment: It belongs to the same domain.
Answer: It sounds like a firewall issue. You can run netsh firewall set service RemoteAdmin enable to create the firewall exception for remote WMI access.
If the account that you're using is not an administrator on the target machine, you'll also need to configure some DCOM settings on the target machine, as outlined here.
Comment: If it was a DCOM issue, wouldn't it prevent me from viewing the event viewer and services remotely? I am able to remotely view the event viewer and services. Also, I do not have windows firewall enabled on the machine.

WMI Security issue


Recreating solution file in Visual Studio 2010

Question: I need help re-creating a web solution file (at least I think that is what I need). I inherited a web application from another developer that left our company. It was created in Visual Studio 2010 and uses ASP.Net 2.0. There was no solution file, so I created a web application project and manually added all folders and files into my new solution. I did not make any changes to any file in the web application.
When I run the app from within Visual Studio, it starts up to the default page fine, but when I click a link on that same page, I get:

Server Error in '/' Application.

The resource cannot be found.
  Description: HTTP 404. The resource you are looking for (or one of its dependencies) could
have been removed, had its name changed, or is temporarily unavailable.  Please review the
following URL and make sure that it is spelled correctly.

   Requested URL: /SomeCompany/startProject.aspx

Version Information: Microsoft .NET Framework Version:2.0.50727.8009; ASP.NET Version:2.0.50727.8008

My original start location: http://mylocalurl:65212/default.aspx
Link on the default page: http://mylocalurl:65212/SomeCompany/startProject.aspx
If, after clicking the link and getting the error page, I can remove "/SomeCompany/", and successfully get to the page. But I've seen the previous developer run it in Visual Studio and click the exact same link with no problem.
I need it to have the /SomeCompany/ in the url and work just like the previous developer had it so I can maintain and debug it as needed. What am I doing wrong in re-creating the solution...or is it another setup problem that I am not thinking of?
Comment: Web.config, URL rewriting.  IIS Setup?
Comment: I've checked the web.config and there is no url rewriting. It is being run from Visual Studio, using file system, so there should not be any IIS setup should there?
Answer: You could have probably just used file -> open web site. It probably is not a Web Application. Visual Studio has multiple types of web projects. Visual Studio will create a solution for you that you can save after you open the website.
Web Application Projects versus Web Site Projects in Visual Studio
Comment: I tried that and it opens without giving me the /SomeCompany/ that I am looking for.
Comment: One thing I that I might have figured out. I am using Visual Studio 2013 (I missed saying that in my original post). VS 2013 opens it up without the /SomeCompany/ structure, but when I go to my old laptop, which has VS 2010, I can open it and it has the structure I want. Is there something in VS 2013 that I need to configure to get it to open the same as when in VS 2010?
Comment: Try creating a web application in IIS under /SomeCompany/ then open website from IIS instead of file system


Javascript loop drop-down options

Question: I have just started learning vanilla JavaScript and I'm trying to create a drop-down menu targeting the HTML snippet.
I attempted to use the loop method to create 25 options but it only displays 1.
My code:
<select name="25dropdown" id="25dropdown">

</select>

Comment: Possible duplicate of [innerHTML with For Loop in Javascript](https://stackoverflow.com/questions/12996763/innerhtml-with-for-loop-in-javascript)
Answer: In each iteration you are replacing the HTML, but you have to keep the previously added HTML as well. Try += instead of =

<select name="25dropdown" id="25dropdown">

</select>

Javascript loop drop-down options


Jquery não valida senha Incorreta

Question: Tenho o seguinte jQuery
$(document).ready(function(){

    $('#email').focus();
    $("#formLogin").validate({
         rules :{
              email: { required: true, email: true},
              senha: { required: true}
        },
        messages:{
              email: { required: 'Campo Requerido.', email: 'Insira Email válido'},
              senha: {required: 'Campo Requerido.'}
        },
       submitHandler: function( form ){
            var dados = $( form ).serialize();
            $.ajax({
              type: "POST",
              url: "<?php echo base_url();?>entrega/verificarLogin?ajax=true",
              data: dados,
              dataType: 'json',
              success: function(data)
              {
                if(data.result == true){
                    window.location.href = "<?php echo base_url();?>entrega";
                }
                else{
                    $('#call-modal').trigger('click');
                }
              }
              });
              return false;
        },

        errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
            $(element).parents('.control-group').addClass('success');
        }
    });

});

E tenho o método VerificarLogin, no CodeIgniter.
public function verificarLogin(){

    $this->load->library('form_validation');
    $this->form_validation->set_rules('email','Email','valid_email|required|xss_clean|trim');
    $this->form_validation->set_rules('senha','Senha','required|xss_clean|trim');
    $ajax = $this->input->get('ajax');
    if ($this->form_validation->run() == false) {

        if($ajax == true){
            $json = array('result' => false);
            echo json_encode($json);
        }
        else{

            $this->session->set_flashdata('error','Os dados de acesso estão incorretos.');
            redirect($this->login);
        }
    }
    else {

        $email = $this->input->post('email');
        $senha = $this->input->post('senha');

        $this->load->library('encrypt');
        $senha = $this->encrypt->sha1($senha);

        $this->db->where('email',$email);
        $this->db->where('senha',$senha);
        $this->db->where('status',1);
        $this->db->limit(1);
        $usuario = $this->db->get('usuario')->row();
        $permissao = $usuario->idPermissao;

        $sql = "SELECT * FROM permissoes WHERE idPermissao = '{$permissao}'";
        $permissao = $this->db->query($sql)->row('permissoes');

        if(count($usuario) > 0){

            $dados = array('nome' => $usuario->nome, 'empresa' =>  $usuario->empresa, 'id' => $usuario->idUsuario, 'idCliente' => $usuario->idCliente, 'permissao' => $usuario->idPermissao, 'permissoes' => $permissao, 'logado' => TRUE);
            $this->session->set_userdata($dados);

            if($ajax == true){
                $json = array('result' => true);
                echo json_encode($json);
            }
            else{
                redirect(base_url().'entrega');
            }

        }
        else{

            if($ajax == true){
                $json = array('result' => false);
                echo json_encode($json);
            }
            else{
                $this->session->set_flashdata('error','Os dados de acesso estão incorretos.');
                redirect($this->login);
            }
        }

    }

}

E o HTML:
<form  class="form-vertical" id="formLogin" method="post" action="<?php echo base_url()?>entrega/verificarLogin">
      <?php if($this->session->flashdata('error') != null){?>

              <button type="button" class="close" data-dismiss="alert">×</button>
              <?php echo $this->session->flashdata('error');?>

      <?php }?>

<img src="<?php echo base_url()?>assets/img/logo-home.png" alt="Logo" />

                <input id="email" name="email" type="text" placeholder="Email" />

                <input name="senha" type="password" placeholder="Senha" />

        <button class="btn btn-info btn-large"/> Logar</button>

</form>

Na hora de entrar, entra normal se a senha estiver certa.
Se estiver errada, não vem a mensagem... e não estou conseguindo achar o erro.
Answer: Aparentemente a validação do login no banco de dados esta sendo feita na condição:
"if(count($usuario) > 0){"
então caso não exista o login e senha digitado, ele entra no else.
Portanto acho que o programa identifica o erro nesse else.
Para saber se está nesse trecho de código, você tem que dar um print dentro dessa condição e fazer um teste com um login que não existe. segue exemplo:
if($ajax == true){

  print('a');

  $json = array('result' => false);
  echo json_encode($json);
} else {

  print('b');

  $this->session->set_flashdata('error','Os dados de acesso estão incorretos.');
  redirect($this->login);
}

se printar "a" ou "b", você já saberá onde alterar o programa para que seja exibido um erro ao entrar com um login inválido.
Espero ter ajudado.

Jquery não valida senha Incorreta


How to add days to a DateTime variable with custom format

Question: I'm using two DateTime Pickers each with a custom format "dd-MMM-yy"
I try to add one day to them but it isn't working.
Here's my code:
DateTime current = from_txt.value;
current.AddDays(1);

DateTime Picker from_txt properties.
custom format = "dd-MMM-yy"
Format = custom format

I want to add one day as I said before without changing the format. Is it possible?
Thanks in advance
Comment: Please, note that `current.AddDays(1);` adds one day and then *throws away* the result
Comment: What does the format have to do with adding a day to it? What do you mean by "it isn't working"?
Comment: Do this: `var current = DateTime.ParseExact(from_txt.value, "dd-MMM-yy", CultureInfo.InvariantCulture);`
Comment: @DavidConrad Not working means days are not getting added. I used MessageBox to display current. There I noticed that the date remained same throughout. Hope now you understood my problem. :(
Comment: @DmitryBychenko Yes I noticed that. so I did this : `current = current.AddDays(1);` Now my problem is rectified. I sincerely thank eveyone for helping me out.
Answer: Once you add the days you have to save that in another variable. As clearly stated above, the AddDays() method throws away that value.
We can do this :-
DateTime new_date = current.AddDays(1);

The new_date variable  will have the incremented value.


How to display HTML stored in a database from an ASP.NET MVC view?

Question: I have HTML code edited by FCKEditor stored in a database and would like to display (well render) it onto a view. So, for instance, something stored as:
<>pre<>This is some sample text<>pre</&gt

Will be displayed to the user as:
This is some sample text

(With the appropriate style for pre-formatted-text)
The view already has the required string to display from ViewData, I'm just not sure what the best way to show it to the user is.
Answer: Try this:
<%= System.Web.HttpUtility.HtmlDecode(yourEncodedHtmlFromYouDatabase) %>

More info here.
Comment: this doesn't work for Razor, for Razor use @Html.Raw(System.Web.HttpUtility.HtmlDecode(Model.yourhtmlvalue))
Comment: Checking the date of my answer .. it was PRE Razor :P
Comment: Thanks for bringing the date to my attention Pure, I have quoted just for somebody's info, its true Razor was not in existence when u posted your answer.
Answer: The answer provided by Pure.Krome is flawless for MVC2, but consider Razor syntax:
@Html.Raw(System.Web.HttpUtility.HtmlDecode(Model.yourEncodedHtmlFromYourDatabase))

Alternatively,
@Html.Raw(Server.HtmlDecode(Model.yourEncodedHtmlFromYourDatabase))

Comment: How can I make it so to be a link text
Answer: You want to use @Html.Raw(str).
See MSDN for more information.

Returns markup that is not HTML encoded.
This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.


How does Java structure memory for an object's members?

Question: I'm trying to figure out how Java structures/allocates memory for objects. (Yes this is implementation specific. I'm using the Oracle 1.7 runtime for this.) I did some work on this here and here and the results are confusing.
First off, in both referenced links, when I allocated an array of objects, the equivalent of new Object[10000], it used 4 bytes per object. On a 32-bit system this makes perfect sense. But I'm on a 64-bit system so what's going on here?

Is Java limited to a 32-bit address space even on 64-bit systems?
Is Java limited to a 32-bit address space per array and each array object then has a pointer to where the elements are?
Something else?

Second, I compared the memory footprint of 8 booleans vs. a byte as the variables in a class. The 8 booleans requires 24 bytes/object or 3 bytes/boolean. The single byte approach requires 10 bytes/object.

What is going on with 3 bytes/boolean? I would understand 4 (making each an int) and definitely 1 (making each a byte. But 3?
And what's with expanding a byte to 10 bytes? I would understand 8 where it's expanding a byte to a native int (I'm on a 64-bit system). But what's with the other 2 bytes?

And in the case of different ways to create a RGB class it gets really weird.

For a class composed of 3 byte variables it uses 24 bytes/instance. Expensive but understandable as each uses an int.
So I tried where each class is a single int with the RGB stored in parts of the int (using bit shifting). And it's still 24 bytes/instance. Why on earth is Java taking 3 ints for storage? This makes no sense.
But the weirdest case is where the class has a single variable of "byte[] color = new byte3;" Note that the byte is allocated so it's not just a null pointer. This approach takes less memory than the other two approaches. How???

Any guidance as to what is going on here is appreciated. I have a couple of classes that get allocated a lot and the flywheel pattern won't work (these objects have their values changed all over the place).
And an associated question, does the order of declaring variables matter? Back in the old days when I did C++ programming, declaring "int, byte, int, byte" used 4 int's work of space while "int, int, byte, byte" used 3.
Comment: There are both 64-bit and 32-bit versions of the Java Runtime.
Comment: The benefit of not specifying how memory is actually used is that you can have different ways of doing it. Related: http://docs.oracle.com/javase/7/docs/technotes/guides/vm/performance-enhancements-7.html (32bit pointers in 64bit vm)
Answer: There are far too many questions here but I'll address two of them.

Is Java limited to a 32-bit address space even on 64-bit systems?

32-bit Java is limited to a 32-bit address space. 64-bit Java is not.

Is Java limited to a 32-bit address space per array and each array object then has a pointer to where the elements are?

A Java array is indexed by an int which is 32 bits.
Answer: Understood that you are on a 64bit system but are you running a 32bit or 64bit jvm?  The JVM itself has an influence on many optimizations that will affect the results of your testing.  There are many JVMs (although admittedly only a few are popular) and some may have better, or different, optimizations than others.


Cauchy sequence in a complete Riemannian manifold

Question: Let $M$ be a complete Riemannian manifold, $N\subset M$ a closed submanifold, $p\in M\setminus N$ and $d(p,N)$ the distance from $N$ to $p$. I would like to show that there exists a point $q\in N$ such that $d(p,q)=d(p,N)$.
Question: does there always exist a Cauchy sequence $(q_i)_{i\in \mathbb{N}}\subset N$ such that $d(p,q_i)\to d(p,N)$?
If so, the completeness of $M$ (and thus of $N$) would imply that the sequence $(q_i)_{i\in \mathbb{N}}$ converges to some $q\in N$ such that $d(p,q)=d(p,N)$, as desired.
How do I find such a sequence? Is the existence a property of complete metric spaces?
Comment: That's the definition of $d(p,N)$ as $\inf_{q \in N} d(p,q)$. Then use that  bounded sequences on $N$ (ie. $d(q_1,q_n) \le C$) have a convergent subsequence (because Riemannian manifolds are locally compact) and $d(p,q_n) \le C'$ implies $d(q_1,q_n) \le C$
Comment: The $d$ of $M$ and $N$ are the same ? So the sequence $q_i \in N$ such that $d(p,q_i) \to d(p,N)$ has a convergent subsequence.
Comment: Yes, the distances are the same. My question is why the sequence $q_i\in N$ such that $d(p,q_i)\to d(p,N)$ exists. I think this is a basic fact about metric spaces that I am forgetting. Thanks
Answer: Let $q\in N$ and $G$ be a closed geodesic ball with center at $p$ and radius $r=d(p,q)$. The intersection $A$ of $G$ and $N$ is compact and consequently the function $d(p,q_i)$ restricted to $A$ attains its minimum in $A$.


Multer unexpected field error handling

Question: The route with my multer middleware goes something like this.
router.post('my-route-path', multer.single('file'), controllerFunc)

The multer function I have defined is to allow a single file uploaded to the file system. Everything works fine, the issue is if I have define the field name to be file If in my client request I set the field name to be file it works great. But if I give it xyz then it throws an error. Which it should the problem is I can't seem to catch that error, in my catch(e) block of my promise.
This is the error I get
Error: Unexpected field
at makeError (F:\Servup\chat\node_modules\multer\lib\make-error.js:12:13)
at wrappedFileFilter (F:\Servup\chat\node_modules\multer\index.js:40:19)
at Busboy.<anonymous> (F:\Servup\chat\node_modules\multer\lib\make-middleware.js:114:7)
at emitMany (events.js:146:13)
at Busboy.emit (events.js:223:7)
at Busboy.emit (F:\Servup\chat\node_modules\busboy\lib\main.js:38:33)
at PartStream.<anonymous> (F:\Servup\chat\node_modules\busboy\lib\types\multipart.js:213:13)
at emitOne (events.js:115:13)
at PartStream.emit (events.js:210:7)
at HeaderParser.<anonymous> (F:\Servup\chat\node_modules\dicer\lib\Dicer.js:51:16)
at emitOne (events.js:115:13)
at HeaderParser.emit (events.js:210:7)
at HeaderParser._finish (F:\Servup\chat\node_modules\dicer\lib\HeaderParser.js:68:8)
at SBMH.<anonymous> (F:\Servup\chat\node_modules\dicer\lib\HeaderParser.js:40:12)
at emitOne (events.js:115:13)
at SBMH.emit (events.js:210:7)

The current implementation that I tried in my catch block was this. (this doesn't work)
catch(e => {
    if (e === 'Unexpected field') {
       // catch that error here
    }
});

Answer: You can catch an unexpected field error by doing this
url: https://www.npmjs.com/package/multer
var upload = multer().single('avatar')

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err) {
      // An error occurred when uploading
      return
    }

    // Everything went fine
  })
})

Multer unexpected field error handling


I don't know why it's throwing System.ArgumentOutOfRangeException

Question: I'm trying to figure out why is this error showing, but I can't. I think that everything's okay, but at some point the value "i" at readTest is == 2. Which is not supposed to... listW has 2 objects, and the "i" should only be 0 and 1. I don't where the 2 is coming from. Am I making anything wrong? I've done some testing and the i=2 only happens at readTest. What's happening?
Thank you for your attention guys
public void readTest(int i)
        {
            for (int j = 0; j != leftListList[i].getKeyValues().Length; j++)
            {
                string read = ws.Read(listW[i], wi[i].GetKey(), leftListList[i].getKeyValues()[j]);
                WsRead wsRead = wi[i].BuildRead(read, leftListList[i].getKeyValues()[j]);
                readList.Add(wsRead);

                Console.WriteLine("READ: " + leftListList[i].getKeyValues()[j]);
            }
        }

        public void threadTest()
        {
            for (int i = 0; i != listW.Length; i++)
            {
                    Thread t = new Thread(() => readTest(i));
                    t.Start();
                }
            }

Comment: You have a wild `else` running around.
Comment: look into `foreach` loops, they'd make your code way more readable.
Answer: Introduce a local variable, say index:
for (int i = 0; i < listW.Length; i++) // i < listW.Length is more readable
{
    int index = i;
    ...
    else
    {
        // now each thread has its own index
        Thread t = new Thread(() => readTest(index));
        t.Start();
    }
}

when Thread finally starts (it takes time to create a new thread), the loop is completed and thus i == 2
Comment: Omg! Thank you so much! You're my lifesaver!


criar uma tela de busca

Question: Estou dando sequência em uma aplicação em ASP.Net MVC e preciso fazer uma tela de busca.
A questão é a seguinte:
Criei uma tabela onde os usuários cadastram suas habilidades.
Preciso de uma view onde terá um campo texto onde a pessoa digitará por exemplo: "Costura". Clica em buscar e a aplicação deve retornar todas os usuários que tem a palavra "Costura" dentro do campo habilidades da tabela.
Como implementar isso?
É como esses campos de pesquisa que temos em todos os sites. Acredito ser bem simples, mas não sei por onde começar.
Gostaria de no controller fazer um select ... where... like '%@PALAVRADIGITADA%' só que não sei a sintaxe para passar essa variável e tal.
Se alguém puder me dar uma luz, desde já agradeço.
Comment: Qual tipo de acesso você faz ao seu banco, SQLConnection ou com Entity ?
Comment: Você pode colocar na sua pergunta trechos do seu código já começado?
Comment: Cara vou colocar como comentário, mas olha esse link, que é do site oficial do asp.net mvc, ou até o asp.net também. Nesse link tem uma busca muito fácil de fazer, e dá um norte bem legal e dessa maneira você pode seguir adiante ! [Segue o link](http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view). Siga esse exemplo do @HarryPotter também pra ter outra noção de como fazer !
Answer:
Exemplo com Entity Framework
Crie um Controller e coloque dois métodos com o nome de Pesquisa. O método Pesquisa decorado com HttpGet responderá as requisições Get e o decorado com HttpPost responderá pelas requisições Post. Quanto clicar no botão vai para o método Pesquisa decorado com HttpPost, que possui um paramentro texto que é enviado do formulário Html.
Controler
public class HomeController : Controller
{
    private readonly ModelDb db;
    public HomeController()
    {
        db = new ModelDb();
    }

    ~HomeController()
    {
        db.Dispose();
    }

    [HttpGet]
    public ActionResult Pesquisa()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Pesquisa(string texto)
    {
        return View(db.Pessoas.Where(x => x.Nome.Contains(texto)).OrderBy(x => x.Nome));
    }
}

View:
@model IEnumerable<WebApp.Models.Pessoas>
@{ Layout = null; }
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Pesquisa</title>

         @using (Html.BeginForm())
         {

Digite o nome

             <input type="text" name="texto" id="texto" placeholder="Digite a pesquisa" />

<button type="submit">Filtrar</button>

         }

            Id
            Nome

        @{
            if (Model != null)
            {
                foreach (var item in Model)
                {

                        @item.PessoaId
                        @item.Nome

                }
            }
        }

Ao clicar no botão Filtrar ele vai para o método Pergunta com paramento texto e fará um filtro (SQL like pelo nome da entidade Pessoas) e enviará o resultado para a mesma tela.

criar uma tela de busca


Obter valores duplicados do Vetor

Question: Gostaria de obter somente os valores que estão duplicados no array
Estou tentando fazer assim:
$cdCursos = array(1, 2,3,4,5,3 );
echo "
";
print_r( $cdCursos );
echo "
";
$withoutDup  = array_unique($cdCursos);
echo "
";
print_r( $withoutDup );
echo "
";
$duplicates  = array_diff($cdCursos, $withoutDup);
echo "
";
print_r( $duplicates );
echo "
";

O valores estão retornando assim, respectivamente:
Array
(
    [0] => 1
    1 => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 3
)
Array
(
    [0] => 1
    1 => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Array
(

)

Tentei essa resposta, mas não deu certo
Answer: $arr = array(1, 2,3,4,5,3);

$uarr = array_unique($arr);

print_r($uarr); //Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

echo "
";
echo "
";

var_dump(array_diff($arr, array_diff($uarr, array_diff_assoc($arr, $uarr)))); //array(2) { [2]=> int(3) [5]=> int(3) }

echo "
";
echo "
";
$unicos=(array_diff($arr, array_diff($uarr, array_diff_assoc($arr, $uarr))));

print_r($unicos); //Array ( [2] => 3 [5] => 3 )

no ideone
no sandbox
Comment: Boa, garoto! Exatamente o que eu queria. Muito obrigao
Answer: Utilize a função array_diff_key ao invés da array_diff para este caso.
print_r(array_diff_key($cdCursos, array_unique($cdCursos)));

Obter valores duplicados do Vetor


Propositional Calculus - Validity Question

Question: I have the following question:

And I have drawn up the truth table below:

My question is I see there is one truth value that both the premise and conclusion have in common, but does that mean that the premise does or does not entail the conclusion? Thanks for any help!
Comment: Your truth table is wrong. The premise is true in more than one case.
Comment: $warm(Susan) \lor warm(Mary)$ is a *disjunction*; thus it is *false* only in the case $F-F$. You have to fix rows 6 and 8.
Comment: The conclusion is *entailed* by the premise when in every row where the premise has value T also the conclusion has T.
Comment: It is worst than before : the structure of the t-t must be : David/Susan/Mary/Susan or Mary/David and (Susan or Mary). We have parentheses in the formula ! Thus, when warm(David) is F the final column must have F, because it is a *conjunction*.
Comment: Thank you for all your comments, I have updated my truth table to the values I think it should be now. As the columns 'David and 'Premise' are different, the I understand the answer should be that 'Premise does not entail conclusion'?
Comment: **NO**. The def is [see above] : "The conclusion is entailed by the premise when in every row where the premise has value T also the conclusion has T". The premise has T only in the last three rows; in these rows warm(David) (the conclusion) has T. Thus : "Premise **does** entail conclusion".
Comment: Ah I see, thanks so much for all your help Mauro!
Comment: You have also to use your "intuition"; if the premise is a conjunction, for sure **both** concjuncts "individually" are entailed by the premise. If my coffee is black and hot, it is for sure hot. The same approach may help you with your other question: if my coffee is **not** black, why this must entail that it is hot ?
Answer:
My question is I see there is one truth value that both the premise and conclusion have in common, but does that mean that the premise does or does not entail the conclusion?

No, we cannot conclude this. I'm afraid of confusing you with formalism.. but I better explain it in details. In usual terminology, entailment in the propositional calculus is defined this way: let $\Gamma$ be a set of formulae and $\phi$ a formula. We say that $\Gamma$ entails $\phi$ iff for any valuation $v$, if $v(\psi)=1, \psi \in \Gamma$ then $v(\phi)=1$ (Roughly speaking, whenever all formulae in $\Gamma$ are true, $\phi$ must be true). This is why it's always better, when working with truth tables, to just check the lines all premises are true and see if in any of those lines the conclusion is false. If it's not the case, we say the premises entail the conclusion.


How do you remove duplicate rows of primary key and also group by in SQL Bigquery?

Question: SQL BigQuery - I have duplicate rows on the primary key that I need to remove (I don't want to permanently delete from the table). I have to GROUP BY several other fields to aggregate results, and am having issues since I have to include the primary key but cannot group by it and remove duplicates at the same time.
I saw examples on stack but am having issues applying to this case. I have tried the below, and that is not resulting in any groupings because I have to group by the ID to leave it in the select statement.
SELECT Distinct (ID),Event_ID,Event_Name,Sum(Quantity), Sum(Price*Quantity)
FROM table
GROUP BY ID, Event_ID, Event_Name

I tried removing ID from the group by clause and adding "Min (Distinct (ID))," as the first select line, but that was not removing the duplicates.
I also tried
SELECT Distinct (ID),Event_ID, Event_Name, Sum(Quantity) ,Sum(Price*Quantity),
FROM table

INNER JOIN
  (SELECT ID as DeduplicatedID
  FROM table
  GROUP BY ID) deduplicatedtable ON table.ID = deduplicatedtable.ID

GROUP BY ID, Event_ID, Event_Name

and  received this error
Thanks in advance!

of the group at the ID level, however some of these IDs have duplicates, which provide incorrect TotalQuantity and TotalRevenue numbers when grouped by the Event

of what I would want the grouped data to look like, but this is incorrect and includes the duplicate IDs when the quantity and rev fields are summed.
Comment: Primary keys -- by definition -- do not have duplicates.  Please explain what column or columns should not be duplicated.  Sample data and desired results would be helpful.
Comment: correct - I guess it is supposed to be the primary key but for some reason there are duplicates of certain rows and I can't parse out a rhyme or reason why it is only some rows and not others...I am adding screenshots of data now to Original post
Comment: added the pictures above
Comment: What exactly is duplicated? The the entire row or only the id value? I mean, for the duplicated ID value, the rest of the row is similar or different?
Comment: There are several answers to do this in this [post](https://stackoverflow.com/questions/12239169/how-to-select-records-without-duplicate-on-just-one-field-in-sql), including Gordon's. Try [this one](https://stackoverflow.com/a/29912858/11928117)
Comment: @rmesteves the entire row is duplicated
Comment: If the entire row is duplicated then both of the below answers should work for you.
Answer: Does this do what you want?
SELECT MIN(ID) as id, Event_ID,Event_Name,Sum(Quantity), Sum(Price*Quantity)
FROM table
GROUP BY Event_ID, Event_Name

Comment: unfortunately that does not get rid of the duplicates for me; unsure why exactly
Comment: to add, when I run this, it is getting rid of all of the other IDs that are not duplicates and that are not the min ID
Answer: Try doing
WITH t as (
SELECT Distinct *
FROM table
)
SELECT ID, Event_ID, Event_Name, Sum(Quantity), Sum(Price*Quantity)
FROM t
GROUP BY ID, Event_ID, Event_Name

Answer: If, as I suspect, there is one field that is not duplicated, find it and use ANY_VALUE(not_duplicated_field). The ANY_VALUE function returns any value from the input or NULL if there are zero input rows. The value returned is non-deterministic, which means you might receive a different result each time you use this function.
For example:
SELECT DISTINCT ID, Event_ID, ANY_VALUE(Event_Name), sum(Quantity), sum(Price*Quantity)
FROM blabla.jack
GROUP BY id, Event_ID


How can I retrieve information about the current request's URL?

Question: I need help finding a way to get the current request URL in a controller and, based on that, change the webform name in the controller.
My code:
'#url' => Url::fromRoute('entity.webform.canonical',['webform' => 'form1'])

In this line of code, how can I switch between form1 or form2 based on whether the request URL contains a particular path?
Answer: URL info is available from the request_stack service. In procedural code getting the URL looks like this:
$url = \Drupal::request()->getRequestUri();

There's also a helper to get query parameters if you need them, e.g.
if (!empty(\Drupal::request()->query->get('foo'))) {

}

In your case you should inject the request_stack service into your controller, and get the request object from its getCurrentRequest() method (rather than getting it from \Drupal::request() directly).
Answer:
I need help finding a way to get the current request URL in a
controller

In a controller get the request with a type-hinted argument Request $request:
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Url;

class ExampleController extends ControllerBase {

  /**
   * Controller to return a link to a webform.
   */
  public function action(Request $request) {

    // calculate $webform with $request->getPathInfo()

    return [
      '#type' => 'link',
      '#title' => 'Foo',
      '#url' => Url::fromRoute('entity.webform.canonical', ['webform' => $webform]),
      '#cache' => ['contexts' => ['url.path']],
    ];
  }

}

You can get other information from the request, but then you need to adjust the cache context(s). See for example https://drupal.stackexchange.com/a/245597/47547
Comment: No, this is the most basic usage of a controller receiving a request and returning a response.
Comment: You don't need to inject it?


Solving the Points on a Rotated Rectangle

Question: I am working in AS3.
I have a generic rectangle. This rectangle can have any length, any width and any rotation. I am trying to solve for the x and y coordinates of the four corners of the rectangle. I know the coordinates of the centre of the rectangle, I know its width, its height, the y distance between the highest and lowest point and the x distance between the farthest left and farthest right point as well as knowing the rotation.
My code currently looks like this (Object, of course, being the rectangle in question, keep in mind that when I apply this it can have any dimensions - This is just one possibility. Initial width and height are the actual length and width, while width and height referenced later are the x and y distances between the highest and lowest points and the farthest left and right points, rotation is of course rotation, and x and y are the object's centre coordinates).
<code>import flash.events.Event;
addEventListener(Event.ENTER_FRAME, Rotate, false, 0, true);

var Radius:Number = Math.sqrt(((Object.height / 2) * (Object.height / 2)) + ((Object.width / 2) * (Object.width / 2)));

function Rotate(event:Event)
{

    Object.rotation += 1;
    Marker1.x = Math.sqrt((Radius * Radius) - ((Object.height / 2) * (Object.height / 2))) + Object.x;
    Marker2.x = - Math.sqrt((Radius * Radius) - ((Object.height / 2) * (Object.height / 2))) + Object.x;
    Marker3.y = Math.sqrt((Radius * Radius) - ((Object.width / 2) * (Object.width / 2))) + Object.y;
    Marker4.y = - Math.sqrt((Radius * Radius) - ((Object.width / 2) * (Object.width / 2))) + Object.y;

    Marker1.y = Object.y + (Object.height / 2);
    Marker2.y = Object.y - (Object.height / 2);
    Marker3.x = Object.x + (Object.width / 2);
    Marker4.x = Object.x - (Object.width / 2);

}
</code>
As you can see I am attempting to use circle geometry to place four small circles (Markers 1-4) at the corners of the rectangle, just for testing purposes to confirm that I have gathered the correct coordinates. Problem is, the coordinates will always be placed in either +x and +y or -x and -y, but never the other two quadrants of the graph. I can't figure out a simple way of dynamically simulating the +- of the quadratic equation in the program. Does anyone know of a way to find these four points with and length, width and rotation of the rectangle?
Answer: If you represent the coordinates of the corners as offsets from the midpoint of the rectangle you can easily rotate them anti-clockwise by an angle θ with
dx' = dx × cos θ - dy × sin θ
dy' = dx × sin θ + dy × cos θ
You can then add the rotated offsets to the midpoint to recover the new coordinates of the corners.
Comment: Can anyone tell me how this is usually named in Math


Number of linear independent vectors multiples of other given their components have to sum to a fixed value.

Question: My goal is to find, in any arbitrary dimension, how many linear independent vectors there are in the set made of all of the possible vectors in N whose components sum to a fixed value.
$$A= \lbrace(x_0,x_1, \ldots, x_n): x_i\in \mathbb{N}\hspace{5pt}\left| \hspace{5pt}\sum x_i\leq c\right. \rbrace$$
given the defintion of $A$, the number of all possible vectors in the 2-dimensional case is $x(x-1)/2$, if $c=4$ then $A=\lbrace \\
(0,0)(0,1)(0,2)(0,3)(0,4)\\
(1,0)(1,1)(1,2)(1,3)\\
(2,0)(2,1)(2,2)\\
(3,0)(3,1)\\
(4,0)\rbrace$
For my purpose i would like to know which vectors are not multiples of other vectors in terms of tuple values. Where $(2,2)$ is a multiple of $2\cdot(1,1)$ as my interested in the ratio between the values, $(0.5,0.5)$ in this case or ratio of (0,1) for $(0,1),\ldots,(0,x)$. But i'm not interested in knowing that $(2,1) = 2\cdot(1,0)+(0,1)$
is it possible to deduce a general formula?
Comment: I have to say I am lost. I'm not sure what you are asking - is it for the number of "n-"tuples which form the equivalent of a "basis" in a vector space. And do you want the sum equal to a fixed value, or $\le$ a fixed value, as in the table.
Comment: Sorry for not being so clear, what i have to do is to determine for example, given a space dimension and the constraint of sum of components less or equal to a constant, all of the vectors which are not multiple of other vectors in terms of tuple's values.
Answer: If I understand correctly, you're looking for a basis of $$\left\langle \left(\begin{array}{c}a_0\\a_1 \\ \vdots \\ a_n\end{array}\right): a_i\in \mathbb{Z}\hspace{5pt}\left| \hspace{5pt}\sum a_i=\sigma\right.\right\rangle$$ where $\sigma$ is some fixed integer.
Take $\sigma\cdot\epsilon_i$ for $i=1,\ldots, n$, where $\epsilon_i$ is the unit vector with a $1$ in the $i^\text{th}$ coordinate and $0$s elsewhere.  It's easy to see that all of these are members of your desired set, and that they span $\mathbb{Q}^n$ (or $\mathbb{R}^n$, whichever vector space you're in).  So the dimension of this space is $n$.
Comment: I think what you are referring to is the fact that given the basis i can obtain all the other vectors as a linear combination of the basis itself. What i'm looking for is find vectors whose tuple's values are multiple of other vectors.
Comment: @fady then that isn't what linearly independent means.


Problema a fazer a query dentro da segunda Dropdown

Question: Entra sempre no erro do ajax:
error: function (ex) {
                    alert('Failed to retrieve vigararias.' + ex);
                }

Erro na tela:

Failed to retrieve vigararias.[object Object]

View:

                            @Html.Label("Dioceses", htmlAttributes: new { @class = "control-label col-md-2" })

                               @Html.DropDownList("Dioceses", (SelectList)ViewBag.dioceses, "--Escolha uma diocese--", htmlAttributes: new { @class = "form-control" })

                            @Html.Label("Vigararias", htmlAttributes: new { @class = "control-label col-md-2" })

                                @Html.DropDownList("Vigararias", new SelectList(string.Empty, "VigarariaID", "Nome"), "--Escolha uma Vigararia--", htmlAttributes: new { @class = "form-control" })

                                    <input type="submit" value="Criar" class="btn btn-primary" />

Controller:
 public ActionResult CriarParoquia()
        {
            ViewBag.Dioceses = new SelectList(db.Diocese, "DioceseID", "Nome");
            return View();
        }

public JsonResult GetVigarariasByDioceses(int DioceseId)
        {
            // Obter Vigararias de uma Diocese utilizando LINQ.
            var vigararias = db.Vigararia
                .Where(v => v.DioceseID == DioceseId)
                .Select(v => new { v.VigarariaID, v.Nome })
                .OrderBy(v => v.Nome);

            return Json(new SelectList(vigararias,"VigarariaID","Nome"));
        }

Comment: Essa *Action* `GetVigarariasByDioceses` não está marcada com `[HttpPost]`?
Comment: Não estava, mas mesmo assim dá o mesmo erro."Failed to retrieve vigararias.[object Object]".
Comment: Chega a entrar na *Action*?
Comment: Não, fiz breakpoint e não entra.
Answer: Isto aqui não vai funcionar:
    public JsonResult GetVigarariasByDioceses(int DioceseId)
    {
        // Obter Vigararias de uma Diocese utilizando LINQ.
        var vigararias = db.Vigararia
            .Where(v => v.DioceseID == DioceseId)
            .Select(v => new { v.VigarariaID, v.Nome })
            .OrderBy(v => v.Nome);

        return Json(new SelectList(vigararias,"VigarariaID","Nome"));
    }

Mais especificamente esta parte:
return Json(new SelectList(vigararias,"VigarariaID","Nome"));

Não se passa um SelectList por JSON porque o código JS não entende a estruturação de SelectList. O correto seria:
    [HttpPost]
    public JsonResult GetVigarariasByDioceses(int id)
    {
        // Obter Vigararias de uma Diocese utilizando LINQ.
        var vigararias = db.Vigararia
            .Where(v => v.DioceseID == DioceseId)
            .Select(v => new { v.VigarariaID, v.Nome })
            .OrderBy(v => v.Nome);

        return Json(vigararias, JsonRequestBehavior.AllowGet);
    }

Note que id:
data: { id: $("#Dioceses").val() },

Precisa ser igual ao argumento da Action:
public JsonResult GetVigarariasByDioceses(int id)

Aqui, naturalmente, precisa ter os nomes que você definiu em Controller:
$.each(vigararias, function (i, vigararia) {
    $("#Vigararias").append('<option value="' + vigararia.VigarariaID + '">' + vigararia.Nome + '</option>');
});

Comment: Mesmo assim não entra no método.
Comment: Esqueci um detalhe. Veja agora.
Comment: Finalmente, agora só tem um problema na Dropdown, não vai buscar o nome das vigararias, aparece "undefined".
Comment: @user10271 Editei a resposta.
Comment: Obrigado por tudo.


NBA finals - home teams are expected to win, yet phx suns series win probability increased after winning g1 and g2 at home. how to explain?

Question: nba finals is a best of 7 series (first to win 4 games). in the nba, home court is decently advantageous, to the point where the home team is generally expected to win.
this past week saw the phx suns win g1 and g2 at home. not an unexpected result, but the probability of them winning the entire series also increased substantially (60% prior to g1 to 88% post g2).
my non-qual understanding is that they have banked two wins. so regardless of whether or not the predictive models expect them to win home games 1 and 2, they have proven it. by proving it, they have changed the parameters of the predictive modeling - no longer is it a 7 game series, first to 4 wins, but now it is a 5 game series, where phx suns have to win two out of 5, and the bucks have to win 4 out of 5.
so is the 60% actually comparable to 88% since they're talking about different things?
let me know if i can better explain the situation.
the question is: if the suns are expected to win a 7 game series (60% win probability), why does winning games 1 and 2 at home increase their win probability to 88%?
if they are expected to win games 1 and 2 (let's say 100% of the time), why would their series win probability increase when the events are occurring as expected?
Comment: Prior belief can be updated, depending on your model. Would need a formulation of the question.
Comment: Don't understand the confusion. Suppose I wanted to know plausibility of tossing two sixes. 1/36. Great. I look at the first. It's a six. The plausibility of two sixes conditioned on this knowledge is 1/6.
Comment: Are these probabilities based on how people are betting?
Answer: While winning at home is very likely, there was still a possibility of losing those games at home. The original probability included that possibility, now we have seen the first two games and there's no longer any uncertainty about their result.
Depending on how the probability is calculated, it may also reflect an updated belief on how the teams stack up relative to each other (obviously a lot was known from the rest of the season already on that, but this is still also extra information one can take into account).
Comment: ok, that all makes sense. then what happens if the bucks win their home games, g3 and g4. Then the series becomes a best of 3; and each team has won their expected games. and we can assume that the positive extra information learned about the suns are countered by the positive extra information learned about the bucks.

in that case, one would assume that the sun's series win probability would move from 88% back to 60%, but i'm pretty sure it doesn't work like that - so how can we explain that change?
Comment: thanks. then what happens if the bucks win their home games, g3 and g4. Then the series becomes a best of 3; and each team has won their expected games. and we can assume that the positive extra information learned about the suns are countered by the positive extra information learned about the bucks. in that case, one would assume that the sun's series win probability would move from 88% back to 60%, but i doubt that's correct. said another way, if the sun's win probability for a 7 game series is 60%, in a vacuum, there win probability for a 3 game series should be 60% as well.
Comment: That would definitely shift things back the other way. Given that they were favorites to win a 7 game series, they'd be favorites to win a 3 game series, but with a lower probability (even ignoring everything else like "momentum" etc.), because in 3 games the better team would be less likely to win, because in 3 games more things happen just by chance than in 7.


Como inverter a ordem de uma frase?

Question: Tentei fazer um programa que recebe uma frase e retorna a frase na ordem inversa. Exemplo:
Entrada: "Hello, Java!";
Saída: "Java! Hello,";
Tentei fazer, mas não está dando certo.
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String line1 = scanner.nextLine();
        String line2 = scanner.nextLine();
        String[] a = line1.split(",");

        for(int i=line1.length-1; i >= 0; i--);
            System.out.print(a[i] + " ");

        System.out.println(line1);
        System.out.println(line2);
    }
}

Comment: o que está acontecendo?
Answer: Tem alguns erros aí.
Um deles é que tem um ; no for encerrando o bloco e não executando o que deseja que se repita fazendo com que uma linha solta nem faça sentido porque usa uma variável que só existe dentro do laço.
Também está pegando o tamanho de line1 quando seu array é o a.
Não sei o que esse line2 está fazendo aí, tirei, e tirei as impressões no fim porque elas não parecem ser necessárias pelo problema descrito.
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String line1 = scanner.nextLine();
        String[] a = line1.split(",");
        for (int i = a.length - 1; i >= 0; i--) System.out.print(a[i] + " ");
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Entendi !!
Muito Obrigado.
Comment: @MatheusBorba veja no [tour] a melhor forma de dizer obrigado.

Como inverter a ordem de uma frase?


SQL CE thread unsafe - alternatives?

Question: I have discovered that SQL CE is not thread safe:
SQL CE objects are not thread-safe and are not thread affinitive either. If an instance of SqlCeConnection or SqlCeTransaction is shared across threads without ensuring thread safety, then that may lead to Access Violation exception.)
I do need to share connection since there are lot of client instances, each of them reading/writing to DB at the same time.
Also in order to maintain the speed I do not want to use locking, I guess I would need to use standard SQL server, is it right?
Thanks
Comment: The objects aren't thread safe but the database is, if you use different object (especially a different connection object) for each thread.
Answer: No database product, no matter how high you move up the chain, will let your share connections and transactions between threads concurently. You will always have to serialize access to a transaction/connection. You are asking for a non-sense requirement. One thread is going to commit what the other just rolled back? There are many products that support thousands and thousands of clients reading and writing the database at the same time. None, ever, 'shared' connections between threads.
To achieve high scalability you should do the same thing everyone else does:

use connection pooling to amortize the cost of login handshake
associate a connection with a request for the duration of servicing a request
use short transactions
optimize access path to avoid reading unnecessary data (eliminate all scans)
use proper locking granularity

If the load is read intensive then you can consider a versioned isolation model, like read committed snapshot in SQL Server. If the load is update intensive then you must follow OLTP principles and use short, granular locks to do any update, while avoiding work on correlated items from different transactions to reduce deadlock probability.
Comment: SQL CE doesn't implement connection pooling, by the way. I think it's meant to be on the same machine as the application[s] using it, so "connecting" isn't an especially high overhead.
Answer: If SQL CE has the features you need you should look at sql express instead of buying standard, however neither product was optimized for multiuser access like sql standard and above.
Answer: You are correct, SQL CE does not support having multiple connections coming into a single databsae. You need to move up the chain to something a bit bigger.
SQL Express would be the next step up, and definitely works under multi-user scenarios. And best of all, it is free. So as long as the limits placed on it won't stop you from getting the job done, you will be much better off using it.
Also, it is practically an in-place upgrade to move from Express to Standard when the time comes.

SQL CE thread unsafe - alternatives?