Help with Kanto mount, 55" tv, and 24" between studs

Question: I want to mount my 55" tv (39.2 lbs) on a Kanto mount (https://web.archive.org/web/20170317095158/http://www.kantoliving.com/product/pdx680/) but the studs are spaced 24" apart. I've been doing some reading and from what I've gathered I'd have to use a 3/4" plywood to reinforce the gap and tv. Any suggestions on what I need?
Correction, the wall mount is the Kanto PDX650 (https://web.archive.org/web/20170418215212/http://kantoliving.com:80/product/pdx650 which is made for studs with 16") spacing not the PDX680. Sorry.
Comment: I just remounted a similar tv with a similar mount at my office. Four 3/16" lag screws held it in place, rock solid. I have no concerns using that particular mount alone with your tv, even at 24" centers (it's rated for 125 lbs., after all). I'd try that before making things needlessly complicated.
Comment: Kanto claims that it can be used on studs up to 24" apart (assuming you can position it to hit 2 studs). However, full extension of a mount of this type puts a lot of strain on the mounting support. I would reinforce with plywood or at least a 1x6 board bolted into studs.
Answer: It is not uncommon to hang one studs that are 24" apart so.  I have a 60" TV hung on 24" studs.   As long as the steel mount is spanned across two studs and securely fastened to the studs (with lag bolts), you'll be fine.
Edit:
Well, now that your answer says the specs are only for 16" studs (and after reading the specs, it shows the wall plate is only 21"), then, NO, this won't work obviously.  You'll need a different wall plate that can accomodate the span of two studs.  I would not attempt to make this work unless you get crafty with a welder (it isn't worth it, buy a different plate).  You need it spanned across two studs, with very strong fasteners.  Considering this is a swivel out mount, it will put great stress on your fasteners, and they need to be lag bolts into studs.


MySql view records last 24 hour records

Question: I have a schedule run at 12:00. I need to see all records for the last 24 hour.
I use this where clause;
Where DATE(Date_field) = DATE(NOW() - INTERVAL 24 HOUR)

Now I see only the records from the last 12 hour
Where DATE(Date_field) >= DATE(NOW() - INTERVAL 24 HOUR)

Now I see the records from the last 12 hour and the day before.
I've also tried
Where DATE(Date_field) = DATE(NOW() - INTERVAL 1 DAY)

now I see all records of the past day and not those records in this day to 12:hour
Where DATE(Date_field) = DATE(NOW() - INTERVAL 0 DAY)

I see only records of the last 12 hour
Who can help me to see records of the last 24 hour.
Thanks
Answer: Don't convert your datetime in a simple date without time
where Date_field >= NOW() - INTERVAL 24 HOUR

MySql view records last 24 hour records


Do characters from the World of Warcraft: Starter Edition carry over to the full game?

Question: I want to start getting some characters to level 20 before I become a member, so I was going to play the free version for a while. But, can I use the characters I created in the free version when I become a member?
Answer: Yes. They do in fact carry over. If your subscription lapses your account reverts to a starter account, and you can play characters at or below level 20. Here's some more official information: https://us.battle.net/support/en/article/world-of-warcraft-starter-edition


What fixing to use for hanging heavy structure to wall

Question: I'm building an enclosed storage space above a staircase. The base would be fixed on three sides: on banister on one side (fixed to the floor, can take pretty much any load) and two walls on two more sides.  The walls are solid, combination of air brick and silicon brick. The base is made from an 18 mm thick plywood, and is approximately 80x80 cm. I expect the base plus whatever I'd store on it to be around 20-25 kg weight.
To fix it to the two walls, I'm planning to use L-shaped angle profile along the whole width, essentially creating the support for the base to lay on. The base will then be attached to this support using M6 bolts with nuts.  But what fixing should I use to attach the angle profile to the wall?
Again, these are two lengths of L-angle profile, about 80 cm in length each. Together with a fixed support on the third side, they need to support up to 25 kg in weight. My first thought was just usual wall plugs and screws, at least 30 mm into the wall, 4 along each of the two lengths.  Would this be sufficient?
Comment: Or this? [Mounting heavy shelves to brick wall](https://diy.stackexchange.com/questions/149635/mounting-heavy-shelves-to-brick-wall)
Comment: Or this? [How can I securely hang a very heavy object on wall made of hollow bricks?](https://diy.stackexchange.com/questions/164514/how-can-i-securely-hang-a-very-heavy-object-on-wall-made-of-hollow-bricks)
Comment: Or this? [Best way to mount a floating L-shaped desk to a brick wall](https://diy.stackexchange.com/questions/76772/best-way-to-mount-a-floating-l-shaped-desk-to-a-brick-wall)
Comment: [More yet](https://www.google.com/search?q=site%3Adiy.stackexchange.com+mount+to+brick+wall)
Answer: Wall plugs into brick?  That seems entirely reasonable for a 40kg load.
If the load might be higher (eg: children) then brick screws, expanding bolts, or glue in anchors might be better.


php form stay on page with div showing close form

Question: I have the following form that works except for the success message staying on the same page.
I keep racking my brain, but at this point it is mush.
**Problem
I need to have the form close and show the 'success' DIV when the form is submitted.
Right now the only thing I can do is get it to go to a thanks.php page by using a header.
all the code is here at jsfiddle: http://jsfiddle.net/webs4me/hyArd/1/
except the send.hello.php which is below: - Thanks
   <?php
   // Clean up the input values
   foreach($_POST as $key => $value) {
     if(ini_get('magic_quotes_gpc'))
       $_POST[$key] = stripslashes($_POST[$key]);

     $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
   }

   // Honeypot don't send - THIS WILL BE HIDDEN LATER
   if(!empty($_POST["confirm_email"])) {
   header("location:spam.php");exit;
   }

   // Assign the input values to variables for easy reference
   $name = $_POST["name"];
   $email = $_POST["email"];
   $confirm = $_POST["confirm_email"];
   $phone = $_POST["phone"];
   $message = $_POST["message"];

   // Send the email *********** enter your email address and message info
   $to = "email@example.com";
   $subject = "Website message: $name";
   $message = "From:\n$name\n\nEmail:\n$email\n\nPhone:\n$phone\n\nMessage:\n$message";
   $headers = "From: $email";

   mail($to, $subject, $message, $headers);

   header('location: thanks.php');

   ?>

Comment: You don't want to reload the page with the form? then you need ajax
Comment: do you have a suggestion code for AJAX. I have been looking.
Comment: I also did not know if there was a way to echo the response and die/exit the form showing the div. kind of a hide/show onlclick but onsubmit instead
Comment: Also your `#success{display:none}` is never changing the display, and.. what should `thanks.php` display?
Comment: @porfiriopartida I only had the display to hide the remarks. The thanks.php is just text that says, Thanks for your message!
Answer: Since you're already using JQuery, use $.POST:
http://api.jquery.com/jQuery.post/
$.ajax({
    type: "POST",
    url: url,
    data: data,
    success: success,
    dataType: dataType
});

data would be constructed from the values of all the form's inputs.
url would be the hello.php page
You'd add either an onsubmit function to the form, or take out the submit button and add a regular input button with an onclick call to a function that builds data and calls $.POST
Comment: @webs4me It does work, but you're probably missing a few pieces. 1. You need a "success" function that handles what to do on success, 2. Your "hello.php" page needs to output something that tells of success or failure (prferably a JSON object), 3. You need to set "dataType". Please read the JQuery url I provided, and see this example: http://www.w3schools.com/php/php_ajax_database.asp I am sorry, but I will not write all the code for you. You need to do some learning and adapt the code to your situation so you can "learn to fish."
Comment: @porfiriopartida if you're using Ajax, you no longer need to redirect, so there is no thanks.php anymore.
Comment: @Don Im not using a database. Just PHP Server
Comment: @Don thanks. i am not asking you to write it for me, but a good explaination would help someone learn to catch the fish. you left out the database which is why i did not understand it. i am not using a database. thanks for sending the link. i understand what you were trying to achieve by your answer.
Comment: @webs4me Don's code should be placed in a submit call of the form, url should be send.hello.php and data (you must see the doc) could be a serialized form, then you have to call a function on success (see ajax doc) and there you will call the unhide success...
Comment: If you use ajax then there is no point in this case to call spam or thanks.php that's true, that's why I asked what about thanks.php we don't know if his code has to do something there (most likely not). Then he could change it for a response status but we don't know that, we only know that he wants to call a thanks.php and render its message?


Getting rid of site created via the developer tools

Question: I was snooping around the dev tools and noticed an option to create a "Debug Arena". I decided to try creating one. I immediately got an error though that it hadn't been setup correctly, but it added a location on the map called "Site".
I realized that I'm on permadeath and didn't know what would happen if I visited it, so I never went near it. It's stuck on my map now though, and also creates an error every time I start the game. See the screenshot for the debug logs, and a picture of the "Site" (with my settlement to the left of it).

I've searched all over the dev tools to find an option to delete map sites, but haven't found anything.
How can I remove the site?
Answer: I found a reddit post (thanks r/vividflash) on how to do it and decided to document it a little more thoroughly.

I ended up editing the save file. My file was found at
C:\user\%username%\AppData\LocalLow\Ludeon Studios\RimWorld by Ludeon Studios\Saves

Then I found the .rws file with my save name, and made a backup copy of it.
I opened the save using Notepad++ as noted in the Reddit post. My save was 11mb, so the built-in Notepad didn't have a chance of opening it.
I searched for "arena" and found multiple nodes in the tree that looked like:

    <def>Debug_Arena</def>
    <ID>386</ID>
    <tile>26840</tile>
    <faction>null</faction>
    <creationGameTicks>17762348</creationGameTicks>

I had accidentally created other weird things on the map as well when I was messing around, and they all seemed to be referred to as "Debug_Arena"s. I deleted them all, loaded up the save, and all the weird map sites had disappeared.


how to extract a value from json string

Question: I have a source table as like below

on top this table there is a business logic implemented as like below
select id, TO_JSON_STRING(ARRAY_AGG(STRUCT(name,salary,deptno))) as d_list
from `project.dataset.sample_tab`
group by 1

Now after applying business logic the table look like below

From the above table i want to extract only salary column data for additional calculations. how we can extract ? please suggest me
I tried JSON_EXTRACT(d_list,"$.salary") but it is giving me null values
Answer: Use below
select id, json_extract(trim(d_list, '[]'),"$.salary") salary
from (
  select id, TO_JSON_STRING(ARRAY_AGG(STRUCT(name,salary,deptno))) as d_list
  from `project.dataset.sample_tab`
  group by 1
)

if applied to sample data in your question - output is

how to extract a value from json string


How to find x so that $\|A x\| = \|A\| \|x\|$ holds

Question: The subbordinance property of matrix-vector multiplication states that
$\|A x\| \le \|A\| \|x\|$
where $\|x\|$ is the norm of vector $x$ and $\|A\|$ is the induced norm of matrix $A$.
Many textbooks provide the proof of this result in theory, but none gives a specific way to find such an $x$ that satisfies the equality $\|Ax\| = \|A\|\|x\|$. For example, given a simple 2x2 matrix $A$, how would one find a 2-D vector $x$ that satisfies the equality?
I am actually interested in the significance of such vector $x$, in addition to its existence in theory.
The Cauchy-Schwarz inequality $|\langle x, y \rangle| \le \|x\|\|y\|$ becomes an equality if vectors $x$ and $y$ are linearly dependent, i.e., $y=cx$, or the angle between $x$ and $y$ is zero. Is there some similar interpretation for $A$ and $x$ that satisfy the equality $\|Ax\|=\|A\|\|x\|$ ?
Comment: Are you interested in some particular classes of matrix norms? Sometimes, this problem can be relatively easy (matrix $p$-norms for $p=1,2,\infty$). I'm afraid that generally applicable algorithms which take simply a matrix and vector norms as the input might not exist. I would start by looking on resources about computing some interesting norms (e.g., [here](http://www.cs.princeton.edu/~aravindv/matrixpqnorms.pdf)). Most of the algorithms actually compute or estimate such $x$'s.
Comment: Probably a bad idea, but might work for small matrices: Write $A \begin{bmatrix}x_1 \\ x_2 \end{bmatrix}$ as a function of $x_1$ and $x_2$, and maximize it with the constraint $\|x\|=1$?
Comment: @angryavian : I think OP wants an explicit algorithm. Diagonalization is explicit enough :) See my answer.
Comment: Sorry about my answer, I made an elementary mistake... -_-
Answer: We have to maximize
$$\|A{\bf x}\|^2=\langle A{\bf x}, A{\bf x}\rangle=\langle A^*A\,{\bf x},{\bf x}\rangle$$
subject to the condition $\|x\|^2=1$. The map $A^*A$ , resp. its matrix $[A^*A]$,  is symmetric positive definite. Therefore there exists an orthonormal basis of ${\mathbb R}^n$ with
$$[A^*A]={\rm diag}(\lambda_1,\lambda_2,\ldots,\lambda_n),\qquad \lambda_1\geq\lambda_2\geq\ldots\geq\lambda_n\geq0\ .$$
Using this basis we have to maximize
$$\sum_{k=1}^n\lambda_k x_k^2$$
subject to the condition $x_1^2+x_2^2+\ldots+x_n^2=1$. The maximum  obviously has the value $\lambda_1$, and is taken, e.g., at the vector ${\bf e}:=(1,0,\ldots,0)$. It follows that
$$\|A{\bf x}\|=\sqrt{\|A{\bf x}\|^2}\leq\sqrt{\lambda_1}\qquad(\|{\bf x}\|=1)\ ;$$
and on the other hand we have $\|A{\bf e}\|=\sqrt{\lambda_1}$.
When $$A=\left[\matrix{a&b\cr c&d\cr}\right]$$ we can write a general unit vector in the form ${\bf x}=(\cos\phi,\sin\phi)$, and then have to maximize
$$\eqalign{\|A{\bf x}\|^2&=(a^2+c^2)\cos^2\phi+2(ab+cd)\cos\phi\sin\phi+(b^2+d^2)\sin^2\phi\cr
&={a^2+c^2+b^2+d^2\over2}+{a^2+c^2-b^2-d^2\over2}\cos(2\phi)+(ab+cd)\sin(2\phi)\ .\cr}$$
A well known formula for the amplitude of a trigonometric binomial then gives
$$\lambda_1={a^2+c^2+b^2+d^2\over2}+{1\over2}\sqrt{(a^2+c^2-b^2-d^2)^2+4(ab+cd)^2}\ .$$
Comment: This is still only with respect to the operator norm induced by the Hilbert space norm on $\mathbb C^n$.
Comment: @user161825 I may be mistaken, but I'm pretty sure that's exactly what the OP wants, even if s/he doesn't make the structure of the underlying space explicit.
Answer: In general, we have $\|A\|^2=\|A^* A\|$. Furthermore, $A^*A\geq 0$, so there is a unit vector $x$ such that
$$\|Ax\|^2=\langle x,A ^*Ax\rangle=\|A^*A\|=\|A\|^2.$$
In fact, any unit eigenvector $x$ of $A^*A$ corresponding to the largest eigenvalue of $A^*A$ will work.
To clarify, this is with respect to the operator norm induced by the 'standard' norm on $\mathbb C^n$ which makes that space into a Hilbert space (in order that we may easily speak of the adjoint of an operator).
Comment: @triple_sec Yes, but it depends on what the vector norm is. *A* vector norm induces *the* operator norm; therefore, if one does not fix any vector norm, it can be referred to as *an* operator norm. That's not just play with words as what can be true for one (matrix) operator norm, does not need to hold for another. What I say is that this answer is correct *only if* the underlying norm is Euclidean (therefore, for the spectral matrix norm).
Comment: Take
$$A=\left(\begin{matrix}1&2\\3&4\end{matrix}\right)$$
Then $\|A\|^{2}_{1} = 36$ but $\|A^* A\|_{1} = 34$. Are you sure that in general it holds $\|A\|^2=\|A^* A\|$?
Comment: Yes, with respect to the operator norm.
Comment: $\|A\|_1$ is also an operator norm, there is no **the** one and only operator norm. This is true only for the spectral norm.
Comment: @AlgebraicPavel AFAIK, when one talks about "the" operator norm of a matrix $\mathbf A$ (or, in general, any continuous linear operator from one vector space to another), its customary interpretation is $$\|\mathbf A\|\equiv\sup\{\|\mathbf A\mathbf x\|\,|\,\|\mathbf x\|\leq1\}.$$ However, you are right in the sense that for a finite-dimensional vector space, all norms on its dual space are equivalent.
Comment: @triple_sec I think the confusion stems from considering different norms on the space $\mathbb C^n$ to begin with. I'm so used to using the 'natural' Hilbert space structure that nothing else occurred to me.
Comment: @AlgebraicPavel You're right, the OP doesn't state explicitly the norm structure of the underlying vector space (or what this space actually _is_ in the first place), but this vagueness nevertheless doesn't prevent me from being almost sure that s/he means $\mathbb R^n$ or $\mathbb C^n$ with the Euclidean norm. If this is the case, then the standard dual-space operator norm seems to me the most natural default choice when we're talking about matrix norms.
Comment: thank you, @AlgebraicPavel, for restoring some sanity into my brain!
Answer: Thanks to everyone who contributed to this discussion. Here is what I got:
Consider
||Ax||^2=<(Ax),(Ax)>=x^*(A^*A)x
if x is the eigenvector corresponding to the greatest eigenvalue of A^*A, which is the spectrum norm ||A||_2 squared, i.e., (A^*A) x=||A||^2 x, then the above becomes
||Ax||^2=x^*||A||^2 x=||A||^2 =(||A|| ||x||)^2
i.e.,
||Ax||=||A|| ||x||
However, this result is only valid for the spectrum norm ||A||_2, the greatest singular value of A (square root of the greatest eigenvalue of A^*A). It would be nice to know how to find such an x for the equality to hold for other forms of norm of A, such as ||A||_1 and ||A||_int, if such methods exist.
Comment: If you have a look on the proof of how $\|A\|_1$ and $\|A\|_{\infty}$ are equated to certain max over row/column sums, you will see how to obtain these $x$'s for these norms as well. It is even easier than for the spectral norm.
Answer: For the $2$-norm, pick $x$ to be a singular vector corresponding to the largest singular value of $A$.
The SVD is visualized in this picture, which illustrates the fact that $A$ maps a circle to an ellipse (or a sphere to an ellipsoid).
The singular values and singular vectors of $A$ satisfy:
\begin{equation*}
A v_i = \sigma_i u_i.
\end{equation*}
The picture makes it clear that the $2$-norm of $A$ is $\sigma_1$, the largest singular value of $A$.
So
\begin{align*}
\| A v_1 \|_2 &= \| \sigma_1 u_1 \|_2 \\
&= \sigma_1 \\
&= \|A\|_2 \\
&= \|A \|_2 \|v_1\|_2.
\end{align*}
(Note that the singular vectors are all unit vectors.)
This is equivalent to some of the other answers, which don't mention the SVD explicitly.


comparing fairness in single processor vs multiprocessor

Question: The guarded-command looping construct
do
Condition ⇒ Command
...
Condition ⇒ Command
od

involves nondeterministic choice, as explained in the text. An important theoretical concept related to potentially nonterminating nondeterministic computation
is fairness. If a loop repeats indefinitely, then a fair nondeterministic choice must
eventually select each command whose guard is true. For example, in the loop
do
true ⇒ x := x+1
true ⇒ x := x-1
od

both commands have guards that are always true. It would be unfair to execute x := x+1 repeatedly without ever executing x := x-1.
Most language implementations are
designed to provide fairness, usually by providing a bounded form. For example,
if there are n guarded commands, then the implementation may guarantee that
each enabled command will be executed at least once in every 2n or 3n times
through the loop.
Because the number 2n or 3n is implementation dependent,
though, programmers should assume only that each command with a true guard
will eventually be executed.
Is fairness easier to provide on a single-processor language implementation
or on a multiprocessor?
Comment: We require you to provide proper attribution for the original source of all copied material: https://stackoverflow.com/help/referencing
Answer: Most languages have a serial model of execution, like machine code, not executing each statement in parallel with arbitrary ratios of executions.  For example in C,
  for (int i=0; i<10 ; i++){
     if (true) puts("hello");
     if (true) puts("world");
  }

You'll always get output like
hello
world
hello
world

in that order.

Fair (or at least non-starving) thread-level parallelism is pretty easy on single or multi-core machines, with pre-emptive multi-tasking.  Most languages with a thread model are designed around pre-emptive thread scheduling, where one thread running an infinite loop (even with no system calls) won't starve other threads.
Multi-core is harder to implement a correct OS for (e.g. you need locking, not just disabling interrupts), but does allow more threads to be running at once.


How do you know why the AI is sour at you?

Question: I was playing as Lich King V and encountered the following enemy Warlocks:

Ash-Haar the Wisest
Rjakh
Miralibus the Hat

While Miralibus stayed friendly with me most of the time and issued only one small (100) gold request, Rjakh immediatly declared War by demanding all of my Gold which I was unable to fullfill obviously. Also Ash-Haar was declaring War pretty fast on me and both disliked my by "90" (actualy value in the game) without me killing something from them or entering their Territory.
So how is determined if an AI declares War or dislikes you? Is it predetermined by race?
Comment: Just what we need, racist AIs.
Comment: It seems in the original release version of the game the AI is very aggressive, with war being almost unavoidable - some reviews on the net mentions this problem/feature. Maybe it will change in future patches?
Answer: By opening the diplomacy screen and mousing over the portrait of an AI Great Mage, you can get a numerical value of their attitude towards you, along with a list of the factors that sum up to this attitude.
For example, "Envy of the Leader" is -15 attitude, and current war is -100 attitude. "Religion" is a factor somehow, but I'm seeing a positive value for that vis a vis a Great Mage with perfect indifference towards every god.
I'm not sure how the demand system works, but my guess is AI will issue demands if their attitude is negative.


How do I select GTK icon theme?

Question: I run Lubuntu 13.10 with the window manager Blackbox. I have set the GTK theme to Lubuntu-default in settings.ini:
$ cat ~/.config/gtk-3.0/settings.ini
[Settings]
gtk-theme-name = Lubuntu-default

This makes GTK3 applications use the Box icon theme; in GPicView, for instance, the toolbar icons look like this:

In Gedit, however, the toolbar icons look like this:

How do I make Gedit use the Box icon theme?
Answer: Set gtk-icon-theme-name to lubuntu in ~/.gtkrc-2.0 (for GTK 2 applications) and in ~/.config/gtk-3.0/settings.ini (for GTK 3 applications). Here is the content of my GTK config files:
$ cat ~/.gtkrc-2.0
include "/usr/share/themes/Lubuntu-default/gtk-2.0/gtkrc"
gtk-font-name = "DejaVu Sans 10"
gtk-icon-theme-name = "lubuntu"

$ cat ~/.config/gtk-3.0/settings.ini
[Settings]
gtk-theme-name = Lubuntu-default
gtk-icon-theme-name = lubuntu

In /usr/share/themes/Lubuntu-default/gtk-2.0/gtkrc the property gtk-icon-theme-name is set to Lubuntu (capitalized) which must be a bug because there is no such icon theme installed on my system.

How do I select GTK icon theme?


Estimate Area Under Graph

Question: Estimate the area under the graph of f(x) = 6/x from x = 1 to x = 7 using 6 approximating rectangles and right endpoints.
I keep getting 1 for delta x because (B-A)/N, and then I get values 1,3,6,10,15,21. Then I plug each of those into f(x), add them all together, but I'm not getting the correct answer. Could someone let me know what I'm doing wrong?
Thanks!
Answer: $\Delta x=1$ is correct.  Then you need to multiply by $f(x)$ at some point in the interval to get the area of the rectangle.  The third rectangle ranges from $x=3$ to $x=4$, so $f(x)$ ranges from $6/3=2$ to $6/4=1.5$.  Certainly it should not be $6$.
Comment: It must be the x values I'm getting wrong. I get the x values and plug each into f(x), then add them all together.
Comment: The $x$ values are just $1,2,3,4,5,6,7$, where the rectangles range from one to the one above.  Maybe you can explain where $21$ came from?
Comment: I honestly don't know. Thank you for your help
Comment: @Shelby: You are, indeed, getting the $x$-values wrong. Note that it says "using...right endpoints." What they mean by that is that for the function value $f(x)$ on the interval $\bigl[A+k\Delta x,A+(k+1)\Delta x\bigr],$ you should "plug in" $x=A+(k+1)\Delta x.$ For example, on the interval $[5,6],$ you should plug in $6.$
Comment: Is 6 correct for the area of the first rectangle?
Comment: Yes if you use $f(x)$ values from the left side of the rectangle.  I missed the "right endpoints", so you should use $2$ for the $x$ value of the first rectangle-it ranges from $1$ to $2$.
Comment: Thanks! That helped a lot!

Estimate Area Under Graph


ASP.NET Token-based authorization is too long

Question: I have ASP.NET REST API service and it works pretty fast and fine, except of authorization, I'm using standart Token auth, based on Owin.Security, here is what it looks like:
<code>    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(10),
            AllowInsecureHttp = true,

        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);
</code>
}
I didn't change anything, it is from template project and it works fine, except of time. It tooks about a 30 seconds to get back a bearer token from server.
I'm pretty new to ASP.NET development and I have no idea why it is so long, I have 10 users and 3 roles in my database, and I'm sure it can work faster, but don't know how
other rest request (POST, GET) works fast and fine, it takes 30 seconds only for /Token request
well, I've republished my server solution and now it takes randomly from 3 to 30 seconds to get auth token, it is pretty strange behavior, isn't it?
Comment: @Greag.Deay Facing same issue, Authentication tooks more then 5 secords for log in. Did you find any way to resolve this issue ?
Comment: @gauravbhavsar actually, I don't remember now, I saved auth token to local storage, so user doesn't need to do login everytime, and if I switch deploy mode from debug to release it goes a bit faster, but since ASP 5.0 released, I guess things may have been changed
Comment: Can you look at the fiddler trace to see request to which Url(s) is taking 30 seconds or if this is distributed among different requests?
Comment: @ezile nono, it is just for token request myazuresite.com/Token
other works  fast and fine
Answer: 1) If you requesting token right after application startup, then some application initialization logic is being occured before the first execution of any controller method.
2) If you are using remote SQL server instance, this can cause long request processing. Try local profiling using local SQL server.


How to make a function of MAE and RAE without using library(Metrics)?

Question: My goal is to create functions of Mean Absolute Error (MAE) and Relative Absolute Error (RAE) without using any kind of library, like library(Metrics).
I try to input a formula inside a function for both MAE and RAE
mae <- function(a, b)
{
    mean(abs(a, b))
}

rae <- function(a, b)
{
    abs(a,b )
}

However, both function provide different answer compare to the function below,
library(Metrics)
stats <- function(a,b)
    {
        mae <- mae(a,b)
        rae <- rmse(a,b)
    }

Comment: I think it's a conceptual issue. Look at the definition of [MAE](https://en.wikipedia.org/wiki/Mean_absolute_error) for instance. Your `mae` function uses `abs` but doesn't really do any subtraction.
Comment: @NelsonGon. The input is already edited. Thank You.
Comment: See `Metrics`' implementation : `Metrics::rae` and compare it to theory. Not sure why your functions take one input?
Answer: Your function is wrong. You can use the following function to calculate mae and rae without any package
x <- c(1.1, 1.9, 3.0, 4.4, 5.0, 5.6)
y <- c(0.9, 1.8, 2.5, 4.5, 5.0, 6.2)

mae1 <- function(x,y)
  {
  mean(abs(x-y))
  }

mae1(x, y)
#> [1] 0.25

rae1 <- function(x,y)
  {
  sum(abs(x-y))/sum(abs(x - mean(x)))
  }

rae1(x,y)
#> [1] 0.1666667

library(Metrics)
#> Warning: package 'Metrics' was built under R version 3.6.2

mae(x, y)
#> [1] 0.25
rae(x,y)
#> [1] 0.1666667

Created on 2019-12-27 by the reprex package (v0.3.0)
It is giving same output as that of Metrics package.
Update
If your data contains NAs then the above functions, as well as the functions of package Matrics, will fail. Under such situation use the following code
x <- c(1.1, 1.9, 3.0, 4.4, 5.0, 5.6, NA)
y <- c(0.9, 1.8, 2.5, 4.5, 5.0, 6.2, 2)

mae1 <- function(x,y, na.rm=TRUE)
  {
  mean(abs(x-y), na.rm=na.rm)
  }

mae1(x, y, na.rm=TRUE)
#> [1] 0.25

rae1 <- function(x,y, na.rm=TRUE)
  {
  sum(abs(x-y), na.rm=na.rm)/sum(abs(x - mean(x, na.rm=na.rm)), na.rm=na.rm)
  }

rae1(x,y, na.rm=TRUE)
#> [1] 0.1666667

library(Metrics)
#> Warning: package 'Metrics' was built under R version 3.6.2

mae(x, y)
#> [1] NA
rae(x,y)
#> [1] NA

Created on 2019-12-27 by the reprex package (v0.3.0)
Comment: Now you try with some data provided in my answer. It is giving same output as that of `Metrics` package.
Comment: In order to avoid conflict between `Metrics` package functions and newly created functions, I have defined the `mae1` and `rae1`.
Comment: @HYDR0GEN Now see my update for datasets containing NAs.
Comment: I tried the function, yet it provides different answer compare to the function with library(Metrics).


How to copy string char by char in c?

Question: I have a chunk of memory I'm declaring on the heap.
char *str;
str = (char *)malloc(sizeof(char) * 10);

I have a const string.
const char *name = "chase";

Because *name is shorter than 10 I need to fill str with chase plus 5 spaces.
I've tried to loop and set str[i] = name[i] but there's something I'm not matching up because I cannot assign spaces to the additional chars. This was where I was going, just trying to fill str with all spaces to get started
int i;
for (i = 0; i < 10; i++)
{
    strcpy(str[i], ' ');
    printf("char: %c\n", str[i]);
}

Comment: `strcpy()` is for you.
Comment: Going by what you write, you should fill str with the name, *four* spaces and terminating `'\0'` byte. Or if you want 10 actual chars, then make the array length 11, so you have room for the `'\0'`.
Comment: Show some actual code.
Answer: As the others pointed out, you need
 //malloc casting is (arguably) bad
 str = malloc(sizeof(char) * 11);

and then, just do
 snprintf(str, 11, "%10s", name);

Using snprintf() instead of sprintf() will prevent overflow, and %10swill pad your resulting string as you want.
http://www.cplusplus.com/reference/cstdio/snprintf/
Answer: If you want str to have 10 characters and still be a C-string, you need to '\0' terminate it.  You can do this by mallocing str to a length of 11:
str = malloc(11);

Note there's no need to cast the return pointer of malloc.  Also, sizeof(char) is always 1 so there's no need to multiply that by the number of chars that you want.
After you've malloc as much memory as you need you can use memset to set all the chars to ' ' (the space character) except the last element.  The last element needs to be '\0':
memset(str, ' ', 10);
str[10] = '\0';

Now, use memcpy to copy your const C-string to str:
memcpy(str, name, strlen(name));

Answer: easy to use snprintf like this
#include <stdio.h>
#include <stdlib.h>

int main(){
    char *str;
    str = (char *)malloc(sizeof(char)*10+1);//+1 for '\0'
    const char *name = "chase";

    snprintf(str, 11, "%-*s", 10, name);//11 is out buffer size
    printf(" 1234567890\n");
    printf("<%s>\n", str);
    return 0;
}

How to copy string char by char in c?


Multinomial Logistic regression, no graphical display using ggplot2

Question: I have the following data obtained from a survey among women. I ran some commands and obtained the coefficients, p value and relative risk as I followed the guidelines displayed by [http://www.ats.ucla.edu/stat/r/dae/mlogit.htm]
I appreciate them.
I came with the following commands
However, I could not get graphs displayed.
Can someone help me out please?
Thanks.
Here is the data
age:32  39  40  35  55  30  60  55  28  25  35  28  30  50  25  35  47  38  54  38  54  48  52  48  41  51  43  49  51  63  39  64  38  29  36  44  57  28  46  51  22  60  56  55  41  35  30  60  68  30  36  25  45  50  32  43  52  55  45  58  53  51  50  52  80  67  48  38  32  52  35  60  51  34  46  38  35  28  80  48  91  40  45  40  58  40  45  37  38  25  58  53  42  60  70  68  62  53  53  66  40  39  35  32  25  40  40  45  51  48  58  44  47  52  57  35  57  92  88  87  43  44  40  47  41  52  40  42  49  40  37  40  38  30  44  38  39  32  41  38  42  40  29  26  38  31  43  38  36  32  28  28  34  37  32  40  39  31  42  38  38  36
rel:Chris   Chris   Chris   Chris   Trad    Islam   Trad    Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Islam   Chris   Chris   Chris   Chris   Chris   Islam   Chris   Trad    Chris   Chris   Islam   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Islam   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Islam   Chris   Chris   Chris   Chris   Chris   Islam   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Trad    Chris   Chris   Chris   Chris   Trad    Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Trad    Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Chris   Trad    Trad    Chris   Chris   Chris   Chris   Chris
pet:Three   Three   Two Three   Three   One Two One Three   One Two Three   Three   Three   Two Three   Three   Three   Three   Three   Three   Three   One Three   Three   Three   Three   Three   Three   Two Two Two Three   Three   Three   Two Three   Three   Three   Three   One One Three   Three   Three   One Three   Three   One One Three   Three   One One Three   Three   Three   Three   Two Three   Three   Three   Three   Two One One Two Two One Two One One Two One One One Two One Three   One Two One Two Two Three   One Two Two Two Two Two Two Three   Two Two Two Two Two One One Three   One Three   Three   Three   Three   One Three   Three   Two Three   Three   Three   Three   Three   One Three   Two One Two Three   Three   Three   Two Two One Three   Two Three   Two Three   Two Three   Two Three   Three   Three   Three   Two Three   Two Three   Three   Two Two Three   Three   Two Three   Three   Three   Three   Three   Three   Three   Three   Two Three   Three   Three   Three   Three
Sec=read.table("Second.txt", header=TRUE)
Sec
attach(Sec)
library(nnet)
library(ggplot2)
library(reshape2)
m1 <- multinom(pet ~ age+rel, data = Sec)
summary(m1)
Relrisk=exp(coef(m1))
Relrisk
z <- summary(m1)$coefficients/summary(m1)$standard.errors
z
p <- (1 - pnorm(abs(z), 0, 1))*2
p
 frame=data.frame(age=rep(seq(22,92,by=0.434),3),rel=rep(c("Chris","Islam","Trad"),each=54))
frame
attach(frame)
pred=cbind(frame,predict(m1,newdata=frame,type="probs", se= TRUE))
pred

Preprobmelt=melt(pred,id.vars=c("rel","age"),value.name="Probability")
Preprobmelt

Graph=ggplot(Preprobmelt,aes(x = age,y=Probability, colour=rel,group=age))

geom_line()

facet_grid(variable~ .,scales = "free")

Graph

No lines displayed
Comment: Here are a few tips for the [next time](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) you want to post a well formed question.
Answer: I don't see the necessary plus signs for constructing a ggplot object properly. It should be:
 Graph=ggplot(Preprobmelt,aes(x = age,y=Probability, colour=rel,group=age)) +
  geom_line() +
  facet_grid(variable~ .,scales = "free")

Note carefully how three things are being added together with plus (+) signs.
You should probably also explicitly print ggplot objects in a script:
 print(Graph)

Answer: Just try this (you don't need the continuous variable 'age' as group in ggplot aes()):
Graph=ggplot(Preprobmelt,aes(x = age,y=Probability, colour=rel)) +
geom_line(lwd=1.2) +
facet_grid(variable~ .,scales = "free")

Graph


Need help making a button play multiple sounds in Adobe Flash

Question: I'm having an issue trying to get my code work for my Adobe Flash project. Basically I'm trying to get a button to play a random sound everytime it's clicked which works but I can't have that same code on the same frame for a different button which is why it gives me this error.
Here is my code:
    import flash.utils.Dictionary;
import flash.events.MouseEvent;

var request:URLRequest = new URLRequest("19103_b.mp3");
var ci_diese:Sound = new Sound();
ci_diese.load(request);

var request_two:URLRequest = new URLRequest("19203_b.mp3");
var d_diese:Sound = new Sound();
d_diese.load(request_two);

var request_three:URLRequest = new URLRequest("19204_b.mp3");
var f_diese:Sound = new Sound();
f_diese.load(request_three);

var play_liste = 0;

var dictSounds = new Dictionary ();

dictSounds[1] = d_diese;
dictSounds[2] = ci_diese;
dictSounds[3] = f_diese;

fireweapon_H3AR.addEventListener (MouseEvent.MOUSE_DOWN, mouseDownHandler);

function mouseDownHandler (event:MouseEvent) : void {
    play_liste = Math.ceil(Math.random () *3);
    dictSounds[play_liste].play ();

ready_H3AR.addEventListener (MouseEvent.MOUSE_DOWN, mouseDownHandler);

function mouseDownHandler (event:MouseEvent) : void {
    play_liste = Math.ceil(Math.random () *3);
    dictSounds[play_liste].play ();}
}
import flash.utils.Dictionary;
import flash.events.MouseEvent;

var request:URLRequest = new URLRequest("Readya.mp3");
var ci_diese2:Sound = new Sound();
ci_diese2.load(request);

var request_two:URLRequest = new URLRequest("Readyb.mp3");
var d_diese2:Sound = new Sound();
d_diese2.load(request_two);

var request_three:URLRequest = new URLRequest("Readyc.mp3");
var f_diese2:Sound = new Sound();
f_diese2.load(request_three);

var play_liste = 0;

var dictSounds = new Dictionary ();

dictSounds[1] = d_diese2;
dictSounds[2] = ci_diese2;
dictSounds[3] = f_diese2;

ready_H3AR.addEventListener (MouseEvent.MOUSE_DOWN, mouseDownHandler);

function mouseDownHandler (event:MouseEvent) : void {
    play_liste = Math.ceil(Math.random () *3);
    dictSounds[play_liste].play ();}
}

Any way to rewrite this to accommodate more than one button? The first half works up until it repeats itself at "import flash." I've been searching everywhere for answers so please help!!
Answer: You should not name two functions or two variables the same, because the last ones are going to overwrite the first ones.
For example
var request:URLRequest = new URLRequest("19103_b.mp3");

is then overwritten
var request:URLRequest = new URLRequest("Readya.mp3");

The same happens with the button ready_H3AR an the function listener mouseDownHandler
By the way, you don't need to import the classes twice:
import flash.utils.Dictionary;
import flash.events.MouseEvent;

Comment: Okay, I guess I'll delete the duplicate functions
Answer: Usually when a task or a block of code is intended to be used many times, it's better to put it in a function to get a simpler and more maintainable code.
So you can do like this :
var sounds:Array = [
    ['01.mp3', '02.mp3', '03.mp3'],     // sounds for the 1st button
    ['04.mp3', '05.mp3', '06.mp3']      // sounds for the 2nd button
];

var sound:Sound,
    sound_channel:SoundChannel = new SoundChannel();

function play_sound(sound_name:String): void
{
    var request:URLRequest = new URLRequest('mp3/' + sound_name);
    sound = new Sound();
    sound.addEventListener(Event.COMPLETE, on_sound_loaded);
    sound.load(request);
}
function on_sound_loaded(e:Event): void
{
    // if you want, you can stop the current playing sound
    // otherwise you don't need the SoundChannel
    sound_channel.stop();
    sound_channel = Sound(e.target).play();
}

button_01.addEventListener(MouseEvent.MOUSE_DOWN, on_press);
button_02.addEventListener(MouseEvent.MOUSE_DOWN, on_press);
function on_press(e:MouseEvent): void
{
    // to get values : 0, 1 or 2
    var random:int = int(Math.random () * sounds[0].length);
    // if it's the 1st button so pick the sound from the 1st sounds array
    if(e.currentTarget.name == 'button_01'){
        play_sound(sounds[0][random]);
    } else {
        play_sound(sounds[1][random]);
    }
}

Hope that can help.
Comment: It definitely did! Thank you! Putting the sounds in the array is what I was looking for.


How to prevent Ctrl + c from killing my node process?

Question: I am trying to use this function for delaying the process from ending right when I am pressing Ctrl + c, but the process stops right away without doing anything.
<code>(() => {
    ['SIGINT', 'SIGTERM', 'SIGQUIT']
        .forEach(signal => process.on(signal, async () => {
            let promise = new Promise((res, rej) => {
                setTimeout(() => res("Now it's done!"), 3000)
            });

            // wait until the promise returns us a value
            let result = await promise;

            // "Now it's done!"
            console.log("=======================YESSSSSSSSSS=======================")

    }));
})();
</code>
Comment: It shouldn't do anything the way it is setup. The process won't remain open if you don't run something on it. To make this easier, what is your goal? Just to note that if you are just trying to run a node process in the background you can use "node myscript.js &", or as a service use pm2 or something similar. There again if there is nothing running the process will terminate (pm2 is useful for running a node server)
Comment: @Caharpuka thanks for your response. But the promise shouldn't be resolved first before closing the process?
Comment: You run the process, it receives no signal, does not create any promise, and ends. There is nothing here to make it wait till it receives a signal. If you want that you would need some timeout keeping it alive indefinitely till the signal is received.
Comment: Can you show me please how to do it?
Answer: <code>const wait = () => setTimeout(wait, 1000); // Loop to keep the process alive

process.on('SIGINT', () => {
        setTimeout(() => {
                /* Code to run before exiting */
                process.exit()
        }, 3000);
});

wait();
</code>
However, this doesn't actually check that everything is finished. Ending a process gracefully if you have some I/O operations happening doesn't involve setting a rough grace period for them to finish, but rather letting them report back somehow when they have finished, using Promise.all() or whatever.


Botfather step-by-step bot (telegram/ruby)

Question: I've really been dragging myself from asking this question here, but after googling forever I feel It's needed. So:
I'm trying to build a bot with a similar structure as the Botfather in telegram. I'd like to enable a step by step configuration for users using my bot. So if I ask "What's your email?" I'd like them to naturally be able to answer that and I'll know what question they answered. And that's the problem, I can't seem to figure out a good structure for knowing which question they answered and what to trigger. All documentation in every bot I've scanned simply use a structure like this:
if message.text == 'london'
  bot.api.send_message(chat_id: message.chat.id, text: 'Correct!')
end

And this is not very beneficial when I don't know what the user will write or if I have duplicated accepted answers for different questions. I've tried using replies and ForceReply etc, but this also creates a weird structure and don't look as clean in the feed as natural messages.
Simply put: How do I know if a message goes together with a question and then trigger something?
Sorry for a somewhat unstructured question, hopefully one of you awesome people have an answer to my issue.
Comment: There are probably better forums for questions such as these since this is unstructured as you note, but why cant question be a variable you are comparing as well, why couldnt a q/a pair be a dictionary? question => answer. You are not limited to one conditional in an if.
Comment: You need a structure to track what question was asked of whom and then later you can compare the answer. You'll need to sketch in some more code.
Comment: If you solved the problem, please edit your question to show your code
Answer: In my bot I'm creating a "TelegramChat" recod in DB and store in "AwaitingReplyTo" field a reference to a "question" and some related information (for example id of an account that need to be updated).
Something like:
def ask_question(question):
  ...
  telegram_chat_record(chat_id).awaiting_reply_to = "question:" + question
  telegram_chat_record.save_to_db()
  ...

def dispatcher(update):
  telegram_chat_record = get_telegram_chat_record(update)
  if telegram_chat_record.awaiting_reply_to == "question:What is your favorite city?":
    check_reply_to_favorite_city(update)
  ...

Comment: This is great! I started building on something similar and this made the cream on the cake. You sir, are awesome! Thanks!


Rest API UPDATE/DELETE - check if resource exists or not?

Question: This is basically best practice question. In my Rest API (that I am currently working on) I have routes matching PUT and DELETE requests on URLs like /resources/{resourceID}. Behind the API lies SQL DB.
In general, executing a DELETE or UPDATE query on non-existing resource ID in SQL databases gives no error, only the affectedRows returns 0.
Now I have a question on how to perform such request properly:

check if the resource with given ID exists prior to UPDATE or DELETE (which involves additional SQL query)
trigger the UPDATE / DELETE query without checking for existence and inspect the result of SQL query and return HTTP 404 in case when affectedRows == 0?

I personally prefer the later one. But I can think of other DBMS (not SQL or not relational) where performing INSERT, UPDATE or DELETE queries may not return any information about affected rows. How to proceed in such cases?
Comment: Take a look here: https://github.com/for-GET/http-decision-diagram
Answer: Once you are performing DELETE and UPDATE operations using the resource ID, I cannot see any problems on checking the number of affected rows. This should be enough to check whether your resource exists or not.
Basically:

For databases which the affected rows can be checked, just perform a DELETE or an UPDATE.
For databases which this feature is not available, perform a query first.
Comment: See my answer do you agree?
Answer: As a user of your API I would expect to get a HTTP 404 for a non-existent resource independent of the used HTTP method.
Me trying to delete /users/ted when I really wanted to delete /users/tod could be a huge problem. Without 404 I would assume everything worked fine and the user I wanted to delete was in fact deleted. When in reality I deleted a non-existing user.
Comment: This is obvious. I am more interested in considering whether to do extra query to find out if the resource exists or rely on the result from DB engine after DELETE / UPDATE on non-existent resource... And how to handle this in case the DB engine does not provide any useful result in this case...
Comment: So your question isn't about the tags api or rest but more database related. As others have pointed out you should try to use the possibilities of your database as much as possible. If not supported first try to select the row before deleting it.
Answer: In the update service I'd return 201 (CREATED) in case the resource isn't there and you want your services to be 'tolerant', otherwise return 404 if you want your clients to strictly adhere to your protocol.
In case of delete, You could return 404 if the client tries to delete a non existing resource, or if you keep track of deleted resources (some services do it, they just flag 'deleted' a resource, e.g. in order to give clients the chance to undo the operation) you could return 409 (CONFLICT) to tell the client that the resource is already deleted.
In case of DBMS that don't give a clue about affected rows, you could query the resource prior to executing the action (be it insert, update or delete). It's a bit of an overkill, but if that's the only way to know about the state of the resource prior to acting on it and you don't expect performance problems, it may be a viable solution.
Answer: I don't prefer to check the number of affected row for updating records cause if the updated values are same as previous values then the number of affected row will be 0 which will result to 404 http status and that is not actually what happened.
I don't know either the solution 1 is perfect. But it seems to work in this case.


Where to install Aldryn-boilerplates?

Question: The question is where should I install Aldryn-boilerplates framework?
I've created virtualenv called env, after that activated it.
But what now? Should I install that framework inside my project directory? Or it is OK to place it in root dir - /home/stp.
Need your advice.
Comment: Python will take care of the installation for you. Simply type `pip install aldryn-boilerplates` once you have activated the virtual environment.
Comment: Thanks alot, I'll try it!
Answer: Use pip inside your virtualenv, for easier dependencies management

Where to install Aldryn-boilerplates?


jQuery Datepicker doesn't response

Question: i'm using this very simple datepicker code from the jQuery UI docs but it doesn't work on my Mac:
<!doctype html>

    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />

    <input type="text" id="date-picker" />

Can anybody tell me why it doesn't work? Thanks in advance!
Comment: You have to include jquery before, also you have two references to jquery js, check: http://jsfiddle.net/bwjb02rf/
Answer: jQuery UI is dependent upon jQuery.
Therefore you need to include the jQuery script before the jQuery UI script:
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />

No need to include jQuery twice either. The above will suffice.
Here is a working example.
Comment: First line is css of jQuery UI.You can load it anywhere.
Comment: But isn't the first line related to jQuery UI?
Comment: The first line is the stylesheet. In this case, its order doesn't effect the scripts (`.js` files) below it.
Answer: You should add jquery before adding jqueryui.
You added jquery twice.Remove one
<!doctype html>

        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />

    <input type="text" id="date-picker" />

Answer: yeahh include jquery before jquery ui
<!doctype html>

    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />

    <input type="text" id="date-picker" />

jQuery Datepicker doesn't response


Generate PDF with iTextSharp - multiple images saved in List - C#

Question: I have an asp.net webform project where I generate a pdf document from data that is saved in a database using iTextSharp. Everything works perfectly, except when I need to generate my images, saved in a List string. I put a breakpoint, I am reading the data, but every time it throws me errors in the part Image.GetInstance(item). If I left it like that, it throws me an error the System.IO.PathTooLongException: 'The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.' I have also tried to convert the item to string, but then it says that the path could not be found. I even tried to convert the whole list to List byte, but I came up with the same errors. My List string in the database looks something like this format:
ImgList: ["904u3jg8orut390jgg","09re8im09mj3895gh","509tgj390h359"].
I tried and googled the errors each and every one of them, but I could not find a solution. I have even tried to enable longpath in Windows, but it did not work for me. If someone could help me, I would be very grateful. Here is my code.
EDIT: I think that the problem is with the splitting and replacing the characters. When I add the string to the list, I am getting an extra quotes and backslash, wrapped in like this "\"... \"". I have tried to trim, to replace the characters but nothing successful. I have tried to change the imgList = imgList.Select(s => s.Replace("\"", string.Empty)).ToList(); with imgList = imgList.Select(s => s.Replace("\\b\"", string.Empty)).ToList(); but it did not work. Any help?
 //getting data from database
 string strList = dt.Rows[0]["imgList"].ToString();
 List<string> imgList = new List<string>(strList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
 imgList = imgList.Select(s => s.Replace("\"", string.Empty)).ToList();
 imgList = imgList.Select(s => s.Replace("[", string.Empty)).ToList();
 imgList = imgList.Select(s => s.Replace("]", string.Empty)).ToList();

//assign the value
pdf.ImageList = imgList;

//using iTextSharp
  foreach (var item in pdf.ImageList)
        {
           if (item.Count() >= 1)
               {
            Image image = Image.GetInstance(item);
           }
         }

Comment: *"those images are ... and converted ToBase64String the byte[]"* - so those images are base64-encoded... consequential you have to bas64-decode the database contents again to get the image byte arrays. Then feed those images byte arrays into `Image.GetInstance`.
Comment: You need to provide more informations.

Errors seems to be clear- path/file name is too long.
To what path you are reffering ?
You didnt share with us a path where You are saving these files.
What is the length of column in the database, in which you hold the image name ?
Comment: It is saved in postgresql as jsonb @bartosz-olchowik
Comment: In what format are the images in the database? Your `string strList = dt.Rows[0]["imgList"].ToString();` makes that database entry a string, whatever it may have been originally...
Comment: @mkl those images are uploaded,  HttpPostedFile in byte[] from Binary Reader and converted ToBase64String the byte[]
Comment: Yes @mkl you were right, I converted the item and it worked great! Thanks!
Comment: Ok, I'll make that an actual answer (in contrast to a mere comment) which you can accept.
Answer: In a comment you mentioned:

those images are uploaded, HttpPostedFile in byte[] from Binary Reader and converted ToBase64String the byte[]

So those images are base64-encoded... consequentially you have to base64-decode the database contents again to get the image byte arrays. Then you can feed those image byte arrays into Image.GetInstance.


PHP/MySQL cell showing info from another recordset

Question: I am creating a PHP/MySQL web site. On one page there is a table which is showing a recordset of users (Recordset1). One of the users field is company (idempresa), where I am storing the id field from the table companies. The table shows the user fields: username, email, company. As you may guess, the cell for the company value shows the company value (idempresa) and not the company name which is part of Recordset2. This the code for the cell:
<code><?php echo $row_Recordset1['idempresa']; ?>
</code>
How could I update the cell content to show the company name?
Comment: I am using Dreamweaver, how can I do this?
Comment: Thank you @nathanhayfield, could you post your comment as answer, so I can accept it?
Answer: Best place would be in your query as a Left Join. Then you will have both record sets in one. Here is a link to an example: w3schools.com/sql/sql_join_left.asp
Comment: Thanks nathan, I have change the sql part of Recordset1 to this: SELECT *
FROM tbusuarios LEFT JOIN tbempresas ON tbusuarios.idempresa=tbempresas.idEmpresa


Null Value not getting stored in database of column type datetime

Question: So here is portion of the code:
if (String.IsNullOrEmpty(strStartDate.ToString()))
{
    myCommand.Parameters.AddWithValue("@job_start_date", DBNull.Value);
}
else
{
    myCommand.Parameters.AddWithValue("@job_start_date", strStartDate);
}

Note: Yes, the column is nullable in the database. It is of type "DateTime"
Yes, the DateTime is declared as nullable in the actual project as well. Looks like this:
public datetime? strStartDate {get; set;}

So the entire function is big but this is the part that I am having trouble with. If the second condition executes, this means that the entered value is a proper value. The result is stored in the database. However, if the first condition is executed, I don't even get an error, it just says "successfully added" which is a modal that is supposed to show after the form is submitted.
In other words, both conditions execute and show no error, however, if the first condition is executed, it does not store anything at all in that whole row. The row does not exist in sql. I am sorry if I have confused anyone but I have been having trouble with this the whole day.
Comment: `strStartDate` is not a string, don't treat it like one.
Comment: Also, recommended reading: https://dba.stackexchange.com/a/195952/1288
Comment: So how can I store the value as null, if nothing is picked in the form? The form has a datetimepicker. Also I made an edit look again. I forgot to add ToString() before
Comment: `if (!strStartDate.HasValue))`
Comment: Wait what is the difference between `if (String.IsNullOrEmpty(strStartDate.ToString()))` and `if (!strStartDate.HasValue))` in this situation?
Comment: sql server 2008 is really old, maybe an update would be i order
Comment: I suspect the problem has to do with the DateTimePicker and how you're transferring that value to `strStartDate`.  If nothing else, what does the debugger show happening?
Comment: if `strStartDate` is `null` then `if (String.IsNullOrEmpty(strStartDate.ToString()))` is going to throw a null reference exception.
Answer: Don't convert datetime to string in if
By default DBType of SqlParameter is String
Use Add overload method instead of AddWithValue
if (strStartDate == null)
{
    myCommand.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@job_start_date",
                        Direction = ParameterDirection.Input,
                        DbType = DbType.DateTime,
                        Value = DBNull.Value
                    });
}
else
{
    myCommand.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@job_start_date",
                        Direction = ParameterDirection.Input,
                        DbType = DbType.DateTime,
                        Value = strStartDate
                    });
}

Done!
Comment: Better yet ax the if/else and just do `Value = (object?)strStartDate ?? DBNull.Value`
Comment: Error is not to set the `null` value. Error is to set `datatype` of that parameter and then set its value.


Timezone getting set wrong in WSL?

Question: Running Ubuntu in WSL2 my clock is getting screwed up somehow. And when I try to set it again using:
sudo dpkg-reconfigure tzdata
It still gets set about an hour behind the real time.
The screenshot shows the real current time in Windows, and also Windows via an RDP connection to the machine running WSL2/Ubuntu.
The purple terminal window is the Ubuntu having trouble.
Not super-great with Linux; any idea what's causing the time to be set wrong?
Comment: I know that Windows sets the hardware clock to local time instead of UTC because it's a barbaric neanderthal.  In dual boot configurations you have to either change how Windows or Ubuntu derives local time, but I was not aware that this is necessary in WSL.  Did you or some application explicitly set the time or adjust time settings in Ubuntu? Because it's possible that messing with it caused the same discrepancy in a dual boot config. You may need to make Ubuntu derive time from local time, or you can configure Windows to derive local time from UTC. https://askubuntu.com/q/169376
Answer: Is there any chance the computer has been in Sleep or Hibernate, or is the WSL machine running in a VM?  That was (at one point) known to cause WSL's "hardware clock" to become out-of-sync with the real/Windows time.
Reference:  This Stack Overflow answer and the related Github issue.
The core issue (at least the Sleep/Hibernate issue) is fixed by the 22.214.171.124 WSL2 kernel release, which you can update to (if you aren't on it already) with wsl --update (in recent Windows releases) or via Windows Update (assuming you have allowed "other Microsoft products" to update as part of it).
However, there may still be clock drift issues, as noted in that Github issue.
If so, try a sudo hwclock -s, and if that doesn't fix it, a wsl --shutdown and restart.
Comment: Sounds like you've hit the nail on the head. I came across this later, which also mentions hibernation being an issue (https://tomssl.com/fixing-clock-drift-in-wsl2-using-windows-terminal). Recently the power went out in a storm, and send that WSL computer into hibernation. I think that probably did it. Currently I used the workaround on his page, but will look into using one from the above as well. thanks!
Comment: As a side note I just checked the WSL kernel version and it's `Kernel version: 184.108.40.206`. Looks like they didn't get it sorted out yet, lol.
Comment: x86_64 Linux 184.108.40.206-microsoft-standard-WSL2 and is still broken
Comment: Using `wsl --update` is a great hotfix for WSL issues. Fixes time-drift and update errors in signed repos. Highly recommend!
Note, if you leave a WSL process—like a VS Code instance—open when the computer sleeps/hibernates that can cause some issues.
Comment: @SentientFlesh `wsl --update` checks for a new release of WSL.  If it finds it, it shuts down (e.g. `wsl --shutdown`, as mentioned in my answer) and installs it.  However, if there's no new WSL update, then `wsl --update` is a no-op as far as I can tell.  I just tested this by setting the date incorrectly in Ubuntu, then running a `wsl --update`, which did not correct the date/time.  Can you provide more info on what behavior you are seeing with `wsl --update`?  Thanks!
Comment: @NotTheDr01ds With incorrect time, ran `wsl --update` in PS and it fixed the time. Ran the command with correct time and got:
```
Checking for updates.
The most recent version of Windows Subsystem for Linux is already installed.
```
Changed WSL time using `sudo date -s "2027-11-11 11:11:11"` and confirmed with `date`.

Ran `wsl --update` in PS again, received the same message as above, but now my WSL time is correct from when before I changed it manually.
Comment: @NotTheDr01ds Ah, I just found out why `wsl --update` seemed to be working. Since I have one remote server I connect to over a VPN that requires the server time to match I have a check in my `.bashrc` that checks to make sure I'm not connected to said server, and if not, run `sudo hwclock -s` to correct the system time if needed. So that little line in my `.bashrc` was making it look like `wsl --update` was working when really it was just WSL performing a check on whether or not it's okay to update the time.

Timezone getting set wrong in WSL?


.each() to toggle class not working

Question: I have a JavaScript .each() function which check the value of my div tag and toggle a css class. I am just checking the value fetched from my db and giving the a particular color.
$(".c").each(function() {
     if ($(this).text() < 4) {
           $(".col").toggleClass("yellow");
     } else if ($(this).text() >= 4 && $(this).text() <=6) {
           $(".col").toggleClass("orange");
     } else if ($(this).text() >= 6 && $(this).text() <=10) {
           $(".col").toggleClass("red");
     }
});

The problem is when I ran the code only the last else if which is the toggleClass("red') runs. And I am only getting one color which in this case is red displayed,don't know why.
My HTML is looped in a php foreach loop:

'.$marks.'

Marks

'.$highest.'

Highest

Like thhe above image I was looking to put my text and number in a same color
Comment: `$(this).closest('.col').toggleClass(...)`  I'm assuming you only want to toggle the col that is the parent of the c.  `$('.col')` is a global lookup and will change them all.
Comment: @Taplar is correct, and additionally .text() is returning the text as a string, and you are comparing it to integers. Even if your string contains a number, the comparison is not going to be what you want. Try using parseInt, i.e. parseInt('5') returns 5 the number.
Comment: @the_hobbes Using a comparison operator against a number forces a conversion of the other operand to a number.
Comment: Also small logical side note, if the first if is false, you know in the first else if that >= 4 will be true.  And like wise for the next else if it will be >= 6, so you could reduce those conditionals a little
Comment: yes, just like in stack overflow we have  answer column for each question. Which turns green when answered. That element contains both the number and text "submittion".I also want to include my H6 into the Color element
Comment: @ScottMarcus true but not if there are any non-numeric characters included. '5a' > 3 is false, parseInt('5a') > 3 is true. However you're right in terms of his current markup.
Answer: Your code sets the class on all the .col elements. to isolate just the one you are matching, you need to use .closest() to look for the closest ancestor that matches your criteria.

$(".c").each(function() {
  if($(this).text() < 4){
    $(this).closest($(".col")).toggleClass("yellow");
  } else if ($(this).text() >= 4 && $(this).text() <=6){
    $(this).closest($(".col")).toggleClass("orange");
  } else if ($(this).text() >= 6 && $(this).text() <=10){
    $(this).closest($(".col")).toggleClass("red");
  }
});
.col { width: 5em; text-align:center; padding:1em; margin:5px; float:left; }
.yellow { background-color:yellow; }
.orange { background-color:orange; }
.red { background-color:red; }
h4, h6 { margin:0; }

4

Marks

7

Highest

2

Highest

Answer: You are setting all .col elements. Change to this:

$(".c").each(function() {
     if($(this).text() < 4){
           $(this).parent().toggleClass("blue");
     } else if ($(this).text() >= 4 && $(this).text() <=6) {
           $(this).parent().toggleClass("orange");
     } else if ($(this).text() >= 6 && $(this).text() <=10) {
           $(this).parent().toggleClass("red");
     }
});
.red {
    color: red;
}

.blue {
    color: blue;
}

.orange {
    color: orange;
}

2

Marks

5

Highest

I used blue color so to make the difference more visible.
Comment: Thank you for your answer, But , I was looking for the whole div to be of the same color and include the H6 tag in the same color
Comment: Just add .parent(). Edited the answer.
Comment: Oh ok, thank you that's what I was looking for. I really appreciate your help.
Comment: OK. If it was helpful, please accept/upvote. Thanks.
Answer: Try the below script:
$("div.col h4.c").each(function() {
     if($(this).text() < 4){
           $("div.col").toggleClass("yellow");
}
     else if ($(this).text() >= 4 && $(this).text() <=6){
           $("div.col").toggleClass("orange");
}
     else if ($(this).text() >= 6 && $(this).text() <=10){
           $("div.col").toggleClass("red");
}

});

Comment: Answers on Stack Overflow should explain what the problem was and how your code solves it. It should not just be a post of code that works. Additionally, your solution doesn't solve the problem. It would do exactly the same thing that is happening to the OP already.

.each() to toggle class not working


Working with scientific notation in Netezza

Question: I have a table with data in scientific notation (string).  How can I make this a usable figure in Netezza (not a string)?
select * from
(
select '1.4545615464654E-14' as text_column
union
select '1.7891561464654E-14'
) foo

Answer: Turns out you can actually cast these strings:
select cast(foo.text_column as numeric(15,15) )
from
(
select '1.4545615464654E-14' as text_column
union
select '1.7891561464654E-14'
) foo


Broadcasting gameplay from one computer to another?

Question: How can I broadcast my desktop (like Windows Remote Desktop, VNC, etc.) while I'm playing a game, with enough speed that my gameplay will be somewhat smooth?  Can anyone recommend some other software (Mac OS, Linux)?
VNC framerate is just a little low.  I can understand someone will say that the latency is just too high, but with a service like OnLive (http://onlive.com) which is over the internet, I have a hard time believing that my local network is too slow to handle it.
Comment: @Matthew that is not true, VNC has several compression modes. Depending on client, you can set it to do JPEG compression, which may end up being fast enough. RDP also does compression, but it works at GDI level and hence is rather bad for things like video or games - in fact I suspect you can't even use RDP for games.
Comment: OnLive does video compression; VNC and RDP do not (AFAIK).  You'll need something that does it.
Comment: For any programmers out there willing to take on a challenge, the [x264 encoder](http://www.videolan.org/developers/x264.html) (which is open source) has a zero-latency option and can compress video game footage rather well in real time at 60 fps.
Comment: @romkyns, by "video compression" he means that it compress "images in motion" much more efficiently than just JPEG compression of individual screenshots (which is what VNC does).
Comment: @Den VNC does some basic inter-frame compression (like copying regions around), but it would obviously suck for games compared to codecs like h264.
Comment: Related question: http://superuser.com/questions/78515/is-there-any-software-that-can-capture-the-screen-and-turn-it-into-a-fake-webcam
Answer: If you want to broadcast your game play over the internet, take a look at Justin.tv (http://www.justin.tv). Unfortunately I haven't hosted any live gaming sessions on it, but I watch a lot of games using the site. The game play appears smooth and does not display any lag.
This video shows how to set up your computer for broadcasting WoW.
A lot of people use it so I think it would be a good choice.
If you only want to share your desktop on a LAN, this might not be suitable.
Comment: Justin.tv has a Broadcast Video Games page with a download link to Dyyno program. (found this page while following a link shown in the video above) But that program is free only for the first 10 broadcasts.
Comment: You can use Flash Media Encoder from Adobe (free). http://www.justin.tv/p/video_games.. this link describes how to set it up for consoles but you can pass the stuff about the console, tv and probably the mixer to get it set up for a PC
Comment: twitch.tv is a site, owned by justin.tv, but designed specifically for those looking to stream games to the public, but this may not be a good idea if you don't want whoever to watch it, but only specific people.
Answer: As of right now the best option to stream video games from your computer to people is the program XSplit. Fantastic program and is free as long as you are not using it for commercial use. It makes it extremely simple to setup and stream without any problem. It works with twitch.tv and several other streaming sites flawlessly.
Most of the Starcraft 2 streamers I believe now use this program. Which is why I started to use this program to stream to my friends while laddering and it really does make streaming easy.
Answer: If you just want to stream locally, you might want to use ffmpeg. It can use x264 coded with zerolatency option for streaming. See ffmpeg streaming guide.


How far apart should I space rafters for a 13ft patio?

Question: I'm looking to build a patio roof (shed style) and need to span 13ft. I've found several span tables online, some of them with different maximum distances between the rafters.
Is it ok to use 2x8s with 24" OC? - I've used this span calculator with the below variables to get a maximum span of 13'-10":

wood: SPF (I'm using the usual pressure treated lumber)
deflection limit: L/240
spacing: 24in
snow load: 30psf
dead load: 10psf

It will look something like this:
Comment: Why would you spend the extra money on pressure treated wood for rafters?  The point of a roof is that what is underneath it doesn't get wet.
Comment: If the roof material is waterproof and the overhangs are properly configured so water drips off rather than running onto the framing, there's no need for pressure-treated material here. Be sure the flash the top connection to the wall properly as well.
Comment: Comintern, this is a good point, thanks for bringing it up! I thought that you need it, if the roof is not fully enclosed. I'm building something like [this](http://sepio.ca/wp-content/uploads/2013/01/pergola_cover_013.jpg). Do I need treated wood on the outside skirting then, or not even there?
Comment: Of course you want pressure treated wood. The variation of temperature, fog, rain and other climate phenomenon will make it wet or moist even under roof, and the treatment will also prevent fungus etc.
Outside = always treated wood ! Enjoy the pergola!
Answer: A couple problems with the span calculation, IMHO (I am not a Licensed Professional Engineer):
Select structural (the lumber grade) is frequently impossible to come by at an ordinary lumberyard, will cost the earth if it can be had, and is even less available (AFAIK) in pressure treated (though you should not need that, as per comments.)
Number 2 is generally the grade you should design for unless you are sure you have a source for a better grade and can stand the price of it... You can get the same loading from 2x8  number 2 on 19.2" centers (5 per 8 feet - there's a symbol on most modern tape measures for that spacing) as your select structural on 24". Or you can get significantly more load (or span) from 2x10 number 2 on 24" centers
The position of this roof on the sidewall of a house (if it's "like the picture") may cause the buildup of a snowdrift on the roof - that needs to be allowed for if the 30 lb snow load is anything other than mythical (ie, I think that snow load is the code standard minimum, so it is often in code where snow is never expected....)


How to refer to an underlying element for the error method

Question: I am looking for a possibitlity to refer to an element which is a bit deeper in the grammar in the error function.
My grammar snippet looks like that:
Declaration:
    name = ID "=" decCon=DecContent
;

    DecContent:
        singleContent=VarContent (op+=OPERATOR nextCon+=VarContent)*
    ;

        VarContent:
            (unOP=("+"|"-"))? num = NUMBER
            | string = STRING
            | (unOP=("+"|"-"))? reference = [Declaration]
            | arrayContent = ArrayLiteral
            | embraced = "(" embrCon=DecContent ")"
        ;

Now I want the error mehtod not to refer to "decCon" (eINSTANCE.declaration_decCon) but to, let's say, "string" in the rule "VarContent".
How would I manage this?
Do I have to implement custom scopes for that?
Greeting Krzmbrzl
Answer: I assume that you implemented a check method in you validation class. Ok, instead of implement a method
@Check
def checkDeclaration(Declaration d) {
    //...
}

you should implement a method
@Check
def checkVarContent(VarContent v) {
    //...
}

where you iterate upwards (el.eContainer() ...) until you are at the declaration level to perform the check. Then you can assign the error marker to the element you want.
Edit:
Because an Xtext grammar describes an EMF meta model, Xtext generates a regular EMF meta model from your grammar and the AST one works with is an instance of this model. In this case, e.g., VarContent, Declaration, ... are model classes wich derive from Eobject. From the EMF concept the meta model also has a containment hierarchy. The method EObject EObject.getEContainer() returns the parent element of a model element. With some model knowledge one can cast the returned Eobject to the concrete class and then use it.
Comment: Look into my answer again, I added some stuff.
Comment: First of all thank you for your reply... It looks really promising to me :)  But could you please explain to me what el.eContainer() does and how I have to use it? (Sry but I'm just starting out with validation so I'm not quite familiar with Xtend and it's methods)


How to declare and fill a two dimensional array with a function vba

Question: I have an array that is declared within a subroutine. I want it filled with two values. one for each coordinate of a list of cells. I know that this isn't always the best way to do this, but for reasons involving the rest of my program, I need to do it exactly this way.
'This sub contains more, I've just included only the relevant stuff
    Sub Start_Click()
        Dim arTime() As Integer
        arTime = FillTimeArray(arTime)
    End Sub

'This is used to fill the array with a list of 12 columns that are 24 rows long
'They are offsetted intentionally

    Function FillSpotArray(ByRef arr() As Integer) As Integer()
        For j = 0 To 11
            For i = 0 To 23
                arr(i, j) = Format(i + 2, j + 1)
            Next i
        Next j
    End Function

Comment: Your function is named `FillSpotArray` but in your test Sub you are calling `FillTimeArray`...
Comment: *I want it filled with two values. one for each coordinate of a list of cells* Does that mean that there are exactly 2 values, or are there 2 values for each coordinate? Also `Format(i + 2, j + 1)` only can be wrong => `Format(0 + 2, 0 + 1) = Format(2, 1)` and `1` is not a valid formatting... please make sure you know what [`Format()`](https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/format-function-visual-basic-for-applications) is doing. (You may be looking for `Array(i + 2, j + 1)`... )
Answer: You have not dimensioned your array:
Sub Start_Click()
    Dim arTime(23, 11) As Integer
    arTime = FillTimeArray(arTime)
End Sub

Answer: You need to Dim you array, call the function correctly, and return the output correctly in the function
Sub Start_Click()
    Dim arTime As Variant
    arTime = FillSpotArray()
End Sub

'This is used to fill the array with a list of 12 columns that are 24 rows long
'They are offsetted intentionally

Function FillSpotArray() As Integer()
    Dim arr(23, 11) As Integer
    For j = 0 To 11
        For i = 0 To 23
            arr(i, j) = Format(i + 2, j + 1)
        Next i
    Next j
    FillSpotArray = arr
End Function

I'm not entirely sure of your use of Format here though


How to get only the first instance of an array that is true of a condition

Question: I'm new to PHP and I'm trying to modify my Wordpress-based Learning Management theme (called Academy on ThemeForest) to be able to work out which lesson in the current course the user is up to.
In other words, I want to run a check to see which lessons the user has completed, getting only the ID of the first lesson in the course hierarchy that has not been completed.
Here's everything I know:
Within the loop of a single post (in this case a "course"), this is how I get the array of the current course's lessons:
<?php $lessons_array = ThemexCourse::sortLessons(ThemexCourse::$data['course']['lessons']); ?>

This produces this nested array:
Array ( [0] => WP_Post Object ([ID] => 117 [menu_order]=>1) [1] => WP_Post Object ([ID] => 124 [menu_order]=>2) [2] => WP_Post Object ([ID] => 156 [menu_order]=>3))

I've truncated it a bit since the two values, [ID] and [menu_order], are the most important: they tell you the ID of each lesson and their hierarchy in the course.
But this is where I get stuck: I don't want to get all of the lesson IDs, just the one the user has yet to complete.
In order to check if a user has completed a lesson or not, I've been using this:
<?php if(ThemexCourse::isCompletedLesson($lesson_ID)) { echo 'Completed'; } ?>

So using the above information, is it possible to return a single ID of only the next incomplete lesson?
Thanks to anyone in advance for your help!
Answer: I think that should do it:
$next_lesson = NULL;
foreach($lessons_array as $index=>$lesson) {
   if(!ThemexCourse::isCompletedLesson($lesson->ID)) {
       $next_lesson = $lesson;
       break;
   }
}

echo "Next lesson is: " . $next_lesson->ID;

Comment: Thanks for the prompt reply, but this returns the following error  "Cannot use object of type WP_Post as array" on line 3 of your code.


Getting error: expected '{' before '(' token

Question: I am enrolled in Stanford's algorithms part-1 course and I am trying to implement a quick find algorithm in c.
Below is my code for implementing quick find.
  #include <stdio.h>
#include <stdlib.h>
#define n 10
void union (int, int, int *);
void connected(int, int, int *);
int main(){

    //initializing array value to it's index value
    int i;
    int id[n];
    for(i = 0 ; i < n;i++)
    {
        id[i] = i;
    }
    union(0,5,id);
    union(3,4,id);
    union(5,8,id);
    connected(3,4,id);
    connected(0,8,id);

}

void union(int a, int b,int *p)
{
    int x, y;
    x = p[b];
    y=  p[a];
    for(int i = 0; i < n; i++)
    {
        if (p[i]==y)
            p[i] = x;
    }

}

void connected(int a, int b,int *p)
{
    if(p[a]==p[b])
        printf("connected");
    else
        printf("not connected");

}

Whenever I compile the program, the following errors are generated.
I have already checked my function prototypes and declarations but I am unable to find the problem.
quick_find.c:4:12: error: expected '{' before '(' token
 void union (int, int, int *);
            ^
quick_find.c:4:6: error: two or more data types in declaration specifiers
 void union (int, int, int *);
      ^
quick_find.c: In function 'main':
quick_find.c:15:7: error: expected '{' before '(' token
  union(0,5,id);
       ^
quick_find.c:16:7: error: expected '{' before '(' token
  union(3,4,id);
       ^
quick_find.c:17:7: error: expected '{' before '(' token
  union(5,8,id);
       ^
quick_find.c: At top level:
quick_find.c:23:11: error: expected '{' before '(' token
 void union(int a, int b,int *p)
           ^
quick_find.c:23:6: error: two or more data types in declaration specifiers
 void union(int a, int b,int *p)

Comment: You are editing the code as you go along and invalidating answers.  That is VERY unfriendly.  Please stop doing that; SO is not a syntax/grammar removal tool.  Copy/paste your code and, if you wish to signal edits, APPEND the modified copy or ask another question!
Comment: now look at your post on Stack Overflow: all those `union`s are coloured blue, unlike say `connected` which is in black. Dark blue means that it is a language keyword, not unlike `if` or `while`.
Comment: Edits are meant for adding new information that **clarifies** the question, *not changing it*. If you have a different question (particularly if the code changes), ask it **as a new question**. Changing the question using edit like you have is aweful because it desychronises the existing answers from the question, which makes those answers hard to stumble upon for future viewers. Please think of others when you edit. Adios...
Comment: I'd close this as typo of typos.
Answer: union is a reserved keyword, you can not use it as an identifier.
Comment: More generally,_you cannot use it as an identifier_.
Comment: Suggested solution: use unite as a function name, instead?
Answer: Notice the extra {
void union{(int a, int b,int *p)
          ^

NOTE: This answer was posted before the OP edited the question to remove the typo (mentioned in this answer). Check the edits for clarity.

ANOTHER NOTE:
Use the standard definition of main()
int main(void) //if no command line arguments.

Comment: I hope you're not serious...
Comment: Up to you:)    As of now, you have one upvote.  I downvoted the question too because of the unfriendly edits.
Comment: @R.I.P.Seb ah this **was** another typo in the previous code.
Comment: So the question should be downvoted.
Comment: @AnttiHaapala, Yup, OP edited the question after I posted.
Comment: The function call was origianlly 'void union{(int a, int b,int *p)',   The OP then removed the bracket, so making this answer look wrong:(  That is apart from the misuse of 'union'.
Comment: @MartinJames, should I delete the answer?
Comment: @AnttiHaapala In that case, this gets a +1 from me for answering the question, and the question gets a -1 for changing the answer. Thanks for picking me up on that... and sorry for coming to a premature conclusion.
Comment: @R.I.P.Seb well, I did the same.
Comment: @AnttiHaapala, I'll just edit the answer to include information that this answers the unedited question that the OP posted in the beginning. It will not misguide the people visiting then.

Getting error: expected ‘{’ before ‘(’ token


Trying to find a specific string in a file with RegEx

Question: I have a file with the following format:
define host{
     use             generic-printer
     host_name       imp-p-125
     address         184.108.40.206
     hostgroups      network-printers
    }

 define service{
        use     generic-service
        host_name       imp-p-125
        service_description     Toner 1 Status
        check_command   check_toner1
        check_interval  240
        retry_interval  2
        notification_interval   245
        }

I'm trying to find the host_name line (1imp-p-1251), with the objetive to not repeat a host that exists in the file.
I have the following code to do this, but it's always telling me "found" for all the names that I put in the keyboard.
sub openFile {

  open(FILE, "/home/server/test2.txt");
  print "file open!\n";
  print "hostname(Example 'imp-p-125'): ";

  my $name = <STDIN>;
  chomp $name;

if (grep{$name} <FILE>){
      print "found\n";
}else{
    print "word not found\n";
}
  close FILE;
}

I was searching options to use a RegEx with STDIN method, but I can't find anything yet.
Thanks in advance.
Comment: I think RegEx or regex is acceptable... RegeX makes it seem like a video game or ActiveX...
Comment: Thanks, but i'm still searching for help!!
Answer: You've misunderstood what the grep function does. It evaluates the expression (in this case $name) for each element passed to it and if true, that element is returned. If $name contains a value, then it'll always be true, so it'll return every line in file and it'll always print the "Found" result.
Instead you want to use a regular expression. This is what a regular expression looks like.
if($somevalue =~ /pattern/)

You want to process every line so you'll also need a loop, like a while loop. If you leave out $somevalue, like many Perl functions and operators, it'll default to $_ which is what this loop will use to give you each line of the file. And since $name might contain characters that are considered special in regular expressions, surrounding it with \Q and \E means it'll be treated as just regular characters.
my $found=0;
while(<FILE>)
  {
  if( /\Q$name\E/ )
    {
    $found=1;
    }
  }
if($found)
  {
  print "Found\n";
  }
else
  {
  print "word not found\n";
  }

You're also using an outdated method of opening the file and also not checking it opened. Consider replacing it with this
if(open(my $file, "<", "/home/server/test2.txt"))
  {
  # Your code to process the file goes inside here
  close($file);
  }

PS Don't forget to replace <FILE> with <$file>