Laravel: How to set custom header while redirecting to any url

Question: I am using Laravel 5.0 and trying to redirect to a url with custom headers. But somehow I am not getting the header value in redirected page or we can say header value is not getting sent while redirecting.
I am using this code:
return redirect('http://www.anydomain.com')
            ->header('customvalue1', $customvalue1)
            ->header('customvalue2', $customvalue2);

Please let me know if I'm doing something wrong.
Comment: Same issue here, did you find an answer to this ? The suggested response below doesn't change anything to me (on v5.1).
Answer: I'm afraid, the other answer is completely wrong and misleading.
It's impossible to redirect to a page with custom headers set, no matter what language or framework you use. In other words, there's no way to trigger an HTTP redirect and cause the client (browser) to add a custom header.
You might be thinking that this code should work just fine:
return redirect('http://www.anydomain.com')
     ->header('customvalue1', $customvalue1)
     ->header('customvalue2', $customvalue2);

But it won't. You're setting the custom headers for the response which is instructing the browser to redirect, not for the redirect itself.
The only way for a site to instruct a browser to issue an HTTP request with a custom header is to use Javascript and the XMLHttpRequest object. And it needs CORS implemented on the target server to allow such ajax requests.
Please note that a page can not set HTTP request headers unless it's making an async request using XMLHttpRequest. Meaning that you can't do such redirection with the custom header on the client-side as well.
That's not how the web works.


Can you buy an inexpensive rectifier/dc power source for cheap flickering LED Christmas lights?

Question: OK, I bit on Home Depot's door buster LED christmas lights... 150 LED lights for under $5 each. How could I resist? (Answer: By remembering that cheap LEDs flicker, AND that I'm sensitive to it. )
https://www.instyleled.co.uk/what-causes-led-flicker-and-how-can-i-stop-it-happening/
Seeing as how they were door-busters, they are also non-returnable. I'd like to figure out how to make them work. I've done some research, which has shown that it's possible to create a dc rectifier/transformer/ that will make the flickering stop.
https://www.youtube.com/watch?v=mqRd3q7k9OU
Now, I think I can do all of that (I love soldering that gives you that much room to screw up. BUT, I'd rather just pay $5 for a professional version that absolutely positively won't overheat and burn down my house. I can NOT find anything that's not built for uses like under-cabinet lighting or dimmers, and which have specific connectors for specific manufacturers. Does anyone know if anyone sells something like this, or if there are kits that are a little LESS DIY in nature? Thanks!
Comment: This might belong better on electronics.stackexchange.com
Comment: The problem is, a 150-lamp light probably has several series segments, and **each segment may be facing the opposite direction**. Otherwise it imbalances the AC load, makes power-factor crazy, and limits how many strings can be stacked safely.  That means if you supply DC, half your lights will be off, in ~40-light groups.   Either take em back or hack em further.
Comment: Dunno, but if it were me I'd get a frequency doubler, or similar circuit to run the LEDs at 120, 240, or higher Hz.  Then you won't see the flicker and you won't over-drive the LEDs by running them on DC.   As to price - consider the cost of non-flickering LED strings and certainly don't spend more than 50% of that on your converter.
Comment: Any leads on how to handle the frequency doubling? Youtube seems to think that's identical to voltage doubling... which seems NOT so smart. I don't know enough about this to know how to dig for the right info.
Answer: No-one will sell a commercial product like that.  It's dangerous.
DC is nasty business. Seriously, go to mouser and pick any random power relay.  Look at its specs for AC, and then look at its specs for DC.  Whoa!
DC is de-rated by a large factor because when a DC arc strikes, it doesn't self-extinguish because the voltage never goes to zero.  An arc, once struck, doesn't feel pity or remorse or fear and it absolutely will not stop until it's burned up so much conductor it can no longer bridge the gap, and if that sets your house on fire, too bad.  If you've seen old "snap switches" which have a considerable action to them, they are preloading and releasing a "snap" action which creates a large gap when the contact breaks. Larger switches and contactors have designed-in "blowouts" which bend the arc into an arc-chute.  The point is, interrupting DC takes a lot more design and engineering than interrupting AC. And a short is a much bigger deal.
Now when you rectify AC into DC, you get a bouncing-ball waveform.

Supposedly that should self-extinguish same as full-wave AC, but capacitance will prevent it from getting all the way to zero.  If you add a smoothing capacitor, then it has no chance to extinguish. You wouldn't want to do that anyway, because that would raise the average (RMS) voltage, which could overcurrent the LEDs.  LEDs are non-linear, so a small voltage increase makes a big current increase.  The curves are in LED spec sheets.
Of course if you could constant-current regulate each LED chain, it's perfectly wired for that.
Comment: Holy crap, hadn't thought about the arc-related issues. That's a huge consideration. Given THAT, does that make the solution in the video I included in the question (the bridge rectifier) a really BAD idea? I would sort of assume that the fuses included in the lights would still work, so that even if the AC/DC *does* ramp up in a short situation, the circuit would still get blown, right? House is saved? Hopefully?
Comment: I would fuse it, but use nice long 1-1/4" automotive fuses.  I can tell you they interrupt 75V just fine.  You might also look at getting an AFCI receptacle to plug this thing into.  As long as you're not using capacitor smoothing, the AFCI should see the arc even through a rectifier.
Comment: Another option if you don't mind more hacking is to lower the voltage by dividing the array.  Your lights already have a hot+neutral "trunk" running down them to allow daisy chaining.  You could break and re-splice the segments to work on a lower voltage such as 12VDC or 24VDC, which is a lot less scary.  Current would go up in proportion, so your ability to daisy-chain strings would be limited accordingly.


How to create certificate authority certificate with makecert?

Question: I'm trying to create a website which uses SSL with a self-signed certificate.
Here's what I do:
Create authority certificate:
makecert -n "CN=root signing authority" -r -sv root.pvk root.cer

Create target certificate
makecert -r -pe -n "CN=localhost" -b 01/01/2012 -e 01/01/2020 -sky exchange localhost.cer -sv localhost.pvk

Sign the created certificate
makecert -ic root.cer -iv root.pvk -n "CN=localhost" -sv localhost.pvk -pe -sky exchange localhost.cer

Create a certificate with private key inside
pvk2pfx.exe -pvk localhost.pvk -spc localhost.cer -pfx localhost.pfx

Now, I want to use firefox for debugging website. To do that, I need to import the authority root certificate (root.cer) into the trusted certificate list.
However, when I'm trying to do this, I'm getting following error message:

This is not a certificate authority certificate, so it can't be imported into  the certificate authority list.

I've done something similar with fiddler's authority certificate, and it went fine, which means  that there's a problem with my process of creating authority certificate.
How do I properly create certificate authority certificates?
Answer: Maybe you could try adding the -cy authority parameter on the root certificate creation, like that:
makecert -n "CN=root signing authority" -cy authority -r -sv root.pvk root.cer

Thus you declare you are creating an authority certificate and that should do the job.. or at least take you on track =)
I tried myself to create a root certificate using this commandline and to import it into Firefox: I can confirm that if you don't add the "-cy" parameter, Firefox will not consider that a valid root certificate.
Hope that helps!
Comment: Arsen's question is two months old, but I thought it would be useful to reply it anyway =)
Comment: just a brief side-note to say that windows' makecert.exe utility cannot set the SubjectAltName field and, since browsers are starting to check this one for HTTPS name validation, this could be a problem when you want to produce SSL/TLS certificates using makecert. There are alternatives like OpenSSL or powershell, though.. For details see https://textslashplain.com/2017/03/10/chrome-deprecates-subject-cn-matching/
Answer: Two of the best and simple help pages:
https://blogs.msdn.microsoft.com/benjaminperkins/2014/05/05/make-your-own-ssl-certificate-for-testing-and-learning/
https://blog.jayway.com/2014/09/03/creating-self-signed-certificates-with-makecert-exe-for-development/
Some examples:
certmgr.exe -add -all -c "benperkmeCA.cer" -s -r localMachine Root

makecert -pe -iv benperkmeCA.pvk -n "CN=benjamin-perkins.me" -eku 184.108.40.206.126.96.36.199.1 -ss my -sr localmachine -sky exchange -ic BenperkmeCA.cer IIS-ServerCert-Benperk.cer

makecert -pe -iv benperkmeCA.pvk -n "CN=benjamin-perkins.me" -eku 188.8.131.52.126.96.36.199.1 -ss my -sr localmachine -sky exchange -ic BenperkmeCA.cer IIS-ServerCert-Benperk.cer

makecert -pe -iv benperkmeCA.pvk -n "CN=benjamin-perkins.me" -eku 22.214.171.124.184.108.40.206.1 -ss my -sr localmachine -sky exchange -ic BenperkmeCA.cer IIS-ServerCert-Benperk.cer

makecert -pe -iv benperkmeCA.pvk -n "CN=benjamin-perkins.me" -eku 22.214.171.124.22.214.171.124.1 -ss my -sr localmachine -sky exchange -ic BenperkmeCA.cer IIS-ServerCert-Benperk.cer


C# TrimStart with string parameter

Question: I'm looking for String extension methods for TrimStart() and TrimEnd() that accept a string parameter.
I could build one myself but I'm always interested in seeing how other people do things.
How can this be done?
Comment: Your question is not very clear. What should the string parameter do exactly in a trim function? (Assuming that you are not referring to the mandatory 'this string' syntax of the extension method)
Comment: So you want two functions with the same functionality as TrimStart/TrimEnd | Or you want one that will strip the input characters from the start/end?
Comment: Yes, same functionality as TrimStart and TrimEnd, but accepts a string instead of a char.
Comment: String in .Net has Trim, TrimEnd and TrimStart, do you not want to use them? or are you wanting to see how this might be done as a learning exercise?
Answer: To trim all occurrences of the (exactly matching) string, you can use something like the following:
TrimStart
public static string TrimStart(this string target, string trimString)
{
    if (string.IsNullOrEmpty(trimString)) return target;

    string result = target;
    while (result.StartsWith(trimString))
    {
        result = result.Substring(trimString.Length);
    }

    return result;
}

TrimEnd
public static string TrimEnd(this string target, string trimString)
{
    if (string.IsNullOrEmpty(trimString)) return target;

    string result = target;
    while (result.EndsWith(trimString))
    {
        result = result.Substring(0, result.Length - trimString.Length);
    }

    return result;
}

To trim any of the characters in trimChars from the start/end of target (e.g. "foobar'@"@';".TrimEnd(";@'") will return "foobar") you can use the following:
TrimStart
public static string TrimStart(this string target, string trimChars)
{
    return target.TrimStart(trimChars.ToCharArray());
}

TrimEnd
public static string TrimEnd(this string target, string trimChars)
{
    return target.TrimEnd(trimChars.ToCharArray());
}

Comment: This is not a good solution since it also trims a partial match: "foobartes".TrimEnd("test".ToCharArray()) results in foobar. Imho it should only trim if you get an exact match.
edit: quickfix: add a target.EndsWith(trimChars) check before trimming
Comment: Honestly the part about `TrimStart/End(trimChars.ToCharArray());` should really be deleted. That will pretty much never work as expected except in a naive test and then garble strings in production usage.
Comment: Thanks for the `string.ToCharArray()` tip.
Comment: This will loop forever if `trimString == ""`, also not sure you always want `"12123".TimeStart("12") == "3"`.
Comment: agreed, this doesn't sound like what the op was requesting.  I was under the assumption they want to trim a certain string from the beginning of a larger string.  Simply TrimStarting all of the chars in the string could remove cases where it does not match exactly.
Comment: @smg agreed, it shouldn't be a while loop, should be a simple "if" instead
Comment: It should read "if (String.IsNullOrEmpty(trimString)) return target;"
Answer: TrimStart and TrimEnd takes in an array of chars. This means that you can pass in a string as a char array like this:
var trimChars = " .+-";
var trimmed = myString.TrimStart(trimChars.ToCharArray());

So I don't see the need for an overload that takes a string parameter.
Comment: Note that this solution matches the trim chars in **any** order. For example, if `myString="Sammy"` and `trimChars="Sam"` it will return `"y", but the expected result is "my". So  it trims too much, and does not regard the trim word as such.
Comment: As @Matt explained, this way is a bit risky to do it. This will happen because the Trim(Start/End) take an array of chars as an argument, not a string. Given that example you can also have `myString="Sammy"` and `trimChars="SaX"`; this will result in `"mmy"`. Make sure that's your desired behaviour
Comment: Wow, that's embarrassing.  I didn't realize that's how it worked.  Thanks!
Answer: I thought the question was trying to trim a specific string from the start of a larger string.
For instance, if I had the string "hellohellogoodbyehello", if you tried to call TrimStart("hello") you would get back "goodbyehello".
If that is the case, you could use code like the following:
string TrimStart(string source, string toTrim)
{
    string s = source;
    while (s.StartsWith(toTrim))
    {
        s = s.Substring(toTrim.Length - 1);
    }
    return s;
}

This wouldn't be super-efficient if you needed to do a lot of string-trimming, but if its just for a few cases, it is simple and gets the job done.
Comment: This should be `toTrim.length`, without the `-1` right?
Answer: To match entire string and not allocate multiple substrings, you should use the following:
    public static string TrimStart(this string source, string value, StringComparison comparisonType)
    {
        if (source == null)
        {
            throw new ArgumentNullException(nameof(source));
        }

        int valueLength = value.Length;
        int startIndex = 0;
        while (source.IndexOf(value, startIndex, comparisonType) == startIndex)
        {
            startIndex += valueLength;
        }

        return source.Substring(startIndex);
    }

    public static string TrimEnd(this string source, string value, StringComparison comparisonType)
    {
        if (source == null)
        {
            throw new ArgumentNullException(nameof(source));
        }

        int sourceLength = source.Length;
        int valueLength = value.Length;
        int count = sourceLength;
        while (source.LastIndexOf(value, count, comparisonType) == count - valueLength)
        {
            count -= valueLength;
        }

        return source.Substring(0, count);
    }

Comment: Thank you, nice code. I just apply a bit changes to it » `if (source == null){return null;}` in my App. I think it is a better choose in this cases.
Answer: from dotnetperls.com,

Performance
Unfortunately, the TrimStart method is not heavily optimized. In
specific situations, you will likely be able to write character-based
iteration code that can outperform it. This is because an array must
be created to use TrimStart.
However: Custom code would not necessarily require an array. But for
quickly-developed applications, the TrimStart method is useful.
Comment: And how can it be implemented? I think that was the question.
Answer:
There is no built in function in C# - but you can write your own extension methods which I will show you below - they can be used like the builtin ones to trim characters, but here you can use strings to trim.
Note that with IndexOf / LastIndexOf, you can choose if it is case sensitive / culture sensitive or not.
I have implemented the feature "repetitive trims" as well (see the optional parameters).
Usage:
// myStr:   the string that needs to be trimmed
// trimStr: the string to trim from myStr
var trimmed1 = myStr.TrimStart(trimStr);
var trimmed2 = myStr.TrimEnd(trimStr);
var trimmed3 = myStr.TrimStr(trimStr);
var trimmed4 = myStr.Trim(trimStr);

There is one function TrimStr(..) trimming from the start and from the end of the string, plus three functions implementing .TrimStart(...), .TrimEnd(...) and .Trim(..) for compatibility with the .NET trims:
Try it in DotNetFiddle
public static class Extension
{
    public static string TrimStr(this string str, string trimStr,
                  bool trimEnd = true, bool repeatTrim = true,
                  StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
    {
        int strLen;
        do
        {
            strLen = str.Length;
            {
             if (trimEnd)
                {
                  if (!(str ?? "").EndsWith(trimStr)) return str;
                  var pos = str.LastIndexOf(trimStr, comparisonType);
                  if ((!(pos >= 0)) || (!(str.Length - trimStr.Length == pos))) break;
                  str = str.Substring(0, pos);
                }
                else
                {
                  if (!(str ?? "").StartsWith(trimStr)) return str;
                  var pos = str.IndexOf(trimStr, comparisonType);
                  if (!(pos == 0)) break;
                  str = str.Substring(trimStr.Length, str.Length - trimStr.Length);
                }
            }
        } while (repeatTrim && strLen > str.Length);
        return str;
    }

     // the following is C#6 syntax, if you're not using C#6 yet
     // replace "=> ..." by { return ... }

    public static string TrimEnd(this string str, string trimStr,
            bool repeatTrim = true,
            StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
            => TrimStr(str, trimStr, true, repeatTrim, comparisonType);

    public static string TrimStart(this string str, string trimStr,
            bool repeatTrim = true,
            StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
            => TrimStr(str, trimStr, false, repeatTrim, comparisonType);

    public static string Trim(this string str, string trimStr, bool repeatTrim = true,
        StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
        => str.TrimStart(trimStr, repeatTrim, comparisonType)
              .TrimEnd(trimStr, repeatTrim, comparisonType);

}

Now you can just use it like
    Console.WriteLine("Sammy".TrimEnd("my"));
    Console.WriteLine("Sammy".TrimStart("Sam"));
    Console.WriteLine("moinmoin gibts gips? gips gibts moin".TrimStart("moin", false));
    Console.WriteLine("moinmoin gibts gips? gips gibts moin".Trim("moin").Trim());

which creates the output

Sam
my
moin gibts gips? gips gibts moin
gibts gips? gips gibts

In the last example, the trim function does a repetitive trim, trimming all occurances of "moin" at the beginning and at the end of the string. The example before just trims "moin" only once from the start.
Comment: Note that TrimStr is used internally by Trim, TrimStart and TrimEnd.
Comment: The difference is that you can use TrimStr to decide via parameter if you want a trim from the start or from the end of the string.
Answer: I'm assuming you mean that, for example, given the string "HelloWorld" and calling the function to 'trim' the start with "Hello" you'd be left with "World". I'd argue that this is really a substring operation as you're removing a portion of the string of known length, rather than a trim operation which removes an unknown length of string.
As such, we created a couple of extension methods named SubstringAfter and SubstringBefore. It would be nice to have them in the framework, but they aren't so you need to implement them yourselves. Don't forget to have a StringComparison parameter, and to use Ordinal as the default if you make it optional.
Answer: If you did want one that didn't use the built in trim functions for whatever reasons, assuming you want an input string to use for trimming such as " ~!" to essentially be the same as the built in TrimStart with [' ', '~', '!']
public static String TrimStart(this string inp, string chars)
{
    while(chars.Contains(inp[0]))
    {
        inp = inp.Substring(1);
    }

    return inp;
}

public static String TrimEnd(this string inp, string chars)
{
    while (chars.Contains(inp[inp.Length-1]))
    {
        inp = inp.Substring(0, inp.Length-1);
    }

    return inp;
}

Answer: Function to trim start/end of a string with a string parameter, but only once (no looping, this single case is more popular, loop can be added with an extra param to trigger it) :
public static class BasicStringExtensions
{
    public static string TrimStartString(this string str, string trimValue)
    {
        if (str.StartsWith(trimValue))
            return str.TrimStart(trimValue.ToCharArray());
        //otherwise don't modify
        return str;
    }
    public static string TrimEndString(this string str, string trimValue)
    {
        if (str.EndsWith(trimValue))
            return str.TrimEnd(trimValue.ToCharArray());
        //otherwise don't modify
        return str;
    }
}

As mentioned before, if you want to implement the "while loop" approach, be sure to check for empty string otherwise it can loop forever.

C# TrimStart with string parameter


Handling Google Instant inside Kynetx

Question: How is the Kynetx plugin triggered? Is it by the page onload event?
Google Instant is interfering with the Kynetx plugin. WebScarab shows multiple GETs to Google on a search (Instant is ON) but no calls back to cs.kobj.net.
Does Kynetx have a plan to adapt their framework to handle Google's new Instant feature? Does it already exist? I can't find very much documentation on it.
Answer: Great question. The new search annotation functionality was completed within days of Google instant being released by Google. The in depth documentation for using the new search annotation functionality that is compatible with Google instant can be found at http://docs.kynetx.com/docs/NEW_Search_Annotation_V2.0

Handling Google Instant inside Kynetx


How can I do the join between two queries, not get duplicate rows and make it compatible with looker studio?

Question: I'm trying to create a visualization in looker studio based on a BQ query. The query looks like follows:
agg as (
  select * from
  quotes
  inner join budgets using(id,store,month)
  inner join sales using(id,store,month)
  inner join payments using(id,store,month)
  inner join specs using(id)
),t1 as (
  select worker_spec,
  worker_name,
  store,
  payment,
  quotes,
  sales,
  total_budget
  from agg
),t2 as (
  select worker_spec,
  store,
  sum(payment) as all_payments,
  sum(quotes) as all_quotes,
  sum(sales) as all_sales,
  sum(total_budget) as all_total_budget
  from agg
  group by worker_spec,store
)

The result I'm trying to achieve is this:

store
worker_spec
all_payments
all_quotes
all_sales
all_total_budget
worker_name
payment
quotes
sales
total_budget

store_1
spec_1
123
240
19357991
42775873
"john, doe"
23
48
2741950
5837899

store_2
spec_1
20
32
4013910
9045256
"john, doe"
20
32
4013910
9045256

store_3
spec_1
104
211
15828317
40646381

Soo basically, I'm trying to get in the same table all fields by store and spec, and if a worker doesn't work in a specific store, just get null values for that row.
I manage to get this output by completing the query above this way:
select * from (
  select * from t2
  where worker_spec = (
    select distinct worker_specfrom t1
    where worker_name = 'john, doe'
)
)
left join (
  select * from t1
  where worker_name = 'john, doe'
) using(store,worker_spec)

But this can't be used in Looker Studio (or Data Studio), because I need to set the worker's name dynamically. I also tried to use parameters in Looker studio, but I can't find a way to populate the parameter by using data from source (in case the number of names change or a worker does not work there anymore).
On the other side, completing the query above by just doing a join between t1 and t2 gives me this kind of output:
select * from t2
right join t1 using(worker_spec)
where worker_name = 'john, doe'

store
worker_spec
all_payments
all_quotes
all_sales
all_total_budget
worker_name
payment
quotes
sales
total_budget

store_1
spec_1
123
240
19357991
42775873
"john, doe"
23
48
2741950
5837899

store_2
spec_1
20
32
4013910
9045256
"john, doe"
23
48
2741950
5837899

store_3
spec_1
104
211
15828317
40646381
"john, doe"
23
48
2741950
5837899

store_1
spec_1
123
240
19357991
42775873
"john, doe"
20
32
4013910
9045256

store_2
spec_1
20
32
4013910
9045256
"john, doe"
20
32
4013910
9045256

store_3
spec_1
104
211
15828317
40646381
"john, doe"
20
32
4013910
9045256

Which has double the amount of rows required.
How can I achieve the result I need?
Answer: To achieve the desired result dynamically without hardcoding the worker's name in the query, you can modify the query using subqueries.
WITH
  agg AS (
    SELECT *
    FROM quotes
    INNER JOIN budgets USING (id, store, month)
    INNER JOIN sales USING (id, store, month)
    INNER JOIN payments USING (id, store, month)
    INNER JOIN specs USING (id)
  ),
  t1 AS (
    SELECT
      worker_spec,
      worker_name,
      store,
      payment,
      quotes,
      sales,
      total_budget
    FROM agg
  ),
  t2 AS (
    SELECT
      worker_spec,
      store,
      SUM(payment) AS all_payments,
      SUM(quotes) AS all_quotes,
      SUM(sales) AS all_sales,
      SUM(total_budget) AS all_total_budget
    FROM agg
    GROUP BY worker_spec, store
  ),
  worker_filter AS (
    SELECT DISTINCT worker_name
    FROM t1
  )
SELECT
  t2.store,
  t2.worker_spec,
  t2.all_payments,
  t2.all_quotes,
  t2.all_sales,
  t2.all_total_budget,
  t1.worker_name,
  t1.payment,
  t1.quotes,
  t1.sales,
  t1.total_budget
FROM t2
CROSS JOIN worker_filter
LEFT JOIN t1 ON t2.store = t1.store
  AND t2.worker_spec = t1.worker_spec
  AND t1.worker_name = worker_filter.worker_name;


Browser is not displaying php output or Errors

Question: I have installed LAMP on Ubuntu 12.04. I am able to work with MySQL through Command prompt and User Interface, but when I try to execute a PHP script which includes HTML and MySQL statements, the browser is not displaying the script output and no errors are shown.
Comment: Possible duplicate of [PHP errors are not showing in browser only page goes blank](http://askubuntu.com/questions/887612/php-errors-are-not-showing-in-browser-only-page-goes-blank)
Comment: Do you have error-reporting turned on? In your php config file change the error_reporting to E_all and restart Apache.
Comment: Can you post your php script on http://paste.ubuntu.com/?
Answer: Apart from the solution dan08 provided, may I know if you have write/execute privilege to the default /var/www directory? Try saving a sample file to that directory.
Run your script as http://localhost/[directory name]/[file name].php
Ok, you can do it now. Fine, if your browser shows well on http://localhost, then run http://localhost/phpmyadmin (i assume that you have phpmyadmin installed and configured properly for mysql- if not, consider installing it). Can you login and see the localhost interface of mysql?
If you can see nothing, restart apache.


No connectivity from Broadcom 4322

Question: While browsing the web I was notified that my Dell Vostro 1720 was offline.  After no luck rebooting my D-Link Verizon WiFi router, I saw my laptop could not connect wirelessly to anything, even a USB dongle.  I can only connect to a wired connection now. Where do I start in diagnosing this?
Comment: Please run the script that is in the accepted answer in the link below so we may see the information needed to help diagnose the issue.
Comment: Thanks, Wild Man! I'll do this & post the results here on Sunday.
Comment: Wild Man (or anyone else who my be able to understand this), here is the link to the diagnosis of the wifi issue:  http://pastebin.ubuntu.com/7826786/
Comment: Did you manually install the driver? It shows a hard block is your physical switch off?
Comment: If you tried the answer below you will need to remove the b43 driver before we continue. b43 partially supports your device but not completely.
Comment: I just copied & pasted the string below into a terminal.  I don't know if it removed the b43 driver...and I don't know how to do it if it did not.  I did not see a physical switch for the wifi on the laptop either...maybe I'm not looking in the right place.
Comment: @WildMan I think I may have one of my badges taken away...!  This laptop was given to me a few months ago & I was completely unaware it had a switch for wifi!  Lo & behold when I examined the box intently, there it was..."OFF"!  Thanks you so much for the help!  I wish I had posted this before I stayed up until 1:30am trying to figure it out over the weekend.
Comment: When i get home i will make this my answer so you can accept it. Glad it's working
Answer: Install the device driver package:
sudo apt-get install firmware-b43-installer

If already installed, reinstall it:
sudo apt-get --purge autoremove firmware-b43-installer && sudo apt-get install firmware-b43-installer

Comment: I tried both of these & neither was successful.  Thanks for the info, though!
Answer: According to the information from the script that you posted your wifi is hardblocked that usually means the switch is physically off and needs turned on.
Some computers have a switch, others the wifi is turned on with the fn key + f2 or some other key similar.

No connectivity from Broadcom 4322


Minecraft Corrupt Jar After Deleting Meta-inf

Question: I'm trying to install OptiFine on minecraft and I'm taking the following steps:

Open minecraft with archive manager
Delete the Meta-Inf folder
Open OptiFine with archive manager
Copy contents of OptiFine to minecraft archive
Close both archives
Open minecraft with java -jar minecraft.jar
At this point I get `Invalid or corrupt jarfile minecraft(1) (copy).jar!

Even just deleting the meta-inf folder gives me this error. I'm on linux mint 12. Any help is greatly appreciated!
Comment: The problem may be outside the minecraft.jar. Try this: backup your .minecraft folder; delete it; load fresh minecraft; do what you wanted to do.
Comment: What archive manager are you using?
Answer: You must rename it to: minecraft.jar.
Answer: You need to make sure your jar is named minecraft.jar
I would suggest deleting your bin folder and letting Minecraft download a fresh copy before trying this again.


How to group and sum certain columns of an array based on their classification (eg to group cities by country)

Question: The issue
I have arrays which track certain items over time. The items belong to certain categories. I want to calculate the sum by time and category, e.g. to go from a table by time and city to one by time and country.
I have found a couple of ways, but they seem clunky - there must be a better way! Surely I'm not the first one with this issue? Maybe using np.where?
More specifically:
I have a number of numpy arrays of shape (p x i), where p is the period and i is the item I am tracking over time.
I then have a separate array of shape i which classifies the items into categories (red, green, yellow, etc.).
What I want to do is calculate an array of shape (p x number of unique categories) which sums the values of the big array by time and category. In pictures:

I'd need the code to be as efficient as possible as I need to do this multiple times on arrays which can be up to 400 x 1,000,000
What I have tried:
This question covers a number of ways to groupby without resorting to pandas. I like the scipy.ndimage approach, but AFAIK it works on one dimension only.
I have tried a solution with pandas:

I create a dataframe of shape periods x items
I unpivot it with pd.melt(), join the categories and do a crosstab period/categories

I have also tried a set of loops, optimised with numba:

A first loop creates an array which converts the categories into integers, i.e. the first category in alphabetical order becomes 0, the 2nd 1, etc
A second loop iterates through all the items, then for each item it iterates through all the periods and sums by category

My findings

for small arrays, pandas is faster
for large arrays, numba is better, but it's better to set parallel = False in the numba decorator
for very large arrays, numba with parallel = True shines
parallel = True makes use of numba's parallelisation by using numba.prange on the outer loops.

PS I am aware of the pitfalls of premature optimisation etc etc - I am only looking into this because a significant amount of time is spent doing precisely this
The code
import numpy as np
import pandas as pd
import time
import numba

periods = 300
n = int(2000)
categories = np.tile(['red','green','yellow','brown'],n)
my_array = np.random.randint(low = 0, high = 10, size = (periods, len(categories) ))
# my_arrays will have shape (periods x (n * number of categories))

#---- pandas
start = time.time()

df_categories = pd.DataFrame(data = categories).reset_index().rename(columns ={'index':'item',0:'category'})
df = pd.DataFrame(data = my_array)
unpiv = pd.melt(df.reset_index(), id_vars ='index', var_name ='item', value_name ='value').rename( columns = {'index':'time'})
unpiv = pd.merge(unpiv, df_categories, on='item' )
crosstab = pd.crosstab( unpiv['time'], unpiv['category'], values = unpiv['value'], aggfunc='sum' )

print("panda crosstab in:")
print(time.time() - start)
# yep, I know that timeit.timer would have been better, but I was in a hurry :)
print("")

#---- numba
@numba.jit(nopython = True, parallel = True, nogil = True)
def numba_classify(x, categories):
    cat_uniq = np.unique(categories)
    num_categories = len(cat_uniq)
    num_items = x.shape[1]
    periods = x.shape[0]
    categories_converted = np.zeros(len(categories), dtype = np.int32)
    out = np.zeros(( periods, num_categories))

    # before running the actual classification, I must convert the categories, which can be strings, to
    # the corresponsing number in cat_uniq, e.g. if brown is the first category by alphabetical sorting, then
    # brown --> 0, etc

    for i in numba.prange(num_items):
        for c in range(num_categories):
            if categories[i] == cat_uniq[c]:
                categories_converted[i] = c

    for i in numba.prange(num_items):
        for p in range(periods):
            out[ p, categories_converted[i] ] += x[p,i]

    return out

start = time.time()

numba_out = numba_classify(my_array, categories)
print("numba done in:")
print(time.time() - start)

Comment: Have you consider using groupby like `pd.DataFrame(data = my_array, columns=categories).groupby(level=0, axis=1).sum()`? and there is possibly a numpy version of groupby (somewhere on stackoverflow) that could also increase the speed :)
Answer: You can use df.groupby(categories, axis=1).sum() for a substantial speedup.
import numpy as np
import pandas as pd
import time

def make_data(periods, n):
    categories = np.tile(['red','green','yellow','brown'],n)
    my_array = np.random.randint(low = 0, high = 10, size = (periods, len(categories) ))

    return categories, pd.DataFrame(my_array)

for n in (200, 2000, 20000):
    categories, df = make_data(300, n)
    true_n = n * 4

    start = time.time()
    tabulation =df.groupby(categories, axis=1).sum()
    elapsed = time.time() - start

    print(f"300 x {true_n:5}: {elapsed:.3f} seconds")

# prints:
300 x   800: 0.005 seconds
300 x  8000: 0.021 seconds
300 x 80000: 0.673 seconds

Comment: Ah good to know, I don't have a numba environment set up so I couldn't test that out. But that's pretty common when it comes to `DataFrames`. You could definitely write a function that uses groupby, and have your other function that uses numba. Then a third function that wraps both of them with an `if` statement that checks the `dataframe` size and calls the more appropriate function.
Comment: This is brilliant! I wasn't familiar with using the axis argument in groupby. Do you know of other examples / docs? Panda page for groupby provides no examples https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html
Comment: Unfortunately I don't know of anywhere with a lot of examples- try searching it on stackoverflow or coding creek. It's an application I've picked up from answering questions on here. If it helps to think about it this way, it's the functional equivalent of transposing your dataframe, grouping/aggregating, then transposing back.
Comment: PS on my PC, numba becomes faster than your solution only for arrays > (300 x 400,000). Maybe I can build some logic to run numba only on massive arrays, and your code on all others


Get id of logged in user to show categories

Question: I have a table join which handles the user_id and the cat_id and depending on which user is logged in depends on which categories they can see - however, I can only get this working by explicitly typing in the users id into the code and need it to know which user it is logged in:
    <?php

    try{
        $results = $dbh->query("SELECT *
                                FROM cat_List
                                INNER JOIN user_cat_link_table
                                ON cat_List.Cat_ID = user_cat_link_table.Cat_ID
                                WHERE user_cat_link_table.UserID = 10 //HERE IS THE ISSUE!
                                ");

    }catch(Exception $e) {
        echo $e->getMessage();
        die();
    }

    $docs = $results->fetchAll(PDO::FETCH_ASSOC);

    foreach($docs as $docs){

    echo '

'.$docs["cat_title"].'

        ';}
    ?>

The user gets signed in with this script:
<?
session_start();
if(isset($_SESSION['user'])){
    header("Location:home.php");
    exit;
}

    $dbh=new PDO('mysql:dbname=######;host=localhost', '######', '######');/*Change The Credentials to connect to database.*/
    $email=$_POST['username'];
    $password=$_POST['pass'];

    if(isset($_POST) && $email!='' && $password!=''){
        $sql=$dbh->prepare("SELECT * FROM user_login WHERE username=?");
        $sql->execute(array($email));

    while($r=$sql->fetch()){
        $p=$r['password'];
        $p_salt=$r['psalt'];
        $id=$r['id'];
        $email=$r['username'];
        $firstname=$r['firstname'];
        $lastname=$r['lastname'];
    }

        $site_salt="subinsblogsalt"; /*Common Salt used for password storing on site. You can't change it. If you want to change it, change it when you register a user.*/
        $salted_hash = hash('sha256',$password.$site_salt.$p_salt);

    if($p==$salted_hash){
        $_SESSION['user']=$id;
        $_SESSION['username']=$email;
        $_SESSION['firstname']=$firstname;
        $_SESSION['lastname']=$lastname;

        header("Location:home.php");

    }else{
        echo "
Username/Password is Incorrect.
";
        }
    }
?>

There are 3 tables, there is the user_login table, a cat_list table and a table which handles the relationship, but the burning issue is getting the script to know who the user is and how those categories which are associated to the user from the rows in the third table.
Comment: **WARNING:** Please use proper [password hashing](http://www.phptherightway.com/#password_hashing) methods and do not use SHA256. Due to the pervasiveness of Bitcoin mining, where systems can do tens of trillions of hashes per second, it's basically worthless.
Comment: Is the ID in question stored in `$_SESSION['user']`?  If so, just use that.
Answer: You are using sessions so in the php page where you need to use the user id just do:
<?php
session_start();
$actusr = $_SESSION['user'];
    try{
        $results = $dbh->query("SELECT *
                                FROM cat_List
                                INNER JOIN user_cat_link_table
                                ON cat_List.Cat_ID = user_cat_link_table.Cat_ID
                                WHERE user_cat_link_table.UserID = '$actusr'");

Comment: `$actusr` that stands to be a string. If it is in fact a string, it needs to be quoted. *Just saying*. Best to cover all the bases ;-)
Comment: ah peccato, I don't have skype. I'm from Quebec, si... je suis francophone. which explains why I can understand Italian rather well ;-)
Comment: @Fred-ii- you are right! typo error. Edit my answer to fix!
Comment: It wasn't necessarily a typo. The session id could be an integer, and we don't know that for certain. As I said, it's best to cover all the bases. I'd of made a note at the bottom saying that, if it's a string, then to quote it ;-) *Cheers* - Now we'll see if the OP accepts it. :-) buongiorno/buona sera.
Comment: @Fred-ii- now I remember, you speak a bit of italian! :)
Comment: si Lelio, io studiare la lingua Italiana. I can read it quite well and listen very well, but still difficulty building my own sentences. I'm only a year into it, but I would advance faster if I were in an Italian environment, which there aren't many around here. I would have to travel a bit further out of town in order to in "The Italian Village". ;-)
Comment: @Fred-ii- maybe here is off topic but if you want to do some conversation we can arrange some on skype. BTW where are you from?
Comment: Nice to see that green ticky ;-) *benissimo!*
Answer: As I can see in your second script, you save the logged in user id in the $_SESSION['user'] global variable.
So you just have to change your query to a prepared statement like so:

session_start();

try{
        $results = $dbh->prepare("SELECT *
                                FROM cat_List
                                INNER JOIN user_cat_link_table
                                ON cat_List.Cat_ID = user_cat_link_table.Cat_ID
                               WHERE user_cat_link_table.UserID = :user_id //HERE IS THE ISSUE! ");
$dbh->execute(array(':user_id' => $_SESSION['user']));

}...

to dynamically select the category depending on wich user is logged in.
Comment: if the two scripts are in two different pages you have to start the session on the second page to get this working.


No Animations in Unity Dock

Question: I've noticed that animations in the Unity dock are no longer showing.  I've installed the Paper Theme and Cairo dock (which I later removed).  I don't know what reports to run to help identify the problem.  If this questions isn't specific enough please let me know what additional information is needed.
Answer: This seems to be the result of the Paper theme.  Removing the theme restores the animations to the Unity dock.

No Animations in Unity Dock


Iterate through all sheets of all workbooks in a directory

Question: I am trying to combine all spreadsheets from all workbooks in a directory into a single df. I've tried with glob and with os.scandir but either way I keep only getting the first sheet of all workbooks.
First attempt:
import pandas as pd
import glob

workbooks = glob.glob(r"\mydirectory\*.xlsx")
list = []
for file in workbooks:
    df = pd.concat(pd.read_excel(file, sheet_name=None), ignore_index = True)
    list.append(df)
dataframe = pd.concat(list, axis = 0)

Second attempt:
import os
import pandas as pd
df = pd.DataFrame()
path = r"\mydirectory\"
with os.scandir(path) as files:
    for file in files:
        data = pd.read_excel(file, sheet_name = None)
        df = df.append(data)

I think the issue lies with the for loop but I'm too inexperienced to pin down the problem. Any help would be greatly appreciated, thx!!!
Comment: Please use something else than `list` as a variable btw.
Comment: I've only used it here in the example, not in the actual code. Apologies for the confusion...
Answer: If I understand what you have written correctly, you want something like this:
import pandas as pd
import glob

# list of workbooks in directory
workbooks = glob.glob(r"\mydirectory\*.xlsx")
l = []

# for each file in list
for file in workbooks:
    # Class for file allows for retrieving sheet names
    xl_file = pd.ExcelFile(file)
    # concatenate DataFrames created from each sheet in the file
    df = pd.concat([pd.read_excel(file, sheet) for sheet in xl_file.sheet_names], ignore_index=True)
    # append to list
    l.append(df)
# concatenate all file DataFrames to one DataFrame.
dataframe = pd.concat(l, axis=0)

This loops through the sheets within the Excel file for the concatenation, the only difference to what you had already written.
Alternative:
Alternatively, without needing to first find the sheet names, the dictionary created by pd.read_excel(file, sheet_name=None) can used.
import pandas as pd
import glob

# list of workbooks in directory
workbooks = glob.glob(r"\mydirectory\*.xlsx")
l = []

# for each file in list
for file in workbooks:
    # concatenate the dictionary of dataframes from pd.read_excel
    df = pd.concat(pd.read_excel(file, sheet_name=None), ignore_index=True)
    l.append(df)
# concatenate all file DataFrames to one DataFrame.
dataframe = pd.concat(l, axis=0)

A good explanation/example of the use of sheet_name=None can be found here.  In short, the use of this returns a dictionary of DataFrames for each sheet.  This can then be concatenated to one DataFrame, as above, or an individual sheet's DataFrame could be accessed through dictionary["sheet_name"].
Comment: Thanks, it works just perfectly. Would you be so kind to explain what I was doing wrong? I was under the impression that `pd.read_excel(file, sheet_name=None)` would open each and every sheet of each and every file, that would then be concatenated and appended to the list. Is it not the case?
Comment: I have added an alternative above with `sheet_name=None`.  You are correct that you can access all sheets at once, it just returns a dictionary, not a concatenated DataFrame.
Comment: Hi, thanks a lot for the explanation! Just a follow up question: the alternative code you're suggesting is exactly the same as my first attempt, which was not returning the correct result. What I was ending up with was the first sheet of each file, repeated as many times as the total number of sheets in the directory.
Comment: You're right, I didn't notice that when I was making the edit!  I don't know if the `list` name was causing the problem for you, but by using `l` I didn't have any problems, do you?  So theoretically, you're attempt should have been correct.
Comment: No, as I said I only used `list` here in the example... I have no clue why it didn't work for me, will let you know if I manage to solve the mystery.


jQuery toggle/vertical slider effect with multiple Divs

Question: Actually, I am new to jQuery and I am writting a sample page with jQuery functions. In this page I am making use of toggle function. Please help me to get the intended effect. I am trying to get it but it is not working properly.
The effect I am trying to apply is;

There are 2 buttons on the page, say Button1 and Button2.
There are 2 Divs, say Div1 and Div2.
Initially both Divs are hidden and only 2 buttons are visible.
If Button1 is clicked, Div1 should get toggle down and vice versa.
If Div1 is in open state and Button2 is clicked, Div1 should go up slightly and Div2 should fall down.

I have written some code with CSS applied on it. But I am not getting the sliding effect as it gives with only one Div.
I have written Javascript as;
var IsPanelDown = false;
var IsPanel2Down = false;

$(document).ready(function() {

 // Expand Panel
 $("#open").click(function(){
 if (IsPanel2Down == false)
 {
     $("div#panel2").slideUp("slow");
     IsPanel2Down = false;
 }
  $("div#panel").slideDown("slow");
     IsPanelDown = true;
 });

 // Collapse Panel
 $("#close").click(function(){
  $("div#panel").slideUp("slow");
  IsPanelDown = false;
 });

 // Switch buttons from "Log In | Register" to "Close Panel" on click
 $("#toggle a").click(function () {
  $("#toggle a").toggle();
 });

  $("#toggle2 a").click(function () {
  $("#toggle2 a").toggle();
 });

 $("#open1").click(function(){
 if(IsPanelDown == false)
 {

  $("div#panel").slideUp("slow");
  IsPanelDown = false;
 }
  $("div#panel2").slideDown("slow");
     IsPanel2Down = true;
 });

 // Collapse Panel
 $("#close1").click(function(){
  $("div#panel2").slideUp("slow");
  IsPanel2Down = false;
 });
});

Comment: I am looking for something similar to this, but with multiple Divs.
http://web-kreation.com/index.php/tutorials/nice-clean-sliding-login-panel-built-with-jquery/
Answer: I'm also as new as you are to jquery, but i guess if you used live property it would help you, like this :
$("#toggle a").live('click', function() { $(this).functionName(); });

Answer: SlideUp/SlideDown control visibility, not positioning.  Use CSS or the document structure to control the relative positioning of the two DIVs when they are visible.
Answer: It's not tested but try something like this

  <button>button 1</button>
  <button>button 2</button>

Answer: Assuming you've got similar markup to this:
<button id="button1">Toggle Div1</button>
<button id="button2">Toggle Div2</button>

Content in DIV 1

Content in DIV 2

Then use jQuery like this:
$('button').click(function(e) {
  // get the ID of the button so we can work out which DIV to show
  var m = $(this),
      id = m.attr('id').replace('button', ''); // should be either "1" or "2" after this

  // hide the DIV that's visible, if any
  $('.container:visible').slideUp('fast');

  // slide the one we want down
  $('#div' + id).slideDown('fast');
});

There are loads of ways to do this - it sort of depends on your markup!


Everything but ssh does not connect over the internet

Question: I am having trouble getting my Ubuntu server to connect to the internet. To be clear, LAN works perfectly. I am running 14.04 LTS. I cannot ping Google.com yet ssh works over the internet as well as LAN. I do have a static IP set up, but that was working before. I set my DNS servers to google's, but still nothing. apt-get install/update returns cannot resolve host to us.archive.Ubuntu.com. My repo sources are working. I am out of ideas regarding what to do next. Any help would be VERY appreciated.
Still broken with and without the nameservers in interfaces and still able to ping 188.8.131.52 with both
Here's interfaces, resolv.conf is empty.
auto lo
iface lo inet loopback

auto eth0

#iface eth0 inet dchp

iface eth0 inet static
        address 192.168.1.3
        network 192.168.1.0
        netmask 255.255.255.0
        broadcast 192.168.1.255
        gateway 192.168.1.1
        nameserver 126.96.36.199
        nameserver 18.104.22.168

Comment: Try `ping 126.96.36.199` -- did that work? If so, you have network connectivity. If that ends up being the case, then your DNS is boken. How (or where/which file) did you set your DNS servers? Can you show us /etc/resolv.conf and /etc/network/interfaces? (Let me guess: you are doing SSH by IP. I bet your DNS is just broken).
Comment: Pinging 18.104.22.168 works, so DNS is broken. Thank you for your help!
Comment: Ok, so then it really seems like however you set the DNS didn't work. Did you set it in /etc/network/interfaces? In /etc/resolv.conf? /etc/resolvconf/resolv.conf.d/{head|tail|base}?
Comment: @Azendale Added interfaces, resolv.conf is empty
Answer: You were very close with your /etc/network/interfaces configuration.
It should have been something like this:
iface eth0 inet static
        address 192.168.1.3
        network 192.168.1.0
        netmask 255.255.255.0
        broadcast 192.168.1.255
        gateway 192.168.1.1
        dns-nameservers 184.108.40.206 220.127.116.11

The nameservers <ip> syntax is if you go the resolvconf route instead.
(See https://askubuntu.com/a/51332/9308 for the details on that route.) It sounds like you got it for the most part on your own though and it is working.
Answer: FIXED!
added nameserver 220.127.116.11 to etc/resolvconf/resolv.conf.d/base and works perfectly now. Thank you @Azendale!


How should I organize this(simple polling system) in my relational database?

Question: My goal is a simple polling system where users can create a poll question, provide the poll with a set of options(answers) and vote on each poll. I'll provide a simple set of fields I need to collect. Then, I'll provide my solution. Could you tell me if my solution is acceptable?

Fields required: questionText, date, (poster)userId, options(answers), response, (responder)userID, responseDate

My curent solution:

Table: Polls
Fields: questionID, questionText, date, userID

Table: Options
Fields: optionID, optionText, questionID

Table: Respnoses
Fields: responseID, optionID, userID, responseDate

So to find if a user has responded to a specific poll, I would have to query like this:

SELECT responseID FROM Responses
WHERE userID = [user's id] AND optionID IN(
Select optionID FROM Options
WHERE questionID = [specific questionID])

Does that query make sense too?
Thanks in advance.
Comment: Sorry, I hope that works. I've been using SO for a while, but never actually posted.
Answer: This model looks fine to me, as does the query. I'm a fan of JOINs, so I would have structured your select query more like this (not a recommendation, just a clarifying alternative):
SELECT p.questionText, o.optionText AS selected_answer, r.responseDate, r.userID
FROM Responses r
    JOIN Options o ON r.optionID = o.optionID
    JOIN Polls p ON o.questionID = p.questionID
WHERE r.userID = [user ID]

My only thought is that, depending on your needs and how auditable you'll want this system to be, you may want extra fields such as timestamps on the Options and Polls tables. (A "date_edited" versus "date_created"? In low-stakes contexts this may not be needed.)
Comment: Thanks, I'll look into that suggestion. This is mostly a project to try to remember what I learned in my web dev and dbms classes, but I would like to keep best practices in mind.


Custom emacs-like key bindings on os x: DefaultKeyBinding.dict not working as expected

Question: I'm trying to add to the emacs-like key bindings in OS X 10.7.5.  In particular, in the default key bindings, alt-d and alt-b insert special characters, while I would like them to delete a word and move back a word. I've created a file ~\Library\KeyBindings\DefaultKeyBinding.dict with the following content:
{
    "~d" = "deleteWordForward:";
}

(as suggested in the answers to this question)
and opened a new terminal window (I tried rebooting, too) but now the alt-d combination just beeps at me, and does nothing else.  Any clues?
Comment: I want to use the emacs keybindings *outside* of the GUI version of emacs, e.g. in a terminal window.  But specifically, the usual emacs keybindings do not work in the *console / terminal* emacsclient/server version of emacs.  I use this version frequently because it starts instantly and that feature is useful for quick editing tasks, and for editing 'git' commit messages and rebase scripts.
Comment: Can you please help me understand why the standard Emacs key-bindings don't work for you?  For example, putting these inside the `.emacs` file in the home directory seem to work well:  `(global-set-key (kbd "M-b") 'backward-kill-word)` `(global-set-key (kbd "M-d") 'kill-word)`.  I have never had to play around with `~\Library\KeyBindings\DefaultKeyBinding.dict` and I've been using Emacs on OSX for about a year now.
Comment: Note that DefaultKeyBinding.dict is good for mappings in standard OS X text fields (e.g. in TextEdit, in web page text boxes, in address bars, etc.), not in Terminal.
Answer: This should do the trick -- within the Terminal.app Keyboard settings, check the box Use option as meta key.  [I verified the solution works with OSX Snow Leopard 10.6.8.]  Solution obtained from here:  http://iancwill.com/blog/?p=116
Comment: BINGO!   I owe you a beer.


Implementing iPad General Setting Page

Question: So far I have customized the tableview and implemented the iPad General Setting Page. Below is the code for tableview which will change frame accordingly. But the issue is when I insert/delete rows or section in the tableview. My tableviewcell backgroundview (not cell) width get shrinks. Any idea what wrong am I doing here?
<code>- (void)setFrame:(CGRect)frame
{
    if (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)
    {
        CGFloat inset =10;
        frame.origin.x += inset;
        frame.size.width -= 2 * inset;//The issue is in this line
    }
    [super setFrame:frame];
}
</code>
Comment: Please let me know if it is not clear?
Answer: I found the simple solution to achieve this. No need of customizing UITableView subclass. Just take the outlet of tableview and set the frame and change the color of backgroundview. like that below:-
<code>CGFloat tableBorderLeft = 10;
CGFloat tableBorderRight = 10;
CGRect tableRect = self.view.frame;
tableRect.origin.x += tableBorderLeft; // make the table begin a few pixels right from its origin
tableRect.size.width -= tableBorderLeft + tableBorderRight; // reduce the width of the table
yourTableView.frame = tableRect;
self.view.backgroundColor=[UIColor colorWithRed:(239/255.0f) green:(239/255.0f) blue:(244/255.0f) alpha:1.0];
</code>

Implementing iPad General Setting Page


Android Ad integration and ad image formats

Question: Wondering if there are any android advertisement platform/SDK's that would let me pick the size for the ad? I have attached a screen shot of an app layout and I am interested in replacing one or two of the tiles with an Ad... Is there an android ad platform that you would recommend?
I have been digging into some of the ad sdk's and the closest I could find was the rectangle ad's offered by millennial media. Although I am not sure if they would let me pick an aspect ratio/size that is closest to their recommended aspect ratio of 1.2
I also looked at AdMob but it looks like only support banners or full page ads..
Answer: I can confirm that Admob does only offer banner or interstitial ads.


Numpy matrix multiplication causing windows exception

Question: This morning I updated my anaconda environment in the usual way using conda update --all. This seems to have broken matrix multiplication in Numpy. During the update Spyder, of which I use the iPython console to run this code, was updated from version 220.127.116.11 to version 126.96.36.199. This is the the update report generated by anaconda. Furthermore, I am running Python version 3.9.10, iPython version 7.31.1 and Numpy version 1.22.2 on a windows 10 machine.
Every time I try to run either np.dot(A, B), np.matmul(A, B) or A @ B with square two-dimensional Numpy arrays I get a Windows fatal exception with code 0xc06d007e. But when either A or B are one-dimensional arrays, the matrix multiplication works as expected. Below I show a minimal code snippet reproducing this:
Python 3.9.10 | packaged by conda-forge | (main, Feb  1 2022, 21:22:07) [MSC v.1929 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 7.31.1 -- An enhanced Interactive Python.

In[1]: import numpy as np

In[2]: dims = 1

In[3]: N = 30

In[4]: A = np.arange(N**dims).reshape(*[N]*dims)

In[5]: B = np.eye(N)

In[6]: B @ A
Out[6]:
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12.,
       13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25.,
       26., 27., 28., 29.])

In[7]: dims = 2

In[8]: A = np.arange(N**dims).reshape(*[N]*dims)

In[9]: B @ A

Windows fatal exception: code 0xc06d007e

Main thread:
Current thread 0x00003934 (most recent call first):
  File "C:\Users\timvr\AppData\Local\Temp\ipykernel_18916\2990787033.py", line 1 in <module>

Restarting kernel...

I've tracked the error to the @array_function_from_c_func_and_dispatcher(_multiarray_umath.dot) decorator decorating the definition of dot in ENVIRONMENT_PATH\Lib\site-packages\numpy\core\multiarray.py.
Comment: I suppose it is better to create a bug ticket in `numpy`, since the code does work in general (just checked).
Comment: Thank you for the reply. I will do that.
Answer: I was able to resolve the issue by reinstalling Spyder, Numpy and their dependencies. After each reinstall I ran the code in my original question to see if anything had broken yet. The list of packages that I manually reinstalled after uninstalling Spyder and Numpy were:

Numpy
Scipy
Spyder
Uncertainties
QCodes
QuTip
HDF5
PyQTGraph
LMFit


Restriction of scalars of a torus

Question: Let $k$ be a number field, $l/k$ be a finite extension, and $T_{/l}$ be a linear algebraic torus over $l$.

Is $R_{l/k}(T_{/l})$ a linear algebraic torus over $k$? Here $R_{l/k}$ is the restriction of scalars.

What about the same question above with "group of multiplicative type" instead of "torus"?
Answer: Yes. Let's call the torus $T$. Then by definition $R_{l/k}(T)(k_s) = T(l\otimes_k k_s)$ where $k_s$ is the separable (or use algebraic closure, doesn't matter), and $l\otimes_kk_s$ is a product of copies of $k_s$ since $l/k$ is separable. So over the separable closure $R_{l/k}(T)$ still is isomorphic to a bunch of copies of $\mathbb{G}_m$. One can also see that this applies to diagonalizable subgroups.

Restriction of scalars of a torus


Can a local web server be created for Windows 8 Surface RT

Question: My goal is to run flash locally on a Windows Surface RT tablet. From research, I have found that for websites to run flash, they have to be whitelisted on Microsoft's website. Through further research, I have found how to hack the whitelist to add any domain:
http://www.redmondpie.com/how-to-enable-flash-for-any-site-in-windows-8-rt-metro-internet-explorer-10/.
However, I cannot add the local file system (i.e. C:\ or file:\\) as they are not domains. One solution, I have though of is by using localhost. How can I write a web server to run on Windows 8 Surface RT, or can it be done?
In C#, I know you can use System.Net.HttpListener: http://www.codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server.aspx. Is System.Net.HttpListener supported with Surface RT? If not, what are alternative solutions to play flash locally?
Comment: HttpListener is not supported by the windows store api. All network relelated classes are client side. Unless there is a hack/workaround/some other class it is not possible to have a server running (using WinRT)
Comment: Adobe is "committed" to bringing Adobe Air to Windows RT (Metro). Lee Brimelow (works at Adobe) tweeted that it should be released first half of 2013: https://twitter.com/leebrimelow/status/268815503349411841 Not sure if that's good news or bad news for you.
Answer: Theoretically, it is possible. You need to use StreamSocketListener to get a StreamSocket. Then you handle http input from that socket (tons of work), and send back your response. I've made my protocol work. One thing you might need to pay attention is that you might need a second machine to send the http request. I use IE from another PC to send the test request. Win8 network isolation won't allow tcp connections between 2 apps of a same machine...
Comment: If it helps, network isolation DOES allow the use of localhost within the same process. See http://msdn.microsoft.com/en-us/library/windows/apps/hh770532.aspx#network_isolation_and_loopback. "Network communications using an IP loopback address cannot be used for interprocess communication (between two different apps) because this is restricted by network isolation. Network communication using an IP loopback address is allowed within an app within the same process for communication purposes."


Wondering where to house api call logic. inside the Container or Component?

Question: I have a container that passes props and an apiCall action to a component which will mainly just render the result of that call. My question is should I leave the invoking of that action up to the component or move it out into the container and just pass the array of items to the component?
Here is my container code. The fetchShowingsListShowings is the one in question. Also, I will be renaming that soon enough so bear with me.
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../actions/showingsListActions';
import ShowingsList from '../components/ShowingsList';

const ShowingsListContainer = (props) => {
  return (
    <ShowingsList
        isLoading={props.isLoading}
        showings={props.showings}
        fetchShowingsListShowings={props.actions.fetchShowingsListShowings}
    />
  );
};

ShowingsListContainer.propTypes = {
  isLoading: PropTypes.bool.isRequired,
  showings: PropTypes.array.isRequired,
  actions: PropTypes.object.isRequired
};

const mapStateToProps = (state) => {
  return {
    isLoading: state.showingsList.isLoading,
    showings: state.showingsList.showings
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    actions: bindActionCreators(actions, dispatch)
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ShowingsListContainer);

And my component. Which calls the API action on componentWillMount.
import React, { PropTypes } from 'react';
import ShowingsListItem from './ShowingsListItem';

class ShowingsList extends React.Component {
  componentWillMount() {
    this.props.fetchShowingsListShowings();
  }

  render() {
    return (
      this.props.isLoading ?
Loading...
 :

        {this.props.showings.map((showing,index) => <ShowingsListItem showing={showing} key={'showing' + index}/>)}

    );
  }
}

ShowingsList.propTypes = {
  isLoading: PropTypes.bool.isRequired,
  showings: PropTypes.array.isRequired,
  fetchShowingsListShowings: PropTypes.func.isRequired
 };

export default ShowingsList;

Thanks in advance.
Answer: So in React with Redux the term 'Container' just means a component that is connected to the Store, essentially whatever you use the react-redux 'connect' method with. Your ShowingsList can be a 'dumb' (or functional) component meaning it's just a component that takes in data and displays content. The general 'best' practice is to have your dumb components just be concerned with presentation, and your container components handle all the logic interacting with the Redux Store. If you follow this logic, fetch the data in the container, and pass the data to the nested component. That being said, it'll work either way so you don't really need to change anything if you're happy with it now.
To follow this pattern do something like this:

modify your Container component to be an ES6 class extends React.Component.. and optionally change your ShowingsList to be a functional component (like your ShowingsList is now)
put a componentWillMount in your Container and put the API call there.
pass the list to the presentational component.

Here's an article written by Dan Abramov, the author of Redux on this very topic.
https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.g695y2gwd
Comment: Got it, I originally had it that way but wasn't quite sure what best practices were so I flip flopped. Thanks for the quick reply.


My child flushed a flashlight down the toilet, how do I get it out?

Question: My 2 year old flushed flashlight down the toilet a couple weeks ago, and now its starting to clog. It worked fine at first, so I thought that maybe it went all the way down, but I've been having to plunge it fairly regularly for the past couple of days after a few "solid" flushes. After I plunge it, it works fine, but I have a feeling the flashlight didn't go all the way down as originally assumed. Do I have to remove the toilet off the floor to get it out?
Comment: Possible duplicate of http://diy.stackexchange.com/questions/13417/how-to-unclog-a-toilet-solid-object-obstruction
Comment: @NiallC. I already reached inside with gloves and tried to poke around with a coat hanger, it's either deeper in the trap or beyond the trap.
Comment: If the body of the flashlight has any iron/steel in it, you might be able to pull it out with neodymium magnet glued to the end of a plumbing snake.  If non-ferrous...
Answer: The first (and most likely) place it's stuck is at the top bend inside the toilet. That's usually a rather tight turn. The second place is at the bottom, either above or below the floor flange. The bend going into the house drain stack is usually fairly gentle but there are ridges that can catch larger objects.
In short, there is no simple way to answer "where". The low-cost route is go and buy a wax ring, then pull the tank and bowl. you can then look up the toilet's internal trap and see if it's wedged in there, and stand a reasonable chance of getting it out with a wire.
If the flashlight is not in the toilet you will need to call a plumber. Get one with a fiberscope, not just a power auger - this isn't a blockage you can chop up and send down the pipe, you need to find it and extract it. We are not concerned about getting the light back, we are concerned it doesn't get stuck somewhere more expensive, like under the back lawn.


Ubuntu 16.04 Eclipse launcher icon problems

Question: I am running Ubuntu 16.04 LTS, with the latest version of Eclipse installed from their website. In the Unity Launcher bar to the left, I can't get the icon for Eclipse to be anything except a question mark. I have created a .desktop file with the appropriate paths for Exec= and Icon= , and I have made the item executable via chmod. The functionality of the .desktop file is not a problem. I just can't get the icon that shows up to change.
The name does change from Eclipse to Workspace Launcher when Eclipse finally starts. Any help would be much appreciated.
EDIT: the code:
[Desktop Entry]
Exec=/home/**removed**/eclipse/java-mars/eclipse/eclipse
StartupNotify=true
Terminal=false
Type=Application
Icon=/usr/share/icons/eclipseIcon.xpm

*username removed for security purposes.
EDIT: Reinstalling fixed any and all Eclipse problems that I had.
Answer: I have been able to resolve this by just removing the eclipse.desktop file from ~/.local/share/applications and then exiting and launching eclipse again:
I followed this solution: https://askubuntu.com/a/735924
Comment: This worked for me. I freaked out a little after my icon's image turned to a "?", but then it went back to the STS icon.
Comment: @Baalmart Worked like a charm
Answer: I had a similar problem. I tried ScottC's answer mentioned here. I created the .desktop file on my desktop location, added the exec path as <eclipse installation directory>/eclipse and icon path as <eclipse installation directory>/icon.xpm and then pinned it to the launcher. This worked for me.
Comment: Thanks for the nice answer. A detailed answer is appreciated.
Answer: I never had those problems. I have my desktop file in the eclipse folder, copy and modify it from version to version and than drag&drop it from nautilus to the launcher.
Here is my eclipse desktop file:
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Exec=/home/USERNAME/Apps/eclipse-neon/eclipse --clean -vm /usr/lib/jvm/java-8-oracle/jre/bin -vmargs -Dfile.encoding=UTF-8 -Xms256m -Xmx3000m -XX:+UseG1GC -XX:+UseStringDeduplication
Name=Eclipse JEE neon
Icon=/home/USERNAME/Apps/eclipse-neon/eclipse-neon.png
Name[de_DE]=Eclipse JEE Neon

You also want my custom eclipse neon logo, it's great! ;) here you go: https://i.stack.imgur.com/IoBJs.jpg
Answer: The icon entry must have a fully qualified path to the actual XPM image file. If you keep your eclipse folder in your home directory, the eclipse.desktop entry becomes:
Icon=/home/USERNAME/eclipse/icon.xpm
Annoyingly, Neon ships with the Mars icon. This will make you sad and miss the planetary theming, if left unchanged.
For example, Neon for Android should have a green accent:
https://i.stack.imgur.com/KyrBO.jpg (use GIMP to convert this PNG to XPM, default alpha).
You should never adulter the blue&white Eclipse logo, that is blasphemy. The accent is now agnostic since the planet theme was abandoned. Phobos would have been the perfect name for an Eclipse release ...
Answer: I just faced the same problem and solved it by changing the name of the Icon name in the desktop file.
Using Ubuntu 16.04.3 and Eclipse Oxygen and by looking at the eclipse folder, I saw that the icon has the name 'icon.xpm' , whereas in the desktop file in
~/.local/share/applications, the name is 'eclipse'.
So, I replaced:
Icon=eclipse
by:
Icon=$your_eclipse_path/icon.xpm

and it worked for me.
Answer: In the sample you have mentioned in the top, the required key "Name" is missing. In Ubuntu 16 when I execute desktop-file-install command it fails with the following error:
/usr/share/applications/eclipse.desktop: error: required key "Name" in group "Desktop Entry" is not present

To solve that you need to add the "Name" entry
Name=Eclipse

Answer: Add desktop entry for launcher here(/usr/share/applications/eclipse.desktop) with changes in icon and exec path. Even your problem exist, try this one
remove space in your exec and icon path or use back slash Ex:
Exec=/home/<some dir>/eclipse Mars/eclipse
         **->/home/<some dir>/eclipse\ Mars/eclipse**

Answer: Add desktop entry for launcher here(/usr/share/applications/eclipse.desktop) with changes in icon and exec path. Even your problem exist, try this one
remove space in your exec and icon path or use back slash
 Ex:
Exec=/home//eclipse Mars/eclipse
         ->/home//eclipse\ Mars/eclipse
Answer: The .desktop file must be at $HOME/.local/share/applications.
See this answer and the original source.


decode uiwebview string

Question: i have a uiwebview. when i read string (from ) from this uiwebview i encodes come characters like #. how can i decode?
for example it gives %23test instead of #test. i need #test
thanks.
Answer: You can use the stringByReplacingPercentEscapesUsingEncoding: method of NSString:
<code>NSString *encoded = @"%23test";
NSString *decoded = [encoded stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
</code>
Comment: hi aBitObvious, it has problems while getting % char. it gives "%58'den ysnky'ye tepki" as "X'den ysnky'ye tepki". how can i solve? thanks.    http://stackoverflow.com/questions/4338123/decoding-problem-uiwebview
Comment: What string are you expecting back?
Comment: my string is  "%58'den ysnky'ye tepki". i would like to write is as  and when clicked i want to get it back.
Comment: Before putting the string into the html, encode it using `stringByAddingPercentEscapesUsingEncoding`.  For the `href`, use double quotes instead of single quote to delimit the url: `NSString *html = [NSString stringWithFormat:@"Click This", encodedString];`.
Comment: oohh, right. i was missing that single quote deliminating the string. thanks again.

decode uiwebview string


Piecewise continuity with countably infinite discontinuities

Question: If a function has countably infinite number of discontinuities, can it still be called piecewise continuous [say greatest integer function]? I read that a piecewise continuous has finitely many discontinuities.
Thanks for the help in advance.
Comment: I would say the greatest integer function $\lfloor x \rfloor$ is piecewise continuous, despite having infinitely many discontinuities.  But the discontinuities have no cluster points.
Comment: Thank you. Could you please elaborate on what you mean by cluster points? Also do you mean to say countably infinite jump discontinuities can be taken as piecewise continuity?
Answer: Yes, take for example $f(x)=\frac 1 {cos(x)} $. It's discontinuous in all the points of the form of $\frac \pi 2 + k \pi$ but is still piecewise continuous in the open sets $(\frac \pi 2 + k \pi, \frac \pi 2 + (k+1)\pi)$ (it's quotient of elementary continuous function that don't vanish in the interval considered).
Answer: For an interval extending to infinity, say $[0,\infty)$, a function is said to be piecewise continuous if it is piecewise continuous in every closed interval $[a,b]$ such that $[a,b]\subset[0,\infty)$.
Thus, the greatest integer function is piecewise continuous as in every finite interval, the points of discontinuity are finite and the left and right hand limits at these points are finite.


ssmpt : how to configure php?

Question: I isntalled successfull ssmtp:
/etc/ssmtp/ssmtp.conf

email@example.com
email@example.com
mailhub=ssl0.ovh.net:587
#mailhub=ns0.ovh.net:587
UseSTARTTLS=YES
FromLineOverride=YES
email@example.com
AuthPass=********

And trying it with:
 echo content | mail -s "subject" firstname.lastname@example.com

This works and I do receive email
my ssmpt seems also ok:
 ls -la /usr/sbin/sendmail
lrwxrwxrwx 1 root root 5 Jul 15  2014 /usr/sbin/sendmail -> ssmtp

my php.ini has:
sendmail_path = "/usr/sbin/sendmail -t -i"

However, when I try to send email through the mail() function: I receive FALSE
tail /var/log/apache2/error.log

gives me: sendmail: Cannot open mailhub:25
Any idea ?
Comment: Can you submit mail using that particular sendmail command `/usr/sbin/sendmail -t -i` on the command line?
Answer: It looks like ssmtp doesn't support the -i argument, and requires -oi instead.  Note that -oi means the same thing and should work on other sendmail implementations.
Could you try changing your sendmail command to /usr/sbin/sendmail -t -oi?
ssmtp manpage at: https://linux.die.net/man/8/ssmtp.

ssmpt : how to configure php?


What does mysql_escape_string() do?

Question: What does mysql_escape_string() do? I am updating a database. When I am using $_POST('variable')
it's not getting updated, but using it with mysql_escape_string($_POST()) it works fine. I am calling this by ajax.
Comment: Please, don't use `mysql_*` functions for new code. They are no longer maintained and the community has begun the [deprecation process](http://goo.gl/KJveJ). See the [**red box**](http://goo.gl/GPmFd)? Instead you should learn about [prepared statements](http://goo.gl/vn8zQ) and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you can't decide, [this article](http://goo.gl/3gqF9) will help to choose. If you care to learn, [here is good PDO tutorial](http://goo.gl/vFWnC).
Comment: Use mysql_real_escape_string over mysql_escape_string. Better yet use PDO
Comment: mysql_escape_string has been DEPRECATED as of PHP 5.3 try using mysql_real_escape_string
Answer: mysql_escape_string is one of PHP mysql extension functions. It escapes a string provided as parameter for the function. Escapes means prepends backslash (\) to special characters.

mysql_escape_string is designed to be used with mysql_query function, to safely pass MySQL query parameters to the query. Safely means with no possibility to affect and change the desired query behaviour. Learn more by searching for "sql injection", e.g. Secure Development Guidelines on MDN.
special characters escaped with mysql_escape_string are: the null byte (0), newline (\n), carriage return (\r), backslash (\), single quote ('), double quote (") and substiture (SUB, or \032). % and _ are not being escaped with this function.
mysql_escape_string has been deprecated as of PHP 5.3.0. It should be replaced with mysql_real_escape_string function, which in addition to escaping the string, takes into account the current character set of the connection.
use of both mysql_escape_string and mysql_real_escape_string is discouraged with recommended alternatives of MySQLi or PDO_MySQL extensions.

In your case, the most probable reason why $_POST('variable') does not work, is that it contains one or more of the special characters, thus the MySQL query you're executing is unintentionally changed and broken. You're calling it with AJAX and if you're not processing the AJAX errors, you may not be able to see the error messages.

What does mysql_escape_string() do?


How to import data from MS Access to Sql Server by coding

Question: I need to import an Access database by code to Sql Server. My software that is made in C # for many years has been integrated into an Access database. From now  we are migrating to Sql Server and the intention is in the upgrade to the next version the system will only work with Sql Server. I think at first of creating a Sql database with the same names of tables and columns and the software read the Access tables and save the data in the Sql database. Is there any other more practical way to do this by coding?
I've been searching and found just tools ready, but nothing by coding.
Comment: Why do this in code if its a one off task? SSMA/SQL Server Migration Assistant can do this and give you a good starting point.
Comment: Why in this case I would have to access computer by computer of each user and install the SqlServer to make the migration. The intention is that by the software, in the form created by visual studio, when updating the software for the new version, the user himself can migrate to the new database just by clicking an Ok button, for example.
Answer: Ok, lets say your access Database table has 3 columns, 1st one is type of integer, 2nd is string (varchar) nad 3rd one is DateTime (date).
So this is the code you have to do for passing data from Access to Sql Server:
<code>DataTable table = new DataTable();
// get data from access
using(OleDbConnection conn = new OleDbConnection("connString1"))
{
     using(OleDbDataAdapter da = new OleDbDataAdapter(@"SELECT * FROM MyTable", conn))
           da.Fill(table);
}

//insert data into Sql server:
using(SqlConnection conn = new SqlConnection("connString2"))
{
     using(SqlCommand cmd = new SqlCommand())
     {
            cmd.CommandText = @"INSERT INTO MyTable VALUES (@p1, @p2, @p3)";
             cmd.Connection = conn;
             cmd.Parameters.Add("@p1", SqlDbType.Int);
             cmd.Parameters.Add("@p2", SqlDbType.CarChar, 50);
             cmd.Parameters.Add("@p3", SqlDbType.DateTime);
             conn.Open();

             for(int i = 0; i < table.Rows.Count; i++)
             {
                    cmd.Parameters["@p1"].Value = Convert.ToInt32(table.Rows[i][0]);
                    cmd.Parameters["@p2"].Value = table.Rows[i][1].ToString();
                    cmd.Parameters["@p3"].Value = Convert.ToDateTime(table.Rows[i][2]);
                    try
                    {
                          cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                           MessageBox.Show(ex.Message);
                           break;
                    }
             }
     }
}
</code>
Comment: That's exactly what I'm thinking of doing. So does it mean that there is no simpler way to do that?
Comment: its the simplest way to do it through code.
Comment: @vijayvikcs Tkx!


How to replace tab navigation screen to stack navigation screen in react native

Question: I am using stack navigation for the login module, When login is successful after that I navigate to the tab navigation (Home screen). When the user goes to log out from the profile screen after that I am not able to navigate on stack navigation (login screen).
I am searching on google but still have not found any related answer
this is the navigation screen code:-
const Stack = createNativeStackNavigator();

const Tab = createBottomTabNavigator();

function Navigation() {
  const [token, setToken] = useState('');
  const [sessionHandle, setSessionHandle] = useState(false);

  AsyncStorage.getItem('token', (err, result) => {
    setToken(result);
    if (!token) {
      setSessionHandle(false);
    } else {
      setSessionHandle(true);
    }
  });

  const {width, height} = Dimensions.get('window');

  function MyTabs() {
    return (
      <Tab.Navigator
        initialRouteName="HomeTab"
        screenOptions={{
          headerShown: false,
          tabBarActiveTintColor: Colors.black,
          tabBarInactiveTintColor: Colors.gray,
          tabBarStyle: {height: width * 0.18, borderRadius: 40},
        }}>
        <Tab.Screen
          name="HomeTab"
          component={ProductFlowNavigation}
          options={{
            tabBarLabel: 'Home',
            tabBarLabelStyle: {
              fontSize: 12,
              fontFamily: 'Poppins-Regular',
              marginBottom: 10,
            },
            tabBarIcon: ({focused}) => {
              const set_color = focused ? Colors.bright_sky_blue : Colors.gray;
              return <Ionicons name="ios-home" color={set_color} size={25} />;
            },
          }}
        />

        <Tab.Screen
          name="OrderHistory"
          component={OrderHistory}
          options={{
            tabBarLabel: 'History',
            tabBarLabelStyle: {
              fontSize: 12,
              fontFamily: 'Poppins-Regular',
              marginBottom: 10,
            },
            tabBarIcon: ({focused}) => {
              const set_color = focused ? Colors.bright_sky_blue : Colors.gray;
              return <Ionicons name="timer" color={set_color} size={25} />;
            },
          }}
        />

        <Tab.Screen
          name="Profile"
          component={Profile}
          options={{
            tabBarLabel: 'Profile',
            tabBarLabelStyle: {
              fontSize: 12,
              fontFamily: 'Poppins-Regular',
              marginBottom: 10,
            },
            tabBarIcon: ({focused}) => {
              const set_color = focused ? Colors.bright_sky_blue : Colors.gray;
              return <Ionicons name="person" color={set_color} size={25} />;
            },
          }}
        />
      </Tab.Navigator>
    );
  }

  function MyLoginSignupNavigation() {
    return (
      <Stack.Navigator initialRouteName="Login">
        <Stack.Screen
          name="Signup"
          component={SignUp}
          options={{headerShown: false}}
        />

        <Stack.Screen
          name="Login"
          component={Login}
          options={{headerShown: false}}
        />
        <Stack.Screen
          name="Home"
          component={MyTabs}
          options={{headerShown: false}}
        />
      </Stack.Navigator>
    );
  }

  return (
    <NavigationContainer>
      {sessionHandle ? <MyTabs /> : <MyLoginSignupNavigation />}
    </NavigationContainer>
  );
}

export default Navigation;

Answer: @mahesh you are switching between tab and stack navigation based on "sessionHandle", so i suggest you if you want to logout just set the value of "sessionHandle" to false, it will direct you to stack navigation first screen
{sessionHandle ? <MyTabs /> : <MyLoginSignupNavigation />}

you navigation depends on sessionHandle
Hopefully it will help you
Comment: thank you, Alok Singh, but my log-out function is on the profile screen not on the navigation screen. then how do I change the @sessionhandle  value on the profile screen
Comment: you can use redux or cotext api to manage state across the app @mahesh
Comment: I am using redux to manage state
Comment: then you can change the sessionhandle state through the redux.


cannot ping to ip base on host name

Question: i have two PC
1. 192.168.56.102 => winXP
2. 192.168.56.103 => ubuntu 10.04 (bind9 and apache2 installed)

i have registered simas.tes to 192.168.56.103
what i did :
# vi /etc/bind/named.conf.local

zone "simas.tes" {
    type master;
    file "/etc/bind/zones/simas.tes.db";
};

zone "56.168.192.in-addr-arpa" {
    type master;
    file "/etc/bind/zones/rev.56.168.192.in-addr.arpa";
};

then :
# vi /etc/bind/zones/simas.tes.db

simas.tes.  IN  SOA ns1.simas.tes.  admin.simas.tes. (
    2006081401
    28800
    3600
    604800
    38400
)

simas.tes.  IN  NS      NS1.simas.tes.
simas.tes.  IN  MX  10  mta.simas.tes.

www IN  A   192.168.56.103
mta IN  A   192.168.56.103
ns1 IN  A   192.168.56.103

then :
# vi /etc/bind/zones/rev.56.168.192.in-addr.arpa

@ IN SOA ns1.simas.tes. admin.simas.tes. (
    2006081401;
    28800;
    604600;
    604800;
    86400
)

    IN  NS  ns1.simas.tes.
103 IN  PTR simas.tes.

my dig state :
root@my-ubuntu:/var/www# dig simas.tes

; <<>> DiG 9.7.0-P1 <<>> simas.tes
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 9559
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;simas.tes.         IN  A

;; AUTHORITY SECTION:
simas.tes.      38400   IN  SOA ns1.simas.tes. admin.simas.tes. 2006081401 28800 3600 604800 38400

;; Query time: 0 msec
;; SERVER: 192.168.56.103#53(192.168.56.103)
;; WHEN: Thu May  3 17:25:05 2012
;; MSG SIZE  rcvd: 73

my nslookup state :
root@my-ubuntu:/var/www# nslookup simas.tes
Server:     192.168.56.103
Address:    192.168.56.103#53

*** Can't find simas.tes: No answer

now i can access simas.tes site from 192.168.56.102 (my winXP), but i cannot ping to simas.tes (instead of 192.168.56.103)..
what i miss? .. i just want to know how to ping simas.tes successfully.
Comment: zone "0.168.192.in-addr.arpa" in your reverse DNS might better be zone "56.168.192.in-addr.arpa"...
Comment: i got problem with this code, i have put that reserve DNS before
Answer: It looks to me like you're missing an "IN A" entry for "simas.tes." in the /etc/bind/zones/simas.tes.db file. One possibility to set that would be:
simas.tes.  IN A       192.168.56.103
simas.tes.  IN NS      NS1.simas.tes.In this example, I added the "A" record I mentioned above your existing NS record.

cannot ping to ip base on host name


How to use useReducer hook with async data in React?

Question: I'm trying to use the useReducer hook to fetch data from an API and then update state. Since this is a small project, I'm trying to avoid using useContext, and instead just passing the dispatch function down as props.
How I've done it before is using a normal reducer for manipulating state, and an asyncReducer for fetching data, however I can't figure out how to use the two together. Would appreciate any guidance. I'll supply a link to the full code below. Just visit the repo and hit the period key (.) to view it. Main files to look at are App.js, reducer.js and letters.jsx
[]https://github.com/robert-levy/cocktail-finder
Comment: I'm not quite sure what you mean by making a reducer async.
Comment: A reducer is not meant to have any logic that requires fetching data.
Comment: Here's a part of a project I worked on before which used a async reducer to make api calls, and then a second reducer to manipulate state. I want to try do something similar.  https://www.codepile.net/pile/vg4WNOe2
Comment: Not sure if any other people can weigh in here, but I'm not sure this is a pattern you want to follow. I've never heard of it. Maybe it's because I'm used to Redux, where your async api calls are handled via actions, completely separate from the reducers. Perhaps I am wrong though.
Comment: I haven't really seen this pattern either, but I was shown it while on a React course provided by my workplace. I'm open to any other ways of doing it, but would prefer to avoid the use of other packages e.g. Redux
Comment: I posted a solution. Not sure if that will work, hopefully it does.
Answer: From checking out the code from your prior application, I'm not positive this will work, but let's see. Change whatever you need to reflect what I have here.
import { reducer, asyncReducer initialState } from './state/reducer'

const App = () => {

  const [state, dispatch] = useReducer(reducer, initialState)

  return (

      <NavigationBar />
      <Container>
        <Row>
          <Letters dispatch={asyncReducer(dispatch)} />
        </Row>
        <Row className="justify-content-center">
          <SearchBar />
        </Row>
        <Row>
          <Cocktails />
        </Row>
      </Container>

  );
}

Comment: Seems to work to me! Thanks very much.


Reducing Run Time Complexity !!! Reducing Nested loops in Python

Question: I am working on the python program which gives/takes standard input/output. The first line gives Number of Test Cases T. Second-line gives the size of data N. Third and Fourth line gives space-separated integers respectively of length N. The program arranges Set A and B that Set A has the maximum number of items that are greater than their equally-indexed items in Set B. Below is my code:
 def main():
   T=int(input())
   for ii in range(T):
        N=int(input())
        revo=list(map(int, input().split()))
        star=list(map(int, input().split()))
        win=0
        for i in range(N):
            a=1
            for j in range(revo[i]):
                b=revo[i]-a
                if b in star:
                    win=win+1
                    t=star.remove(b)
                    break
                a=a+1
        print(win)
main()

The inputs are:
1
10
3 6 7 5 3 5 6 2 9 1
2 7 0 9 3 6 0 6 2 6

The output is 7 because when arranged optimally Set A has 7 items which are greater than in Set B. But when we input large datasets it took long time to produced output. Is there any better functions that I can use to Reduce Run Time?
Answer: Your solution is O(k*n^2), which is really a lot.
 def main():
   T=int(input())
   for ii in range(T): # ignoring number of inputs in time complexity
        N=int(input())
        revo=list(map(int, input().split())) # O(n), doesn't matter
        star=list(map(int, input().split())) # O(n), doesn't matter
        win=0
        for i in range(N): # n
            a=1
            for j in range(revo[i]): # n*k, k depends on
                                     # how big is each number, hard to tell
                b=revo[i]-a
                if b in star: # k*n^2
                    win=win+1
                    t=star.remove(b) # normally this would multiply by n, but
                                     # remove can be called at most n times
                    break
                a=a+1
        print(win)
main()

You could gown down to O(nlogn) if you sorted both lists first. Here's my solution:
def solve(list1, list2):
    list1 = sorted(list1) # n*logn
    list2 = sorted(list2) # 2*n*logn
    pos_in_list1, pos_in_list2 = 0, 0
    while pos_in_list1 < len(list1): # 2*n*logn + n
        if list1[pos_in_list1] > list2[pos_in_list2]:
            pos_in_list1 += 1
            pos_in_list2 += 1
        else:
            pos_in_list1 += 1
    return pos_in_list2

print(solve([3, 6, 7, 5, 3, 5, 6, 2, 9, 1], [2, 7, 0, 9, 3, 6, 0, 6, 2, 6]))
# 7

def main():
    _ = input()  # we don't need n
    list1 = [int(i) for i in input().split()] # O(n), doesn't matter
    list2 = [int(i) for i in input().split()] # O(n), doesn't matter
    print(solve(list1, list2))

O(2*n*logn + n) = O(nlogn)
Comment: I have just integrated and complied it, it works fine on large data sets. Thank you
Comment: Sure but it is still a O(n) operation, that is executed maximum n times during the program, so a total of O(n^2)
Comment: that's a good answer, but still, here time complexity is O(NxN), how can we reach up to O(nlogn)
Comment: It's O(nlogn). I'll add comments about complexity
Comment: you have inserted commas <,> in input, that means it became integer, but the input is actually a  the integers are only space-separated. First, we have to convert them to integers
Comment: Sure but that's a O(n) operation, i skipped it
Comment: Good answer indeed, though I would argue that the complexity of the first solution is k*n^2 because `t=star.remove(b)` is within a `if` loop, and executed maximum once for each value of `i`
Comment: `star.remove(b)` has to find b in star. Also it will always iterate the whol list, because `list.remove` removes all occurrences.
Comment: @Tawy ya you are right. Is there any better solution for time reduction
Comment: @VIKAS There is no better *generic* solution for this problem AFAIK. If your program is still too slow, you will need to provide more detailed explanations for us to help you (Provide actual inputs for which the program is too slow, explain why you need to solve this problem so that maybe we can come up with an alternative, etc...)