Use subqueries to assign column values for each record in laravel

Question: As i know, "Subqueries can assign column values for each record".
example: lets consider this database,
Example database
user (id, name, age)
user_detail (user_id[foreign], user_email, address)

Now we can select all email and name by subquery like this:
    SELECT id, (SELECT user_email FROM user_detail WHERE user_detail.user_id = user.id LIMIT 1) as email,
    name, age
       FROM user
          WHERE 1

This will the output table like:
 _ _ _ _ _ _ _ _ _ _ _ _ _
| id | email | name | age |
+-------------------------+
---------All rows----------

Now how can i query with it laravel eloquent?
More specific ...
I have some tables,
1. session (id, name)
2. account (id, name, group)
3. action (id, action_name, detail)
4. another_table (id, detail)
5. transaction (id, from_account_id, to_account_id, session_id,
   action_table_id, another_table_id, other_attributes )

now i want a single query to get each line as a object, and hole a array
query should return
result (transaction_id, session_name, from_account_name, to_account_name,
        action_name, another_table_detail, other_attributes)

and finally send them to json, such that i read them by just a for loop.
Comment: Why do you have to use a subquery? Are you familiar with [Eloquent relationships](https://laravel.com/docs/eloquent-relationships)?
Comment: Thanks for you reply #Jonas. I wanna learn subquery with laravel and apply them with 4 to 5 table joining. If i use relation than it goes so expensive with eloquent (as i know). That is the tow reason. Can you help me to reach out?
Comment: well, more specific ...
lets have some tables,
1. session (id, name)
2. account (id, name, group)
3. action (id, action_name, detail)
4. another_table (id, detail)
5. transaction (id, from_account_id, to_account_id, session_id, action_table_id, another_table_id, other_attributes )

now i want a single query to get each line as a object, and hole a array
query should return

result (transaction_id, session_name, from_account_name, to_account_name, action_name, another_table_detail, other_attributes)

and finally send them to json, such that i read them by just a for loop.
Comment: You can create a subquery with [`selectSub()`](https://github.com/laravel/framework/blob/1d349728e0b89498e93a2c3cbb3ddde0b74ba92e/src/Illuminate/Database/Query/Builder.php#L236).
Comment: Thanks a lot. I am looking for this. and it works with selectSub().
Answer: Try this
$users = User::join('users', 'users.id', '=', 'user_detail')->get();

Should join two tables with all the records you need.
Comment: Thanks for you reply #rkg. I have this idea and that is a quite good solution. But i want to use it from subqueries. and i am stuck on it. can you help me to reach out?
Answer: Thanks Jonas-staudenmeir. He helps me to find the solution.
In that case we can use selectSub() method from laravel query builder class. selectSub()
For first one:
    $user_email = DB::table('user_detail')
                ->select('user_detail.user_email')
                ->whereRaw('user_detail.user_id = user.id')
                ->take(1);

    $data = DB::table('user')
            ->select('name', 'age')
            ->selectSub($user_email, 'email') // selectSub(sub_query, as)
            ->get();

For second one:
    //session query
    $session = DB::table('session')
                ->select('session.name')
                ->whereRaw('transaction.session_id = session.id')
                ->take(1);
    //from_account query
    $from_account = DB::table('account')
                ->select('account.name')
                ->whereRaw('transaction.from_account_id = account.id')
                ->take(1);
    //to_account query
    $to_account = DB::table('account')
                ->select('account.name')
                ->whereRaw('transaction.to_account_id = account.id')
                ->take(1);
    //action query
    $action = DB::table('action')
                ->select('action.action_name')
                ->whereRaw('transaction.action_table_id = action.id')
                ->take(1);
    //another_table query
    $another_table = DB::table('another_table')
                ->select('another_table.detail')
                ->whereRaw('transaction.another_table_id = another_table.id')
                ->take(1);

    $data = DB::table('transaction')
            ->select('transaction.id as transaction_id', 'other_attributes')
            ->selectSub($session, 'session_name') //session as session_name
            ->selectSub($from_account, 'from_account_name') //from_account as from_account_name
            ->selectSub($to_account, 'session_name') //to_account as to_account_name
            ->selectSub($action, 'action_name') //action as action_name
            ->selectSub($another_table, 'another_table_detail') //another_table as another_table_detail
            ->get();

Though we can use join or left join. Which one is faster it all depends on the data, indexes, correlation, amount of data, query, etc. Subqueries can be slower than LEFT [OUTER] JOINS, but in my opinion their strength is slightly higher readability. join-vs-sub-query


How to add a dynamic cart link to the user menu?

Question: Commerce already defines two menu items in the Navigation menu:

Shopping cart - 'cart' - enabled by default, static
Shopping cart - 'cart/my' - disabled by default, dynamic

'cart/my' uses a custom title callback, 'commerce_cart_menu_item_title' that builds a dynamic menu link in the form: Shopping cart (2 items)
If I want to add a new menu item for the shopping cart to the User Menu, what's the proper way to do this? Do I first need to duplicate a menu item, then override the duplicate?
Ideally, I would be able to set my own title callback so that I can optionally build a dynamic menu in any format I choose.
Answer: You can create a new menu programatically through menu hooks, and a great source for sample code and explanation is the menu_example portion of the Examples Module.
For example
<code>function mymodule_menu() {
     $items['cart/new_menu_item'] = array(
    'title' => 'Shopping cart (# items)',
    'title callback' => 'mymodule_new_menu_item_title',
    'title arguments' => array(TRUE),
    'page callback' => 'mymodule_new_menu_item_redirect',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}
</code>


Index notation.

Question: I have a very basic question concerning index notation, normally used in physic papers. I have never used index notation and it is very difficult to me to translate from index free notation, even in the case of very simple formulas.
I would like to check if the following expression in index notation are correctly written.
a) Let $g$ be a semi-Riemann metric. If $g(U,U)=1$, then $g(\nabla_U U,U)=0$.
Traslation: Let $g_{ij}$ be a semi-Riemann metric. If $U^i U^j g_{ij}=1$, then $g_{ij} U^i U^j_{;k} U^k=0$.
b) Let $V$ a vector field and $f$ a function such that $fV(f)=g(\nabla_V V,V)$. Translation: Let $V^i$ a vector field and $f$ a function such that $f V^i f_{,i}=g_{kj} V^k V^i V^j_{;i}$.
Thanks in advance.
Answer: Yes, your expressions are correct.

For the curious.
It should not be very difficult, once you adopt the so-called abstract index notation point of view.
Let $V$ be a vector space of dimension $n = \dim(V)$, and $\{e_i\}_{i=1,\dots,n}$ be a basis in $V$. Any element $v \in V$ can be written as $v = v^i e_i$, where the Einstein summation assumed every time we have the repeated indices in the expression.
In the dual space $V^* = \mathrm{Hom}(V,\mathbb{R})$ we have the corresponding dual basis $\{\theta^j\}_{j=1,\dots,n}$ with the defining property $\theta^j(e_i) = \delta_i{}^j$, where $\delta_i{}^j$ is the Kronecker symbol, that is $\delta_i{}^i = 1$ for all $i=1,\dots,n$, and $\delta_i{}^j = 0$ for all $i\neq j$. Any element $\omega \in V^*$ is uniquely represented as $\omega = \omega_j \theta^j$.
Furthermore, if $v$ and $\omega$ are as above, a standard computation reveals that $\omega(v) = \omega_i v^i$ for any pair of dual bases involved in obtaining $v^i$ and $\omega_j$.
The abstract index notation is simply viewing $\omega(v)$ and $\omega_i v^i$ as synonymous expressions. Reportedly, physicists do this since the inception of general relativity, just as a heuristic or mnemonic. Roger Penrose suggested a formalized treatment of this notation, which makes it mathematically rigorous. In the nutshell, one uses the indices as labels to distinguish vectors from $1$-forms (by position), and concatenations of indices to denote tensor products.
So, let us write $V^i$ instead of $V$, and $V_i$ let stand for $V^*$. Then the notation $v^i$ will unambiguously imply that $v^i \in V^i$, and similarly $\omega_j$ just means that $\omega_j \in V_j$. Tensor products are now easy to write, e.g. $V^{ij}$ stands for $V\otimes V$, and $V_i{}^j$ is the notation for $V^* \otimes V$. The Kronecker symbol $\delta_i{}^j$ is the abstract index reincarnation of the identity operator $\mathrm{id} \colon V \to V$ due to the canonical isomorphism $\mathrm{Hom}(V,W) \cong V^* \otimes W$, so we can write $\delta_i{}^j \in V_i{}^j$.
These conventions are extended to vector bundles without changes, and it is convenient to denote a vector bundle and the space of its sections by the same letter. In particlular, let $E^i$ stand for the tangent bundle over a manifold $M$, and then by $E_j$ we shall mean the cotangent bundle. The notation $v^i \in E^i$ will mean either a tangent vector at an unnamed point, or, more frequently, a vector field on $M$.
A (semi)-Riemannian metric is viewed as a section of $E_{(i j)}$, and we write this as $g_{ij} \in E_{(i j)}$. The indices $i,j,\dots$ can be regarded as slots, in which corresponding objects may be inserted, so that the the following is a tautology: $g_{i j} U^i U^j = g(U,U)$.
For any tensor $T$ the covariant derivative $\nabla T$ is again a tensor, and in the abstract index notation we write this as $\nabla_i T_{jk\dots}{}^{lm\dots}$, where $T_{jk\dots}{}^{lm\dots} \in E_{jk\dots}{}^{lm\dots}$. Notice that $\nabla_i T_{jk\dots}{}^{lm\dots}$ is a traditional way of writing $(\nabla T)_{ijk\dots}{}^{lm\dots}$.
In particular, $\nabla_U U$ is just the same thing as $U^i \nabla_i U^j$, that is a vector with the index $j$. It can be substituted into one of the indices in $g_{i j}$, so we can write $g_{i j} U^i U^k \nabla_k U^j$ instead of $g(\nabla_U U,U)$. And yes, the repeated indices can be renamed freely, provided the entire expression can be interpreted correctly.
The full power of the abstract index notation becomes apparent when one tries to express a contraction or a tensor part of some tensor with many indices. Try, for example, to give a traditional "index-free" description for $T_{i[jk]}{}^{i}$ where repeating the indices is the contraction, and the brackets $[\cdot]$ denote the antisymmetric part.
Comment: @bosco yes, this way of using semicolon is just another notation for the [covariant derivative](http://en.wikipedia.org/wiki/Covariant_derivative): $T_{j k \dots}{}^{l m \dots}{}_{;i} \equiv \nabla_i T_{j k \dots}{}^{l m \dots}$.
Comment: Ok. Thank. And $U^i \nabla_i U^j$ is equivalent to $U^i U^j_{;i}$, isn't it?

Index notation.


Can open set in $\mathbb{R}^n$ be written as the union of countable disjoint closed sets?

Question: Every open interval in $\mathbb{R}$ can't be written as the union of disjoint closed sets.
This implies that every open sets in $\mathbb{R}$ can't be written as the union of disjoint closed sets.
I wonder if this is also true for $\mathbb{R}^n$ but I have trouble take the proof of $n=1$ to $n\ge2$.
Answer: Indeed, this cannot be done: no (nonempty) open set in $\mathbb{R}^n$ can be written as a countable union of disjoint closed sets. This is a consequence of the Baire category theorem; GEdgar's answer to this question gives the details.

Let me give more details.
Suppose for a contradiction that $U\subseteq\mathbb{R}^n$ is open and $U=\bigcup_{n\in\mathbb{N}} C_n$, with $C_n$ closed and $C_i\cap C_j=\emptyset$ for $i\not=j$.
Let $B_n$ be the boundary of $C_n$, and $B=\bigcup B_n$. (Formally, the boundary of a closed set is the set of all points in the closed set which are not in the interior of the closed set; note that a closed set can be equal to its own boundary, as in the case of the Cantor set.) Then you can show that:

$B$ (viewed as a subspace of $\mathbb{R}^n$) is a complete metric space.
Each $B_n$ is a nowhere dense subset of $B$.

But this is a contradiction, since by the Baire Category Theorem no complete metric space is a countable union of nowhere dense sets.
Comment: It can also be proved via brute force and massive ignorance, along the lines of *my* answer to that same question.
Comment: in my question the closed sets may not be closed ball , is that alright..?
Comment: @hctb It is indeed alright. I've sketched the BCT application; you should be able to fill in the remaining steps yourself.


Variation on neighbourhood base

Question: Suppose $\{\mathscr B(x) \mid x \in X\}$ is a collection of filters (or filter bases) on a set X, with each $x \in \cap\mathscr B(x)$. Then $$\mathscr T = \{U \subseteq X \mid (\forall x \in U)(\exists B \in \mathscr B(x)) B \subseteq U \} $$ defines a topology $\mathscr T$ on X. Note that $\mathscr B(x)$ is not necessarily a neighbourhood base at x, as its members need not be neighbourhoods of x.
Is there an accepted name for such collections, or any interesting known results?
(If we call a space quasi-first-countable if it has such a collection with each $\mathscr B(x)$ having a countable base then.$$\text{First-countable} \implies \text{Quasi-first-countable} \implies \text{Sequential}$$ with none of the implications being reversible. Most of that has been shown in answers to recent questions about d-metrisable spaces. (E.g d-metrizable spaces are sequential. ) Quasi-first-countable is equivalent to d-metrisable.)
Comment: You may want to look at https://en.wikipedia.org/wiki/Pretopological_space
Comment: Sorry David, are you saying it's not necessarily a neighbourhood base because its members aren't necessarily open, or for a different reason? Terminology varies as to whether a neighbourhood must be open.
Comment: @Mike. The members of $\mathscr B(x)$ needn't contain an open set which has x as a member. In fact they can have no open (non-empty) subsets at all. For example, take X to be $\Bbb R$ and let $\mathscr B(x)$ be the filter base formed by taking open neighbourhoods of x in the usual topology and removing all irrationals < x and all rationals > x. (An example of a space that is quasi-first-countable but not first-countable.)
Comment: @user2345215. Thanks.That looks very close but is slightly different. The collections I'm suggesting are indeed neighbourhood systems for pretopologies as defined in your link, but the associated topology is not the same. For instance, with the example in my previous comment the net consisting of all irrationals < x does not converge to x in the associated pretopology but does in the topology I suggest. Perhaps they will be the same whenever the pretopology is a topology, but it's late so I'll leave that for tomorrow.
Comment: @DavidHartley Good example.
Comment: Yes, it does seem that the topology I've derived from $\mathscr B$ is the same as the associated pretopology whenever that is a topology. In other cases it is the "topologisation" of the pretopology: the finest coarser pretopology which is a topology
Answer: tl;dr; I would call such collection a (local) network system.
Let $X$ be a topological space, $x ∈ X$. We call a nonempty collection $\mathscr{B}(x) ⊆ \mathscr{P}(X)$ such that $(∀B ∈ \mathscr{B}(x))\ x ∈ B$.

 (local) network at $x$ if for every neighborhood $U$ of $x$ there is some $B ∈ \mathscr{B}(x)$ such that $x ∈ B ⊆ U$;
 (local) (neighborhood} base at $x$ if in addition every $B ∈  \mathscr{B}(x)$ is a neighborhood of $x$;
 (local) open (neighborhood) base at $x$ if in addition every $B ∈  \mathscr{B}(x)$ is open.

Then the corresponding mapping $\mathscr{B} := \{x \mapsto \mathscr{B}(x): x ∈ X\}$ is called (local) network system, (local) neighborhood system, or (local) open neighborhood system, respectivelly. One can observe that the topology is uniquely determined by such system. As you write, $\mathscr T_\mathscr{B} = \{U \subseteq X \mid (\forall x \in U)(\exists B \in \mathscr B(x))\ B \subseteq U \}$.
On the other hand we may start with a set $X$ and a such mapping $\mathscr{B}$ and ask, when $\mathscr{T}_\mathscr{B}$ is a topology and under what conditions $\mathscr{B}$ is its network system or even (open) neighborhood system.
When we have a set $X$ and a mapping $\mathscr{B}$, by the topology generated by the network / neighborhood / open neighborhood system, we mean just $\mathscr{T}_\mathscr{B}$ and the claim that $\mathscr{B}$ is a corresponding system of induced topology.
So I would say, that $X$ is first-countable if it is generated by some neighborhood system $\mathscr{B}$ such that $\mathscr{B}(x)$ is countable for each $x$. And similarily $X$ is quasi-first-countable if it is generated by some network system $\mathscr{B}$ such that $\mathscr{B}(x)$ is countable for each $x$.
Comment: Well, it's an extension of established convention. There is a notion of network similar to the notion of base, but the sets are not required to be open. So (local) network at a point is similar to (local) (neighborhood) base at a point. And Suggested network system is analoguous to neighborhood system.
Comment: I take it that's your suggestion, not an already established convention? I have been calling them quasi-neighbourhood systems but wanted to know if there is an existing standard.
Comment: (Accidently posted the comment before I'd finished) Quasi-neighbourhood systems differ from the other two you mention in that they are less determined by the topology: every neighbourhood base is a base for the filter of all neighbourhoods which is unique to the topology, but a space can have different quasi-neighbour bases which do not determine the same filter (at the same point). I suspect it is possible to have two systems st. $\mathscr B(x) = \mathscr C(x)$ at some point x but the neighbourhoods of x in the corresponding topologies are different.
Comment: That's possible. I think it is not in contradiction with anything in my answer.
Comment: Yes, there's no contradiction. Sorry. I was just a little uneasy at defining a (local) network at a point x in isolation, it being of little use without the rest of the system. But of course you did from then on use only the whole system.         Can you give a link to any discussion of this notion of network? My searches just turn up discussions of the topology of computer networks.
Comment: See Engelking p. 127, http://en.wikipedia.org/wiki/Base_%28topology%29, or http://dantopology.wordpress.com/2009/11/14/spaces-with-countable-network/.
Comment: It's possible that the notion of (local) network at a point is of little use in isolation, but it makes the structure of the definitions clear and the analogies are visible. It is also used as step in the definition of network / quasi-neighborhood system. You can of course call it quasi-neightborhood system, there is just the thing that there is no notion of quasi-neighborhood of a point.

Variation on neighbourhood base


mysql jdbc connection failure error

Question: We have deployed rest api based application on aws and some times the below error is thrown:

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
  The last packet successfully received from the server was 66,711,586
  milliseconds ago.  The last packet sent successfully to the server was
  66,711,586 milliseconds ago. is longer than the server configured
  value of 'wait_timeout'. You should consider either expiring and/or
  testing connection validity before use in your application, increasing
  the server configured values for client timeouts, or using the
  Connector/J connection property 'autoReconnect=true' to avoid this
  problem.  at
  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  ~[na:1.7.0_85]    at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
  ~[na:1.7.0_85]    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
  ~[na:1.7.0_85]    at
  java.lang.reflect.Constructor.newInstance(Constructor.java:526)
  ~[na:1.7.0_85]    at
  com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
  ~[mysql-connector-java-5.1.27.jar:na]     at
  com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121)
  ~[mysql-connector-java-5.1.27.jar:na]     at
  com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3988)
  ~[mysql-connector-java-5.1.27.jar:na]     at
  com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2598)
  ~[mysql-connector-java-5.1.27.jar:na]     at
  com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
  ~[mysql-connector-java-5.1.27.jar:na]     at
  com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2819)
  ~[mysql-connector-java-5.1.27.jar:na]     at
  com.mysql.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:5346)
  ~[mysql-connector-java-5.1.27.jar:na]     at
  org.apache.commons.dbcp.DelegatingConnection.setAutoCommit(DelegatingConnection.java:371)
  ~[commons-dbcp-1.4.jar:1.4]   at
  org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.setAutoCommit(PoolingDataSource.java:328)
  ~[commons-dbcp-1.4.jar:1.4]   at
  org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:72)
  ~[hibernate-core-4.2.7.Final.jar:4.2.7.Final]     ... 90 common frames
  omitted

This error is thrown randomly and not for any particular api.
This is what is configured in database.xml
<beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                </beans:prop>
                <beans:prop key="hibernate.current_session_context_class">thread</beans:prop>
                <beans:prop key="hibernate.show_sql">false</beans:prop>
                <beans:prop key="maxwait">10000</beans:prop>
                <beans:prop key="maxidle">25</beans:prop>
                <beans:prop key="minidle">5</beans:prop>
            </beans:props>
</beans:property>

Any suggestions will be appreciated.
Thanks,
Gayithri
Answer: This is because that you fail to connect to the database server. The wait_timeout variable represents the amount of time that MySQL will wait before killing an idle connection. Check your network environment.
The error log has already told you why and how to solve the problem. Go try it.

mysql jdbc connection failure error


Mascara em campos Rails

Question: Galera estou apanhando pra uma coisa teoricamente simples, estou querendo por uma mascara de data no meu application.js:
//= require maskedinput
jQuery(function($){
$("#datadoacao").mask("99/99/9999");
});

No meu partial de form:
<%= f.text_field :data_doacao, id: 'datadoacao' %>

E estou usando a gem 'maskedinput-rails'.
Em meu template faço a seguinte chamada
Então eu importei o javascript direto no application.html.erb
<%= javascript_include_tag 'application', 'maskedinput' %>

Alguém sabe o porque de não esta funcionando?
Obs: adicionei o arquivo maskedinput em assests/javascript
Comment: Algum erro no console?
Comment: No seu console do rails nao traz nenhuma mensagem de erro?
Answer: Então eu importei o javascript direto no application.html.erb
<%= javascript_include_tag 'application', 'maskedinput' %>
Answer: Como você já fez o require em seu application.js, certifique-se que fez o require também do JQuery
//= require maskedinput
//= require jquery
jQuery(function($){
   $("#datadoacao").mask("99/99/9999");
});

Seu javascript_include_tag já contém ele, então basta:
<%= javascript_include_tag 'application' %>

Confiram também seu console de erros, caso esteja utilizando o Chrome basta pressionar F12 e selecionar a aba console.
Se tiver tudo OK, deve aparecer algo como:

Caso tenha algum erro, algo como:

Não sei se foi muito básico, mas você exibir alguma mensagem de erro pode ajudar muito no diagnóstico do problema.
Answer: Olá, o que pode fazer também é verificar se o elemento está ficando com o id que você inseriu, o que eu uso geralmente é o seguinte:
<%= f.text_field :data_doacao, input_html: {'id': 'idQueQuer'} %>

Mas inspecione o elemento e confira se está com o id correto.
Answer: Opa, cara, da olhada no MEIOMASK, eu gosto dele, e acho ele respectivamente simples... Eu baixei neste repositório (https://github.com/johnvoloski/meiomask-rails), o funcionamento é mais ou menos como abaixo:

'z': /[a-z]/,
'Z': /[A-Z]/,
'a': /[a-zA-Z]/,
'*': /[0-9a-zA-Z]/,
'/': /[/]/,
'n': /[0-9]/,
'@': /[0-9a-zA-ZçÇáàãâéèêíìóòôõúùü]/

$('#datadoacao').setMask({mask: "nn/nn/nnnn"});

Espero que ajude

Mascara em campos Rails


Importing a daily file with variable name into access database

Question: Let me apologize in advance if this question has been posed somewhere and I overlooked it. I've spent multiple days on this and cannot get it to run 100%.
I am trying to import an excel file that gets sent via email every morning into an access database. The file has a date portion that changes every day. The naming follows the same pattern everyday of "FTTQ m-dd-yyyy". The day shown in the file name is for the previous work day, ex. receive email on 8/25 for FTTQ on 8/24. The code below is what I have so far and it will loop through the folder, however when it reaches the correct day it cannot find it. I have tried a couple variations but Access keeps crashing when I try to run it. Ideally I need Access to find the latest date on the file and import it, such as coming in on Monday and getting the file for Friday/Saturday or during the week getting it for the day before. Any help will be greatly appreciated.
Private Sub Button1_Click()
Dim strToday As String
Dim strFilePath as String
Dim strFile as String

strToday = Format(Date, "m-dd-yyyy")
strFilePath = "C:\Users\cole.stratton\Documents\Procurement\FTTQ 'Note:FTTQ is the beginning of the file name
strFile = Dir(strFilePath, "*.xlsx")

  Do While strFile <> ""
    If Right(strFile,14) = strToday & ".xlsx" Then
      DoCmd.TransferSpreadsheet, acImport, "tblTest",strFile, True
    End If
  strFile = Dir 'Note: I do not understand the point of this line or what it does or supposed to do.
  Loop
End Sub

Answer: To find the latest existing file, I would change the loop like this:
Dim searchDate As Date
Dim strDate As String
Dim strFilePath As String
Dim strFile As String
Dim i As Long

' Search backwards from today for a file with the date name
For i = 0 To -7 Step -1
    searchDate = DateAdd("d", i, Date)
    strDate = Format(searchDate, "m-dd-yyyy")
    strFilePath = "C:\Users\cole.stratton\Documents\Procurement\FTTQ " & strDate & ".xlsx"
    Debug.Print "Looking for: " & strFilePath
    ' Check if file exists
    strFile = Dir(strFilePath)
    If strFile <> "" Then
        ' Note that Dir() only returns the file name, so use strFilePath
        DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "tblTest", strFilePath, True
        ' file found, exit loop
        Exit For
    End If
Next i

Comment: I tried this and when it ran I got Runtime Error 3170: Could not find installable ISAM
Comment: What happens if you remove the comma from between `DoCmd.TransferSpreadsheet` and `acImport`?
Comment: I removed it and now get a type mismatch error on that line it happens for `DoCmd.TransferSpreadsheet acImport, "tblTest", strFilePath, True` and `DoCmd.TransferSpreadsheet acImport, "tblTest", strFile, True`.
Comment: The second argument for `TransferSpreadsheet` should be a value from the *AcSpreadSheetType Enumeration*, but that code is giving it *TableName* ... which should be the *third* argument to `TransferSpreadsheet`.  Check the *DoCmd.TransferSpreadsheet Method* topic in Access' built-in help system from details.
Comment: Completely forgot about that part. Now it is added back in. It's almost there but now Access is looking for the file in the `Documents` folder instead of going to `Documents\Procurement` to find it. Runtime Error: 3011: Could not find the object `C:\Users\cole.stratton\Documents\FTTQ 8-24-2015`.
Comment: Hmm?  Set a breakpoint, run the code and use F8 to step through the code one line at a time and monitor the value of *strFilePath*.
Comment: Edited: corrected DoCmd.TransferSpreadsheet parameters (should have checked that), and added a debug output (goes to the Immediate Window - press Ctrl+g). I can see no reason why it would look in the wrong folder. Unless the path is wrong, then it might default to "My documents".
Comment: That was my mistake on that one and I resolved it. Thank you @HansUp for your support. Now just need to get the person sending the email to fix their headers so access will accept it every time and I will be in good shape.
Answer: ***I'm assuming that you have the closing " in your strFilePath line in your actual code. ****
This line looks like the issue...
strFile = Dir(strFilePath, "*.xlsx")
This page will show you the correct syntax for using Dir...http://www.techonthenet.com/excel/formulas/dir.php
strFile = Dir(strFilePath & "*.xlsx") <-- you were putting the file extension in where the attributes were supposed to go.
However, you also need to change your date.  If the file will have yesterday's date, not today's...strToday = Format(Date-1, "m-dd-yyyy")
This line...
strFile = Dir
sets your string to the next file name that meets your search criteria.
Comment: Wouldn't it be simpler to move each FTTQ.xlsx file from the Procurement folder to an Archive folder after it's been imported?  Then, the task requirement could be simpler ... "if there is an FTTQ.xlsx in the Procurement folder, import it".
Comment: How would I account for coming in on Monday and finding a file for 2-3 days ago? While yes that would work for finding yesterday, there will never be a file that gets saved with a Sunday date, in this case 8/23. I would need it to find 8/21 or 8/22.
Comment: I corrected the mistake and made the changes suggested but get the same runtime error as with the other answer. Runtime Error 3170: Could not find installable ISAM
Comment: @ColeStratton Please explain the logic Access can use to know whether to check for a filename which contains yesterday's date vs. some other earlier date.  Also is it possible that your *Button1_Click* procedure could ever be run twice on the same day?  If so, what should happen then?
Comment: There should be no reason for the button to be clicked more than once per day. As of now do not know what to do if it does happen. Let me provide an example that may help, today received email for FTTQ 8-21-2015. As this is not yesterday, I still need to get that file imported into the database.
Comment: But since today's date is 8-24-2015, how can Access know you want it to look for 8-21-2015 instead of 8-22-2015 or 8-23-2015?
Comment: That would make more sense and it sounds a lot simpler. Is there a question already asked related to this otherwise I will ask another because I do not know how to move files from folder to folder within Access
Comment: `Name "old full filepath here" As "new full filepath here"`  like this ... `Name "C:\share\Access\temp.xlsx" As "C:\share\Access\Archive\temp.xlsx"`
Comment: Sorry, I was distracted by another project.  Looks like you might have gotten this all worked out anyway.


4in6 tunneling software for Windows

Question: I have a VM running Windows 2008 R2, and I need this VM to connect to a remote site using VPN.
The VPN software does not support Windows 2008 R2 or any other 64 bit operating system, so I can't install it on my VM.
But then I have another VM running Windows 2008 SP2 x86, and this is connected to remote site through the VPN software. Between the two VM's I have an ipv6 network. I cannot communicate from the R2 VM to the SP2 VM using ipv4 because the VPN client does not allow split-tunneling.
I was therefore hoping that I could use a 4in6 tunneler to route the ipv4 traffic from my first VM, through the second VM, and finally to the remote network.
I have googled quite a lot, but have not succeeded in finding tunneler software for Windows that supports 4in6. Does such an application exist, or do I need to develop it myself?
Any other suggestions on how to solve this problem would also be appreciated!
[Update]
I still haven't figured out how to solve this.
Any news on ipv6 compatible tunnelers?
Answer: An idea, not really a solution:
Try L2TP or a 4in4 tunneling protocol (GRE?), and then run that over IPv6.
It seems to me that most of the 6in4 tunneling issues was more about setting up manageable routing and less about the protocol specification of the tunnel. The "protocol" in "protocol" encapsulation seems to be done pretty much the same way, it was always the management piece or the gui configuration piece that tripped people up.
Comment: Thanks for your suggestion! How can i run a 4in4 tunnel over IPv6? Not sure how to accomplish that...

4in6 tunneling software for Windows


How to properly compare values of two identical entities?

Question: I have a custom entity that is not revisionable and I need to store any differences made by the user - and only differences, so if nothing has changed there should be no entry.
I am doing this in preSave method because the original entity has the same format as current entity(ie. some fields do some value processing and therefore the original entity does not match the current entity exactly in postSave method).
The issue I am facing is that I cannot properly compare values($entity->toArray()) because the data is not consistent. For example in the original entity a field's value can be 123.8 but in the current entity it can be 123.8999999... If I type cast it to string I end up with something like '123.8' vs '123.80' so the values won't match. Or 1 can be '1' and so on. Also with arrays I think keys get misordered sometimes(either that or the same issue but in the whole array).
I have tried to use the DiffArray::diffAssocRecursive() and Differ::diff() but neither is working reliably.
One thing that comes to mind is doing something like
Differ::diff($entity->view('somemodewithallfield'), $entity->original->view('somemodewithallfield')) but that won't cover fields that are hidden or invisible in UI and also diff would be "ugly" and too big.
So I am wonder what would be the correct solution in this case? I would like to avoid going through each value and doing some insane comparisons and data transformations(string/int/float).
I remember that there was a story on d.org to not save any field data if the data hasn't changed but I haven't looked into that yet and I'm not sure at what state that is at the moment.
Answer: Assuming you have two entities $a and $b.
You can convert them to arrays and compare the two arrays.
// if the position matters
$is_equal = ($a->toArray() === $b->toArray())

// if the position doesn't matter
$is_equal = ($a->toArray() == $b->toArray())

Edit: I thought the OP was about discovering if two entities have identical data.
After reading the question again it seems that OP wants a way to mark what is the difference in data.


HTML search input, and HTML textarea width shrinks on iPad

Question: I am using Bootstrap 3 and AngularJs for this one.
I am doing this for the input type='search':
<input type="search" class="form-control" id='roomSearch' placeholder="Search" ng-model='qText'>

And this for the textarea:
<textarea name='question' id='question' rows='8' ng-model='q.text' class='form-control' ng-maxlength='{{$root.globals.maxLen.med}}' required></textarea>

It looks fine in all major browsers on iPhone and desktop, however; the iPad is rendering these fields like this:

And here

UPDATE!
Here is the CSS for the search box
     #roomSearch {
       margin-top: 8px;
       float: right;
     }

Here is the css for the text area
       .question-form textarea {
       width: 100%;
      }

Answer: I did not see an answer, and this is old so I am guessing the author figured it out, but this worked for me:
textarea, input {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    width: 100%;
 }

This made the textarea and the input fill the full width of the browser.


What macros are defined in a Web2c format file?

Question: Web2c defines its format style using Pascal strings, so there are no separator characters between csnames.  Is there a straightforward way of listing all csnames bound in a .fmt file?
Answer: Arthur Reutenauer answered this question on tex.sx when I asked it there.
The Web2c implementation of Tex has an undocumented command-line switch <code>-debug-format</code>, which dumps lots of information about the format it would compile with to stdout.


How to define a nested member template outside a class template?

Question: Consider the following class template:
template <class T>
class MyClass
{
   void MyFunc();
};

template <class T>
void MyClass<T>::MyFunc()
{
  //...implementation goes here
}

I need to add another function template MyFunc2 which accepts a template argument T2
i.e.,
template <class T>
class MyClass
{
   void MyFunc();

   template <class T2>
   static void MyFunc2(T2* data);
};

template <class T>
void MyClass<T>::MyFunc()
{
  //...implementation goes here
}

template <class T, class T2>
void MyClass<T>::MyFunc2(T2* pData)  // error here
{
  //...implementation goes here
}

I am using VS 2008 compiler. I am getting the error:

error C2244: unable to match function definition to an existing declaration

What should the function's definition and declaration look like in this case?
Comment: More often than not, it is easier to define the template member functions inlined in the class template definition to avoid all this small issues.
Answer: template <class T>
template <class T2>
void MyClass<T>::MyFunc2(T2* pData)
{
  //...implementation goes here
}

$14.5.2/1 - "A template can be
declared within a class or class
template; such a template is called a
member template. A member template can
be defined within or outside its class
definition or class template
definition. A member template of a
class template that is defined outside
of its class template definition shall
be specified with the
template-parameters of the class
template followed by the
template-parameters of the member
template."
Comment: I've always found this syntax awkward, it doesn't get better with nested classes either...
Comment: @Chubsdad: how about the static keyword in the original templated member function declaration? Is it valid to drop it out in the implementation?
Answer: What you're doing is fine, try this out:
template <typename S,typename T>
struct Structure
{
  S s ;
  T t ;

} ;

int main(int argc, const char * argv[])
{
  Structure<int,double> ss ;
  ss.s = 200 ;
  ss.t = 5.4 ;

  return 1;
}

This code works.  If you're getting strange errors, see if you forward declared Structure using only 1 template parameter (that's what I was doing).
Answer: Try this one :
template <class T, class T2>
class MyClass
{
public:
    static void MyFunc2(T2* data);
};

template <class T, class T2>
void MyClass<T, T2>::MyFunc2(T2* pData)
{
    cout << "dummy " << *pData<< "\n";
}

Then
int main()
{
    cout << "Hello World!\n";
    MyClass<int, int> a;
    int *b = (int*)malloc(sizeof(int));
    *b = 5;
    a.MyFunc2(b);
}

Output
Hello World!
dummy 5


What do you use to remove a potent allergen from a classical guitar?

Question: As anyone who gets poison ivy will know, it usually takes a day or two after contact with the plant for an allergic reaction to appear.
Long story short, I got poison ivy without knowing, and happened to play my classical guitar in that grace period before the rash appeared. Having done that, I'm now fairly certain the oil in the ivy plant (the causative agent of the reaction) is all over the guitar, and I need to clean it off.
What should I use to do this? I'm not really trying to give the guitar a conditioning - I thought I would just apply some simple cleaner (soap and water maybe?) and change the strings.
Buy I don't know what cleaner is safe to use, or what cleaner to use on the neck and what to use on the body of the guitar. Any advice?
Comment: Mild dish soap used for hand washing is usually safe for almost any surface that can be made wet. You might research separately what it takes to remove poison ivy oils from surfaces. Also, "disinfect" normally means "kill germs and/or viruses" which is not what you are trying to do. Changing the title of your question would make it more clear.
Comment: Heh. It's not an allergen either. It's an irritant.
Comment: Tecnu is a popular brand of poison ivy cleaner.
Comment: WebMD seems to agree with his allergy assumption.  It specifically mentions an allergic reaction *to* the sap, and goes a step further mentioning that up to 85% of the population isn't even *allergic* to it.  http://www.webmd.com/allergies/guide/poison-ivy-oak-sumac
Answer: I have never encountered this situation, but here is my advice:
I will bet that most of the poison ivy oil is on the strings. Throw the old set of strings away.
While the strings are removed from the guitar, you can clean off the rosewood or ebony fingerboard of the guitar and the top of the guitar with a sponge soaked in a solution of soap and water or dishwashing liquid and water. Make sure not to use too much solution at once. You do not want any water to soak into the wood.
Maybe this would be a good time to condition the fingerboard. While wearing rubber gloves, clean off the fingerboard by rubbing it down with lighter fluid (naphtha). Make sure you are nowhere near any open flames or a source of heat. Then you can condition the fingerboard with lemon oil or guitar fingerboard oil according to the instructions. Do this in a well-ventilated area as the fumes from the fingerboard oil are slightly toxic. Wipe it down with oil, wipe off the excess, leave it to set for at least 24 hours, buff it off thoroughly with a lint-free cloth, and then replace the strings.
Comment: Thank so much for the advice! I've never used lighter fluid to clean a fretboard. I've used it to clean residue off of other surfaces though so I can see why it can be useful on a guitar. And lemon oil is just the best - I've used it on furniture and wood trim instead of refinishing at times - so that makes sense too. I'll assume that the rubber gloves are to protect my hands from the lighter fluid, not from the poison ivy oil, or urushiol.
Comment: I would probably get a fret polishing kit like planet waves makes and go over the frets once after doing all that also.
Answer: I have in fact had this same thing happen. Did yard work. Normal night shower(long after yardwork). Worked on Monday had my gibson hummingbird in the office and picked it up and played it at lunch time. Day 3 got nastiest reaction Ive ever encountered (seeing that I had no idea I had come in contact so never took appropriate steps in the immediate aftermath). Took a 4 days in hell and finally found tecnu . They have a few versions, the original can be used after to pull out any oils still hanging out. Now if i go outside and think I went near any Ive got a large bottle from amazon and take immediate action. Soooo after I was healed (3 weeks later) i picked up my guitar again. I felt itchy immediately that afternoon on my right fore arm and the hives were in lines. Yup my forearm was a prior host and I never went back and cleaned the guitar and I love resting my forearm on the corner of the guitars body. I had the tecnu at that point , treated it (followed the inst.) when i got home and itching was stabilized at mild for 2 days no super blisters like before. Clean the guitar with tecnu. Throw rags away. Do not let anything drip or run off. If tecnu needs to be removed from the guitar. Hydrate the finish after removing thr tecnu. If your guitar is under 400$. Sell it. If its a hummingbird ..mmmmboy take a day off for the cleaning.


Reduce com sort

Question: Preciso reduzir um array, somando os valore (consegui fazendo o código abaixo), agora com essa redução preciso fazer uma espécie de um SORT para depois pegar os 3 maiores e os outros vou fazer tipo um if para outros
Não sei se tem um lib em nodejs que facilitaria.

REDUCE
ORDENAR PELO TRES MAIORES
   var array=[ {

        "paymentId" : 1,
        "value" : 290
    },
    {
        "paymentId" : 2,
        "value" : 223
    },
    {
        "paymentId" : 1,
        "value" : 2333
    },
    {
        "paymentId" : 3,
        "value" : 24432
    },
    {
        "paymentId" : 4,
        "value" : 23424
    },
    {
        "paymentId" : 5,
        "value" : 2323
    },
]
var r = array.reduce(function(pv, cv) {
    if ( pv[cv.paymentId] ) {
        pv[cv.paymentId] += cv.value;
    } else {
        pv[cv.paymentId] = cv.value;
    }
    return pv;
}, {});

console.log(r);

EXEMPLO DE RESULTADO  O 0 SERIA PARA OUTROS
[
    {
        "paymentId" : 3,
        "value" : 24423
    },
    {
        "paymentId" : 4,
        "value" : 23424
    },
    {
        "paymentId" : 1,
        "value" : 2623
    },
    {
        "paymentId" : 0,
        "value" : 2222
    },
]

Answer: Se você vai transformar o array num objeto para poder acessar os ids pelo índice, recomendo armazenar o objeto interno inteiro nesses índices, não apenas seu valor, já que o resultado final deve manter o mesmo formato.
var obj = array.reduce((pv, cv) => {
    if (pv[cv.paymentId]) pv[cv.paymentId].value += cv.value
    else pv[cv.paymentId] = {...cv}
    return pv
}, {})

Agora para poder organiza-lo por meio do método sort, você precisa converte-lo de volta para um array, pois não tem como organizar uma estrutura onde os valores estão associados a uma chave.
var arrayOrdenado = Object.values(obj).sort((a, b) => b.value - a.value)

E a soma dos demais resultados pode ser obtida com reduce:
var resto = {
    paymentId: 0,
    value: resultado.slice(3).reduce((acc, r) => acc + r.value, 0)
}

Funcionamento:

var array = [{"paymentId":1,"value":290},{"paymentId":2,"value":223},{"paymentId":1,"value":2333},{"paymentId":3,"value":24432},{"paymentId":4,"value":23424},{"paymentId":5,"value":2323}]

var obj = array.reduce((pv, cv) => {
    if (pv[cv.paymentId]) pv[cv.paymentId].value += cv.value
    else pv[cv.paymentId] = {...cv}
    return pv
}, {})

var arrayOrdenado = Object.values(obj).sort((a, b) => b.value - a.value)

var resultado = arrayOrdenado.slice(0, 3).concat({
    paymentId: 0,
    value: arrayOrdenado.slice(3).reduce((acc, r) => acc + r.value, 0)
})

console.log(resultado)
Comment: Genial, muito obrigado pela resposta amigo
Comment: Qual melhor forma que você usaria para encontrar os 3 primeiros e o resto colocar no mesmo valor como outros ?
Exemplo
`
[ { paymentId: 3, value: 24432 },
  { paymentId: 4, value: 23424 },
  { paymentId: 1, value: 2623 },
  { paymentId: 0, value: 2546 },
`

Onde o 0 seria a soma dos restante(outros)

Reduce com sort


How should I change the visibility of a TextBox when a ComboBox value changes?

Question: I'm new to programming and I'm trying to change the value of a textbox depending of a selected value on a combo box, since the values are numerical 1 to 20, and depending on the selection it will be the number of text boxes visible. I'm using the event selected index changed.
Here is my code:
private void cbxPIN_SelectedIndexChanged(object sender, EventArgs e)
{
    int pines = Convert.ToInt32(cbxPIN.SelectedItem.ToString());
    if (pines == 1)
    {
        textbox1.visible = true;
    }
    else if (pines == 2)
    {
        textbox1.visible = true;
        textbox2.visible = true;
    }
 ...

    else if (pines == n)
    {
        textbox1.visible = true;
        textbox2.visible = true;
 ...
        textboxn.visible = true;
    }
}

since there are like 25 different numeric values on the combo box is there an easier way of doing this? asides from comparing each different value?
Something like a loop.
Answer: At the least, I'd rewrite it like this, to reduce duplication:
private void cbxPIN_SelectedIndexChanged(object sender, EventArgs e)
{
    int pines = Convert.ToInt32(cbxPIN.SelectedItem.ToString());

    if (pines >= 1)
        textbox1.Visible = true;

    if (pines >= 2)
        textbox2.Visible = true;

    ...

    if (pines >= n)
        textboxn.Visible = true;
}

Actually, I'd add all the TextBox controls to a collection, possibly in the constructor:
List<TextBox> TextBoxes = new List<TextBox> { textbox1, textbox2, ... textboxn };

Then use LINQ's Take() method to grab the first xx number of controls and iterate through them:
foreach (var tb in TextBoxes.Take(pines))
    textBox.Show();

Answer: You want to use a loop structure. You should validate that the number of loops to perform is > 0 and < the number of textboxes you have available, but I'll leave error handling to you.
private void cbxPIN_SelectedIndexChanged(object sender, EventArgs e)
{
    int pines = Convert.ToInt32(cbxPIN.SelectedItem.ToString());
    TextBox textBox;
    for (int i = 1; i <= pines; i++)
    {
        // get the control from the form's controls collection by the control name
        textBox = this.Controls["textbox" + pines.ToString()] As TextBox
        textBox.Visible = true;
    }
}


how to declare a php variable from a mysql fetch result?

Question: i know it might be somthing old but i need to declare a variable or that is what i think.
basically i got a table name request and i need to fetch the last value from the column date. which i did in phpMyAdmin. now i need to fecth that exact value and use it as a variable in php.
<?php
include 'mydb.php';
require_once 'init.php';
$user_id = $user->data()->id ;
 $data = mysql_query("SELECT date FROM request WHERE user_id=   $user_id      ORDER BY latest_request DESC LIMIT 1")  or die(mysql_error());
  $test = array();
   while($row = mysql_fetch_array( $data ))
     {
    echo "" .$row['date']. "	" ;
   }

 ?>

   <?php
 $current_date = echo " .$row['date']. "	" ;
 // result im expecing is 2016-10-17 23:53:48
// echo " $current_date" --- will be 2016-10-17 23:53:48
>?

but all i get is an empty value, how can i accomplish this
Comment: You can't assign an `echo` to a variable. Do `$current_date = "" .$row['date']. "";`...or probably better `$current_date =  $row['date'];` then build your element where you need it.
Comment: i did exactly as you describe as well and all i get is a blank value, i got the query that echoing the value just fine, but i cant get to declare that same value
Comment: You get an empty `td` or nothing is outputting?
Comment: @nogad `$row` should exist outside the while, it'll be the last record (since limit 1 the `while` isnt really needed)
Comment: true that, just not a useful approach it expecting 1 value
Comment: nothing is outputting, and i guess your right $row doesn't mean anything outside while loop. so i'm still thinking how to accomplish this
Comment: You are probably getting a fatal error then. Check your error logs and/or enable reporting.
Answer: If you want to have only one, last row, then maybe better idea would be something like that:
  $sql = 'SELECT date FROM request WHERE user_id=   $user_id      ORDER BY     latest_request DESC LIMIT 1';
  $result = mysql_query($sql, $yourDBCon) or die(mysql_error());
  $row = mysql_fetch_assoc($result);
  print_r($row);

This solutions brings you only one row.
Also make sure you get anything from sql statment.
Comment: the fetch works it outputs fine, but i need to declare a variable that = to the fetcth result so i can use the variable elsewhere
Answer: Here's a working code (based on the fact that you say that the while()-loop works, and that you actually get a result with the $row['date']:
    <?php
    include 'mydb.php';
    require_once 'init.php';
    $user_id = $user->data()->id ;
    $data = mysql_query("SELECT date FROM request WHERE user_id = $user_id ORDER BY latest_request DESC LIMIT 1") or die(mysql_error());
       while($row = mysql_fetch_array( $data )) {
        echo $lastdate = ''.$row['date'].'	' ;
       }

     echo $current_date = ''.$lastdate.'	' ;
?>

Answer: i was able to solve this issues by using pdo insted
<?php
$base_datos = DB::getInstance();
 $base_datos->query ("SELECT  req_date FROM request  wHERE user_id =     $user_id  order by req_date desc  limit 1");
 $last_date = $base_datos->results();
 $request_last_date = $last_date[0];
 $c_date =$request_last_date->req_date;

  echo "$c_date";
?>

this was to get a value from a table on my database and declared it as a value


Find Script start time and uptime in centos

Question: I have a php script (cron job) running on my server which takes up a lot of cpu. I took a look on the code and couldn't find anything wrong. Now I have to check the logs for anomaly and for this I need to get the script start time and/or uptime. I tried top, ps -aux, htop etc but couldn't get that. Is there any other command/method available for this?
ps -aux | grep php shows Oct 11, the date. But How can I get the time?
Answer: You can run
ps -o lstart PID

Which will give the start time of the process.
Comment: Thank you Matthew. However, there is a syntax error in your answer. There should be a comma between lstart and PID.
Comment: No there shouldn't, your supposed to put the pid you want in PID. If you want the start time of EVERY Process then you would do `ps -Ao lstart,pid`
Answer: I suggest wrapping the php script inside a shell script:
date >/your/log ; /usr/bin/time /path/to/your.php
Answer: If you know PID of script; you can get the start time of script with

stat  -c %z /proc/PID

Additionally you can analyze what's going on in script with strace e.g.

strace -p PID -s 128 -tT

This will give you idea where time is spent in this process which appears to be trashing your CPU
Comment: stat -c %z will show the Time of last change right? I need to get the time at which the script started or the script uptime so that I can match it with my log and find the issue. And strace is giving me just a blank output and stat -c %z is giving me the current date.
Comment: that is the time directory of process was created; time is never altered throughout the process lifetime; make sure that you put PID of process instead PID


What constitutes valid machine name syntax?

Question: The MSDN documentation for ServiceController.GetServices stipulates that the function will throw an ArgumentException when

The machineName parameter has invalid syntax.

How can I validate a machine name for valid syntax? Is it similar to Wikipedia's Restrictions on valid host names? I imagine that it would have to cover at least that, but does Windows put any further restrictions on what's valid?
Answer: .Net has an API to verify whether the specified host name is a valid DNS name. http://msdn.microsoft.com/en-us/library/system.uri.checkhostname(v=vs.110).aspx which could be a good run-time check. Use this then you won't have to create a parser for the machine name looking for illegal chars or strlen restrictions.
Answer: Have a look at this: http://support.microsoft.com/kb/909264
Though it mentions Active Directory, I believe the NetBIOS names section applies to all scenarios.
Hope this helps.
Sri
Answer: This is actually not as easy to answer as it seems. The problem is that a machine name often is used unchanged for identification in other services. So its possible to just test its validity as a name for the machine (alphanumeric characters only, no control character, no spaces, no extended charset) but depending on your solution you may want to validate that it also functions as a valid DNS name and perhaps some other services?
I suggest you test both for validity as a NetBIOS and DNS name, here is a good page that describes the rules for both http://support.microsoft.com/kb/909264.


Why do these chords from the plastic bag scene in American Beauty work?

Question: I'm trying to figure out the theory behind these three chords and why they work together. At first I thought it was a C major scale since it tends to want to go there. But there's flats in there so maybe it's in F since there's a B♭, but then where does the E♭ come from?

C - G
E♭ - B♭
F - A - C

I think this could also be written like:

C5 chord
E♭5 chord
F chord

progression here in Synthesia.
Answer: In addition to Tim's great answer, we can also conceptualize this as being in C Dorian.
The Dorian mode is a major scale with a lowered third and seventh. C Dorian would thus have E♭ and B♭.
I think this is especially important to point out because of the A♮ (not A♭!) shown in your link. Another way to conceptualize Dorian is as natural minor with a raised sixth, which would be this A♮.
Dorian is very common in popular music. The I–III–IV of this excerpt is a very common feature of Dorian, as is the emphasized whole step between scale-degrees 6 and 5 (A and G).
Comment: @EzLo For metrical reasons, I hear C as tonic instead of F. To me, the C chords are treated as points of rest, whereas the F chords sound to me like they're waiting to resolve back to C.
Comment: I'd just like to add here that _American Beauty_ is a great film, and part of its greatness is an especially sensitive and original soundtrack.  Just sayin'.
Comment: I just noticed that Scarborough Fair by Simon & Garfunkel is in Dorian too!
Comment: It's a bit tricky, in that all through, it homes on C, but the last chord is F major - and it doesn't sound like it's the first half of a plagal cadence. It sounds back home!
Answer: They just do! But for some theory behind, it's entirely possible to mix in a parallel key. So here, the Eb/Bb (certainly not D#/A#!!) is from C minor. And yes, it could be written as C5 Eb5 F5. There are those amongst us who would argue they're not 'chords', but that's for another post...
It could equally be in F, as those three chords also feature in that key.
That sequence was used a fair bit in the '60s - Knock on Wood comes straight to mind.I - bIII - IV. Or, thinking in F, I - bVII, You Really Got Me. (Although that's nearly in key G!!). Or On Broadway.
Comment: The F chord at the end has an A in the top, so it's a full on F major chord.
Answer: I think this could be in the key of C or F, both major or minor, depending on the melody and the rest of the chords, I could think in examples for all cases if needed. In the major case, Eb would be borrowed from the parallel minor key.
As already said, all notes fit in both C and F minor pentatonics, and power chords over pentatonic scales are an old trick I guess, can't go wrong.
Answer: To my ear, it actually just sound like it's in B-flat major, but completely avoids playing the tonic chord, aka B-flat major. Since it avoids the tonic, it creates this feeling of always floating, never being anchored, like the bag in the scene.
If this is correct, then the chords would be analyzed as ii IV V, repeating.
You can try this out for yourself: end the progression with a B-flat major chord, with the top note also being a B-flat. To me, it sounds like I finally found rest.
Comment: I don't think so since it wants to go back to C5.
Comment: It sounds in C to me too.  Part of the reason is all the pedal tones on C.  No hint of Bb to my ears.
Answer: The piece is modal and written in the key of C dorian.
Dorian is perhaps the brightest of the minor modes, creating a thoughtful and dreamy feel to the music.
The notes in C dorian are the same as Bb major, but in C Dorian, more importance is placed on C as the tonic as opposed to the Bb; we feel a grounding towards the C in this piece, hence why you felt that C major sort of fitted the profile. However, this piece is based off of the Dorian mode in C with flattened 3rd and 7th scale degrees.
 Hope this helps.
Answer: To me it doesn't sound like functional harmony, it sounds like pentatonic music with a weak key center in C. If it was functional harmony in the major-minor system, then we would expect at some point to get a V-i, and the V chord would have a B natural in it. That never happens. Since our ears are attuned to functional harmony, the lack of functional harmony makes it sound enigmatic. That works because the point of the scene is to get across something mysterious and ineffable.
Answer: If you're to stay within the confines of key of C, then Eb and Ab can be viewed as tritone subs: Eb for Am and Bb for Em


How Can I Incorporate my WordPress Blogs into an iOS app?

Question: How Can I Incorporate my WordPress Blogs into an iOS app? I have a beautiful word press site and I want to create a native iOS app. I have knowledge of coding for iOS, but I just don't know how I would go about showing all the latest blogs that are up in a beautiful way.
Thanks in Advance!
Comment: @rmaddy read the question again, he does not want to view it like in a UIWebView but to get the posts and use it.
Comment: Apple will likely reject such an app. They reject apps that can just as easily be done by opening a URL in Safari.
Answer: There are many ways you can achieve that. Here is a list of things you need to do in order to make an iOS app for your WordPress blog:
1) You need to parse the data from your WordPress blog to display it inside your iOS app. You can do it by parsing your blog's RSS feed you can parse JSON.
2) If you are planning to parse the RSS feed, use NSXMLParser to do that. There are other third party libraries available that parse the XML feeds but i would suggest to go with the built in NSXMLParser as there is plenty of help available online for it.
3) If you are planning to parse JSON data, install Feed JSON plugin on your WordPress blog. Once installed, you can go to http://example.com/feed/json to get the JSON data. (You can replace example.com with your blog's URL)
4) To connect to the web services like XML feed and JSON on your blog, you can use third party libraries like AFNetworking or you can use Apple's built in libraries like NSURLConnection and other classes to connect and download the data from the webservice.
5) Here are some very easy tutorials for the steps above. How to Use NSURLConnection, How to fetch JSON or How To Parse RSS with NSXmlParser
You can start your app by completing the above steps and getting started.
6) After that one of the most important thing is to download images asynchronously in the UITableViewCells where you are displaying your blog posts. I would suggest you to download a video from Stanford University's iOS programming course on iTunes U that shows how to do it or you can simply find some tutorials or look for questions on StackOverflow.
7) Then you have to create a UIWebView and when the row of any blog post inside the UITableView is tapped, you can use the link to segue in the UIWebView to show the actual blog post. You can use didSelectRowAtIndexPath in order to pass data between view controllers.
8) Below the view controller that contains the UIWebView, you can add functions like stop, refresh, sharing on Facebook and Twitter etc.
9) As you can see that is a lot of work and business people just think that its easy to develop an iOS app but the truth is that it takes some time to completely package the app and submit to the App Store. You can also outsource your project by using service like Convert WordPress Blog To iOS App that is completely for free if you share revenue with them but its your choice and i recommend you to code it yourself to have complete ownership of you app.
Rest is just a matter of choice of different functions you would like to make in your app to stand out from the rest. You can add a Facebook style sliding navigation controller on the left side to create and parse specific categories on your blog, you can use Flipboard style swiping in your Web View etc etc. For that stuff there are a lot of third party libraries available.
Hope this helps!
Answer: You can read an answer of mine about cloud based ios apps (the db is online) here:
press me
now as i said, to get info from the server you need to use JSON, in wordpress there is a very good and simple plugin for that: JSON API
now the use of that is simple, you can see it in the notes: http://wordpress.org/plugins/json-api/other_notes/
but for example for getting the last posts in the system you need to run the url: http://www.example.org/api/get_recent_posts/
The /api means it's the plugin (you can change that in the settings) and the /get_recent_posts/ is the function.
there are many other functions like this one for everything you need and it can get more complicated than that based on what you want to get from the db.
After running the "query" and getting a response in JSON you need to use it:
Working with JSON in iOS 5 Tutorial
 now for the running of the url i recommend to use AFNetworking
now all you need to do is use the json string you get for getting out info.
this would have some more issues like managing html codes you get in the content respons and so but it's the start, develop your way up :)


How to install / import a Python package from a specific package?

Question: I run a code in Google Colab and get the initial error
/usr/local/lib/python3.7/dist-packages/utils_nlp/eval/rouge/rouge_ext.py in <module>()
     23 import collections
     24
---> 25 from indicnlp.tokenize import sentence_tokenize, indic_tokenize
     26 from ...language_utils.hi.hindi_stemmer import hi_stem
     27 from rouge import Rouge

ModuleNotFoundError: No module named 'indicnlp.tokenize'

How to install (for instance) the tokenize package from indicnlp ?
I tried
!pip install indicnlp.tokenize

which apprently doesn't crack it. How to specify from which package to pip install from ?
I also tried
!pip install indicnlp
from indicnlp import tokenize

which doesn't do it either. I then get the error
---> 30 from indicnlp import tokenize
     31 from utils_nlp import eval
     32 from utils_nlp.eval import rouge

ImportError: cannot import name 'tokenize' from 'indicnlp' (/usr/local/lib/python3.7/dist-packages/indicnlp/__init__.py)

Of course if I just do
!pip install tokenize

it does't know which tokenize to install
Answer: It looks like you just pip installed the wrong library. On pypi I found another project called indic_nlp_library (github repo) that seems to have the packages you're looking for. I can get
!pip install indic_nlp_library
from indicnlp.tokenize import sentence_tokenize, indic_tokenize

to work.
Looks like the indicnlp name was taken on pip by another project.


Prove that $\mathcal P(A \cap B)=\mathcal P(A) \cap \mathcal P (B)$

Question: Probably this is an easy problem, but this time I am not understanding these concepts.
The problem starts with:

Let $\mathcal{P}(A)$ denote the set $\{ x ~|~ x \subseteq A \}$

What I think is correct and that I can say from the above expression is that $x$ is a subset of A.
And then we have a set of questions, for example the first one:
Prove that $\mathcal{P}(A \cap B) = \mathcal{P}(A) \cap
\mathcal{P}(B)$ by showing that the statements $x \in \mathcal{P}(A
\cap B)$ and $x \in \mathcal{P}(A) \cap \mathcal{P} (B)$ are
equivalent.
The only thing that comes in mind is to replace the expression $\mathcal{P}(A \cap B) $ with its equivalent of this $\{ x ~|~ x \subseteq A \}$, but I am not really understanding the process and the logic...
Answer: You are going in the right direction. $\mathcal{P}(A) = \{x | x \subseteq A \}$, so just by replacing the symbols we see $\mathcal{P}(A \cap B) = \{x | x \subseteq A \cap B\}$.  So you are being asked to relate
$$\{x | x \subseteq A \cap B\}$$
To $\mathcal{P}(A) \cap \mathcal{P}(B)$ which is
$$\{x | x \in \mathcal{P}(A) \text{ and } x \in \mathcal{P}(B)\}$$
Does this help you get going?
edit: I want to comment that normally to show two sets are equal the foolproof approach is to show that they are subsets of each other.  Playing with the "rules" of a set to show it is equivalent to another should give you all the information you  need to do this, but if you want to dot your i's for this you ought to show each subset relationship.
Answer: hint: to get from
$$
\{x|x⊆A∩B\}
$$
to
$$
\{x|x∈P(A) \text{ and }x∈P(B)\}
$$
The property $$
X\subset Y \iff X\cup Y = Y
$$can be useful.

solution:
$$\begin{align}
\{x|x∈P(A) \text{ and }x∈P(B)\}
&= \{x|x\subset A \text{ and }x\subset B\}\\
&= \{x|x\cup A = A \text{ and }x\cup B = B\}\\
&= \{x|x\cup A \cup B = A\cup B\}\\
&= \{x|x⊆A∩B\}
\end{align}$$
Comment: yes. See also the other answer!
Comment: @Broly I added the solution as I would have written it.
Comment: @Broly you are right. It was a typo.
Comment: this step is useless. It should be fixed now.
Comment: @Broly this is because of the initial hint: $X⊂Y \iff X∪Y=Y$


How to connect multiple socket.io clients to different URLs in Node.js?

Question: I am trying to connect many socket.io clients for different URLs in Node.js like so :
app.get('/:id',function(req,res){
io.of('/'+id).on('connection',function(socket){
    socket.emit('hello');

})
});

This works however there is a problem :
When a browser refreshs the page http://localhost:3000/xyz for example, the event socket.emit gets fired two times.
If someone accesses the page http://localhost:3000/xyz 10 times, then the event fires 10 times.
This is not good because everytime the user visits that page, the socket events will be fired n+1 times.
What should be done so that I can register sockets to different URLs and at the same time not have this anomaly .
Another thing :
If I do this  :
var sock;

io.of('/'+xyz).on('connection',function(socket){
    sock=socket;

})

app.get('/:id',function(req,res){
    sock.emit('hello');

})

If I use the above code then the socket doesn't get saved succesfully to the sock variable in time. What that means is , I have to do a setInterval of about 1000 .. so that the
sock=socket

line gets fired.
Please help me.
Answer: Because with this, in each request to http://localhost:3000/id, you register a new handler, you should be doing that once, not at every request.
app.get('/:id',function(req,res){
    io.of('/'+id).on('connection',function(socket){
        socket.emit('hello');

    })
});

Comment: Your approahc is wrong, you have to store id-socket relationship, and emit an event to the respected socket by finding it with the id of the request.
Comment: Yes I know that .. but what is the solution for my usecase ?
Answer: I use below approach to achieve this goal:
client side:
var socket = io.connect('http://localhost:8183/?clientId='+clientId,{"force new connection":true});

server side:
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
    console.log("url"+socket.handshake.url);
    clientId=socket.handshake.query.clientId;
    console.log("connected clientId:"+clientId);

});

reference:https://github.com/LearnBoost/socket.io/wiki/Authorizing#global-authorization


How to find the direction between 2 n-dimensional vectors

Question: Can I find the direction of $2$ $n$-dimensional vectors (only $2$ vectors), clockwise or anticlockwise.
For example, If I have $2$ vectors $a=(1,1,1,1,1)$, $b=(2,3,5,6,7)$, function angle(a, b) returns $30°$, and angle $ (b, a) $ will return $-30$°.
I know that the direction can be defined in 2 dimensional space by $x_1y_2 - x_2y_1$.
Can I map the $2$ n-dimensional vectors to $2$ $2$-dimensional vectors(keeping the angle between $2$ vectors not changed or the position not changed between each other) and then check the direction by $2$-dimensional ways? OR any way to find the plane defined by the $2$ $n$-dimensional vectors(From my view, even if they are defined in n-dimensional space, but only $2$ vectors, if the $2$ vectors represent for $2$ intersected lines in n-dimensional space, can I find a $2$-dimensional space(plane) containing the $2$ lines so that I can check the angle and direction in $2$-dimensional ways, like $x_1y_2 - x_2y_1$)?
From my understanding, we can know the direction, clockwise or not in $2$-dimensional space is that we can got the vectors related position by some ways, like using sin/cos and also the formula mentioned, these ways check all the conditions in four quadrant.
But in n-dimensional space, it's hard to compare. Can I map the $2$ $n$-dimension vectors to $2$-dimensional vectors without information losing since in most cases, dimensional reduction will lose information(in this case, if $2$ $n$-dimensional vectors stand for $2$ lines, they can completely present by $2$ $2$-dimensional lines)?
Or can I compare the raw n-dimensional vectors directly to check the related position between each other, such as if $a[0] == b[0]$ (or maybe the projection is the same), then we can get the direction information, if not, compare another dimension between the vectors
Above discussion may be not right. Please correct me or any other right ways to do this.
Appreciate for your help
Comment: What is the meaning of the sign in high dimension ($n>2$) case?
Comment: @user, thanks for the response. I may not understand the question well. From my understanding, I have 2 n-dimensional vectors, even if they are defined by n-dimensional, but only 2 vectors, if these 2 vectors represent 2 intersected lines in n-dimensional space, can I find a plane contains these 2 vectors and then check the direction by 2-dimensional ways (such as $x_1y_2 - x_2y_1$)?
Comment: But this is ambiguous. Observe that already in three dimensions you can look at a pair of vectors from opposite sides wrt. the common plane of the vectors  with the opposite result for the "product" (clockwise vs. counterclockwise).
Answer: In short, you can perform the computation for any number of dimensions greater than 2, and so your answer is essentially answered by this thread. To do the computation, you should be able to compute the norm of a vector and have some familiarity with vector products (dot products and cross products).
What it ultimately boils down to is the right-hand rule in most cases for determining the "direction" or "sign" of the angle once you've computed its magnitude. That said, the sign of the angle is determined arbitrarily to fit an application.
Also, the generalisation of the vector products to higher dimensions has been previously addressed in these threads:

"Geometric definition of the dot product in n-dimensional vector spaces,"
"Cross product in higher dimensions."

In terms of thinking about the plane on which the vectors lie, a plane will always have two dimensions, and so as long as your space has at least two dimensions, you may embed a plane in it. That is, even if you have a 500-dimensional space, a plane will only span a two-dimensional subspace out of the 500 available. If this concept is a bit mind-boggling,  I would strongly recommend researching vector spaces, linear combinations, and linear span. Here are some good introductory resources I've found for this topic:

YouTube Playlist: Essence of Linear Algebra by Grant Sanderson (3Blue1Brown)
YouTube Playlist: MIT 18.06 Linear Algebra, Spring 2005 by Gilbert Strang (MIT OpenCourseWare)

I hope you found this helpful or clarifying in some way.
P.S. the tag "dimensional-analysis" is probably not appropriate for this post, as that is the analysis of base units for physical quantities. (See Wikiepdia - Dimensional Analysis.)
Comment: thanks for the detailed reply. I will check these topics in advance. I see that the tag "dimensional-analysis" has already been removed :). Thanks again


How to use UIStepper in Monotouch

Question: How to use UIStepper Control in an IOS Application. I am using monotouch, C# and examples i have seen are not of c#. the following code doesn't show anything.
<code> UIStepper stepper = new UIStepper();
 var section = new Section();
 section.Add(stepper);
</code>
Answer: This should get you going:
<code>var stepper = new UIStepper(new RectangleF(50, 50, 100, 50));
stepper.MinimumValue = 0;
stepper.MaximumValue = 10;
View.AddSubview(stepper);
stepper.ValueChanged += (object sender, EventArgs e) => Console.WriteLine(stepper.Value);
</code>

How to use UIStepper in Monotouch


How to fix circle and rectangle overlap in collision response?

Question: Since in the digital world a real collision almost never happens, we will always have a situation where the "colliding" circle overlaps the rectangle.
How to put back the circle in the situation where it collides perfectly with the rectangle without overlap?
Suppose that the rectangle is stopped (null velocity) and axis-aligned.
I would solve this problem with a posteriori approach (in two dimensions).
In short I have to solve this equation for t:

Where:

 is a number that answers to the question: how many frames ago did the
collision happen perfectly?
 is the radius of the circle.
 is the center of the circle
 is its velocity.
 and  are functions that return the x and y coordinates of
the point where the circle and the rectangle collide (when the circle is
at  position, that is in the position in which perfectly collide with the rectangle).

Recently I solved a similar problem for collisions between circles, but now I don't know the law of the functions A and B.
Answer: After years of staring at this problem, and never coming up with a perfect solution, I've finally done it!
It's pretty much a straight forward algorithm, no need for looping and approximations.
This is how it works at a higher level:

Calculate intersection times with each side's plane IF the path from current point to future point crosses that plane.
Check each side's quadrant for single-side intersection, return the intersection.
Determine the corner that the circle is colliding with.
Solve the triangle between the current point, the corner, and the intersecting center (radius away from the corner).
Calculate time, normal, and intersection center.

And now to the gory details!
The input to the function is bounds (which has a left, top, right, bottom) and a current point (start) and a future point (end).
The output is a class called Intersection which has x, y, time, nx, and ny.

{x, y} is the center of the circle at intersection time.
time is a value from 0 to 1 where 0 is at start and 1 is at end
{nx, ny} is the normal, used for reflecting the velocity to determine the new velocity of the circle

We start off with caching variables we use often:
float L = bounds.left;
float T = bounds.top;
float R = bounds.right;
float B = bounds.bottom;
float dx = end.x - start.x;
float dy = end.y - start.y;

And calculating intersection times with each side's plane (if the vector between start and end pass over that plane):
float ltime = Float.MAX_VALUE;
float rtime = Float.MAX_VALUE;
float ttime = Float.MAX_VALUE;
float btime = Float.MAX_VALUE;

if (start.x - radius < L && end.x + radius > L) {
   ltime = ((L - radius) - start.x) / dx;
}
if (start.x + radius > R && end.x - radius < R) {
   rtime = (start.x - (R + radius)) / -dx;
}
if (start.y - radius < T && end.y + radius > T) {
   ttime = ((T - radius) - start.y) / dy;
}
if (start.y + radius > B && end.y - radius < B) {
   btime = (start.y - (B + radius)) / -dy;
}

Now we try to see if it's strictly a side intersection (and not corner). If the point of collision lies on the side then return the intersection:
if (ltime >= 0.0f && ltime <= 1.0f) {
   float ly = dy * ltime + start.y;
   if (ly >= T && ly <= B) {
      return new Intersection( dx * ltime + start.x, ly, ltime, -1, 0 );
   }
}
else if (rtime >= 0.0f && rtime <= 1.0f) {
   float ry = dy * rtime + start.y;
   if (ry >= T && ry <= B) {
      return new Intersection( dx * rtime + start.x, ry, rtime, 1, 0 );
   }
}

if (ttime >= 0.0f && ttime <= 1.0f) {
   float tx = dx * ttime + start.x;
   if (tx >= L && tx <= R) {
      return new Intersection( tx, dy * ttime + start.y, ttime, 0, -1 );
   }
}
else if (btime >= 0.0f && btime <= 1.0f) {
   float bx = dx * btime + start.x;
   if (bx >= L && bx <= R) {
      return new Intersection( bx, dy * btime + start.y, btime, 0, 1 );
   }
}

We've gotten this far so we know either there's no intersection, or it's collided with a corner. We need to determine the corner:
float cornerX = Float.MAX_VALUE;
float cornerY = Float.MAX_VALUE;

if (ltime != Float.MAX_VALUE) {
   cornerX = L;
} else if (rtime != Float.MAX_VALUE) {
   cornerX = R;
}

if (ttime != Float.MAX_VALUE) {
   cornerY = T;
} else if (btime != Float.MAX_VALUE) {
   cornerY = B;
}

// Account for the times where we don't pass over a side but we do hit it's corner
if (cornerX != Float.MAX_VALUE && cornerY == Float.MAX_VALUE) {
   cornerY = (dy > 0.0f ? B : T);
}

if (cornerY != Float.MAX_VALUE && cornerX == Float.MAX_VALUE) {
   cornerX = (dx > 0.0f ? R : L);
}

Now we have enough information to solve for the triangle. This uses the distance formula, finding the angle between two vectors, and the law of sines (twice):
double inverseRadius = 1.0 / radius;
double lineLength = Math.sqrt( dx * dx + dy * dy );
double cornerdx = cornerX - start.x;
double cornerdy = cornerY - start.y;
double cornerdist = Math.sqrt( cornerdx * cornerdx + cornerdy * cornerdy );
double innerAngle = Math.acos( (cornerdx * dx + cornerdy * dy) / (lineLength * cornerdist) );
double innerAngleSin = Math.sin( innerAngle );
double angle1Sin = innerAngleSin * cornerdist * inverseRadius;

// The angle is too large, there cannot be an intersection
if (Math.abs( angle1Sin ) > 1.0f) {
   return null;
}

double angle1 = Math.PI - Math.asin( angle1Sin );
double angle2 = Math.PI - innerAngle - angle1;
double intersectionDistance = radius * Math.sin( angle2 ) / innerAngleSin;

Now that we solved for all sides and angles, we can determine time and everything else:
// Solve for time
float time = (float)(intersectionDistance / lineLength);

// If time is outside the boundaries, return null. This algorithm can
// return a negative time which indicates the previous intersection.
if (time > 1.0f || time < 0.0f) {
   return null;
}

// Solve the intersection and normal
float ix = time * dx + start.x;
float iy = time * dy + start.y;
float nx = (float)((ix - cornerX) * inverseRadius);
float ny = (float)((iy - cornerY) * inverseRadius);

return new Intersection( ix, iy, time, nx, ny );

Woo! That was fun... this has plenty of room for improvements as far as efficiency goes. You could reorder the side intersection checking to escape as early as possible while making as few calculations as possible.
I was hoping there would be a way to do it without trigonometric functions, but I had to give in!
Here's an example of me calling it and using it to calculate the new position of the circle using the normal to reflect and the intersection time to calculate the magnitude of reflection:
Intersection inter = handleIntersection( bounds, start, end, radius );

if (inter != null)
{
   // Project Future Position
   float remainingTime = 1.0f - inter.time;
   float dx = end.x - start.x;
   float dy = end.y - start.y;
   float dot = dx * inter.nx + dy * inter.ny;
   float ndx = dx - 2 * dot * inter.nx;
   float ndy = dy - 2 * dot * inter.ny;
   float newx = inter.x + ndx * remainingTime;
   float newy = inter.y + ndy * remainingTime;
   // new circle position = {newx, newy}
 }

And I've posted the full code on pastebin with a completely interactive example where you can plot the starting and ending points and it shows you the time and resulting bounce off of the rectangle.

If you want to get it running right away you'll have to download code from my blog, otherwise stick it in your own Java2D application.
EDIT:
I've modified the code in pastebin to also include the collision point, and also made some speed improvements.
EDIT:
You can modify this for a rotating rectangle by using that rectangle's angle to un-rotate the rectangle with the circle start and end points. You'll perform the intersection check and then rotate the resulting points and normals.
EDIT:
I modified the code on pastebin to exit early if the bounding volume of the path of the circle does not intersect with the rectangle.
Comment: http://stackoverflow.com/questions/22569806/javascript-resolve-a-circle-to-rectangle-collision
Comment: Bravo. This is magnificent.
Comment: One of the best answers on S.O.
Answer: Finding the moment of contact isn't too hard:
You need the position of the circle and rectangle at the timestep before the collision (B) and the timestep after (A).  Calculate the distance from the center of the circle to the line of the rectangle it collides with at times A and B (ie, a common formula for a distance from a point to a line), and then the time of collision is:
tC = dt*(dB-R)/(dA+dB),

where tC is the time of collision, dt is the timestep, dB is the distance to line before the collision, dA is the distance after the collision, and R is the radius of the circle.
This assumes everything is locally linear, that is, that your timesteps are reasonably small, and so that the velocity, etc, don't change much in the timestep where you calculate the collision.  This is, after all, the point of timesteps: in that with a small enough timestep, non-linear problems are locally linear.  In the equation above I take advantage of that: dB-R is the distance from the circle to the line, and dA+dB is the total distance moved, so this question just equates the distance ratio to the time ratio assuming everything is approximately linear within the timestep.  (Of course, at the moment of collision the linear approximation isn't its best, but to find the moment of collision, the question is whether it's linear within a timestep up to to moment of collision.)
Answer: It's a non-linear problem, right?
You take a time step and move the ball by its displacement calculated using velocity at the start of the step.  If you find overlap, reduce the step size and recalculate til convergence.
Are you assuming that the balls and rectangles are both rigid, no deformation?  Frictionless contact?  How will you handle the motion of the ball after contact is made?  Are you transforming to a coordinate system of the contact (normal + tangential), calculating, then transforming back?
It's not a trivial problem.
Maybe you should look into a physics engine, like Box2D, rather than coding it yourself.
Comment: If I understood correctly, your solution is only an approximation and it is very slow... I would to find the variable t with an equation not with a loop.
Comment: No, you fail to understand the fact that this is a non-linear solution.  There is no general equation solution.
Comment: If I find the law for a and b functions I can find the variable t. Look the question in the 'similar problem' link.
Comment: Nope, I understand the physics well enough.


flutter:get the last document from firebase

Question: i have many document inside a collection of firebase. But i want to retrieve only the last document which is present at the bottom. You can see the image . i want to retrieve the highlighted document
Answer: You can use last in following way to get last document.
<code>Firestore.instance.collection("data").snapshots().last
</code>
This will give you only last element.
Comment: I want last 7 uploaded documents how can I perform that


Best way to rotate Magento logs?

Question: We have a lot of sites on Magento and the logs are getting gigantic, so I'm wondering if the best way is to use a cron script to rotate them or logrotate. I want to avoid making file copies as it junks up the folder and makes it hard to navigate, so ideally I would want to have only log lines going back two weeks in one file for each domain. Is this possible or is it better to rotate by file?
Answer: Look at the man pages for logrotate, as well as some of the active uses in the system.  It has  a lot of flexibility including rotation based on size, number of cycles to keep, etc.  It will do what you want.
Check it out.

Best way to rotate Magento logs?


sbt native packager: How to add a logrotate conf file to /etc/logrotate.d/myconf

Question: I have :
      mappings in Universal ++= Seq(
        file("my-application/src/universal/etc/logrotate.d/my-application") -> "/etc/logrotate.d/my-application"
)
But this puts it into /usr/share/my-application/etc/logroteate.d/my-application
Answer: Putting mappings in Universal will put them inside the installation directory.
You have to use the linuxPackageMappings.
Start by reading the docs on this. Then take a look at some of the tests, which also act as examples.
Unfortunatly the packaging API is not refactored yet thus a bit spread out.
The LinuxPlugin trait contains some parts of the mappings methods, too.
<code>linuxPackageMappings += packageMapping(files: (File, String)*)
</code>


Can you connect to a FVS336Gv2 without using VPN Lite Software?

Question: My uncle purchased a NETGEAR ProSafe FVS336Gv2. Now we want to use the VPN functionality of it. I didn't see any mention on the box or the manual that we'd have to pay for a license to use their VPN client. Anyway, I don't want to pay for the license. VPN Lite Software is just the VPN client-side connection stack for Windows.
Is there anyway to connect to this VPN from any version of Windows that doesn't require the license? Is the license for the client, or the server-side connection?
Answer: Yes. This device supports regular, no-frills PPTP connections if you just want to use the built-in Windows VPN functionality.
I stopped buying the FVS range after Netgear were consistently poor with providing SSL VPN drivers for newer operating systems.
Comment: Is their branded client just a skin on top of OpenVPN? I've found that to be the case for several of these type products. In these cases, I've had some success just using the vanilla OpenVPN client.


Como salvar conteúdo dos data sets em arquivos de forma dinâmica?

Question: Tenho um vetor com o nome dos meus datasets e quero armazenar o conteúdo dos mesmos em arquivos .csv individuais de forma dinâmica.
Com o código abaixo, os arquivos são criados, mas ao invés do conteúdo dos data sets, é gravado o nome do data set. já usei o assign() e dá na mesma.
dsets <- c('wairlines', 'wairports', 'wflights', 'wplanes', 'wweather')

for(ix in 1:length(dsets)) {
  write.csv(dsets[ix], file = paste0('./input_orig/',dsets[ix],'.csv'))
}

O código acima deveria ser equivalente a:
write.csv(wairlines,file='./input_orig/wairlines.csv')
write.csv(wairports,file='./input_orig/wairports.csv')
write.csv(wflights,file='./input_orig/wflights.csv')
write.csv(wplanes,file='./input_orig/wplanes.csv')
write.csv(wweather,file='./input_orig/wweather.csv')

Desde já meu agradecimento
Comment: Obrigado pelo copydesk... aprendendo...
Answer: dsets é um vetor de strings, não é uma lista de data.frames.
Para aceder aos data.frames tem que ir buscá-los com get.
Além disso, não é necessário compor os nomes dos ficheiros um a um, o paste é uma função vetorizada.
dsets <- c('wairlines', 'wairports', 'wflights', 'wplanes', 'wweather')
fl <- paste0('./input_orig/', dsets, '.csv')
env <- .GlobalEnv
for(ix in seq_along(dsets)) {
  write.csv(get(dsets[ix], envir = env), file = fl[ix])
}

Ou, sem o vetor de nomes de ficheiros fl:
env <- .GlobalEnv
lapply(dsets, function(x){
  fl <- paste0('./input_orig/', x, '.csv')
  write.csv(get(x, envir = env), file = fl)
})

Answer: Galera, encontrei a solução.... o código correto deveria ser....
dsets <- c('wairlines', 'wairports', 'wflights', 'wplanes', 'wweather')
for(ix in 1:length(dsets)) {
write.csv(get(dsets[ix]), file = paste0('./input_orig/',dsets[ix],'.csv'))
}
Esse get() faz toda a diferença e abre uma super-dimensão de automatização de funções..
Comment: Rui... Obrigado... só vi agora... o crédito será dado...


JSON column expand databricks sql

Question: I have the JSON column which and would like to expand it using databricks sql (no python).
column name is cdi_sentemailstatisticsdata, and each json value has its corresponding id too and sample data:
{"list":[{"Count":91,"EmailClient":"Other","Platform":"Desktop"},{"Count":20,"EmailClient":"Hotmail","Platform":"Desktop"},{"Count":5,"EmailClient":"Chrome Mobile","Platform":"Desktop"},{"Count":2,"EmailClient":"Opera","Platform":"Desktop"},{"Count":35,"EmailClient":"Chrome","Platform":"Desktop"},{"Count":21,"EmailClient":"Outlook","Platform":"Desktop"},{"Count":26,"EmailClient":"Gmail","Platform":"Desktop"},{"Count":1,"EmailClient":"Safari","Platform":"Desktop"},{"Count":1,"EmailClient":"Icloud","Platform":"Desktop"},{"Count":1,"EmailClient":"Thunderbird","Platform":"Desktop"},{"Count":1,"EmailClient":"Outlook.com","Platform":"Desktop"},{"Count":16,"EmailClient":"Chrome Mobile","Platform":"Mobile"},{"Count":22,"EmailClient":"Mobile Safari","Platform":"Mobile"},{"Count":8,"EmailClient":"Hotmail","Platform":"Mobile"},{"Count":6,"EmailClient":"Yahoo","Platform":"Mobile"},{"Count":4,"EmailClient":"Gmail","Platform":"Mobile"},{"Count":1,"EmailClient":"Chrome","Platform":"Mobile"}],"lastUpdate":"2020-11-11T13:31:14.3587369+00:00"}

Desired output should look like this:

Tried something like this but did not work:
SELECT
  json_element.Count AS Count,
  json_element.EmailClient AS EmailClient,
  json_element.Platform AS Platform
FROM
  cdi_sentemailstatisticsdata
LATERAL VIEW
  explode(from_json(json_column.list, 'array<struct<Count:int,EmailClient:string,Platform:string>>')) AS json_element;

Answer: You can use below SQL query.
SELECT
    json_element.Count  AS  Count,
    json_element.EmailClient AS EmailClient,
     json_element.Platform AS Platform
FROM
(
SELECT cdi_sentemailstatisticsdata as json_column from your_table_name
) t
LATERAL  VIEW
explode(from_json(json_column, 'struct<list:array<struct<Count:int,EmailClient:string,Platform:string>>,lastUpdate:string>').list) AS json_element;

Output:

JSON column expand databricks sql


Frobenius mophism, Exercise 7.3 R of Ravi Vakil's book on algebraic geometry

Question: I am a geometry person and got stuck in Exercise 7.3.R which is about Frobenius morphism.
Suppose $p$ is a prime and $r \in \mathbb{Z}^+$. Let $q=p^r$ and $k=\mathbb{F}_q$. Define $\phi :k[x_1,\dots,x_n] \rightarrow k[x_1,\dots,x_n]$ by $\phi(x_i)=x_i^p$ for each $i$, and let $F:\mathbb{A}_k^n \rightarrow \mathbb{A}_k^n$ be the map of schemes corresponding to $\phi$.
(a) Show that $F^r$ is the identity on the level of sets, but is not the identity morphism.
(b) Show that $F$ is a bijection, but is not an isomophism of schemes.
(c) If $K=\bar{F}_p$, show that the morphism $F:\mathbb{A}_K^n \rightarrow \mathbb{A}_K^n$ of $K$-schemes corresponding to $x_i \rightarrow x_i^p$ is a bijection, but no power of $F$ is the identity on the level of sets!
For (a) and (b), I only know the solution when $n=1$ since $k[x]$ is a PID which makes it very easy. But I got stuck when $n>1$.
Comment: My guess is that your proof for (a) and (b) doesn't really need the PID bit. It all should boil down to the fact that with coefficients in $\mathbf{F}_q$ one has $f(x_1^q, \dots, x_n^q) = f(x_1, \dots, x_n)^q$. For (c), I think it's important that $\overline{\mathbf{F}}_p$ is the union of the $\mathbf{F}_q$.
Comment: $k[x_1, \dots, x_n]$ is a UFD. Does that help?
Comment: Thank you @Hoot, I could answer (a) and (b) from your hints.
Comment: I am really confused about these exercise by Vakil, since he does not state what happens with constants. Are they also raised to powers or are they fixed? This gives rise to different morphisms, especially if $k$ is not perfect (of course its perfect in our case).
Comment: I believe the constants are fixed. I don't see why he would word it the way he does otherwise. And in (c) he explicitly says "of $K$-schemes".
Answer: For $c)$, notice that surjections are stable under base change, i.e. $F: \mathbb A_K^n \to \mathbb A_K^n$ is a surjection as the base change of of $F: \mathbb A_k^n \to \mathbb A_k^n$. For injectivity, let $F(\mathfrak p) = F(\mathfrak q)$ for two primes in $K[x_1, \dotsc, x_n]$. In general we have $\phi(\phi^{-1}(A))=A \cap \operatorname{image}(\phi)$ for any subset $A$, i.e. we deduce
$$\mathfrak p \cap K[x_1^p, \dotsc, x_n^p] = \mathfrak q \cap K[x_1^p, \dotsc, x_n^p].$$
From this, you can easily deduce $\mathfrak p = \mathfrak q$: Let $f \in \mathfrak p$. Then $f^p \in \mathfrak p \cap K[x_1^p, \dotsc, x_n^p] = \mathfrak q \cap K[x_1^p, \dotsc, x_n^p] \subset \mathfrak q$, hence $f \in \mathfrak q$, since it is a prime ideal.
Thus we have shown hat $F$ is a bijection on the level of sets. But no power is the identity map:
Let $r > 0$ and $a \in K \setminus \mathbb F_{p^r}$. $(\phi^r)^{-1}((x_1-a))=(x_1-a^{p^r})$, i.e. the prime ideal $(x_1-a)$ is mapped by $F^r$ to $(x_1-a^{p^r})$, which is not the same, since $a \neq a^{p^r}$. Hence $F^r$ is not the identity map.
Answer: Thanks to the hints by Hoot, I try to answer (a) and (b) by the following,
We have $\phi^r(f(x_i))=f(x_i^{q})=f(x_i)^q$, so it is obvious that for every prime ideal $P \subset k[x_1,\cdots,x_n]$, $\phi^r(P) \subset P$, so $P \subset (\phi^r)^{-1}(P)$. Now we show that $(\phi^r)^{-1}(P) \subset P$, which will show that $F^r$ is identity.
For $f\in (\phi^r)^{-1}(P)$, which means $\phi^r(f(x_i))=f(x_i^{q})=f(x_i)^q \in P$, so $f \in P$ since $P$ is a prime ideal.
$F^r$ is not the identity morphism since $\phi^r$ is not identity homomophism.
(b) follows from (a).