How to execute a table of queries in order via Snowpark?

Question: I have a table of DDL statements, the table has four columns but the important ones are the columns 'DDL' and 'Level'. I have a Snowpark python code in VSCode that will execute the DDL statements but I want the code to execute the statements in order of Level i.e. Level 5 statements will execute first, Level 4 next, all the way down to Level 0 statements executing last. E.g.

DDL
Level

create or replace view db.schema.view
0

create or replace table db.schema2.table(col varchar, col2 int)
1

create or replace view db.schema3.view_phones
0

create or replace table db.schema4.table_jobs(col varchar, col2 varchar)
2

create or replace table db.schema.table_phones(col varchar)
1

create or replace table db.schema.table_words(col varchar, col2 int)
2

create or replace table db.schema.table_songs(col varchar, col2 int)
3

create or replace table db.schema.table_drinks(col varchar, col2 int)
4

create or replace table db.schema.table_dbs(col varchar, col2 int)
5

create or replace table db.schema.tables(col varchar, col2 int)
5

My Snowpark python code:
<code>tableName = 'DATABASE.SCHEMA.DDL_TABLE'
query_table = new_session.table(tableName)
df = query_table.to_pandas()

for int in df.index:
    command = df["DDL"][int]
    async_job = new_session.sql(command).collect_nowait()
    print(async_job)
print('Done')
</code>
It's running as an async job which means each statement of the same level should execute together. The reason for this is that Level 0 objects are dependent on some of the other objects in Level 5, such as a Level 0 view needing a level 5-1 table to exist before it itself can be created. Not sure how to account for statements that encounter an error in creating which would mess up the views in lower levels being created so if anyone also has any idea on that end then it would also be appreciated but the main issue is adding some sort of order by level to the code so they are executed by level. Thanks in advance for anyone's help!
Comment: What type of indication are you expecting for a level of jobs to indicate to this code that all of the async jobs are complete before moving to the next level of jobs?
Comment: Also, depending on how many DDL statements you have, it'd probably be easier to just sort your df by level and then iterate through it in a synchronous fashion.  These statements will execute extremely fast, anyway.
Comment: @MikeWalton I'm not sure what indication I'm expecting to be honest as I haven't yet figured that out, but if they execute really fast as you say maybe I could have them wait 5-10 seconds between each level to ensure all levels are created before moving to the next? I just need to figure out how to get the process to check each object has created and to rerun the ddl if they error but I'm not there yet. Also yes, I'll try sorting it by level instead - is it just a case of replacing "DDL" by "level"? Or do I need an extra line? Sorry, I'm new to Snowpark/Python - thanks for the help!
Answer: As Mike indicated probably sync execution will make more sense. The following script orders by level.
<code># Create a SparkSession
from snowflake.snowpark import Session, functions as F, types as T
import os,json;configs = json.load(open(os.path.expanduser("~/credentials.json")))
session = Session.builder.configs(configs).getOrCreate()

# Define the schema for the DataFrame
schema = T.StructType([
    T.StructField("DDL", T.StringType(), True),
    T.StructField("Level", T.IntegerType(), True)
])

# Create the data as a list of tuples
data = [
    ("create or replace view db.schema.view", 0),
    ("create or replace table db.schema2.table(col varchar, col2 int)", 1),
    ("create or replace view db.schema3.view_phones", 0),
    ("create or replace table db.schema4.table_jobs(col varchar, col2 varchar)", 2),
    ("create or replace table db.schema.table_phones(col varchar)", 1),
    ("create or replace table db.schema.table_words(col varchar, col2 int)", 2),
    ("create or replace table db.schema.table_songs(col varchar, col2 int)", 3),
    ("create or replace table db.schema.table_drinks(col varchar, col2 int)", 4),
    ("create or replace table db.schema.table_dbs(col varchar, col2 int)", 5),
    ("create or replace table db.schema.tables(col varchar, col2 int)", 5)
]

# Create the DataFrame
df = session.createDataFrame(data, schema=schema).group_by("LEVEL").agg(F.array_agg("DDL").alias("stmts")).sort(F.col("LEVEL").desc())
df.show()
print("Processing statements...")
for (level, stmts) in df.collect():
    print(f">>>> Processing statements at level {level}")
    for stmt in json.loads(stmts):
        try:
            session.sql(stmt)
        except Exception as e:
            print(f"Error at level {level}")
</code>
Comment: Something like:
def wait_for_all_jobs_to_complete(async_job_list):
    while any(not job.is_done() for job in async_job_list):
        time.sleep(2)  # Sleep for 2 seconds (you can adjust this as needed)
Comment: Thanks @orellabac, the thing is the table could have like over 100 rows and having them execute asynchronously would be more efficient for the amount of queries there potentially could be. The table I'm working with now to test has over 180 rows. Could you also explain why sync would make more sense than async? Thanks!
Comment: If the snippets are simple, the might be quick and you will require less effort for trouble shooting. You can for each level do asyncjobs and capture the asyncjobs and then continue


Want to learn about Linux servers and how to operate them?

Question: I will soon take a dedicated server from a hosting company but I do not know how to operate it. They told me that there will be cPanel and other thing that make it easier. However, I do not know if it is different from shared hosting cPanel?
What I want is some tutorials on how to operate a dedicated server and manage it. Can you help please?
Comment: http://rute.2038bug.com/index.html.gz
Answer: There are some good books I can recommend them to you I have read all of these
1) Red Hat Linux Networking and System administration
2) Red Hat Linux Security and Optimization
3) Official Ubuntu Server book
4) Professional Linux system administration
5) Orielly Apache Cookbook
As some one mentioned above Rute Users tutorial so once you have a basic understanding then I will recommend you reading these books.Red Hat ones are the best I have read till date.Though a bit old but they rock.
The last one for Apache you will need after you have some experience.Apache is some thing which if not known clearly can be a nightmare.Though it is very simple to operate and understand but having a better understanding of it will not harm.
Answer: Taking the administration of a new (GNU/Linux in this case) is not a task to be taken lightly.
You should first try to install linux on a testing platform and follow some guide. As my teacher once said to me, "Linux is for the warned adult". You can do, and probably will (it happened to me a lot of times), screw up a system. Better that you learn this lesson on your testing machine.
If you had work with anything UNIX (BSD, System V, Mac OS, Solaris) you start with almost everything you need because GNU/Linux is a UNIX-ish system with small differences (the base is there).
If you start with a Microsoft background then you will need more time to be sure to know what you're doing. I suggest you to take courses, read books or do tutorials. I don't have any to refer to you because there are plenty of them. You will find what you need.
Comment: In back-up of @Gopoi's post - if you're coming from M$ background you will most certainly screw up at least a dozen times before you start understanding how things really work. When you compile a kernel by yourself - you shall become a "master" :D
Comment: Oh and I know it's a bit late, but thanks for the corrections!!


Question about integral closures and localizations

Question: Suppose $A$ is an integral domain with integral closure $\overline{A}$ (inside its fraction field), $\mathfrak{q}$ is a prime ideal of $A$, and $\mathfrak{P}_1,\ldots,\mathfrak{P}_k$ are the prime ideals of $\overline{A}$ lying over $\mathfrak{q}$. Show that $\overline{A_\mathfrak{q}} = \bigcap\overline{A}_\mathfrak{P_i}$ (note that the LHS is the integral closure of a localization, whereas the RHS is the intersection of localizations of integral closures of $A$).
If it would help, I suppose we could assume that $A$ has dimension 1, so that $\overline{A}$ is Dedekind, though I don't think that assumption is required.
(Geometrically, we're comparing the integral closure of a local ring at a singular point Q of some variety with the intersection of local rings at points in the normalization mapping to Q).
Thanks.
Answer: First notice that without extra hypothesis, the integral closure needs not be finite over $A$, and there might be infinitely many prime ideals lying over a given one in $A$. Nevertheless, the equality holds.
It is easy to see that the LHS is contained in the RHS because the latter is integrally closed and contained in the field of fractions of $A_q$. Let $f$ be an element of the RHS (possibly infinite intersection). Denote by $B=\overline{A}$. Consider the denominator ideal
$$ I=\{ b\in B \mid bf\in B\}$$
of $f$. I claim that $I\cap A$ is not contained in $q$. Admitting this, let $s\in I\cap A\setminus q$, then $sf\in B$ and $f$ is integral over $A_q$.
Now we prove the claim. Suppose that $I\cap A\subseteq q$. Then, geometrically, $q\in V(I\cap A)\subseteq \mathrm{Spec}(A)$. As $A/(I\cap A)\to B/I$ is injective and integral, $\mathrm{Spec}(B/I)\to \mathrm{Spec}(A/(I\cap A))$ is surjective. Identify $V(I)$ with $\mathrm{Spec}(B/I)$, this implies that there exists $p\in V(I)$ such that $p\cap A=q$. So $p$ is a prime ideal of $B$ lying over $q$ and containing $I$. This contradicts the hypothesis $f\in B_p$.
Comment: $\def\frq{\mathfrak{q}}
\def\frp{\mathfrak{p}}$This result is a corollary of the following result (Bourbaki, *Commutative Algebra*, Ch. V, § 2, no. 1, Proposition 2): Let $h:A\to B$ be an integral ring homomorphism, $\frq$ a prime ideal of $A$, $(\frp_i)_{i\in I}$ the family of all prime ideals of $B$ lying above $\frq$ and $S=\bigcap_{i\in I}B-\frp_i$; then $B_\frq=S^{-1}B$. Plus the following observation: if $B$ is some integral domain and for $i\in I$, $S_i\subset B$ is a multiplicatively closed subset of $B$, then $(\bigcap S_i)^{-1}B=\bigcap S_i^{-1}B$ as subrings of $Q(B)$.
Comment: To prove $(\bigcap S_i)^{-1}B=\bigcap S_i^{-1}B$, we note that $\subset$ is easy. Conversely, suppose $b/s\in Q(B)$ is not in $(\bigcap S_i)^{-1}B$. Then $s\not\in\bigcap S_i$, whence $s\not\in S_i$, for some $i$. Thus, $b/s\not\in S_i^{-1}B$.
Answer: Consider $\dim A=1$. One can assume that $A$ is a local Noetherian domain with maximal ideal $m$ and have to prove that $\overline{A}=\bigcap_{i=1}^n\overline{A}_{P_i}$, where $P_1,\dots,P_n$ are all the prime ideals of $\overline{A}$ lying over $m$. (There are only finitely many primes in $\overline{A}$ lying over $m$ because $\overline{A}$ is Dedekind!) Now one can use the well known fact that an integral domain (in our case $\overline{A}$) is the intersection of all its localizations at maximal ideals. Note that a prime ideal $P$ of $\overline{A}$ is lying over $m$ or over $(0)$. The prime ideals $P$ lying over $(0)$ give "large" localizations, i.e. $\overline{A}_P=K$ when $P\cap A=(0)$, where $K$ is the field of fractions of $A$. In particular these primes can be removed from the intersection finally remaining only the primes $P$ lying over $m$.


How to get Signatures for Forums using SQL query?

Question: In a D7 site, I'd like to get all of the user signatures using raw mysql query .
I've found a signature_forum_post table but could not figure out how to make a query that returns both user.id and signature text, so appreciate your help.
Answer: Please try the following.
if ($account->id() && isset($form_state['values']['user_signature'])) {
    if (!$account->get('user_signature')->isEmpty()) {
      db_merge('user_signature')
        ->key(array('uid' => $account->id()))
        ->fields(array(
          'signature__value' => $account->get('user_signature')->value,
          'signature__format' => $account->get('user_signature')->format,
        ))
        ->execute();
    }
    else {
      db_delete('user_signature')
        ->condition('uid', $account->id())
        ->execute();
    }
  }
Comment: Please note that I wanted sql query not php.


Wordpress: How to be redirected to the page when inserting it's page ID into numeric form input with click button SEND?

Question: I would like to know if there's exists some simple code to get to the page i know its ID , I would like to create small input (no matter where in templates)from where the people can easily get to the page if they know it's page ID (4numeric ID is better to remember - permalink name you can mistake . I have the girls portfolio in wordpress - portfolio=pages x jobs in clubs offers=posts , I would like the girls portfolios to be easily findable by ID(s) , if possible the same for the posts=jobs in clubs
The best solution little 4-5numeric input and send=go button in sidebar.php - index.php etc
Answer: i take something like this in here source. Maybe it can help, though i don't know if its working
`function baka_show_form_redirect() {
      $form_search ='<form action="" method="post" name="redirect_to_post_id" class="description" style="color:#fff;font-size:10px;text-align:left;position:fixed;top:40px;">

Theme Feature

Redirect to ID (numerical) :
          <input name="post_id" type="text" maxlength="4" class="description"
              style="width:30px;display:inline;border:none;color:#000" />

        <input name="_redirect_to" type="hidden" value="' . get_permalink() . '" />
      </form>';
  echo $form_search;

}
function baka_validasi_post_id() {
    if( $_POST[ 'post_id' ] && $_POST[ 'post_id' ] != " ) {
          $post_id = $_POST[ 'post_id' ];
          if (absint($post_id)) { //must be integer and not negative
          $url = get_permalink($post_id);

          if ($url) {
              wp_redirect($url); echo " ";
          } else {
              $_redirect_to = $_POST[ '_redirect_to' ];
              wp_die("ID can not be found … <a href ='" . $_redirect_to . "'>Back</a>");
          }
    }

}
}
add_action('wp_head', 'baka_show_form_redirect');
add_action('init', 'baka_validasi_post_id');
?>`
Comment: This is exactly what I was thinking !!! , thanks a lot for this code, but unfortunately it doesn't work in Wordpress 2.9.2 -:(  , Where do I need to insert this code ? directly to the templates or some part to functions.php ? Theres no explanation where to insert it. But I'm happy at least with your code I can explain better this problem. Other thing this code works only with posts , not with pages
Comment: I have also tried to put it in header.php between head and it showes me the error.
Comment: you should put it in functions.php
Comment: after try to using it, i know it's able to seek for post and pages. btw, what kind of error ? if i know i will answer but if it too hard maybe you should consult with the author
Comment: thanks for your respond justjoe , i didn't notice your answers , i'm new here so I didn't see that somebody is responding and notify functions works here with big delay,btw. code is working now , author helped me , I posted the code down on this page. Thanks again for your help
Answer: Resolved !!! works perfect thanks to the author of this code who helped me to make it run from the website link above , so Thanks a lot to both men !!!Thanks to real author of the code and the editor who answered the first question .[link text][1]
<?php
}

function baka_show_form_redirect() {
      $form_search ='<form action="" method="post" name="redirect_to_post_id">

Theme Feature

Redirect to ID (numerical) :
          <input name="post_id" type="text" maxlength="4" class="description"
              style="width:30px;display:inline;border:none;color:#000" />

        <input name="_redirect_to" type="hidden" value="' . get_permalink() . '" />
      </form>';

      echo $form_search;
}

function baka_validasi_post_id() {
    if( $_POST[ 'post_id' ] && $_POST[ 'post_id' ] != '' ) {
          $post_id = $_POST[ 'post_id' ];
          if (absint($post_id)) { //must be integer and not negative

              $url = get_permalink($post_id);

              if ($url) {
                  wp_redirect($url); echo " ";
              } else {
                  $_redirect_to = $_POST[ '_redirect_to' ];
                  wp_die("ID can not be found … Back");
              }
        }
  }
}

add_action('wp_head', 'baka_show_form_redirect');
add_action('init', 'baka_validasi_post_id');
?>

[1]: http://www.bakawan.com/log/howto-wordpress-redirect-based-on-post-id/comment-page-1/#comment-6654"Code author's site"
Answer: I don't know if this is what you are asking, but you can get permalink using id i.e. if you have a pages' id the you can generate permalink like so, <?php echo get_permalink($page_or_post_id); ?> . So whenever you get $id of a page or post you can redirect or show link to that page/post
Comment: Thanks a lot for your comment but i need the option from the answer above , when anybody can  insert the page ID in a little 4numeric input box so the people after submit can be redirected to the page(girl portfolio page) easily (better to remember 4 number than the exact name(permalink) of the girl.)


Theorem 3.17 in Rudin's Analysis

Question: This question refers to Rudin's "Principles of Mathematical Analysis", Theorem 3.17, p.56. In particular let $\left\{s_n\right\}$ be a real sequence and let $E$ be the set of all sub-sequential limits with possibly plus and minus infinity included. Denote $s^*=\sup E$. Suppose $x$ is a real number such that $x>s^*$ and that $s_n \ge x$ for infinitely many values of $n$.
I want to arrive to a contradiction, but i am having some difficulty doing this very rigorously. More precisely, i can see that we obtain subsequences, which after some index become larger than $x$, but why does that mean that we have a sub-sequential limit greater than $x$ (thus contradicting $s^*$)?
Thanks.
Answer: It relies on the following fact (prove it as an exercise) :

$I \subset \mathbb{N}$ is infinite if and only if there exists an
  increasing function $\varphi : \mathbb{N} \to I$ which is bijective.

If you put $I$ the set of all integers $n$ such that $s_n \ge x$, if $I$ was infinite, there would exist, by the previous fact, a subsequence $(s_{\varphi(n)})$ whose all terms are $ \ge x$.
Now, extract a converging sub-subsequence from $(s_{\varphi(n)})$. What can be said about its limit ?
(recall that every sequence of real numbers admits a converging subsequence, possibly in the extended real line)
Comment: He proved it in theorem 3.6 in the form "every sequence in a compact metric space contains a convergent subsequence" or "every bounded sequence of $\mathbb{R}$ converges". I can take it from there. Thanks a lot!
Comment: Thanks Ahriman, it was the very last statement in parenthesis that i was missing :-)
Comment: I think Rudin proved it before in his text, so you can use it. Right ?
Comment: Would you know why this sequence was bounded?
Answer: How about this.
Suppose there are infinite $s_{n}$'s in the sequence $\{s_{n}\}$ such that $s_{n} \geq x$.
Let $\{s_{n_{k}}\}$ be the subsequence of $\{s_{n}\}$ consisting of the $s_{n}$'s that are greater or equal to $x$. Then there are two possibilities:
(i). If $\{s_{n_{k}}\}$ is bounded above, then there exists a real number $y$ such that $y \in E$ and $y \geq x$.(By theorem 3.6-[b] and the fact that we cannot have a subsequence of $\{s_{n_{k}}\}$ that converges to a number less than $x$.) Notice that we have $x > s^{*}$, which implies $y \geq x > s^{*}$, then $s^{*}$ is no longer an upper bound.(A contradiction).
(ii). If $\{s_{n_{k}}\}$ is not bounded above, then we must have $+\infty \in E$.(See the lemma below). Since $+\infty \geq x$ by definition, we get $+\infty \geq x > s^{*}$, which implies, again, that $s^{*}$ is not an upper bound. A contradiction.
Therefore,  there are only finite $s_{n}$'s in the sequence $\{s_{n}\}$ such that $s_{n} \geq x$. That is, there exists an integer $N$ such that $n \geq N$ implies $s_{n} < x$.
You may find this result useful:
Lemma: If a sequence $\{s_{n}\}$ is not bounded above, then there is a subsequence of $\{s_{n}\}$ that converges to $+\infty$.
We can construct a subsequence $\{s_{n_{k}}\}$ that converges to $+\infty$ like this: Let $s_{n_{k}} > k$ for all $k \in \mathbb{N}$ with $n_{1} < n_{2}<\dots$. (Can we do this? If there was no $n_{1}$ such that $s_{n_{1}} > 1$, then $s_{n} \leq 1$ for all $n$, a contradition. After we have chosen $s_{n_{1}}, s_{n_{2}}, \dots$, choose $s_{n_{k}}$ such that $n_{k} > n_{k-1}> \dots > n_{1}$ and $s_{n_{k}}>k$. If there was no such $s_{n_{k}}$ available, then $s_{n_{k}} \leq k$ for all $n > n_{k-1}$. Therefore, $\{s_{n}\}$ is bounded by $\max \{s_{1}, \dots, s_{n_{k-1}}, k\}$, a contradiction. Therefore, we can indeed construct such an sequence $\{s_{n_{k}}\}$ as desired.) Now, notice that for all $M \in \mathbb{R}$, there exists an integer $N$ such that $n_{k} \geq N$ implies $s_{n_{k}} \geq M$. Hence $s_{n_{k}} \to +\infty$, as desired.

Theorem 3.17 in Rudin's Analysis


Image Path Ionic 2

Question: Sou novo no Ionic, venho de desenvolvimento nativo com android e estou um pouco perdido em relação ao apontamento das imagens no IONIC.
Estou criando na page inicial, que chamo de HOME, um menu com quatro opções onde o background de cada opção serão imagens.
Desta forma, coloco o caminho relativo (onde as imagens estão dentro da pasta /src/assets) e rodo o comando $ ionic serve, e funciona normalmente no browser. Contudo, quando faço $ ionic run android, as imagens não aparecem no meu smartphone ou emulador.
Imagino que isso deve ser uma tremenda besteira, mas pra quem ta começando é trabalhoso. Já fazem umas 24 horas que pesquiso, leio conteúdo e não consigo resolver meu problema.
Qual o local correto para colocar as imagens? Como devo referenciar o caminho?
Desde já agradeço!
Answer: Encontrei!!!
link -> https://stackoverflow.com/questions/39952214/correct-way-to-use-image-assets-in-ionic-2
Traduzindo:
Se colocar as imagens dentro de www/img, funcionarão apenas localmente através do $ ionic serve. Pra resolver o problema usando esta forma, é necessário usar o gulp para copiar as imagens para a pasta que você quer antes do build.
Contudo, a forma anterior está obsoleta. O recomendado é usar as imagens dentro de assets/images e referencia-las com src="assets/images/sua-imagem.extensão" Desta forma funcionará tanto localmente quanto em emuladores e devices.

Image Path Ionic 2


A formula that yields a particular graph shape

Question: I would like a formula for a function whose graph has the following properties:

$f(0) = 0$.

$\lim\limits_{x\to\infty}f(x) = y$.

The shape of the function is approximately the following:

It should have an exponential or a logarithm in the formula.

Any function like this?
Comment: Well, yes: the function whose value at $x$ is the height of the graph you have is such a function.
Comment: I think what Arturo is hinting at is that in mathematical terminology, what you want is *formula*, not a *function*. @Arturo, there are clearer ways to make that point, don't you think?
Comment: @ArturoMagidin Could you give any function expression? Thanks!
Comment: @Rahul: Actually, no, I did not mean that, because I was not aware that this is what the OP is trying to do. Hard enough to figure out what he means by what he writes.
Comment: @RahulNarain Yes, I need a formula.
Comment: @Arturo: Yes, I noticed that just after I commented. Thanks.
Comment: There are $\vert \mathbb{R}^\mathbb{R} \vert$ functions from $\mathbb{R}$ to itself.  How many of those do you think have cutesy formulas?
Answer: The graph of $y=5-5e^{-x}$ has the desired characteristics. More generally, if you want $\lim\limits_{x\to\infty}f(x)=a>0$, the function $f(x)=a-ae^{-x}$ works.
Answer: $$y = 5 - 5 \exp(-\alpha x)$$ where $\alpha >0$ will do the job. You can control the rate of growth by playing around with $\alpha$.
Answer: Also your graph doesn't have anything shown for x<0, so presumably its equal to zero there?
i.e. Use a piecewise defined function:
f(x) = a-a*exp(-x) : for positive x and f(x)=0 for non-positive x.


Exibir postagem após as 6 últimas

Question: Olá, estou com uma dúvida na condição do construtor da classe WP_query() do wordpress
No topo do blog eu tenho um loop mostrando em um slider jquery as ultimas 6 postagens do blog
  $query1 = new WP_Query( "showposts=6" );
  while ( $query1->have_posts()) : $query1->the_post();

até aí correto, mas no corpo do blog eu gostaria de exibir apenas as postagens que vieram antes, ou seja.. as 6 últimas no slider e as demais no blog listando os posts
O problemas é que se eu colocar a ordem ascendente ele pega as postagens antigas em primeiro lugar no corpo do blog
$query2 = new WP_Query( "order=ASC&showposts=+6" );
while ( $query2->have_posts()) : $query1->the_post();

Os posts com os ID's ficam da seguinte manteira no slider:
ID 10 - ID 9 - ID 8 - ID 7 - ID 6 - ID 5 - ID 4
E no blog:
ID: 1
ID: 2
ID: 3
Entenda cada ID como uma postagem
Answer: Se você não precisa se preocupar com paginação, offset resolve:
$query2 = new WP_Query( "showposts=6&offset=6" );
while ( $query2->have_posts()) : $query1->the_post();

offset=6 faz a query pular os primeiros 6 posts e pegar os próximos seis.
--
Se precisa da paginação na parte inferior, você pode pegar os IDs da primeira query e excluir da seguinda:
$query1 = new WP_Query( "showposts=6" );
$query1_IDs = wp_list_pluck( $query1->posts, 'ID' );
$query2 = new WP_Query( array( 'showposts' => 6, 'post__not_in' => $query1_IDs ) );

Answer: Você pode fazer um contador e só printar a partir do 6
while(suas condições){
for(i=0;i>=6;i++){ seu echo }
}

vê se isso te ajuda ;)

Exibir postagem após as 6 últimas


Load same webView instance on all tabbars in UITabBarController

Question: I wanted to know if it is possible to load same WKWebView instance in all the tabbars in UITabBarViewController. If it is yes then please share some thoughts/ideas.
I wanted to achieve this thing:-
Tabbar1:- load stackOverflow.com > tap anywhere> it will load another URL
Tabbar 2:- Want to see the new loaded URL here (from the first tab)
Thanks a lot!
Comment: Feel like a bad idea to show same thing in different tab!
Answer: It is possible to shared the same instance, but you must know:

A view cannot be added to two different views at the same time. Each
view in UIKit hierarchy can have only one superview at a time. If you
add a view to a second superview, it will be removed from its previous
superview.

So, the trick here is putting the wkwebview in a shared AppDelegate, and inside your individual childViewController add the shared wkwebview as a child view within viewWillAppear(_ animated:)
 override func viewWillAppear(_ animated: Bool) {
    debugPrint("\(#function)")
    sharedWebView.frame = view.bounds
    sharedWebView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
    view.addSubview(sharedWebView)
  }

In this way, you have have a shared wkwebview.

BTW, I have trouble understanding you request, but still, I wrote a demo project:

Tabbar1:- load stackOverflow.com > tap anywhere> it will load another
URL
Tabbar 2:- Want to see the new loaded URL here (from the first tab)

Check the whole project here


Anybody can tell me why isn't my EC2 AMI booting?

Question: I'm trying to make my own EC2 AMI. I used debootstrap to install the packages onto a partition, copied the kernel modules from the running AMI (Amazon linux) and rebooted. This is what the console output is:

    Xen Minimal OS!
  start_info: 0xb10000(VA)
    nr_pages: 0x6a400
  shared_inf: 0xbef32000(MA)
     pt_base: 0xb13000(VA)
nr_pt_frames: 0x9
    mfn_list: 0x967000(VA)
   mod_start: 0x0(VA)
     mod_len: 0
       flags: 0x0
    cmd_line: root=/dev/sda1 ro 4
  stack:      0x946780-0x966780
MM: Init
      _text: 0x0(VA)
     _etext: 0x621f5(VA)
   _erodata: 0x76000(VA)
     _edata: 0x7b6d4(VA)
stack start: 0x946780(VA)
       _end: 0x966d34(VA)
  start_pfn: b1f
    max_pfn: 6a400
Mapping memory range 0xc00000 - 0x6a400000
setting 0x0-0x76000 readonly
skipped 0x1000
MM: Initialise page allocator for e6c000(e6c000)-0(6a400000)
MM: done
Demand map pfns at 6a401000-7a401000.
Heap resides at 7a402000-ba402000.
Initialising timer interface
Initialising console ... done.
gnttab_table mapped at 0x6a401000.
Initialising scheduler
Thread "Idle": pointer: 0x7a402008, stack: 0x6a030000
Initialising xenbus
Thread "xenstore": pointer: 0x7a402478, stack: 0x6a040000
Dummy main: start_info=0x966880
Thread "main": pointer: 0x7a4028e8, stack: 0x6a050000
"main" "root=/dev/sda1" "ro" "4"
vbd 2049 is hd0
******************* BLKFRONT for device/vbd/2049 **********

backend at /local/domain/0/backend/vbd/571/2049
Failed to read /local/domain/0/backend/vbd/571/2049/feature-barrier.
Failed to read /local/domain/0/backend/vbd/571/2049/feature-flush-cache.
10485760 sectors of 0 bytes
**************************
vbd 2051 is hd1
******************* BLKFRONT for device/vbd/2051 **********

backend at /local/domain/0/backend/vbd/571/2051
Failed to read /local/domain/0/backend/vbd/571/2051/feature-barrier.
Failed to read /local/domain/0/backend/vbd/571/2051/feature-flush-cache.
1835008 sectors of 0 bytes
**************************

    [H
    [J

    GNU GRUB  version 0.97  (1740800K lower / 0K upper memory)

       [ Minimal BASH-like line editing is supported.   For

         the   first   word,  TAB  lists  possible  command

         completions.  Anywhere else TAB lists the possible

         completions of a device/filename. ]

grubdom>
    [9;10H

I don't really understand what's failing.

More info:
So here's what I do:
I create a GB volume, boot an Amazon Linux AMI, mount the volume as say /dev/sdf, create a partition /dev/sdf1, mkfs.ext3 a filesystem on sdf1, debootstrap Debian to it, install a kernel image, create the menu.lst file:
Default 0
Timeout 3
Fallback 1
title Debian
root (hd0,0)
kernel /boot/vmlinuz-2.6.32-5-686 root=/dev/sda1
initrd /boot/initrd.img-2.6.32-5-686
Then I shutdown the Amazon Linux AMI, create a snapshot of the EBS volume, create an AMI from it (using either hd0 or hd00, setting the root device to /dev/sda1 - I set the root partition to be mounted from /dev/sda1 in fstab) and try to boot it. And it fails. This is the console output I can see:
Xen Minimal OS!
start_info: 0xb10000(VA)
nr_pages: 0x6a400
shared_inf: 0x00ba8000(MA)
pt_base: 0xb13000(VA)
nr_pt_frames: 0x9
mfn_list: 0x967000(VA)
mod_start: 0x0(VA)
mod_len: 0
flags: 0x0
cmd_line: root=/dev/sda1 ro 4
stack: 0x946780-0x966780
MM: Init
_text: 0x0(VA)
_etext: 0x61e65(VA)
_erodata: 0x76000(VA)
_edata: 0x7b6d4(VA)
stack start: 0x946780(VA)
_end: 0x966d34(VA)
start_pfn: b1f
max_pfn: 6a400
Mapping memory range 0xc00000 - 0x6a400000
setting 0x0-0x76000 readonly
skipped 0x1000
MM: Initialise page allocator for e6c000(e6c000)-0(6a400000)
MM: done
Demand map pfns at 6a401000-7a401000.
Heap resides at 7a402000-ba402000.
Initialising timer interface
Initialising console ... done.
gnttab_table mapped at 0x6a401000.
Initialising scheduler
Thread "Idle": pointer: 0x7a402008, stack: 0x6a030000
Initialising xenbus
Thread "xenstore": pointer: 0x7a402478, stack: 0x6a040000
Dummy main: start_info=0x966880
Thread "main": pointer: 0x7a4028e8, stack: 0x6a050000
"main" "root=/dev/sda1" "ro" "4"
vbd 2049 is hd0
<code>                                                                        BLKFRONT for device/vbd/2049 **********
</code>
backend at /local/domain/0/backend/vbd/1784/2049
Failed to read /local/domain/0/backend/vbd/1784/2049/feature-barrier.
Failed to read /local/domain/0/backend/vbd/1784/2049/feature-flush-cache.
10485760 sectors of 0 bytes

vbd 2051 is hd1
<code>                                                                        BLKFRONT for device/vbd/2051 **********
</code>
backend at /local/domain/0/backend/vbd/1784/2051
Failed to read /local/domain/0/backend/vbd/1784/2051/feature-barrier.
Failed to read /local/domain/0/backend/vbd/1784/2051/feature-flush-cache.
1835008 sectors of 0 bytes

[H
[J
GNU GRUB version 0.97 (1740800K lower / 0K upper memory)
[m
[4;2H+-------------------------------------------------------------------------+
[5;2H|
[5;76H|
[6;2H|
[6;76H|
[7;2H|
[7;76H|
[8;2H|
[8;76H|
[9;2H|
[9;76H|
[10;2H|
[10;76H|
[11;2H|
[11;76H|
[12;2H|
[12;76H|
[13;2H|
[13;76H|
[14;2H|
[14;76H|
[15;2H|
[15;76H|
[16;2H|
[16;76H|
[17;2H+-------------------------------------------------------------------------+
[m
Use the ^ and v keys to select which entry is highlighted.
Press enter to boot the selected OS, 'e' to edit the
commands before booting, or 'c' for a command-line.
[5;78H
[m
[7m
[5;3H Debian
[5;75H
[m
[m
[6;3H
[6;75H
[m
[m
[7;3H
[7;75H
[m
[m
[8;3H
[8;75H
[m
[m
[9;3H
[9;75H
[m
[m
[10;3H
[10;75H
[m
[m
[11;3H
[11;75H
[m
[m
[12;3H
[12;75H
[m
[m
[13;3H
[13;75H
[m
[m
[14;3H
[14;75H
[m
[m
[15;3H
[15;75H
[m
[m
[16;3H
[16;75H
[m
[16;78H
[5;75H
Comment: Building a working AMI for EC2 takes much more work than what you've done. You are also not providing enough details about the exact steps you took so far.  You don't even mention what distro you're trying to build (debootstrap is for debian, ubuntu; Amazon Linux is CentOS based).  I recommend you find reputable instructions for building a working AMI and follow them.  Or create private AMIs using ec2-create-image against a running instance.
Comment: Try using a different guide. If you are trying to build Debian AMIs, the best ones I know of are listed here: http://wiki.debian.org/Cloud/AmazonEC2Image  I'm sure those authors would be happy to point you to their build instructions. These might be Tom's: https://github.com/tomheady/ec2debian/wiki/64bit-ebs-ami-pvgrub  I used to build public Debian AMIs FROM 2007-2009, but others are doing this now and publishing on the above page.
Comment: Now I also installed a kernel, created a /boot/grub/menu.lst or whatever that file has to be called (the filename correct as you will see) and tried both hd0 and hd00 kernels. Now I see this output: http://pastebin.com/Efam617d
Comment: What EC2 AMI building guide are you following?  It's pretty much a waste of your time to try to figure out on your own how to build an AMI from scratch by adding random files to the image.  Others have solved the issues and published instructions based on years of best practices from the community and hard lessons learned.
Comment: I was following this guide before: http://gista.blog.root.cz/2010/10/18/creating-debian-amazon-ec2-ebs-ami-using-debootstrap/
Comment: When you followed the guide exactly did it work?
Comment: No. It didn't.        .
Answer: According to this write-up:

You may have selected the wrong kernel and it is trying to boot from a non-existant partition. Make sure you are using the correct pv-grub kernel hd0 vs hd00.
You forgot to install grub or installed grub in the wrong place. Make sure you have either /boot/grub/menu.lst or /boot/boot/grub/menu.lst
You have a bad menu.lst file. One mistake I made was giving a boot item a title with a space in it. Make the menu.lst as simple as you can until you get it to boot.


Moving from custom CMS to Drupal and need to keep a myriad of old mod_rewrites

Question: I am moving content from an existing custom built CMS into Drupal 7. There is a host of mod_rewrite rules in place. These rules expand path names in the URL. For example, the rule below effectively expands
RewriteRule ^abc/?(.*)$     /alpha/beta/confusion/$1 [L,R]
Ideally we'd like put these rules inside of /etc/httpd/conf.d/old_redirects.conf. However, the clean URL rules are in .htaccess and are processed first.
Can I remove dependence on .htaccess and move these rules to /etc/httpd/conf/httpd.conf thereby allowing me to import the old_redirects.conf into the httpd.conf file before the Clean URL set of rewrites executes?
(I've referenced the following question How do I use .htaccess to trigger mod_rewrites before D7's Clean URLs take over? and Drupal 7 .htaccess redirects; and while good, they don't quite cover this from the perspective the a need.)
Answer: Moving effort to this question and answer Drupal 7 rewrite not using .htaccess. THis is what I'm trying to do anyhow is eliminate the .htaccess.
However, I discovered a module called htaccess

Htaccess is a module which autogenerates a Drupal root htaccess file based on your settings.
Drupal tries to provide a one size fits all htaccess for Apache webservers, but this goal is increasingly difficult. This module allows the webmaster to set specific options.

Added benefits is that for every drupal core update (in which drupal overwrites htaccess), I just re-deploy my set of rules which this module appends to the active .htaccess file. Additionally, my customization to htaccess are in the database and safe in scheduled backups in from Backup Migrate.


como trabalhar com gênero e espécie de varias tabelas unificando elas para gráficos

Question: Estou a 3 semanas estudando java, possuo uma planilha e nela costa. Gênero e dentro dele a espécie isso na coluna 1 do Excel.
Na coluna 2 possui a quantidade de indivíduos dessa espécie em um determinado volume.
Na coluna 3 a quantidade de células da espécie por determinado volume.
 tabela no link
essa planilha (sendo arquivos em que cada arquivo é um ponto ou no mesmo arquivo, com varias tabelas, sendo cada tabela um ponto) representa uma localidade (ponto1 ou Ponto2....).
se eu possuir 2 pontos e sei que nesses pontos pode ter espécies diferente e iguais, como eu consigo juntar isso e fazer um gráfico para compara os pontos. estou tentando automatizar essa rotina pois eu perco muito tempo fazendo manualmente. procurei na internet e não achei nada nesse sentido.
Gostaria de saber qual biblioteca caso tenha para fazer ou se eu devo fazer em banco de dados e depois puxar... Obrigado.

 cada ponto representa um arquivo/tabela no Excel pois possuo as duas opções
Comment: Olá, meio complexo isso mas não impossível, posso dar uma ideia apenas com a parte para unir elas. Eu utilizaria as lib do "Apache POI - the Java API for Microsoft Documents", com ela vai conseguir ler, criar e alterar um arquivo XLSX. A Lib é bem completa, vai conseguir pegar dados de uma linha ou coluna específica, eu tentaria criar um código para ler os dois arquivos, pegar os dados que deseja dos dois (Ind/L e Cel/L) e ai criar um novo arquivo com desses dados.
Comment: Obrigado pelo norte!!!
Comment: Para te ajudar na parte dos gráficos e ajudar possíveis pessoas que venham a ter essa dúvida no futuro, irei formular uma resposta, espero ter ajudado.
Comment: Ajudou sim. Eu vou estudar e se eu conseguir resolver eu posto a solução. Acho que ate semana que vem eu consigo  ou não kkkk
Answer: O código em si é meio difícil de te responder, mas existem bibliotecas que irão te ajudar a unificar essas tabelas e a gerar gráficos depois.

Apache POI - the Java API for Microsoft Documents: Com esse pacote de libs você consiguirá ler, criar e alterar um arquivo XLSX. A biblioteca é extremamente completa, te permitirá a manipular os dados da forma que precisa.
JFreeChart: Possibilitar a geração de relatórios na forma de gráficos, uma dica é utilizar o Apache POI em conjunto com ele, assim poderá ler um determinado arquivo e assim gerar o gráfico com o JFreeChart.

Links que ajudarão:

Apache POI: Manipulando Documentos em Java
Gráficos com JFreeChart
Tutorial de como ler um arquivo XLSX com Apache POI
Repositório Maven do JFreeChart
Tutorial utilizando JFreeChart
Comment: Opa. Obrigado pela dica do JFreeChart. Agora é por a mão na massa e resolvendo eu posto aqui.


Example of functor not full not faithfull

Question: I am trying to find a functor that is not full nor faithful, if anyone can give me any suggestion, I appreciate it.
Thanks
Answer: Looking at two groups $G,G'$ as categories with one object, functors $G\to G'$ identify with group homomorphisms. Any non injective non surjective group homomorphism will do then.
Answer: A constant functor (all objects map to the same object, all morphisms to the identity morphism) is usually neither full nor faithful.


Python: read binary file into an array

Question: I was trying to import binary data and process it on python:
with open("myData", "rb") as binary_file:

    data = binary_file.read()
    print(data)

b'\x00\x00\x00\t0.000000\r\x00\x00\x00\t0.173902\r\x00\x00\x00\t0.343819\r\x00\x00\x00\t0.491724\r\x00\x00\x00\t0.660698\r\x00\x00\x00\t0.791551\r\x00\x00\x00\t0.890531\r\x00\x00\x00\t0.987460\r\x00\x00\x00\t1.083403\r\x00\x00\x00\t1.180349\r\x00\x00\x00\t1.274278\r\x00\x00\x00\t1.372280\r\x00\x00\x00\t1.470185\r\x00\x00\x00\t1.570129\r\x00\x00\x00\t1.668071\r\x00\x00\x00\t1.764061\r\x00\x00\x00\t1.861004\r\x00\x00\x00\t1.956906\r\x00\x00\x00\t2.051896\r\x00\x00\x00\t2.150841\r\x00\x00\x00\t2.249743\r\x00\x00\x00\t2.345730\r\x00\x00\x00\t2.443689\r\x00\x00\x00\t2.537581\r\x00\x00\x00\t2.636510\r\x00\x00\x00\t2.738474\r\x00\x00\x00\t2.843399\r\x00\x00\x00\t2.941346\r\x00\x00\x00\t3.041276\r\x00\x00\x00\t3.138279\r\

The above just a portion of my whole data. I was trying to convert to string and it doesn't work...
with open("D:/Python/reshape 3D/measurement data/112719_binary/time", "rb") as binary_file:

    data = binary_file.read(32)
    data = data.decode('utf-8')
    print(data)

How should I convert back and put them in a list?
The results above should be [0.000000, 0.173902, 0.343819.....]
Comment: What does "doesn't work" mean?
Comment: must use 'rb'? 'r' and encoding='u8' is woring?
Comment: I would suggest you give a little more info on why you want to turn it into a string, and what you're trying to achieve in order to get better solutions. cheers
Answer: You seem to have a bytes image of a two-column, tab-separated table, where the first column is all zeros and the last one has other field, starting from the second, and convert them to floats:
list(map(float, data.split()[1::2]))
#[0.173902, 0.491724, 0.791551, 0.98746, 1.180349,...

Comment: Thanks a lot!! I need list(map(float, data.split()[1::2])), though.

Python: read binary file into an array


Prove that $\lim_{n\to\infty} a_n=0$.

Question:
Let $a_n>0$ such that $$\lim_{n\to\infty} \left(\frac{a_{n+1}}{a_n}\right)^n<1.$$ Prove that $\lim\limits_{n\to\infty}a_n=0$.

Initially, I tried:
$$\begin{split}
\lim_{n\to\infty} \left(\frac{a_{n+1}}{a_n}\right)^n<1 &\implies \lim_{n\to\infty} e^{\ln\left(\dfrac{a_{n+1}}{a_n}\right)^n}<e^0\\ &\implies \lim_{n\to\infty} e^{\frac{1}{n}\ln\left(\frac{a_{n+1}}{a_n}\right)}<e^0\\ &\implies \displaystyle\lim_{n\to\infty} \frac{1}{n}\ln\left(\frac{a_{n+1}}{a_n}\right)<0
\end{split}$$
I got slighty desparate for an answer so I assumed that the limit $\displaystyle\lim_{n\to\infty} \left(\frac{a_{n+1}}{a_n}\right)$ exists.
Since the limit exists and $a_n>0$ then:
$$
\displaystyle\lim_{n\to\infty} \left(\frac{a_{n+1}}{a_n}\right) = \displaystyle\lim_{n\to\infty} (a_n)^\frac{1}{n}
$$
Combining this with the inequality results in:
$$
\displaystyle\lim_{n\to\infty}\ln(a_n)<0
$$
If anyone has any suggestions, I'll gladly listen. Thanks for the help!
Answer: Let
$$\lim_{n\to\infty}\left(\frac{a_{n+1}}{a_n}\right)^n<e^{-a}<1$$
(so, $a>0$). For $n$ large enough, say $n\ge N,$
$$\log a_{n+1}-\log a_n\le-\frac an.$$
So,
$$\log a_{n+1}\le\log a_N-a\sum_{k=N}^n\frac1k.$$
Since the harmonic series diverges, we deduce
$\log a_n\to-\infty,$ i.e. $a_n\to0.$
Answer: Let $$b_n=\left ({a_{n+1}\over a_n}\right )^n$$ Then $a_{n+1}=a_1b_1b_2^{1/2}\ldots b_n^{1/n}.$ If $b_k<r<1$ for $k> n_0$ then $$a_{n+1}\le a_1b_1b_2^{1/2}\ldots b_{n_0}^{1/n_0}r^{{1\over n_0+1}+{1\over n_0+2}+ \ldots + {1\over n}}$$ The right hand side tends to $0.$ Therefore $\lim a_n=0.$

Prove that $\lim_{n\to\infty} a_n=0$.


'+=: Command not found' when trying to add a value to an array - Shell Script

Question: I am trying to add folder paths to an array. I looked up on the internet and saw this solution. I gave it a try but I get an error message.
My code:
LOCALSITES=()

for d in "$DIRLOC"/*; do
    ${LOCALSITES}+='foo'  #doesnt work
done

echo "${LOCALSITES[*]}"

Error message:
showSites.sh: line 35: +=: command not found

Comment: Don't use `$` or `{}` when assigning to a variable (or array); that's to *get* its value(s). Do use parentheses to add elements, and double-quote the thing being added to avoid possible weird parsing. Finally, it's best to use lower- or mixed-case variable names to avoid conflicts with the many all-caps vars with special functions. Thus: `localsites+=("$d")`. Oh, and you almost never want `[*]` -- use `[@`] instead (and double-quotes around it): `echo "${localsites[@]}"
Comment: @Gordon, putting what should be an answer in a comment is almost (but not quite) as problematic as commenting in an answer. I don't believe comments are indexed for searches in the same way answers are, so they're pretty much useless in terms of helping *future* searchers out, one of the main reasons for SO. It would be far better off were you to answer as an answer! For now, I've incorporated them into the accepted answer.
Answer: ${LOCALSITES}+='foo'

will interpret the current value of that variable, giving you an empty string and therefore making the command read as:
+='foo'

You can see this if you do set -x beforehand:
pax:~$ set -x ; ${xx}+='foo' ; set +x
+ set -x
+ +=foo
+ '[' -x /usr/lib/command-not-found ']'
+ /usr/lib/command-not-found -- +=foo
+=foo: command not found
+ return 127
+ set +x

It's no real different to:
pax:~$ xx=1
pax:~$ ${xx}=2 # should be xx=2
1=2: command not found

To properly append to the array, you need to do:
LOCALSITES+=('foo')

Other things you may want to consider, courtesy of one Gordon Davisson in a comment:

It's probably best to use lower- or mixed-case variable names to avoid conflicts with the many all-caps variables with special functions: localsites+=('foo').
Make sure you select the correct quotes for whether you wish to interpret variables or not: localsites+=('foo') ; localsites+=("${newSite}").
You almost never want [*]. Use [@] instead, and put double-quotes around it: echo "${localsites[@]}".


Taxonomy Term Block View Show Nodes For All Terms in Node?

Question: Hello i achived this once but for some reason i am having a problem with it this time.
Using D6 and Views 3. I have a block view for random videos.

Taxonomy Term ID from URL
Load default argument from node page,
Validator: taxonomy term
Argument Type - Term id's by , or +

Iv checked and unchecked both-
Allow multiple terms per argument
and
Allow multiple arguments to work together
without much success. The desired output would be on a node tagged with 'science' and 'spirituality' the block view would show nodes that are either tagged 'science' or 'spirituality'. At the moment i seem to be getting no results or only nodes tagged with both 'science + spirituality'.
Does anyone know the correct settings for me to show nodes with any of the node's tags?
Thanks
Comment: When u create your node you can chose multiple values(taxonomy terms) from one field, or you have two or more fields for taxonomy terms?
Answer: I am not sure for d6, but in d7 you can do it like this(i believe it can be done same way in d6)
In Contextual filters(your Arguments) you need to add Nid like you did, after add new argument has taxonomy term ID and in WHEN THE FILTER VALUE IS NOT AVAILABLE -> provide default value chose not content from URL but PHP code and do this:
You need to load node and get your taxonomy terms from field.
 $node = node_load(arg(1));
  if($node) {
  $field = field_get_items('node', $node, 'field_YOURFIELDNAME');
  if($field) {
      foreach($node->field_YOURFIELDNAME[LANGUAGE_NONE] as $term) { $terms[] =  $term['tid'];          }
    return implode('+',$terms);
  }
}
  else { return; }

it will return tids of selected taxonomy terms. But its a d7 way with Views 3.
Comment: mmm thanks neok i dont think its the same really for D6 Views 3. Previously i didnt have to add any code. It all seemed to work with a couple of counter intuitive settings but thanks for your reply.
Comment: Hello i am still struggling on with this. I have made up a simple view which you can see here http://pastebin.com/1khJEUCN
Comment: When viewing this node on my site the expected behaviour is for the right hand block to show node in 'chinese' and 'comedy records' (tags) http://onlinebanter.com/chinese/videos/monty-python-i-chinese at the moment it only shows 'chinese'
Comment: Ive went with neok's suggestion as maybe i never ever had it working like i hoped im thinking. I might be getting somewhere as i now get a white screen when viewing a node where the block is placed. It might ust be a problem with the php code for D6 http://pastebin.com/NpdCzuuq
Comment: sorry that was an updated view i last posted there with all the instructions followed as best i could. thanks
Comment: i think there might not be `field_get_items` for d6, read this, http://stackoverflow.com/questions/3840720/reading-node-field-values-in-module-code-using-drupal-6


Contextually modify views output?

Question: On the front page, i'd like the views to output taxonomy differently than i would on a term page.
I know i could modify output using a tpl file indicated by devel_themer; but i'm not certain how one would contextually change it.
How would i go about doing so with a preprocess function?
Is it even possible?
Answer: you could just get the current page with request_uri() and then use some logic to style a view on the home page differently.
Or just create a second view and use the front module to show that view on the home page.

Contextually modify views output?


How do I calculate and permanently store a field value with code

Question: I would like to know how I can manually insert some PHP code inside a CCK node.
What I have is the following code for Drupal 6:
$output .= '
';
$mor = _pitch_detalle($cid, $previamente, $luego);
if (sizeof($mor) > 0) {
  $output .= theme('pitch', $mor);
}
return $output;

This code shows some information that changes from day to day, and each time the users view the page, the information changes.
I want the user to see an unmodified version of that code, the same information that existed when the user created the page.
As the user cannot edit the page, I´m looking to insert a php snippet inside a CCK field that will remain unchanged. But that could lead to problems, so is there any way to do that in a safe way?
Or maybe to insert code inside the template in other way?
Comment: Downvoted due to the last paragraph, because it's  ambiguous and the way it's phrased could led other users down a dangerous path of "code in the database". Please remove or re-phrase, and I'll upvote instead.
Comment: I'm not sure if I understand your question. You want a CCK field to contain a certain value, and that value must not be changed after the node is saved. The code above returns the value for the CCK field - is that correct? Should the field be filled automatically?
Comment: yes, is correct! Is there any way to do this? The output is some kind of programatic views, it´s some sort of view created using that code, and I need it to be pasted inside a node. If I simply paste it over the node it changes every time the values changes... THANKS!
Comment: Sorry about that. How about this way? I´ve rephrased it.
Answer: I haven't done this myself before, so I cannot give really detailed instructions. I think I would do something like this:

Create a CCK text field in the content type(s) of your choice
Create a custom module and implement hook_form_alter
In your form alter function:

Give your CCK text field a #disabled property and set it to true (this will grey out the field so it cannot be edited)
Check if the field is already populated; if not, set the #default_value to the return value of the code in your question

This means that when Drupal builds the form, your custom module will disable the CCK field and put your content in it if that has not been done before. Because we're just populating a form field, all Drupaly stuff like the 'Display Fields' page will keep working.
I hope that helps.


nginx + php5-fpm graceful restart : reload on Ubuntu 14.04 LTS

Question: I tried to find a way to gracvelly restart my server.
I tried sudo service php5-fpm reload && sudo service nginx reload
But this is not working as reloading php5-fpm on Ubuntu 14.04 is not working properly (The php5-fpm instance is showed as unknown)
After executing the previously command I got
sudo service php5-fpm status
> php5-fpm stop/waiting
sudo service php5-fpm restart
> stop: Unknown instance:
> php5-fpm start/running, process 26042
sudo service php5-fpm restart
> stop: Unknown instance:
> php5-fpm start/running, process 26141

The only way I found to restart php5-fpm after that is to run:
sudo killall php5-fpm
sudo service php5-fpm start
> php5-fpm start/running, process 26160

Thank You,
Answer: this one was killing me and all my coworkers too :)
Here's the solution:
Edit the file:

/etc/init/php5-fpm.conf

and uncomment the line containing (it's line 13 on my box):

reload signal USR2

Then kill all the php-fpms:
find their process ids:

ps aux | grep php-fpm

kill them:

sudo kill [proc-id]

And voila your "sudo service php5-fpm restart" is working again


How to constantly update time variables in a Python Script?

Question: I have an if statement below that I want to execute at exactly 11:45 am every single day. The problem is, when I run my Python script, result.tm_min and result.tm_hour are static, holding whatever time it was when I started the script in th first place. I need some way for these values to change in real-time with the clock. So when the time changes from 11:44 to 11:45, result.tm_min also changes from 44 to 45, allowing for the below if statement to execute. If I could get any help with this, that would be awesome.
I'm currently using the time and datetime libraries for this.
if result.tm_hour == 11:
        if result.tm_min == 45:

            post_number = random.randint(1, 5)
            noun_number = random.randint(1, noun_expand_count)
            verb_number = random.randint(1, verb_expand_count)

            noun_file = open("nouns.txt", "r")
            get_noun_line = noun_file.readlines()
            new_noun = get_noun_line[noun_number].strip()
            noun_file.close()

            verb_file = open("verbs.txt", "r")
            get_verb_line = verb_file.readlines()
            new_verb = get_verb_line[verb_number].strip()
            verb_file.close()

            post_file = open("things_to_do.txt", "r")
            get_post_line = post_file.readlines()
            new_post = get_post_line[post_number].strip()
            post_file.close

            message = "@joerogan Hello Joe, today's top two priorities are to:", new_post, new_verb, new_noun
            print(message)
            #api.update_status(message)

Edit: Okay, I did a pip install for the schedule module, tried to rewrite some code, but I'm not getting any output, at all.
def post():
post_number = random.randint(1, 5)
noun_number = random.randint(1, noun_expand_count)
verb_number = random.randint(1, verb_expand_count)

noun_file = open("nouns.txt", "r")
get_noun_line = noun_file.readlines()
new_noun = get_noun_line[noun_number].strip()
noun_file.close()

verb_file = open("verbs.txt", "r")
get_verb_line = verb_file.readlines()
new_verb = get_verb_line[verb_number].strip()
verb_file.close()

post_file = open("things_to_do.txt", "r")
get_post_line = post_file.readlines()
new_post = get_post_line[post_number].strip()
post_file.close

message = "@joerogan Hello Joe, today's top two priorities are to:", new_post, new_verb, new_noun
print(message)
#api.update_status(message)
return

class MyStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        global noun_expand_count, verb_expand_count
        status = status._json['text']

        schedule.every().minute.do(post)

Comment: google this python library:  import schedule
Comment: Please post a complete verifiable example: https://stackoverflow.com/help/minimal-reproducible-example. In another words, how are result.tm_* is being calculated?
Comment: *"I want to execute [code] at exactly 11:45"* - That's typically what you use cron or any other kind of *task scheduler* for, not an `if` statement.
Comment: Okay. I imported Schedule, and tried to set it up, but nothing is happening. I've included the code in an edit.
Answer: Recalculate the current time immediately before checking:
current = datetime.now()
if current.hour == 11 and current.minute == 45:
    # annoy Joe Rogan

However, as others have commented, it might be better to use a purpose-built task scheduling system such as cron.


class weighted classification

Question: I am working on my multi-class classification project and I have a question:
I have three classes in proportion: 50%, 47% and 3%. I decided to use class_weight="balanced" parameter in random forest classifier. Now I want to calculate accuracy. Should I use balanced accuracy or can I use common accuracy?
Answer: Against @gunes, I defend that you can use whatever metric you want. Yes accuracy may give you unexpected results in a imbalanced problem, but the choice of metric is based on the needs of your problem. If all classes have the same cost for errors, then accuracy is the correct metric. What is usually implicit is that the cost of missing a low frequency class (in your case the class with 3%) is higher than missing the other classes. But it may  not be so. Maybe your problem is directing software tickets to the appropriate developer. In this case, I believe, getting one of the low frequency errors correctly is not that important. What is important is sending the most tickets to the correct teams. In this case, accuracy is the correct answer.
More generally, your metric of evaluation has no relation with what tricks you use in your classifier. If the problem requires that you use F1, use it, regardless on which tricks/techniques you used internally to deal with the imbalanced problem.
Answer: If you want to include accuracy as a performance metric, balanced accuracy is a better choice than accuracy because of the imbalance in class distributions here. I would also recommend reading these answers about why accuracy is generally a bad metric.

class weighted classification


Probability of second ball being black

Question: I was taking Caltech - ML Course and solving problem 1.3 in this link
We have 2 opaque bags, each containing 2 balls. One bag has 2 black balls and
the other has a black ball and a white ball. You pick a bag at random and then pick one of the balls in that bag at random. When you look at the ball, it is black. You now pick the second ball from that same bag. What is the probability that this ball is also black?
I tried to do this way:

Since we are trying to find the probability of 2nd being ball being black when we already know that first ball is black. This reduces our problem to probability by which we picked the bag with two black balls.

So the answer should be 1/2.
PS: This is not a homework/assignment. This course has been already finished. I am just taking it offline for learning purpose.
Comment: You happened to forget that the bags contain a white ball, a black ball, but another black ball as well AFTER the first removal.
Answer: Since $2$ of the three black balls are in the $2$-blacks bag, the required probability is $2/3$.
Since intuition can be treacherous, we will in addition do a formal conditional probability calculation.
Let $F$ be the event the first ball is black. The probability of $F$ is $3/4$. For with probability $1/2$, we chose the $2$-blacks bag, in which case the probability of black is $1$, and with probability $1/2$ we chose the mixed bag, in which case the probability of black is $1/2$. Thus $\Pr(F)=(1/2)(1)+(1/2)(1/2)$.
Let $S$ be the event the second ball drawn is black. The probability of $S$ is $1/2$, for $S$ happens precisely if we picked from the $2$-blacks bag.
The event $F\cap S$ happens precisely if $S$ happens. Thus
$$\Pr(S|F)=\Pr(F\cap S)/\Pr(F)=\frac{2}{3}.$$
Comment: Thanks @Andre..This was really helpful
Comment: You are welcome. In conditional probability problems, there are potential pitfalls, so you were right in wanting a formal calculation. But informally, getting a black on the first try makes it more likely that we drew from the $2$-blacks bag.
Answer: Here is how we can proceed. Take this approach. Since first ball drawn is black and you want to find out the probability of second ball being drawn is black So it is the same as probability of telling the bag chosen was the one with 2 black balls.
Hence, use Bayes's theorem and consider these events
<code>A = First ball drawn is black
E = Bag chosen was one with 2B balls
P(A|E) = 1/2
P(A) = 1/2*1 + 1/2*1/2 = 3/4
P(E|A) = P(A|E).P(E)/P(A)
       = (1/2)/(3/4)
       = 2/3 which is correct answer.
</code>
Answer: There is a clear mistake in Blunderboy's explanation.
His answer uses the Bayes formula but then the term P(E) is erroneously excluded from the computation. In addition the value for P(A|B) is simply wrong.
This is the correct formulation of the problem using Bayes theorem:
P(A|E) = 1 ( if we choose the bag with two black balls the probability that we select a black ball is 100%)

P(E) = 1/2 ( each bag can be chosen with equal probability)

P(A)= 3/4 as explained by Andre Nicolas.
Then the Bayes theorem leads us to:
P(E|A)=  P(A|E).P(E)/P(A)
      = (1 * 1/2)/(3/4)=2/3.
Andre Nicolas answer, which uses the Kolmogorov definition instead of the Bayes theorem, is completely correct.
Answer: In addition to @blunderboy's explanation I found this New York Times article very helpful in understanding Bayes's theorem. Also checkout wikipedia, which shows the solution of the example mentioned in the NYT.
Here is the original quote from the NYT together with the example:
The theorem itself can be stated simply. Beginning with a provisional hypothesis about the world (there are, of course, no other kinds), we assign to it an initial probability called the prior probability or simply the prior. After actively collecting or happening upon some potentially relevant evidence, we use Bayes's theorem to recalculate the probability of the hypothesis in light of the new evidence. This revised probability is called the posterior probability or simply the posterior. Specifically Bayes's theorem states (trumpets sound here) that the posterior probability of a hypothesis is equal to the product of (a) the prior probability of the hypothesis and (b) the conditional probability of the evidence given the hypothesis, divided by (c) the probability of the new evidence.
Consider a concrete example. Assume that you're presented with three coins, two of them fair and the other a counterfeit that always lands heads. If you randomly pick one of the three coins, the probability that it's the counterfeit is 1 in 3. This is the prior probability of the hypothesis that the coin is counterfeit. Now after picking the coin, you flip it three times and observe that it lands heads each time. Seeing this new evidence that your chosen coin has landed heads three times in a row, you want to know the revised posterior probability that it is the counterfeit. The answer to this question, found using Bayes's theorem (calculation mercifully omitted), is 4 in 5. You thus revise your probability estimate of the coin's being counterfeit upward from 1 in 3 to 4 in 5.
Comment: Welcome to math.stackexchange.com and thanks for sharing the link. On a side note, link-only answers are discouraged here. Instead put them as comment.
Answer:
If we think of throwing all the balls in a big pool, Then that pool will have BIG POOL = (B1,B1,B2,W2) = 3 BLACK BALLS of which 2 are from U1. According to the problem, we shall select this U1.
Another way :
lets say :  U1 = 2B and U2 : 1W + 1B
$P(U_1|B)=\dfrac{P(B|U_1)\cdot P(U_1)}{P(B|U_1)\cdot P(U_1)+P(B|U_2)\cdot P(U_2)}=\dfrac{1\cdot\dfrac12}{1\cdot\dfrac12+\dfrac12\cdot\dfrac12}=\dfrac23$
$P(U_2|B)=\dfrac13$
The probability that the BLACK ball is drawn the Second time is
$\dfrac23\cdot1+\dfrac13\cdot(0) =\dfrac{2}{3}$
Answer: I am taking the same course, however the question hinted that the solution could be found using Bayes' Theorem.
Although intuitively the answer is $\frac{2}{3}$, using Bayes' Rule actually made finding the solution more difficult. Reformulating the question in the context of Bayes', one can ask "what is the probability after selecting one black marble, that the black marble came from the bag with two black marbles."
Clearly, the probability of selecting two black marbles in a row in the same as selecting one black marble from the bag with two black marbles! And this is where Bay's rules comes into play.
$P = \frac{(0.5)(\frac{2}{2})}{(0.5)(\frac{2}{2}) + (0.5)(\frac{1}{2})}$
$P = \frac{\frac{1}{2}}{\frac{1}{2} + \frac{1}{4}}$
$P = \frac{\frac{1}{2}}{\frac{2}{4} + \frac{1}{4}}$
$P = \frac{\frac{1}{2}}{\frac{3}{4}}$
$P = \frac{1}{2}\cdot \frac{4}{3}$
$P = \frac{4}{6}$
$P = \frac{2}{3}$

Probability of second ball being black


Derivation of Hamilton's equations

Question: The general derivation of Hamilton's equations involve the change in the hamiltonian and consequently the change in the Lagranian that is a function of q and q_dot, L(q,q_dot). This is shown in this simple video https://www.youtube.com/watch?v=jXu6zIItnLM
When deriving Hamilton's equations for q_dot and p_dot, the lagranian is only a function of q and q_dot but not time. Therefore the Lagranian used to derive Hamilton's equations is time-independent as it appears. Does that means that Hamilton's equations for q_dot and p_dot are only right for systems for which the lagranian is time-independent (and therefore the hamiltonian- or energy is conserved) ?
Answer: Lagrange movement equations $(n)$ extracted from $L(q,\dot q,t)$ are equivalent to the $2n$ first order equations
$$
\cases{
\dot p = -H_q\\
\dot q = H_p
}
$$
with $H(p,q, t) = p\dot q-L(q,\dot q,t)$. This last equation is known as  the Legendre transform. Here $L(q,\dot q,t)$ and $H(p,q, t)$ are respectively the Lagrangian and the Hamiltonian. Both can be non autonomous.
Comment: You should add that $p=\frac{\partial L}{\partial \dot q}$ is used to eliminate $\dot q$. Or else you have to define $H$ as the convex support function $$H(p,q,t)=\max_{\dot q}(p\dot q-L(q,\dot q,t)).$$
Comment: Well observed! Thanks.

Derivation of Hamilton’s equations


How can I find the name of the VM image used to create an Azure VM using PowerShell?

Question: If I use Get-AzureVM (PowerShell cmdlet) to fetch a running VM then the fields I get back are
DeploymentName
Name
Label
VM
InstanceStatus
IpAddress
InstanceStateDetails
PowerState
InstanceErrorCode
InstanceFaultDomain
InstanceName
InstanceUpgradeDomain
InstanceSize
HostName
AvailabilitySetName
DNSName
Status
GuestAgentStatus
ResourceExtensionStatusList
PublicIPAddress
PublicIPName
PublicIPDomainNameLabel
PublicIPFqdns
NetworkInterfaces
VirtualNetworkName
ServiceName
OperationDescription
OperationId
OperationStatus

However I cannot see the name of the image used to create the VM.  I can see this information using the Azure portal (under Settings > Properties > SOURCE IMAGE NAME).  How can I get the source image name using PowerShell?
Answer: If you want to check the source image without using cmd/Powershell, then  follow these steps:
How to find the running VM image version.
> Go to azure portal
> Select the running/stopped VM whose image you want to identify
> Go to export template option
> On the right side of the screen, you will see the template window will open in JSON format.
> Ctrl+F (search) > imageReference > you will get your image version in the template.

Answer: You get the source image ID from the operating system disk's properties.
Try this:
$vm = Get-AzureVM -ServiceName serviceName -Name vmName
$vm.VM.OSVirtualHardDisk

Then you should get this for example:
HostCaching     : ReadWrite
DiskLabel       :
DiskName        : multinicdemo-host1-0-201504131546160112
MediaLink       : https://multinicdemo.blob.core.windows.net/vhds/multinicdemo-host1-2015-4-13-17-46-7-664-0.vhd
SourceImageName : a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-201503.01-en.us-127GB.vhd
OS              : Windows
IOType          : Standard
ResizedSizeInGB :
ExtensionData   :

Or in one line:
(Get-AzureVM -ServiceName serviceName -Name vmName).VM.OSVirtualHardDisk.SourceImageName

Answer: In the new 'Az' Powershell module you have to check for source image as below:
> $vm = (Get-AzVM -Name <VM_NAME>)
> $vm.StorageProfile.ImageReference

You should get something like this:
Publisher    :
Offer        :
Sku          :
Version      :
ExactVersion : 1.0.0
Id           : <RESOURCE_ID_FOR_YOUR_IMAGE>

Comment: This answer is correct. The accepted answer provides the OS image which could be different than the Azure Image. I think the original question was looking for this.
Comment: Perfect, this was hard to find! Is it also available in the portal?


Can i have a distribution that is not a marginal of another distribution?

Question: Can there be a distribution that cannot be expressed as a marginal of some other distribution?
Comment: Try in reverse: given a distribution, is it ever impossible to construct a joint distribution of which the original distribution is marginal?
Comment: Every distribution is a marginal of itself.  Less trivially, and more intuitively, suppose $X$ is a random variable with a given distribution and let $Y$ be independent of $X.$  How is the distribution of $X$ related to that of $(X,Y)$?  All you need to do now is show such a $Y$ exists.  Consider any constant random variable.
Answer: The answer is NO.
To reformulate the question: Given any two univariate distributions $F, G$ (represented with their cumulative distribution functions) is there always a bivariate distribution with  $F, G$ as marginals? Yes, for instance by independence.
Comment: And this applies for multivariate distributions, too.


Other Algebraically Independent Transcendentals

Question: I was thinking about a incomplete answer I gave earlier today to a interesting question made by the user lurker. The question was about wheter or not the sum or the product of two transcendental numbers in $\mathbb{C}/\mathbb{Q}$ could result on a algebraic number in the same set. A infinite amount of trivial examples can be shown by manipulating the same transcendental, like shown in the answers and in the comments, but I was intrigued by what I believed being the question's true aim, the non-trivial results.
After fiddling around with some algebra to try and understand the nature of  transcendental extensions, then proceed to read about it during the day, I reached the known result that it depends on wheter or not the two given transcendental numbers are algebraically independent. If they are, then we cannot generate a 'non trivial algebraic' transformation between them that yields a algebraic number (i.e. using only the four basic operations). It's just a question of stating a polynomial with rational coefficients whose roots are the given transcendental numbers.
Now to the real question. From Nesterenko's results [1996] we know the independence of $\pi$, some values of the Gamma $\Gamma$ function and some powers of $e^\pi$. From the unproved Schanuel's conjecture follows that $\pi$ and $e$ are independent.

Are there examples of more notable (conjectured or known) algebraically independent transcendental numbers?
Are there a pair of transcendental numbers, maybe notable constants, whose algebraical dependence has been proved or conjectured?
Answer: Generally speaking the answer is "no," however we have results such as Lindemann-Weierstrass and Baker's theorem and the Gelfond–Schneider theorem (some of which are just refinements of others, but you get the idea). The actual algebraic independent is usually phrased based on sets involving numbers versus their exponentials, and then a careful analysis of properties of the exponential function to show that both cannot simultaneously be algebraic.
However--generally speaking--doing this for specific numbers which don't fit immediately into that framework is a difficult order to fill. This is mostly because transcendentals have very little to work with:  ordinarily we prove facts about them by contradiction because the only fact they have about them is that they have no polynomial with rational coefficients they satisfy. So one argues by assuming a number is algebraic and showing it satisfies some property (usually a bound on some invariant) and then proving that numbers which do not have that property exist in some set, and then those numbers are transcendental.
To give you an idea of the scope of the difficulty, we still do not know if the logarithms of the rational primes are algebraically independent, one of the oldest problems in Diophantine analysis and transcendence.


Problema de recursão, linguagem C

Question: Estou com um problema, em um código que encontrei em que recebe uma string do usuário e a devolve invertida, fazendo isso de forma recursiva.
Porem, não entendo porque a função feita consegue de fato fazer isso.
Segue o código:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void recebeString(char *string)
{
    if(*string)
    {
        recebeString(string+1);
        putchar(*string);

    }

}

int main()
{
    char resultado[250];

    printf("Escreva uma string(frase): ");
    scanf("%[^\n]",resultado); // força o scanf a ler ate encontrar o \n.
    setbuf(stdin, NULL);

    printf("%s\n\n",resultado);

    recebeString(resultado);

    return 0;

}

alguém pode me ajudar?
Answer: O que a função faz é chamar a si mesma incrementando o ponteiro da string, assim as chamadas ficam empilhadas na memória, até que vai chegar um momento em que o if vai falhar porque vai encontrar o \0 que termina a string (assumindo que a string está bem formada). Aí ele vai retornar para a última chamada no ponto logo antes do putchar e vai executar o putchar do último caractere. E vai seguir desempilhando e chamando putchar.
Por isso que ele funciona.
Comment: Eu não sei se você já usou o stackoverflow antes, mas se uma resposta ajuda você pode marcar ela como aceita. Também pode dar um upvote.
Comment: Mas, como a função começa direto no final da string?
Comment: Ela não começa direto no final. Ela começa no início, mas a primeira chamada que ela faz é a ela mesma e isso empilha a execução sem terminar, então o primeiro caractere fica esperando para ser impresso. Quando chega no final e não passa mais no if ela retorna e o primeiro caractere empilhado para ser impresso é o último da string, ele imprime e retorna para o penúltimo e assim sucessivamente até chegar no primeiro novamente.
Comment: Entendi!, vlw cara ajudou abeça!

Problema de recursão, linguagem C


How to develop perfect pitch

Question: If someone would play a random note I'll know what it is but I can't just hear a song and play it.
How am I spouse to do that?
Comment: Welcome! This topic has already been covered, in this thread as well as many others that you can find by searching: [What are some useful and effective exercises for training absolute pitch?](https://music.stackexchange.com/questions/203/what-are-some-useful-and-effective-exercises-for-training-absolute-pitch)
Comment: I suspect you're not asking how to develop perfect pitch - by at least one definition of perfect pitch, anyone who can identify heard notes by name without looking at anything or needing a prior reference note already has perfect pitch, and it seems like you can already pull that off - but how to figure out music by ear, which is a different enough art.
Comment: Exactly:  allow your   "spouse" to do it.
Answer:
If someone would play a random note I'll know what it is

That is all that perfect pitch is.  It is not a magical bullet.
Hearing a song and playing it takes a lot of musical training.  Identifying the starting pitch for someone without absolute pitch is a matter of playing one note and then reorienting themselves with relative pitch.
Having absolute pitch saves you maybe a second of work here.
With some people, perfect pitch surfaces in the course of lots and lots of training, so sometimes it is assumed to be a (sometimes coveted) indicator of musical prowess.
So with a solid musical education and good musical skills, your absolute pitch recognition ability (assuming that you don't lose it over the course of training your musical abilities) may give you an edge for impressing musicians.  But an edge needs substance behind it if it is supposed to make a difference.
Comment: Come on, dv-er. Explain yourself - if you can.
Answer: It will depend mainly on how well you can play an instrument, and we don't know that.
Absolute pitch might work - slowly, were you to recognise and play a tune note by note, but what a slow process that will be.
You also don't say whether it's merely the melody, or the harmonies which go alongside. That's a completely different kettle of worms. For that, just possessing absolute pitch isn't a lot of, if any help. You need to have a good grounding in music theory to be able to decipher the chords, and lots of experience in doing just that.
Sorry, there's no quick route to where you want to be.
Comment: Come on dv-er. Explain yourself.

How to develop perfect pitch


Laravel testing - Problems with created routes

Question: I have a question about routing while testing packages. The function setRoutes creates new routes in the test file as follows:
class PackageTests extends \Orchestra\Testbench\TestCase {
    protected function setRoutes()
    {
        Route::group([
            'prefix' => Package::functionToCall1(),
            'before' => 'filter'
        ], function() {

            Route::get('/', function () {
                return "hello";
            });

        });
        Route::enableFilters();
    }
    protected function getEnvironmentSetUp($app)
    {
        $this->app = $app;
        $this->setRoutes();
        Config::set('app.url', "http://localhost/" );
    }
    public function testFunction1()
    {
        $crawler = $this->call(
            'GET',
            'http://localhost/'
        );
        // doing this call, the function on the prefix is called
        $this->assertResponseOk();
    }
}

Inside the function called in the prefix, functionToCall1() urls are not taken successfully. A call to URL::current() returns "/" and a call to Request::fullUrl() returns "http://:" when phpunit is executed but they returns the full url when used executing a url in the browser. This is the code of the package:
class Package
{
    function functionToCall1()
    {
        var_dump(URL::current() ); // returns "/"
        var_dump(Request::fullUrl()); // returns "http://:"
        // I want them to return 'http://localhost'
    }
}

I tried setting up the url Config::set('app.url', "http://localhost/" ); but it was useless.
To sum up, is there a way to call a function in the prefix and get the testing url?
Thanks, I would really appreciate your answers :)
Answer: I have had to deal with a similar issue. My solution was found here:
Mocking Laravel's Request::segment method
Apparently there is an order of operations issue with testing a Request facade.
I was trying to use Request::segments() before the request was being built, so there were never any segments to return.
I imagine it's the same problem with Request::fullUrl().
Here is my solution:
class MyTestClass extends TestCase
{
    public function setUp()
    {
        // No call to parent::setUp()

        $this->app = $this->createApplication();
        $this->app->request->server->set('REQUEST_URI', '/some/uri');
        $this->client = $this->createClient();
        $this->app->boot();
    }

    public function testWhatever()
    {
        $this->call('GET', '/some/uri');
    }
}

This allows me to get the request data properly, even though it looks pretty bad.


How to check if all packages listed in requirements.txt file are used in Python project

Question: I have a requirements file which contains all installed packages. After big refactoring process of the project some of the listed packages are not needed anymore. The problem is I'm not sure which.
Is there a way to determine which packages listed in the requirements.txt file are actually used in the code?
Comment: `python -v …` Take notes, be fast! ;)
Comment: Do you have automated tests that you can run, ideally with high coverage? The brute force approach is to start with an empty venv, run your tests, and install the packages for each modulenotfounderror,.. until all the tests pass.
Comment: `$ cat **/*.py | grep import` could be a starting point?
Comment: @GinoMempin actually my project is a big cutsom build test automation framework for some product, and it does not have any additional tests.
Comment: @aviya.developer so you;re suggestion is the to write additional script that will grep all of the imported packages? I will probably use this as a last resort. For now I'm thinking of more elegant solution.
Answer: Alternative answer that uses a Python library: pipreqs. See Automatically create requirements.txt.
Running pipreqs with the default arguments will generate a requirements.txt for you.
$ pipreqs /home/project/location
Successfully saved requirements file in /home/project/location/requirements.txt

However, it looks like you're trying to clean up an old requirements.txt file. In this case, pipreqs also comes with a --diff flag, and a --clean flag. From the docs:
--diff <file>         Compare modules in requirements.txt to project imports.
--clean <file>        Clean up requirements.txt by removing modules that are not imported in project.

You can use --diff to determine which libraries need to be removed, and --clean to do it automagically.
Answer: If you are using a virtual environment and have a decent enough test suite that you can repeatedly and automatically run (it's best if you can run it on your local workspace via a script or a simple command), then the brute-force type of approach is to:

Setup a fresh copy of your project (ex. git clone onto a separate folder)
Setup an empty/blank virtual environment
Run your tests
Install missing packages every time you encounter a "ModuleNotFoundError" type of error
Repeat until all tests passes
Export the packages you now have to a separate requirements.txt file (pip freeze > requirements.new.txt or any of the other ways from  Automatically create requirements.txt)

For example, we have this (very) minimal example code:
# --- APP CODE

from numpy import array
from openpyxl import Workbook
from pydantic import BaseModel, ValidationError

class MyModel(BaseModel):
    x: int

# --- TEST CODE

import pytest

def test_my_model():
    with pytest.raises(ValidationError):
        MyModel(x="not an int")

After cloning this and setting up a brand new fresh virtual environment (but without yet installing any of the packages), the 1st attempt to run the tests yields:
(my_venv) $ pytest --maxfail=1 main.py
bash: /Users/me/.venvs/my-proj-7_w3b8eb/bin/pytest: No such file or directory

So then, you install pytest.
Then, you get:
(my_venv) $ pytest --maxfail=1 main.py
...
main.py:1: in <module>
    from numpy import array
E   ModuleNotFoundError: No module named 'numpy'

So then you install numpy.
Then, you get:
(my_venv) $ pytest --maxfail=1 main.py
...
main.py:2: in <module>
    from openpyxl import Workbook
E   ModuleNotFoundError: No module named 'openpyxl'

So then you install openpyxl.
...and so on. Until all the tests passes. Of course, even when your automated tests pass, it's good to also do some manual basic tests to make sure everything is indeed working as before. Finally, generate a new copy of your requirements.txt file, and compare that with the old one, to check for any differences.
Of course, as I mentioned at the start, this assumes you have a decent enough test suite that tests a large % of your code and use cases. (It's also one of the good reasons why you should be writing tests in the first place.).


How to add cglib to a OSGI manifest of RCP client?

Question: I want to use cglib in an RCP client. The RCP client is build using maven and the tycho plugin. We are useing a manifest first strategy.
This is my MANIFEST.MF:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: INFO+ RCP Common UI Plug-in
Bundle-SymbolicName: a.company.prj.rcp.common.ui
Bundle-Version: 8.0.14.qualifier
Bundle-Vendor: Schweizerische Bundesbahnen SBB
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-Activator: a.company.prj.rcp.common.ui.CommonUIPlugin
Bundle-ActivationPolicy: lazy
Export-Package:
 a.company.prj.rcp.common.ui,
 ...
 a.company.prj.rcp.common.ui.wizards.page
Import-Package:
 org.apache.log4j;version="1.2.17"
Require-Bundle:
 org.eclipse.ui;bundle-version="3.7.0",
 org.eclipse.ui.forms;bundle-version="3.5.101",
 com.ibm.ws.jpa.thinclient;bundle-version="8.0.6",
 ...
 a.company.prj.rcp.core;bundle-version="8.0.14",
 ...

To add cglib I changed the Import-Package section to:
Import-Package:
 net.sf.cglib;version="3.2.0",
 org.apache.log4j;version="1.2.17"

Now Eclipse complains with:
No available bundle exports package 'net.sf.cglib'

Ayn ideas how to include cglib with this environment?
Comment: Well you need a cglib Bundle that provides this package in your environment. In Eclipse you usually do that with a custom target platform ( .target file, see for instance this [Tutorial](http://www.vogella.com/tutorials/EclipseTargetPlatform/article.html) ) that you can also reference in your Tycho build.
Answer: You will need to add the cglib bundle to your target platform, i.e., the set of all bundles Tycho will consider when resolving dependencies. You have three options to do so (taken from the Tycho wiki page on this topic):

You can simply add an entire p2 repository to your target platform.
You can use a .target file and reference the cglib bundle therein (as already suggested by stempler).
You can declare a Maven <dependency> on cglib and make Tycho "consider" it.

As you already have a working Tycho build, I suggest you use whatever option you or your colleagues have used in the build before.
One more note: Options 1 and 2 require that the cglib bundle is available in a p2 repository, whereas option 3 works even if the bundle comes from a "normal" Maven repository like the Central Repository. But in all three cases the cglib JAR must be a valid OSGi bundle, i.e., include an OSGi MANIFEST.MF with Bundle-SymbolicName etc.
Answer: You should build the cglib jar file to a plugin and install it in Eclipse before you can use it. You can refer to this link: How can I add the external jar to the eclipse rcp application?


Acesso somente via login e senha, Inibindo acesso direto via url

Question: fiz um sistema de login de acesso, mas gostaria que o usuario fosse obrigado a acesa-lo com o login e senha, inibindo o acesso direto via url.
Qualquer pessoa pode acessar a pagina via URL digitando o endereço. Gostaria de inibir esse tipo de acesso, fazendo que o usuário somente pudesse acessar a página via login e senha!
Estarei adicionando os códigos criados a baixo:
Código do Login:
<?php
session_start();
$_SESSION['logado'] = 1;
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php include "../conexao.php"; ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Painel Adm. - Login</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css' />
<link rel="stylesheet" type="text/css" href="css_login/style.css" />

<?php
$logotipo = $_POST['logotipo'];

$query = mysql_query("SELECT * FROM topo");
$res = mysql_fetch_array($query);
?>

<img src="../upload/<?php echo $res['logotipo'] ;?>" width="auto" height="58" />

<form name="enter" method="post" action="" enctype="multipart/form-data">
Login: <input id="login" type="text" class="txt bradius" name="login" value="" />
Senha: <input  id="senha" type="password" class="txt bradius" name="senha" value="" />
<input type="submit" class="sb bradius" name="enter" value="Entrar" />
</form>
<?php
if(isset($_POST['enter'])){

$login = $_POST['login'];
$senha = $_POST['senha'];

$query = mysql_query("SELECT * FROM usuario WHERE login = '$login' AND senha = '$senha'");
$conta = mysql_num_rows($query);

if($conta == '0'){
echo "";
}else{

while($res = mysql_fetch_array($query)){
$id = $res ['id'];
$nome = $res ['nome'];
$login = $res ['login'];
$senha = $res ['senha'];
$nivel = $res ['nivel'];

if($nivel == 'admin'){
echo "";
}else{
echo "";
}}}}
?>

Página a ser inibida ao acesso direto via URL:
<?php
session_start();
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== 1){
header("Location: http://www.buziosnegocios.com.br/admin/index.php");
} else {
$username = $_SESSION['user'];
$idusername = $_SESSION['iduser'];
session_destroy();
exit;
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Untitled Page</title>
<meta name="generator" content="WYSIWYG Web Builder 10 - http://www.wysiwygwebbuilder.com">
<link href="#.css" rel="stylesheet" type="text/css">

Menu

Se os amigos puderem me ajudar a inibir o acesso direto via URL, ficarei muito grato.
Um BRIGADÃO a todos pela atenção.
Comment: Estude sobre SQLInjection e PDO, sobre a sessão é lógica pura. Procure ver exemplos no youtube... Um exemplo de uma falha de SQLInjection no seu sistema é ... Coloque no usuario isso -> admin' OR 1=1#
Comment: Depois coloque uma senha qualquer e vc tera acesso ao sistema.
Comment: Para inibir o acesso como vc perguntou, coloque embaixo do location um die.
Answer: Se ao logar você inicia a sessão colocando $_SESSION['logado'] = 1 basta
você colocar em um arquivo funcoes.php aonde as suas paginas vão chama-las,
e executar uma função por exemplo:

function validaAcesso($usuario){
   if(empty($usuario)):
      header("Location: http://www.buziosnegocios.com.br/admin/index.php");
   endif;
}

validaAcesso($_SESSION['logado']);

Se a sessão estiver vazia ele não logou pelo painel, então redirecione ele.
você pode aplicar a mesma ideia para o botão de desconectar do painel

function desconectar(){
   session_unset();
    header("Location: http://www.buziosnegocios.com.br/admin/index.php");
}

clicou, removeu a sessão e voltou para o login, claro há n formas de fazer mas essa te da uma boa ideia de como prosseguir.
Answer: Amigo, é mais menos isso:
Ou vc faz uma função que verifica se existe uma sessão com o usuário logado, ou vc inclui o código de verificação em cada página que vc n quer q seja acessada diretamente.
Na logica, vc verifica se o usuário inserido no formulário é igual ao do bd, assim como a senha também. Se for true, cria a sessão e redireciona para a página a ser acessada, se for false vc destrói a sessão e redireciona para a página de login.
Espero ter ajudado.
if($userp == $user && $passp == $pass) {
    $_SESSION['user'] = $userp;
                        $_SESSION['pass'] = $passp;
                        header('Location: inserir.php');
                        exit();
                   }else{
                        unset($_SESSION['user']);
                        unset($_SESSION['pass']);
                        header('Location: index.php');
                    exit();

}
Comment: se for `false` quer dizer que ele não possui a sessão, logo é desnecessário remove-la visto que não existe.
Comment: Eu destruiria a sessão, logo que a sessão só é encerrada com o fechamento do browser, outas aplicações podem ter sessões criadas com o mesmo nome e se não for destruída em algum momento pode não redirecionar a página, dessa forma eu tenho certeza que a sessão é encerrada. Mas fica a critério do nosso amigo, destruir a sessão ou não e redirecionar caso os dados sejam falsos.
Comment: Olá Igor, boa noite!
Eu criei um arquivo chamado protecao.php com o código que vc. recomendou, e ficou assim:
``
Comment: Mas Igor, estou recebendo a seguinte mensagem:

**Warning: Cannot modify header information - headers already sent by (output started at /home/buziosne/public_html/admin/painel/index.php:2) in /home/buziosne/public_html/admin/protecao.php on line 6**

Tanto entrando com o login e senha ou direto pela URL.

O login e senha de acesso para teste é: Login - usuario / Senha - 123

Sou muito leigo em php se tu puderes me mostrar onde estou errando ficarei agradecido.

Endereço para acesso ao teste:
(http://www.buziosnegocios.com.br/admin/painel/)

Obrigadão pela sua atenção.
Comment: Amigo, verifique se você iniciou a sessão, lembrado que a sessão deve esta sempre no top da página. Como você vai utilizar o header Location no meio da página, você deve utilizar antes do session_start() o ob_start() que deve ficar antes do session_start();
Comment:
Answer: Olá amigos estou respondendo a minha própria pergunta, porque consegui resolver com a ajuda de um tutorial do YouTube https://www.youtube.com/watch?v=-yUMdFWrPJc (Que gostaria de compartilhar com os amigos), com algumas adaptações para o meu projeto, e vou publicar abaixo os códigos que criei para que o mesmo funcionasse.
Pagina de Login:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php include "../conexao.php"; ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Painel Adm. - Login</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css' />
<link rel="stylesheet" type="text/css" href="css_login/style.css" />

<?php
$logotipo = $_POST['logotipo'];

$query = mysql_query("SELECT * FROM topo");
$res = mysql_fetch_array($query);
?>

<img src="../upload/<?php echo  $res['logotipo'] ;?>" width="auto" height="58" />

<form name="enter" method="post" action="logar.php" enctype="multipart/form-data">
Login: <input id="login" type="text" class="txt bradius" name="login" value="" />
Senha: <input  id="senha" type="password" class="txt bradius" name="senha" value="" />
<input type="submit" class="sb bradius" name="enter" value="Entrar" />
</form>

Página logar.php:
<?php
session_start();
?>
<?php include "../conexao.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Logando Usuário</title>

<?php
$login = $_POST["login"];
$senha = $_POST["senha"];
$sql = mysql_query("SELECT * FROM usuario WHERE login = '$login' and senha = '$senha'") or die(mysql_error());
$row = mysql_num_rows($sql);
if ($row > 0){
$_SESSION["login"]=$_POST["login"];
$_SESSION["senha"]=$_POST["senha"];
    echo "";
}else{
    echo "Login ou Senha do usuário inválido! Tente Novamente!";
    echo "";
}
?>

Página restrito.php:
<?php
session_start();
if(!isset($_SESSION["login"]) || !isset($_SESSION["senha"])){
header("Location: ../index.php");
exit;
}
?>

Página logout.php:
<?php
session_start();
session_destroy();
header("Location: index.php");
?>

Página de acesso ao Painel index.php:
<?php include "../restrito.php"; ?>

<?php include "topo.php"; ?>
<?php include "cont.php"; ?>

Lembrando aos amigos que fiz o include da pagina restrito.php em todas as página que desejo que seja restrita ao usuário com acesso via login e senha, sem condições de acessa-las direto via url.
Agradeço a todos a atenção dispensada ao meu problema, e espero ajudar com essa solução que encontrei para que funcionasse a restrição via acesso direto pela URL.
Abraços à todos.


Why is a path-connected topological space homotopy equivalent to the classifying space of its loop space?

Question: Given a path-connected topological space $X$ (lets say compactly generated; this entire post will be working in the category of compactly generated topological spaces) with a designated point $x$, we can form the loop space $\Omega X$ of pointed morphisms from $S^1$ to $X$. This has the natural structure of a topological group.
Now given a topological group $G$, we can form its classifying space $BG$. I believe that it is true that $X$ is homotopy equivalent to $B\Omega X$; is this true?
I suspect that you could form some model category of topological groups and some model category of connected topological spaces, and show that $\Omega$ and $B$ are a Quillen equivalence. For one thing, I know that $\Omega BG$ is homotopy equivalent to $G$, and I have a feeling that if I could write out the model structures this should become clear. On the other hand I'm not that fluent in model category theory, and I'm also wondering if there's an elementary way to see this.
Comment: Actually, what is the group structure on $\Omega X$? There are no inverses, and the multiplication is not associative (just homotopy-associative.)
Comment: You might look at this question and discussion for inspiration: http://mathoverflow.net/questions/41525/how-should-i-think-about-delooping
Comment: Oh, I was working with it having the structure of the group under homotopy (in which case reversing the path is an inverse) but I also thought it was an actual group (which it clearly is not.) In this case, there's still a classifying space (from Segal's paper "Categories and Cohomology Theories") but I didn't want to cite that...

Also the linked thread is very helpful, thanks! (Especially the comment of Tom Goodwillie which states that there are multiple possible deloopings, which shows that (perhaps some variant) of my question is false, as my question implies all deloopings are equivalent.
Comment: No model cats needed: Look at the path-loop fibration. You may need to think about what you *mean* by $B\Omega X$ since $\Omega X$ is not a "group," and that's a whole story. Goodwillie's comment is also unrelated: There is one way to deloop something with, say, and $E_1$-structure. The "different ways" he's talking about correspond to choosing different $E_1$-structures. (An $E_1$-structure is like a homotopy associative multiplication on steroids, and is provably equiv to being a loopspace, namely the loopspace of the delooping!)
Comment: google two-sided bar construction, infinite loop spaces, operads, ... it's a whole new world. enjoy!
Answer: This question is answered by Sam Nolen in mathoverflow.