Programs & Examples On #Eshell

Eshell is a command shell written in Emacs Lisp.

How to get input textfield values when enter key is pressed in react js?

Adding onKeyPress will work onChange in Text Field.

<TextField
  onKeyPress={(ev) => {
    console.log(`Pressed keyCode ${ev.key}`);
    if (ev.key === 'Enter') {
      // Do code here
      ev.preventDefault();
    }
  }}
/>

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

I got this error message from a completely different case. It seemed that the exception handler in tensorflow raised it. You can check each row in the Traceback. In my case, it happened in tensorflow/python/lib/io/file_io.py, because this file contained a different bug, where self.__mode and self.__name weren't initialized, and it needed to call self._FileIO__mode, and self_FileIO__name instead.

UTF-8 output from PowerShell

Not an expert on encoding, but after reading these...

... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.

If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding parameter on the out-file cmdlet e.g.

write-output "hello" | out-file "enctest.txt" -encoding utf8

Nothing else you can do on the PowerShell front then, but the following post may well help you:.

php exec() is not executing the command

I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().

Thanks @mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.

So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.

For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.

exec('some_command 2>&1', $output);
print_r($output);  // to see the response to your command

Thanks for all the help guys, I appreciate it ;)

How do I run a Python script from C#?

Execute Python script from C

Create a C# project and write the following code.

using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            run_cmd();
        }

        private void run_cmd()
        {

            string fileName = @"C:\sample_script.py";

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName)
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            p.Start();

            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            Console.WriteLine(output);

            Console.ReadLine();

        }
    }
}

Python sample_script

print "Python C# Test"

You will see the 'Python C# Test' in the console of C#.

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

Trying GO:

package main

import "fmt"
import "math"

func main() {
    var n, m, c int
    for i := 1; ; i++ {
        n, m, c = i * (i + 1) / 2, int(math.Sqrt(float64(n))), 0
        for f := 1; f < m; f++ {
            if n % f == 0 { c++ }
    }
    c *= 2
    if m * m == n { c ++ }
    if c > 1001 {
        fmt.Println(n)
        break
        }
    }
}

I get:

original c version: 9.1690 100%
go: 8.2520 111%

But using:

package main

import (
    "math"
    "fmt"
 )

// Sieve of Eratosthenes
func PrimesBelow(limit int) []int {
    switch {
        case limit < 2:
            return []int{}
        case limit == 2:
            return []int{2}
    }
    sievebound := (limit - 1) / 2
    sieve := make([]bool, sievebound+1)
    crosslimit := int(math.Sqrt(float64(limit))-1) / 2
    for i := 1; i <= crosslimit; i++ {
        if !sieve[i] {
            for j := 2 * i * (i + 1); j <= sievebound; j += 2*i + 1 {
                sieve[j] = true
            }
        }
    }
    plimit := int(1.3*float64(limit)) / int(math.Log(float64(limit)))
    primes := make([]int, plimit)
    p := 1
    primes[0] = 2
    for i := 1; i <= sievebound; i++ {
        if !sieve[i] {
            primes[p] = 2*i + 1
            p++
            if p >= plimit {
                break
            }
        }
    }
    last := len(primes) - 1
    for i := last; i > 0; i-- {
        if primes[i] != 0 {
            break
        }
        last = i
    }
    return primes[0:last]
}



func main() {
    fmt.Println(p12())
}
// Requires PrimesBelow from utils.go
func p12() int {
    n, dn, cnt := 3, 2, 0
    primearray := PrimesBelow(1000000)
    for cnt <= 1001 {
        n++
        n1 := n
        if n1%2 == 0 {
            n1 /= 2
        }
        dn1 := 1
        for i := 0; i < len(primearray); i++ {
            if primearray[i]*primearray[i] > n1 {
                dn1 *= 2
                break
            }
            exponent := 1
            for n1%primearray[i] == 0 {
                exponent++
                n1 /= primearray[i]
            }
            if exponent > 1 {
                dn1 *= exponent
            }
            if n1 == 1 {
                break
            }
        }
        cnt = dn * dn1
        dn = dn1
    }
    return n * (n - 1) / 2
}

I get:

original c version: 9.1690 100%
thaumkid's c version: 0.1060 8650%
first go version: 8.2520 111%
second go version: 0.0230 39865%

I also tried Python3.6 and pypy3.3-5.5-alpha:

original c version: 8.629 100%
thaumkid's c version: 0.109 7916%
Python3.6: 54.795 16%
pypy3.3-5.5-alpha: 13.291 65%

and then with following code I got:

original c version: 8.629 100%
thaumkid's c version: 0.109 8650%
Python3.6: 1.489 580%
pypy3.3-5.5-alpha: 0.582 1483%

def D(N):
    if N == 1: return 1
    sqrtN = int(N ** 0.5)
    nf = 1
    for d in range(2, sqrtN + 1):
        if N % d == 0:
            nf = nf + 1
    return 2 * nf - (1 if sqrtN**2 == N else 0)

L = 1000
Dt, n = 0, 0

while Dt <= L:
    t = n * (n + 1) // 2
    Dt = D(n/2)*D(n+1) if n%2 == 0 else D(n)*D((n+1)/2)
    n = n + 1

print (t)

Executing Batch File in C#

It works fine. I tested it like this:

String command = @"C:\Doit.bat";

ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
// ProcessInfo.CreateNoWindow = true;

I commented out turning off the window so I could SEE it run.

Hide console window from Process.Start C#

This should work, try;


Add a System Reference.

using System.Diagnostics;

Then use this code to run your command in a hiden CMD Window.

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Enter your command here";
cmd.Start();

Disable and enable buttons in C#

button2.Enabled == true ;

thats the problem - it should be:

button2.Enabled = true ;

How to start a Process as administrator mode in C#

This works when I try it. I double-checked with two sample programs:

using System;
using System.Diagnostics;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      Process.Start("ConsoleApplication2.exe");
    }
  }
}

using System;
using System.IO;

namespace ConsoleApplication2 {
  class Program {
    static void Main(string[] args) {
      try {
        File.WriteAllText(@"c:\program files\test.txt", "hello world");
      }
      catch (Exception ex) {
        Console.WriteLine(ex.ToString());
        Console.ReadLine();
      }
    }
  }
}

First verified that I get the UAC bomb:

System.UnauthorizedAccessException: Access to the path 'c:\program files\test.txt' is denied.
// etc..

Then added a manifest to ConsoleApplication1 with the phrase:

    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

No bomb. And a file I can't easily delete :) This is consistent with several previous tests on various machines running Vista and Win7. The started program inherits the security token from the starter program. If the starter has acquired admin privileges, the started program has them as well.

Error in Process.Start() -- The system cannot find the file specified

You can use the folowing to get the full path to your program like this:

Environment.CurrentDirectory

How can I Convert HTML to Text in C#?

Just a note about the HtmlAgilityPack for posterity. The project contains an example of parsing text to html, which, as noted by the OP, does not handle whitespace at all like anyone writing HTML would envisage. There are full-text rendering solutions out there, noted by others to this question, which this is not (it cannot even handle tables in its current form), but it is lightweight and fast, which is all I wanted for creating a simple text version of HTML emails.

using System.IO;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

//small but important modification to class https://github.com/zzzprojects/html-agility-pack/blob/master/src/Samples/Html2Txt/HtmlConvert.cs
public static class HtmlToText
{

    public static string Convert(string path)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.Load(path);
        return ConvertDoc(doc);
    }

    public static string ConvertHtml(string html)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);
        return ConvertDoc(doc);
    }

    public static string ConvertDoc (HtmlDocument doc)
    {
        using (StringWriter sw = new StringWriter())
        {
            ConvertTo(doc.DocumentNode, sw);
            sw.Flush();
            return sw.ToString();
        }
    }

    internal static void ConvertContentTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo)
    {
        foreach (HtmlNode subnode in node.ChildNodes)
        {
            ConvertTo(subnode, outText, textInfo);
        }
    }
    public static void ConvertTo(HtmlNode node, TextWriter outText)
    {
        ConvertTo(node, outText, new PreceedingDomTextInfo(false));
    }
    internal static void ConvertTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo)
    {
        string html;
        switch (node.NodeType)
        {
            case HtmlNodeType.Comment:
                // don't output comments
                break;
            case HtmlNodeType.Document:
                ConvertContentTo(node, outText, textInfo);
                break;
            case HtmlNodeType.Text:
                // script and style must not be output
                string parentName = node.ParentNode.Name;
                if ((parentName == "script") || (parentName == "style"))
                {
                    break;
                }
                // get text
                html = ((HtmlTextNode)node).Text;
                // is it in fact a special closing node output as text?
                if (HtmlNode.IsOverlappedClosingElement(html))
                {
                    break;
                }
                // check the text is meaningful and not a bunch of whitespaces
                if (html.Length == 0)
                {
                    break;
                }
                if (!textInfo.WritePrecedingWhiteSpace || textInfo.LastCharWasSpace)
                {
                    html= html.TrimStart();
                    if (html.Length == 0) { break; }
                    textInfo.IsFirstTextOfDocWritten.Value = textInfo.WritePrecedingWhiteSpace = true;
                }
                outText.Write(HtmlEntity.DeEntitize(Regex.Replace(html.TrimEnd(), @"\s{2,}", " ")));
                if (textInfo.LastCharWasSpace = char.IsWhiteSpace(html[html.Length - 1]))
                {
                    outText.Write(' ');
                }
                    break;
            case HtmlNodeType.Element:
                string endElementString = null;
                bool isInline;
                bool skip = false;
                int listIndex = 0;
                switch (node.Name)
                {
                    case "nav":
                        skip = true;
                        isInline = false;
                        break;
                    case "body":
                    case "section":
                    case "article":
                    case "aside":
                    case "h1":
                    case "h2":
                    case "header":
                    case "footer":
                    case "address":
                    case "main":
                    case "div":
                    case "p": // stylistic - adjust as you tend to use
                        if (textInfo.IsFirstTextOfDocWritten)
                        {
                            outText.Write("\r\n");
                        }
                        endElementString = "\r\n";
                        isInline = false;
                        break;
                    case "br":
                        outText.Write("\r\n");
                        skip = true;
                        textInfo.WritePrecedingWhiteSpace = false;
                        isInline = true;
                        break;
                    case "a":
                        if (node.Attributes.Contains("href"))
                        {
                            string href = node.Attributes["href"].Value.Trim();
                            if (node.InnerText.IndexOf(href, StringComparison.InvariantCultureIgnoreCase)==-1)
                            {
                                endElementString =  "<" + href + ">";
                            }  
                        }
                        isInline = true;
                        break;
                    case "li": 
                        if(textInfo.ListIndex>0)
                        {
                            outText.Write("\r\n{0}.\t", textInfo.ListIndex++); 
                        }
                        else
                        {
                            outText.Write("\r\n*\t"); //using '*' as bullet char, with tab after, but whatever you want eg "\t->", if utf-8 0x2022
                        }
                        isInline = false;
                        break;
                    case "ol": 
                        listIndex = 1;
                        goto case "ul";
                    case "ul": //not handling nested lists any differently at this stage - that is getting close to rendering problems
                        endElementString = "\r\n";
                        isInline = false;
                        break;
                    case "img": //inline-block in reality
                        if (node.Attributes.Contains("alt"))
                        {
                            outText.Write('[' + node.Attributes["alt"].Value);
                            endElementString = "]";
                        }
                        if (node.Attributes.Contains("src"))
                        {
                            outText.Write('<' + node.Attributes["src"].Value + '>');
                        }
                        isInline = true;
                        break;
                    default:
                        isInline = true;
                        break;
                }
                if (!skip && node.HasChildNodes)
                {
                    ConvertContentTo(node, outText, isInline ? textInfo : new PreceedingDomTextInfo(textInfo.IsFirstTextOfDocWritten){ ListIndex = listIndex });
                }
                if (endElementString != null)
                {
                    outText.Write(endElementString);
                }
                break;
        }
    }
}
internal class PreceedingDomTextInfo
{
    public PreceedingDomTextInfo(BoolWrapper isFirstTextOfDocWritten)
    {
        IsFirstTextOfDocWritten = isFirstTextOfDocWritten;
    }
    public bool WritePrecedingWhiteSpace {get;set;}
    public bool LastCharWasSpace { get; set; }
    public readonly BoolWrapper IsFirstTextOfDocWritten;
    public int ListIndex { get; set; }
}
internal class BoolWrapper
{
    public BoolWrapper() { }
    public bool Value { get; set; }
    public static implicit operator bool(BoolWrapper boolWrapper)
    {
        return boolWrapper.Value;
    }
    public static implicit operator BoolWrapper(bool boolWrapper)
    {
        return new BoolWrapper{ Value = boolWrapper };
    }
}

As an example, the following HTML code...

<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
        <header>
            Whatever Inc.
        </header>
        <main>
            <p>
                Thanks for your enquiry. As this is the 1<sup>st</sup> time you have contacted us, we would like to clarify a few things:
            </p>
            <ol>
                <li>
                    Please confirm this is your email by replying.
                </li>
                <li>
                    Then perform this step.
                </li>
            </ol>
            <p>
                Please solve this <img alt="complex equation" src="http://upload.wikimedia.org/wikipedia/commons/8/8d/First_Equation_Ever.png"/>. Then, in any order, could you please:
            </p>
            <ul>
                <li>
                    a point.
                </li>
                <li>
                    another point, with a <a href="http://en.wikipedia.org/wiki/Hyperlink">hyperlink</a>.
                </li>
            </ul>
            <p>
                Sincerely,
            </p>
            <p>
                The whatever.com team
            </p>
        </main>
        <footer>
            Ph: 000 000 000<br/>
            mail: whatever st
        </footer>
    </body>
</html>

...will be transformed into:

Whatever Inc. 


Thanks for your enquiry. As this is the 1st time you have contacted us, we would like to clarify a few things: 

1.  Please confirm this is your email by replying. 
2.  Then perform this step. 

Please solve this [complex equation<http://upload.wikimedia.org/wikipedia/commons/8/8d/First_Equation_Ever.png>]. Then, in any order, could you please: 

*   a point. 
*   another point, with a hyperlink<http://en.wikipedia.org/wiki/Hyperlink>. 

Sincerely, 

The whatever.com team 


Ph: 000 000 000
mail: whatever st 

...as opposed to:

        Whatever Inc.


            Thanks for your enquiry. As this is the 1st time you have contacted us, we would like to clarify a few things:

                Please confirm this is your email by replying.

                Then perform this step.


            Please solve this . Then, in any order, could you please:

                a point.

                another point, with a hyperlink.


            Sincerely,


            The whatever.com team

        Ph: 000 000 000
        mail: whatever st

How to execute an .SQL script file using c#

I couldn't find any exact and valid way to do this. So after a whole day, I came with this mixed code achieved from different sources and trying to get the job done.

But it is still generating an exception ExecuteNonQuery: CommandText property has not been Initialized even though it successfully runs the script file - in my case, it successfully creates the database and inserts data on the first startup.

public partial class Form1 : MetroForm
{
    SqlConnection cn;
    SqlCommand cm;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if (!CheckDatabaseExist())
        {
            GenerateDatabase();
        }
    }

    private bool CheckDatabaseExist()
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=SalmanTradersDB;Integrated Security=true");
        try
        {
            con.Open();
            return true;
        }
        catch
        {
            return false;
        }
    }

    private void GenerateDatabase()
    {

        try
        {
            cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format("drop databse {0}", "SalmanTradersDB"));
            cm = new SqlCommand(sb.ToString() , cn);
            cn.Open();
            cm.ExecuteNonQuery();
            cn.Close();
        }
        catch
        {

        }
        try
        {
            //Application.StartupPath is the location where the application is Installed
            //Here File Path Can Be Provided Via OpenFileDialog
            if (File.Exists(Application.StartupPath + "\\script.sql"))
            {
                string script = null;
                script = File.ReadAllText(Application.StartupPath + "\\script.sql");
                string[] ScriptSplitter = script.Split(new string[] { "GO" }, StringSplitOptions.None);
                using (cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
                {
                    cn.Open();
                    foreach (string str in ScriptSplitter)
                    {
                        using (cm = cn.CreateCommand())
                        {
                            cm.CommandText = str;
                            cm.ExecuteNonQuery();
                        }
                    }
                }
            }
        }
        catch
        {

        }

    }

}

Execute multiple command lines with the same process using .NET

I prefer to do it by using a BAT file.

With BAT file you have more control and can do whatever you want.

string batFileName = path + @"\" + Guid.NewGuid() + ".bat";

using (StreamWriter batFile = new StreamWriter(batFileName))
{
    batFile.WriteLine($"YOUR COMMAND");
    batFile.WriteLine($"YOUR COMMAND");
    batFile.WriteLine($"YOUR COMMAND");
}

ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/c " + batFileName);
processStartInfo.UseShellExecute = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;

Process p = new Process();
p.StartInfo = processStartInfo;
p.Start();
p.WaitForExit();

File.Delete(batFileName);

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

How to spawn a process and capture its STDOUT in .NET?

I needed to capture both stdout and stderr and have it timeout if the process didn't exit when expected. I came up with this:

Process process = new Process();
StringBuilder outputStringBuilder = new StringBuilder();

try
{
process.StartInfo.FileName = exeFileName;
process.StartInfo.WorkingDirectory = args.ExeDirectory;
process.StartInfo.Arguments = args;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.EnableRaisingEvents = false;
process.OutputDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
process.ErrorDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
var processExited = process.WaitForExit(PROCESS_TIMEOUT);

if (processExited == false) // we timed out...
{
    process.Kill();
    throw new Exception("ERROR: Process took too long to finish");
}
else if (process.ExitCode != 0)
{
    var output = outputStringBuilder.ToString();
    var prefixMessage = "";

    throw new Exception("Process exited with non-zero exit code of: " + process.ExitCode + Environment.NewLine + 
    "Output from process: " + outputStringBuilder.ToString());
}
}
finally
{                
process.Close();
}

I am piping the stdout and stderr into the same string, but you could keep it separate if needed. It uses events, so it should handle them as they come (I believe). I have run this successfully, and will be volume testing it soon.

ProcessStartInfo hanging on "WaitForExit"? Why?

Workaround I ended up using to avoid all the complexity:

var outputFile = Path.GetTempFileName();
info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args) + " > " + outputFile + " 2>&1");
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(File.ReadAllText(outputFile)); //need the StandardOutput contents

So I create a temp file, redirect both the output and error to it by using > outputfile > 2>&1 and then just read the file after the process has finished.

The other solutions are fine for scenarios where you want to do other stuff with the output, but for simple stuff this avoids a lot of complexity.

How to include NA in ifelse?

You can't really compare NA with another value, so using == would not work. Consider the following:

NA == NA
# [1] NA

You can just change your comparison from == to %in%:

ifelse(is.na(test$time) | test$type %in% "A", NA, "1")
# [1] NA  "1" NA  "1"

Regarding your other question,

I could get this to work with my existing code if I could somehow change the result of is.na(test$type) to return FALSE instead of TRUE, but I'm not sure how to do that.

just use ! to negate the results:

!is.na(test$time)
# [1]  TRUE  TRUE FALSE  TRUE

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

First kill all the hanged instances of httpd, and then try restarting Apache:

service httpd restart

How to scanf only integer?

Use fgets and strtol,

A pointer to the first character following the integer representation in s is stored in the object pointed by p, if *p is different to \n then you have a bad input.

#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
    char *p, s[100];
    long n;

    while (fgets(s, sizeof(s), stdin)) {
        n = strtol(s, &p, 10);
        if (p == s || *p != '\n') {
            printf("Please enter an integer: ");
        } else break;
    }
    printf("You entered: %ld\n", n);
    return 0;
}

Get parent directory of running script

Got it myself, it's a bit kludgy but it works:

substr(dirname($_SERVER['SCRIPT_NAME']), 0, strrpos(dirname($_SERVER['SCRIPT_NAME']), '/') + 1)

So if I have /path/to/folder/index.php, this results in /path/to/.

<script> tag vs <script type = 'text/javascript'> tag

<!-- HTML4 and (x)HTML -->
<script type="text/javascript"></script>


<!-- HTML5 -->
<script></script>

type attribute identifies the scripting language of code embedded within a script element or referenced via the element’s src attribute. This is specified as a MIME type; examples of supported MIME types include text/javascript, text/ecmascript, application/javascript, and application/ecmascript. If this attribute is absent, the script is treated as JavaScript.

Ref: https://developer.mozilla.org/en/docs/Web/HTML/Element/script

Confirm deletion in modal / dialog using Twitter Bootstrap?

I'd realise its a very old question, but since i wondered today for a more efficient method of handling the bootstrap modals. I did some research and found something better then the solutions which are shown above, that can be found at this link:

http://www.petefreitag.com/item/809.cfm

First load the jquery

$(document).ready(function() {
    $('a[data-confirm]').click(function(ev) {
        var href = $(this).attr('href');

        if (!$('#dataConfirmModal').length) {
            $('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
        } 
        $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
        $('#dataConfirmOK').attr('href', href);
        $('#dataConfirmModal').modal({show:true});
        return false;
    });
});

Then just ask any question/confirmation to href:

<a href="/any/url/delete.php?ref=ID" data-confirm="Are you sure you want to delete?">Delete</a>

This way the confirmation modal is a lot more universal and so it can easily be re-used on other parts of your website.

What is sharding and why is it important?

If you have queries to a DBMS for which the locality is quite restricted (say, a user only fires selects with a 'where username = $my_username') it makes sense to put all the usernames starting with A-M on one server and all from N-Z on the other. By this you get near linear scaling for some queries.

Long story short: Sharding is basically the process of distributing tables onto different servers in order to balance the load onto both equally.

Of course, it's so much more complicated in reality. :)

Can I run Keras model on gpu?

Yes you can run keras models on GPU. Few things you will have to check first.

  1. your system has GPU (Nvidia. As AMD doesn't work yet)
  2. You have installed the GPU version of tensorflow
  3. You have installed CUDA installation instructions
  4. Verify that tensorflow is running with GPU check if GPU is working

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

for TF > v2.0

sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))

(Thanks @nbro and @Ferro for pointing this out in the comments)

OR

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

output will be something like this:

[
  name: "/cpu:0"device_type: "CPU",
  name: "/gpu:0"device_type: "GPU"
]

Once all this is done your model will run on GPU:

To Check if keras(>=2.1.1) is using GPU:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

All the best.

How to run mvim (MacVim) from Terminal?

If you have homeBrew installed, this is all you have to do:

brew install macvim
brew linkapps

Then type mvim in your terminal to run MacVim.

Retrieving an element from array list in Android?

What I understand your question is that you want to fetch an element in an ArrayList at a specific location.

Suppose your list contains Integers 1,2,3,4,5 and you want to fetch the value 3. Then the following lines of code will work.

ArrayList<Integer> list = new ArrayList<Integer>();
        if(list.contains(3)){//check if the list contains the element
            list.get(list.indexOf(3));//get the element by passing the index of the element
        }

Either ways you could use list.get(list.lastIndexOf(3))

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

    >>import pandas as pd
    >>import numpy as np
    >>data.shape
    (480,193)
    >>type(data)
    numpy.ndarray
    >>df=pd.DataFrame(data=data[0:,0:],
    ...        index=[i for i in range(data.shape[0])],
    ...        columns=['f'+str(i) for i in range(data.shape[1])])
    >>df.head()
    [![array to dataframe][1]][1]

enter image description here

Tensorflow image reading & display

I used CIFAR10 format instead of STL10 and code came out like

filename_queue = tf.train.string_input_producer(filenames)
read_input = read_cifar10(filename_queue)
with tf.Session() as sess:       
    tf.train.start_queue_runners(sess=sess)
    result = sess.run(read_input.uint8image)        
img = Image.fromarray(result, "RGB")    
img.save('my.jpg')

The snippet is identical with mttk and Rosa Gronchi, but Somehow I wasn't able to show the image during run-time, so I saved as the JPG file.

Why is HttpClient BaseAddress not working?

Ran into a issue with the HTTPClient, even with the suggestions still could not get it to authenticate. Turns out I needed a trailing '/' in my relative path.

i.e.

var result = await _client.GetStringAsync(_awxUrl + "api/v2/inventories/?name=" + inventoryName);
var result = await _client.PostAsJsonAsync(_awxUrl + "api/v2/job_templates/" + templateId+"/launch/" , new {
                inventory = inventoryId
            });

Target class controller does not exist - Laravel 8

If you are using laravel 8

just copy and paste my code

use App\Http\Controllers\UserController;

Route::get('/user', [UserController::class, 'index']);

Split string to equal length substrings in Java

Here is a one liner implementation using Java8 streams:

String input = "Thequickbrownfoxjumps";
final AtomicInteger atomicInteger = new AtomicInteger(0);
Collection<String> result = input.chars()
                                    .mapToObj(c -> String.valueOf((char)c) )
                                    .collect(Collectors.groupingBy(c -> atomicInteger.getAndIncrement() / 4
                                                                ,Collectors.joining()))
                                    .values();

It gives the following output:

[Theq, uick, brow, nfox, jump, s]

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

In MS DOS copying several files to one file

make sure you have mapped the y: drive, or copy all the files to local dir c:/local

c:/local> copy *.* c:/newfile.txt

What is the proper declaration of main in C++?

From Standard docs., 3.6.1.2 Main Function,

It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

int main() { / ... / } and int main(int argc, char* argv[]) { / ... / }

In the latter form argc shall be the number of arguments passed to the program from the environment in which the program is run.If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings.....

Hope that helps..

How to force Sequential Javascript Execution?

I tried the callback way and could not get this to work, what you have to understand is that values are still atomic even though execution is not. For example:

alert('1'); <--- these two functions will be executed at the same time

alert('2'); <--- these two functions will be executed at the same time

but doing like this will force us to know the order of execution:

loop=2;
total=0;
for(i=0;i<loop;i++) {
           total+=1;
           if(total == loop)
                      alert('2');
           else
                      alert('1');
}

PHP is not recognized as an internal or external command in command prompt

You need to Go to My Computer->properties -> Advanced system setting

Now click on Environment Variables..

enter image description here

Add ;C:\xampp\php in path variable value

enter image description here

Now restart command prompt DONE!

Note: Make sure you run CMD via run as administrator

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I know this is not an answer, but I'd like to contribute to this matter for what it's worth. It would be great if they could release justify-self for flexbox to make it truly flexible.

It's my belief that when there are multiple items on the axis, the most logical way for justify-self to behave is to align itself to its nearest neighbours (or edge) as demonstrated below.

I truly hope, W3C takes notice of this and will at least consider it. =)

enter image description here

This way you can have an item that is truly centered regardless of the size of the left and right box. When one of the boxes reaches the point of the center box it will simply push it until there is no more space to distribute.

enter image description here

The ease of making awesome layouts are endless, take a look at this "complex" example.

enter image description here

Route [login] not defined

Laravel ^5.7

The Authenticate Middleware

Laravel ^5.7 includes new middleware to handle and redirect unauthenticated users.

It works well with "web" guard... of course the "login" route (or whatever you name your login route) should be defined in web.php.

the problem is when your are using custom guard. Different guard would redirect unauthenticated users to different route.

here's a quick workaround based on John's response (it works for me).


app/Http/Middleware/Authenticate.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * @var array
     */
    protected $guards = [];




    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $this->guards = $guards;

        return parent::handle($request, $next, ...$guards);
    }




    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {

            if (in_array('admin', $this->guards)) {

                return route('admin.login');
            }

            return route('login');
        }
    }
}

Source : Issue #26292

How do you add a scroll bar to a div?

<head>
<style>
div.scroll
{
background-color:#00FFFF;
width:40%;
height:200PX;
FLOAT: left;
margin-left: 5%;
padding: 1%;
overflow:scroll;
}


</style>
</head>

<body>



<div class="scroll">You can use the overflow property when you want to have better       control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better </div>


</body>
</html>

How to set different colors in HTML in one statement?

_x000D_
_x000D_
.rainbow {_x000D_
  background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
  background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
  color:transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<h2><span class="rainbow">Rainbows are colorful and scalable and lovely</span></h2>
_x000D_
_x000D_
_x000D_

How to show changed file name only with git log?

Thanks for your answers, @mvp, @xero, I get what I want base on both of your answers.

git log --name-only 

or

git log --name-only --oneline

for short.

How to completely uninstall Android Studio from windows(v10)?

To Completely Remove Android Studio from Windows:

Step 1: Run the Android Studio uninstaller

The first step is to run the uninstaller. Open the Control Panel and under Programs, select Uninstall a Program. After that, click on "Android Studio" and press Uninstall. If you have multiple versions, uninstall them as well.

Step 2: Remove the Android Studio files

To delete any remains of Android Studio setting files, in File Explorer, go to your user folder (%USERPROFILE%), and delete .android, .AndroidStudio and any analogous directories with versions on the end, i.e. .AndroidStudio1.2, as well as .gradle and .m2 if they exist.

Then go to %APPDATA% and delete the JetBrains directory.

Finally, go to C:\Program Files and delete the Android directory.

Step 3: Remove SDK

To delete any remains of the SDK, go to %LOCALAPPDATA% and delete the Android directory.

Step 4: Delete Android Studio projects

Android Studio creates projects in a folder %USERPROFILE%\AndroidStudioProjects, which you may want to delete.

UICollectionView Self Sizing Cells with Auto Layout

If you implement UICollectionViewDelegateFlowLayout method:

- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath*)indexPath

When you call collectionview performBatchUpdates:completion:, the size height will use sizeForItemAtIndexPath instead of preferredLayoutAttributesFittingAttributes.

The rendering process of performBatchUpdates:completion will go through the method preferredLayoutAttributesFittingAttributes but it ignores your changes.

SQL Server: IF EXISTS ; ELSE

EDIT

I want to add the reason that your IF statement seems to not work. When you do an EXISTS on an aggregate, it's always going to be true. It returns a value even if the ID doesn't exist. Sure, it's NULL, but its returning it. Instead, do this:

if exists(select 1 from table where id = 4)

and you'll get to the ELSE portion of your IF statement.


Now, here's a better, set-based solution:

update b
  set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
  on b.id = a.id
where
  b.id = yourid

This has the benefit of being able to run on the entire table rather than individual ids.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.

You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.

javascript create empty array of a given size

As of ES5 (when this answer was given):

If you want an empty array of undefined elements, you could simply do

var whatever = new Array(5);

this would give you

[undefined, undefined, undefined, undefined, undefined]

and then if you wanted it to be filled with empty strings, you could do

whatever.fill('');

which would give you

["", "", "", "", ""]

And if you want to do it in one line:

var whatever = Array(5).fill('');

Set focus on textbox in WPF

txtCompanyID.Focusable = true;
Keyboard.Focus(txtCompanyID);

msdn:

There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true.

You could break after the setting line and check the value of IsKeyboardFocused property. Also check if you really reach that line or maybe you set some other element to get focus after that.

How to delete/remove nodes on Firebase

In case you are using axios and trying via a service call.

URL: https://react-16-demo.firebaseio.com/
Schema Name: todos
Key: -Lhu8a0uoSRixdmECYPE

axios.delete(`https://react-16-demo.firebaseio.com/todos/-Lhu8a0uoSRixdmECYPE.json`). then();

can help.

VS 2017 Git Local Commit DB.lock error on every commit

I'm not using Git directly thru Visual Studio but using the Git Desktop client.

I did however get a similar error but solved it by closing Visual Studio before Committing changes to master.

Safely limiting Ansible playbooks to a single machine?

AWS users using the EC2 External Inventory Script can simply filter by instance id:

ansible-playbook sample-playbook.yml --limit i-c98d5a71 --list-hosts

This works because the inventory script creates default groups.

How to add soap header in java

i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

Basically JAVA_HOME is use to set path of the java . it is use in windows. it's used for set path of the multiple software like as java EE , ANT and Maven. this is the steps to solve your problem:

only for core java to set path : path :"C:\Program Files\Java\jre1.8.0_77\bin" but when you are use multi built like as ANT , core java then you are used JAVE_HOME in environment .

follow the steps :

JAVA_HOME:"C:\Program Files\Java\jre1.8.0_77\bin" ANT_HOME:"C:\ant\apache-ant-1.9.6"

Path: JAVA_HOME, ANT_HOME; it is the systematic way to set the environment variable..

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

You should check if you have @Component, @Repository or similar added on the class

Android WebView progress bar

According to Md. Sajedul Karim answer I wrote a similar one.

webView = (WebView) view.findViewById(R.id.web);
progressBar = (ProgressBar) view.findViewById(R.id.progress);
webView.setWebChromeClient(new WebChromeClient());

setProgressBarVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        setProgressBarVisibility(View.VISIBLE);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        setProgressBarVisibility(View.GONE);
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        Toast.makeText(getActivity(), "Cannot load page", Toast.LENGTH_SHORT).show();
        setProgressBarVisibility(View.GONE);
    }
});

webView.loadUrl(url);

private void setProgressBarVisibility(int visibility) {
    // If a user returns back, a NPE may occur if WebView is still loading a page and then tries to hide a ProgressBar.
    if (progressBar != null) {
        progressBar.setVisibility(visibility);
    }
}

Convert a list of characters into a string

If your Python interpreter is old (1.5.2, for example, which is common on some older Linux distributions), you may not have join() available as a method on any old string object, and you will instead need to use the string module. Example:

a = ['a', 'b', 'c', 'd']

try:
    b = ''.join(a)

except AttributeError:
    import string
    b = string.join(a, '')

The string b will be 'abcd'.

Converting dictionary to JSON

No need to convert it in a string by using json.dumps()

r = {'is_claimed': 'True', 'rating': 3.5}
file.write(r['is_claimed'])
file.write(str(r['rating']))

You can get the values directly from the dict object.

Converting a string to a date in a cell

I was struggling with this for some time and after some help on a post I was able to come up with this formula =(DATEVALUE(LEFT(XX,10)))+(TIMEVALUE(MID(XX,12,5))) where XX is the cell in reference.

I've come across many other forums with people asking the same thing and this, to me, seems to be the simplest answer. What this will do is return text that is copied in from this format 2014/11/20 11:53 EST and turn it in to a Date/Time format so it can be sorted oldest to newest. It works with short date/long date and if you want the time just format the cell to display time and it will show. Hope this helps anyone who goes searching around like I did.

ISO C90 forbids mixed declarations and code in C

I think you should move the variable declaration to top of block. I.e.

{
    foo();
    int i = 0;
    bar();
}

to

{
    int i = 0;
    foo();
    bar();
}

How to expand 'select' option width after the user wants to select an option

you can try and solve using css only. by adding class to select

select{ width:80px;text-overflow:'...';-ms-text-overflow:ellipsis;position:absolute; z-index:+1;}
select:focus{ width:100%;}

for more reference List Box Style in a particular item (option) HTML

Multi Select List Box

Common elements in two lists

consider two list L1 ans L2

Using Java8 we can easily find it out

L1.stream().filter(L2::contains).collect(Collectors.toList())

SelectedValue vs SelectedItem.Value of DropDownList

They are both different. SelectedValue property gives you the actual value of the item in selection whereas SelectedItem.Text gives you the display text. For example: you drop down may have an itme like

<asp:ListItem Text="German" Value="de"></asp:ListItem>

So, in this case SelectedValue would be de and SelectedItem.Text would give 'German'

EDIT:

In that case, they aare both same ... Cause SelectedValue will give you the value stored for current selected item in your dropdown and SelectedItem.Value will be Value of the currently selected item.

So they both would give you the same result.

C++ Structure Initialization

You can even pack Gui13's solution into single initialization statement:

struct address {
                 int street_no;
                 char *street_name;
                 char *city;
                 char *prov;
                 char *postal_code;
               };


address ta = (ta = address(), ta.city = "Hamilton", ta.prov = "Ontario", ta);

Disclaimer: I don't recommend this style

How to access parent Iframe from JavaScript

// just in case some one is searching for a solution
function get_parent_frame_dom_element(win)
{
    win = (win || window);
    var parentJQuery = window.parent.jQuery;
    var ifrms = parentJQuery("iframe.upload_iframe");
    for (var i = 0; i < ifrms.length; i++)
    {
        if (ifrms[i].contentDocument === win.document)
            return ifrms[i];
    }
    return null;
}

How do I remove newlines from a text file?

perl -p -i -e 's/\R//g;' filename

Must do the job.

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

However, numbering starts at 1, so:

x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)

z = np.sin(x)
plt.figure(2)
plt.plot(x, z)

w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)

Also, if you have multiple axes on a figure, such as subplots, use the axes(h) command where h is the handle of the desired axes object to focus on that axes.

(don't have comment privileges yet, sorry for new answer!)

Getting the filenames of all files in a folder

You could do it like that:

File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
    System.out.println("File " + listOfFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    System.out.println("Directory " + listOfFiles[i].getName());
  }
}

Do you want to only get JPEG files or all files?

JavaScript: Collision detection

Here's a very simple bounding rectangle routine. It expects both a and b to be objects with x, y, width and height properties:

function isCollide(a, b) {
    return !(
        ((a.y + a.height) < (b.y)) ||
        (a.y > (b.y + b.height)) ||
        ((a.x + a.width) < b.x) ||
        (a.x > (b.x + b.width))
    );
}

To see this function in action, here's a codepen graciously made by @MixerOID.

DateTime group by date and hour

Using MySQL I usually do it that way:

SELECT count( id ), ...
FROM quote_data
GROUP BY date_format( your_date_column, '%Y%m%d%H' )
order by your_date_column desc;

Or in the same idea, if you need to output the date/hour:

SELECT count( id ) , date_format( your_date_column, '%Y-%m-%d %H' ) as my_date
FROM  your_table 
GROUP BY my_date
order by your_date_column desc;

If you specify an index on your date column, MySQL should be able to use it to speed up things a little.

mysql after insert trigger which updates another table's column

DELIMITER //

CREATE TRIGGER contacts_after_insert
AFTER INSERT
   ON contacts FOR EACH ROW

BEGIN

   DECLARE vUser varchar(50);

   -- Find username of person performing the INSERT into table
   SELECT USER() INTO vUser;

   -- Insert record into audit table
   INSERT INTO contacts_audit
   ( contact_id,
     deleted_date,
     deleted_by)
   VALUES
   ( NEW.contact_id,
     SYSDATE(),
     vUser );

END; //

DELIMITER ;

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

First two answers here: How to enable CORS in AngularJs

How do I get a Date without time in Java?

The most straightforward way:

long millisInDay = 60 * 60 * 24 * 1000;
long currentTime = new Date().getTime();
long dateOnly = (currentTime / millisInDay) * millisInDay;
Date clearDate = new Date(dateOnly);

Best algorithm for detecting cycles in a directed graph

The way I do it is to do a Topological Sort, counting the number of vertices visited. If that number is less than the total number of vertices in the DAG, you have a cycle.

How would you make two <div>s overlap?

Just use negative margins, in the second div say:

<div style="margin-top: -25px;">

And make sure to set the z-index property to get the layering you want.

How do I make HttpURLConnection use a proxy?

Since java 1.5 you can also pass a java.net.Proxy instance to the openConnection(proxy) method:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

If your proxy requires authentication it will give you response 407.

In this case you'll need the following code:

    Authenticator authenticator = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication("user",
                    "password".toCharArray()));
        }
    };
    Authenticator.setDefault(authenticator);

Import CSV file as a pandas DataFrame

Here's an alternative to pandas library using Python's built-in csv module.

import csv
from pprint import pprint
with open('foo.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = reader.next()
    column = {h:[] for h in headers}
    for row in reader:
        for h, v in zip(headers, row):
            column[h].append(v)
    pprint(column)    # Pretty printer

will print

{'Date': ['2012-06-11',
          '2012-06-12',
          '2012-06-13',
          '2012-06-14',
          '2012-06-15',
          '2012-06-16',
          '2012-06-17'],
 'factor_1': ['1.255', '1.258', '1.249', '1.253', '1.258', '1.263', '1.264'],
 'factor_2': ['1.548', '1.554', '1.552', '1.556', '1.552', '1.558', '1.572'],
 'price': ['1600.20',
           '1610.02',
           '1618.07',
           '1624.40',
           '1626.15',
           '1626.15',
           '1626.15']}

Example of SOAP request authenticated with WS-UsernameToken

May be this post (Secure Metro JAX-WS UsernameToken Web Service with Signature, Encryption and TLS (SSL)) provides more insight. As they mentioned "Remember, unless password text or digested password is sent on a secured channel or the token is encrypted, neither password digest nor cleartext password offers no real additional security. "

console.writeline and System.out.println

First I am afraid your question contains a little mistake. There is not method writeline in class Console. Instead class Console provides method writer() that returns PrintWriter. This print writer has println().

Now what is the difference between

System.console().writer().println("hello from console");

and

System.out.println("hello system out");

If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.

Here is an example I have just implemented.

import java.io.Console;


public class TestConsole {
    public static void main(String[] args) {
        Console console = System.console();
        System.out.println("console=" + console);
        console.writer().println("hello from console");
    }
}

When I ran the application from command prompt I got the following:

$ java TestConsole
console=java.io.Console@93dcd
hello from console

but when I redirected the STDOUT to file...

$ java TestConsole >/tmp/test
Exception in thread "main" java.lang.NullPointerException
        at TestConsole.main(TestConsole.java:8)

Line 8 is console.writer().println().

Here is the content of /tmp/test

console=null

I hope my explanations help.

assign multiple variables to the same value in Javascript

Nothing stops you from doing

moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Check this example

_x000D_
_x000D_
var a, b, c;_x000D_
a = b = c = 10;_x000D_
console.log(a + b + c)
_x000D_
_x000D_
_x000D_

Batch file. Delete all files and folders in a directory

Just a modified version of GregM's answer:

set folder="C:\test"
cd /D %folder%
if NOT %errorlevel% == 0 (exit /b 1)
echo Entire content of %cd% will be deleted. Press Ctrl-C to abort
pause

REM First the directories /ad option of dir
for /F "delims=" %%i in ('dir /b /ad') do (echo rmdir "%%i" /s/q)

REM Now the files /a-d option of dir
for /F "delims=" %%i in ('dir /b /a-d') do (echo del "%%i" /q)

REM To deactivate simulation mode remove the word 'echo' before 'rmdir' and 'del'.

IntelliJ Organize Imports

ALT+ENTER was far from eclipse habit ,in IDEA for me mouse over did not work , so in setting>IDESetting>Keymap>Show intention actions and quick-fixes I changed it to mouse left click , It did not support mouse over! but mouse left click was OK and closest to my intention.

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

How to center the text in a JLabel?

The following constructor, JLabel(String, int), allow you to specify the horizontal alignment of the label.

JLabel label = new JLabel("The Label", SwingConstants.CENTER);

How to debug in Android Studio using adb over WiFi

You can find the adb tool in /platform-tools/

cd Library/Android/sdk/platform-tools/

You can check your devices using:

./adb devices

My result:

List of devices attached
XXXXXXXXX   device

Set a TCP port:

./adb shell setprop service.adb.tcp.port 4444

./adb tcpip 4444

Result message:

restarting in TCP mode port: 4444

To init a wifi connection you have to check your device IP and execute:

./adb connect 192.168.0.155:4444

Good luck!

Can you overload controller methods in ASP.NET MVC?

I have achieved this with the help of Attribute Routing in MVC5. Admittedly I am new to MVC coming from a decade of web development using WebForms, but the following has worked for me. Unlike the accepted answer this allows all the overloaded actions to be rendered by the same view file.

First enable Attribute Routing in App_Start/RouteConfig.cs.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );            
    }
}

Optionally decorate your controller class with a default route prefix.

[RoutePrefix("Returns")]
public class ReturnsController : BaseController
{
    //.......

Then decorate your controller actions that overload each other with a common route and parameters to suit. Using type constrained parameters you can use the same URI format with IDs of different types.

[HttpGet]
// Returns
public ActionResult Index()
{
    //.....
}

[HttpGet]
[Route("View")]
// Returns/View
public ActionResult View()
{
    // I wouldn't really do this but it proves the concept.
    int id = 7026;
    return View(id);
}

[HttpGet]
[Route("View/{id:int}")]
// Returns/View/7003
public ActionResult View(int id)
{
    //.....
}

[HttpGet]
[Route("View/{id:Guid}")]
// Returns/View/99300046-0ba4-47db-81bf-ba6e3ac3cf01
public ActionResult View(Guid id)
{
    //.....
}

Hope this helps and is not leading somebody down the wrong path. :-)

How to alter a column and change the default value?

ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';

A second possibility which does the same (thanks to juergen_d):

ALTER TABLE foobar_data CHANGE COLUMN col col VARCHAR(255) NOT NULL DEFAULT '{}';

cannot redeclare block scoped variable (typescript)

For those coming here in this age, here is a simple solution to this issue. It at least worked for me in the backend. I haven't checked with the frontend code.

Just add:

export {};

at the top of your code.

Credit to EUGENE MURAVITSKY

How to use JQuery with ReactJS

You should try and avoid jQuery in ReactJS. But if you really want to use it, you'd put it in componentDidMount() lifecycle function of the component.

e.g.

class App extends React.Component {
  componentDidMount() {
    // Jquery here $(...)...
  }

  // ...
}

Ideally, you'd want to create a reusable Accordion component. For this you could use Jquery, or just use plain javascript + CSS.

class Accordion extends React.Component {
  constructor() {
    super();
    this._handleClick = this._handleClick.bind(this);
  }

  componentDidMount() {
    this._handleClick();
  }

  _handleClick() {
    const acc = this._acc.children;
    for (let i = 0; i < acc.length; i++) {
      let a = acc[i];
      a.onclick = () => a.classList.toggle("active");
    }
  }

  render() {
    return (
      <div 
        ref={a => this._acc = a} 
        onClick={this._handleClick}>
        {this.props.children}
      </div>
    )
  }
}

Then you can use it in any component like so:

class App extends React.Component {
  render() {
    return (
      <div>
        <Accordion>
          <div className="accor">
            <div className="head">Head 1</div>
            <div className="body"></div>
          </div>
        </Accordion>
      </div>
    );
  }
}

Codepen link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110 (I changed this link to https ^)

How can I pretty-print JSON using Go?

By pretty-print, I assume you mean indented, like so

{
    "data": 1234
}

rather than

{"data":1234}

The easiest way to do this is with MarshalIndent, which will let you specify how you would like it indented via the indent argument. Thus, json.MarshalIndent(data, "", " ") will pretty-print using four spaces for indentation.

How do I get the browser scroll position in jQuery?

Since it appears you are using jQuery, here is a jQuery solution.

$(function() {
    $('#Eframe').on("mousewheel", function() {
        alert($(document).scrollTop());
    });
});

Not much to explain here. If you want, here is the jQuery documentation.

Make selected block of text uppercase

Update on March 8, 2018 with Visual Studio Code 1.20.1 (mac)

It has been simplified quite a lot lately.
Very easy and straight forward now.

  1. From "Code" -> "Preferences" -> "Keyboard shortcuts"
  2. From the search box just search for "editor.action.transformTo", You will see the screen like: screenshot of keyboard shortcuts setup dialog in Visual Studio Code (mac)

  3. Click the "plus" sign at the left of each item, it will prompt dialog for your to [press] you desired key-bindings, after it showing that on the screen, just hit [Enter] to save.

PHP Pass by reference in foreach

First loop

$v = $a[0];
$v = $a[1];
$v = $a[2];
$v = $a[3];

Yes! Current $v = $a[3] position.

Second loop

$a[3] = $v = $a[0], echo $v; // same as $a[3] and $a[0] == 'zero'
$a[3] = $v = $a[1], echo $v; // same as $a[3] and $a[1] == 'one'
$a[3] = $v = $a[2], echo $v; // same as $a[3] and $a[2] == 'two'
$a[3] = $v = $a[3], echo $v; // same as $a[3] and $a[3] == 'two'

because $a[3] is assigned by before processing.

How to loop through each and every row, column and cells in a GridView and get its value

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                String header = dataGridView1.Columns[i].HeaderText;
                //String cellText = row.Cells[i].Text;
                DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column 
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
                int colWidth = column.Width; // store columns width after auto resize           
                colWidth += 50; // add 30 pixels to what 'colWidth' already is
                this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
            }
        }

Find empty or NaN entry in Pandas Dataframe

you also do something good:

text_empty = df['column name'].str.len() > -1

df.loc[text_empty].index

The results will be the rows which are empty & it's index number.

How to change value of a request parameter in laravel

If you need to update a property in the request, I recommend you to use the replace method from Request class used by Laravel

$request->replace(['property to update' => $newValue]);

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I had the same error and ended up solving it by upgrading my Oracle ojdbc driver to a version compatible with the Oracle database version

Best Practice: Software Versioning

I basically follow this pattern:

  • start from 0.1.0

  • when it's ready I branch the code in the source repo, tag 0.1.0 and create the 0.1.0 branch, the head/trunk becomes 0.2.0-snapshot or something similar

  • I add new features only to the trunk, but backport fixes to the branch and in time I release from it 0.1.1, 0.1.2, ...

  • I declare version 1.0.0 when the product is considered feature complete and doesn't have major shortcomings

  • from then on - everyone can decide when to increment the major version...

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

How to use confirm using sweet alert?

document.querySelector('#from1').onsubmit = function(e){

 swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!",
    closeOnConfirm: false,
    closeOnCancel: false
 },
 function(isConfirm){

   if (isConfirm){
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

    } else {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
         e.preventDefault();
    }
 });
};

Strings in C, how to get subString

#include <stdio.h>
#include <string.h>

int main ()
{
        char someString[]="abcdedgh";
        char otherString[]="00000";
        memcpy (otherString, someString, 5);
        printf ("someString: %s\notherString: %s\n", someString, otherString);
        return 0;
}

You will not need stdio.h if you don't use the printf statement and putting constants in all but the smallest programs is bad form and should be avoided.

SQL Server Insert Example

To insert a single row of data:

INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');

To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');

To insert multiple rows of data in SQL Server 2008 or later:

INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'

Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I also got the same issue of IE9 rendering in IE7 Document standards for local host. I tried many conditional comments tags but unsuccesful. In the end I just removed all conditional tags and just added meta tag immediatly after head like below and it worked like charm.

<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Hope it helps

Best way to read a large file into a byte array in C#?

use this:

 bytesRead = responseStream.ReadAsync(buffer, 0, Length).Result;

Java: Calling a super method which calls an overridden method

I don't believe you can do it directly. One workaround would be to have a private internal implementation of method2 in the superclass, and call that. For example:

public class SuperClass
{
    public void method1()
    {
        System.out.println("superclass method1");
        this.internalMethod2();
    }

    public void method2()
    {
        this.internalMethod2(); 
    }
    private void internalMethod2()
    {
        System.out.println("superclass method2");
    }

}

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

Determine if char is a num or letter

Neither of these does anything useful. Use isalpha() or isdigit() from the standard library. They're in <ctype.h>.

Understanding inplace=True

Yes, in Pandas we have many functions has the parameter inplace but by default it is assigned to False.

So, when you do df.dropna(axis='index', how='all', inplace=False) it thinks that you do not want to change the orignial DataFrame, therefore it instead creates a new copy for you with the required changes.

But, when you change the inplace parameter to True

Then it is equivalent to explicitly say that I do not want a new copy of the DataFrame instead do the changes on the given DataFrame

This forces the Python interpreter to not to create a new DataFrame

But you can also avoid using the inplace parameter by reassigning the result to the orignal DataFrame

df = df.dropna(axis='index', how='all')

Set new id with jQuery

Did you try

$(this).val('test');

instead of

$(this).attr('value', 'test');

val() is generally easier, since the attribute you need to change may be different on different DOM elements.

How to do fade-in and fade-out with JavaScript and CSS

Here's my attempt with Javascript and CSS3 animation So the HTML:

 <div id="handle">Fade</div> 
 <div id="slideSource">Whatever you want images or  text here</div>

The CSS3 with transitions:

div#slideSource {
opacity:1;
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;     
transition: opacity 3s; 
}

div#slideSource.fade {
opacity:0;
}

The Javascript part. Check if the className exists, if it does then add the class and transitions.

document.getElementById('handle').onclick = function(){
    if(slideSource.className){
        document.getElementById('slideSource').className = '';
    } else {
        document.getElementById('slideSource').className = 'fade';
    }
}

Just click and it will fade in and out. I would recommend using JQuery as Itai Sagi mentioned. I left out Opera and MS, so I would recommend using prefixr to add that in the css. This is my first time posting on stackoverflow but it should work fine.

How to create relationships in MySQL

Adding onto the comment by ehogue, you should make the size of the keys on both tables match. Rather than

customer_id INT( 4 ) NOT NULL ,

make it

customer_id INT( 10 ) NOT NULL ,

and make sure your int column in the customers table is int(10) also.

PHP Undefined Index

I don't see php file, but that could be that -
replace in your php file:

$query_age = $_GET['query_age'];

with:

$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

Most probably, at first time you running your script without ?query_age=[something] and $_GET has no key like query_age.

Return positions of a regex match() in Javascript?

Here is a cool feature I discovered recently, I tried this on the console and it seems to work:

var text = "border-bottom-left-radius";

var newText = text.replace(/-/g,function(match, index){
    return " " + index + " ";
});

Which returned: "border 6 bottom 13 left 18 radius"

So this seems to be what you are looking for.

The executable was signed with invalid entitlements

I have found that "get-task-allow" needs to be checked for Development builds but unchecked for Distribution builds. The easiest way to accomplish this (AFAIK) is to have two entitlements files in your project: Entitlements.plist and EntitlementsDebug.plist - and to reference the proper one in the build project settings for the various configurations in your project.

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

In my case, I was getting this error in AndroidStudio 4.1.1 while updating compileSdkVersion to 29.

If you are having dependent project in build.gradle, All you need to do is Update same compileSdkVersion in dependent project's build.gradle as well.

Steps:

  1. Click on your app folder in Project view of AndroidStudio.
  2. Select Open Module Settings.
  3. In Project Structure >> Check how many modules are there?
  4. If there are more than one modules, you will have to update compileSdkVersion, buildToolsVersion & Project dependency as well.

That worked for me :)

How to parse string into date?

CONVERT(DateTime, ExpireDate, 121) AS ExpireDate

will do what is needed, result:

2012-04-24 00:00:00.000

Read a Csv file with powershell and capture corresponding data

What you should be looking at is Import-Csv

Once you import the CSV you can use the column header as the variable.

Example CSV:

Name  | Phone Number | Email
Elvis | 867.5309     | [email protected]
Sammy | 555.1234     | [email protected]

Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:

$Name = @()
$Phone = @()

Import-Csv H:\Programs\scripts\SomeText.csv |`
    ForEach-Object {
        $Name += $_.Name
        $Phone += $_."Phone Number"
    }

$inputNumber = Read-Host -Prompt "Phone Number"

if ($Phone -contains $inputNumber)
    {
    Write-Host "Customer Exists!"
    $Where = [array]::IndexOf($Phone, $inputNumber)
    Write-Host "Customer Name: " $Name[$Where]
    }

And here is the output:

I Found Sammy

MongoDb query condition on comparing 2 fields

If your query consists only of the $where operator, you can pass in just the JavaScript expression:

db.T.find("this.Grade1 > this.Grade2");

For greater performance, run an aggregate operation that has a $redact pipeline to filter the documents which satisfy the given condition.

The $redact pipeline incorporates the functionality of $project and $match to implement field level redaction where it will return all documents matching the condition using $$KEEP and removes from the pipeline results those that don't match using the $$PRUNE variable.


Running the following aggregate operation filter the documents more efficiently than using $where for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where, which can slow down the query:

db.T.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$gt": [ "$Grade1", "$Grade2" ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

which is a more simplified version of incorporating the two pipelines $project and $match:

db.T.aggregate([
    {
        "$project": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
            "Grade1": 1,
            "Grade2": 1,
            "OtherFields": 1,
            ...
        }
    },
    { "$match": { "isGrade1Greater": 1 } }
])

With MongoDB 3.4 and newer:

db.T.aggregate([
    {
        "$addFields": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
        }
    },
    { "$match": { "isGrade1Greater": 1 } }
])

Bash array with spaces in elements

Escaping works.

#!/bin/bash

FILES=(2011-09-04\ 21.43.02.jpg
2011-09-05\ 10.23.14.jpg
2011-09-09\ 12.31.16.jpg
2011-09-11\ 08.43.12.jpg)

echo ${FILES[0]}
echo ${FILES[1]}
echo ${FILES[2]}
echo ${FILES[3]}

Output:

$ ./test.sh
2011-09-04 21.43.02.jpg
2011-09-05 10.23.14.jpg
2011-09-09 12.31.16.jpg
2011-09-11 08.43.12.jpg

Quoting the strings also produces the same output.

How to customize Bootstrap 3 tab color

_x000D_
_x000D_
.panel.with-nav-tabs .panel-heading {_x000D_
  padding: 5px 5px 0 5px;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-tabs {_x000D_
  border-bottom: none;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-justified {_x000D_
  margin-bottom: -1px;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DEFAULT ***/_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
  background-color: #ddd;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:focus {_x000D_
  color: #555;_x000D_
  background-color: #fff;_x000D_
  border-color: #ddd;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f5f5f5;_x000D_
  border-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #555;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL PRIMARY ***/_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3071a9;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:focus {_x000D_
  color: #428bca;_x000D_
  background-color: #fff;_x000D_
  border-color: #428bca;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #428bca;_x000D_
  border-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  background-color: #4a9fe9;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL SUCCESS ***/_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #d6e9c6;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #fff;_x000D_
  border-color: #d6e9c6;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #dff0d8;_x000D_
  border-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3c763d;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL INFO ***/_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #bce8f1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #fff;_x000D_
  border-color: #bce8f1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #d9edf7;_x000D_
  border-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #31708f;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL WARNING ***/_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #faebcc;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #fff;_x000D_
  border-color: #faebcc;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #fcf8e3;_x000D_
  border-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #8a6d3b;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DANGER ***/_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #ebccd1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #fff;_x000D_
  border-color: #ebccd1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f2dede;_x000D_
  /* bg color */_x000D_
  border-color: #ebccd1;_x000D_
  /* border color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #a94442;_x000D_
  /* normal text color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ebccd1;_x000D_
  /* hover bg color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  /* active text color */_x000D_
  background-color: #a94442;_x000D_
  /* active bg color */_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">_x000D_
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<!------ Include the above in your HEAD tag ---------->_x000D_
_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1>Panels with nav tabs.<span class="pull-right label label-default">:)</span></h1>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-default">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1default" data-toggle="tab">Default 1</a></li>_x000D_
            <li><a href="#tab2default" data-toggle="tab">Default 2</a></li>_x000D_
            <li><a href="#tab3default" data-toggle="tab">Default 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4default" data-toggle="tab">Default 4</a></li>_x000D_
                <li><a href="#tab5default" data-toggle="tab">Default 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1default">Default 1</div>_x000D_
            <div class="tab-pane fade" id="tab2default">Default 2</div>_x000D_
            <div class="tab-pane fade" id="tab3default">Default 3</div>_x000D_
            <div class="tab-pane fade" id="tab4default">Default 4</div>_x000D_
            <div class="tab-pane fade" id="tab5default">Default 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-primary">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1primary" data-toggle="tab">Primary 1</a></li>_x000D_
            <li><a href="#tab2primary" data-toggle="tab">Primary 2</a></li>_x000D_
            <li><a href="#tab3primary" data-toggle="tab">Primary 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4primary" data-toggle="tab">Primary 4</a></li>_x000D_
                <li><a href="#tab5primary" data-toggle="tab">Primary 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1primary">Primary 1</div>_x000D_
            <div class="tab-pane fade" id="tab2primary">Primary 2</div>_x000D_
            <div class="tab-pane fade" id="tab3primary">Primary 3</div>_x000D_
            <div class="tab-pane fade" id="tab4primary">Primary 4</div>_x000D_
            <div class="tab-pane fade" id="tab5primary">Primary 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-success">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1success" data-toggle="tab">Success 1</a></li>_x000D_
            <li><a href="#tab2success" data-toggle="tab">Success 2</a></li>_x000D_
            <li><a href="#tab3success" data-toggle="tab">Success 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4success" data-toggle="tab">Success 4</a></li>_x000D_
                <li><a href="#tab5success" data-toggle="tab">Success 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1success">Success 1</div>_x000D_
            <div class="tab-pane fade" id="tab2success">Success 2</div>_x000D_
            <div class="tab-pane fade" id="tab3success">Success 3</div>_x000D_
            <div class="tab-pane fade" id="tab4success">Success 4</div>_x000D_
            <div class="tab-pane fade" id="tab5success">Success 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-info">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1info" data-toggle="tab">Info 1</a></li>_x000D_
            <li><a href="#tab2info" data-toggle="tab">Info 2</a></li>_x000D_
            <li><a href="#tab3info" data-toggle="tab">Info 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4info" data-toggle="tab">Info 4</a></li>_x000D_
                <li><a href="#tab5info" data-toggle="tab">Info 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1info">Info 1</div>_x000D_
            <div class="tab-pane fade" id="tab2info">Info 2</div>_x000D_
            <div class="tab-pane fade" id="tab3info">Info 3</div>_x000D_
            <div class="tab-pane fade" id="tab4info">Info 4</div>_x000D_
            <div class="tab-pane fade" id="tab5info">Info 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-warning">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1warning" data-toggle="tab">Warning 1</a></li>_x000D_
            <li><a href="#tab2warning" data-toggle="tab">Warning 2</a></li>_x000D_
            <li><a href="#tab3warning" data-toggle="tab">Warning 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4warning" data-toggle="tab">Warning 4</a></li>_x000D_
                <li><a href="#tab5warning" data-toggle="tab">Warning 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1warning">Warning 1</div>_x000D_
            <div class="tab-pane fade" id="tab2warning">Warning 2</div>_x000D_
            <div class="tab-pane fade" id="tab3warning">Warning 3</div>_x000D_
            <div class="tab-pane fade" id="tab4warning">Warning 4</div>_x000D_
            <div class="tab-pane fade" id="tab5warning">Warning 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-danger">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1danger" data-toggle="tab">Danger 1</a></li>_x000D_
            <li><a href="#tab2danger" data-toggle="tab">Danger 2</a></li>_x000D_
            <li><a href="#tab3danger" data-toggle="tab">Danger 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4danger" data-toggle="tab">Danger 4</a></li>_x000D_
                <li><a href="#tab5danger" data-toggle="tab">Danger 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1danger">Danger 1</div>_x000D_
            <div class="tab-pane fade" id="tab2danger">Danger 2</div>_x000D_
            <div class="tab-pane fade" id="tab3danger">Danger 3</div>_x000D_
            <div class="tab-pane fade" id="tab4danger">Danger 4</div>_x000D_
            <div class="tab-pane fade" id="tab5danger">Danger 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<br/>
_x000D_
_x000D_
_x000D_

converting a javascript string to a html object

If the browser that you are planning to use is Mozilla (Addon development) (not sure of chrome) you can use the following method in Javascript

function DOM( string )
{
    var {Cc, Ci} = require("chrome");
    var parser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
    console.log("PARSING OF DOM COMPLETED ...");
    return (parser.parseFromString(string, "text/html"));
};

Hope this helps

What is the best way to modify a list in a 'foreach' loop?

Here's how you can do that (quick and dirty solution. If you really need this kind of behavior, you should either reconsider your design or override all IList<T> members and aggregate the source list):

using System;
using System.Collections.Generic;

namespace ConsoleApplication3
{
    public class ModifiableList<T> : List<T>
    {
        private readonly IList<T> pendingAdditions = new List<T>();
        private int activeEnumerators = 0;

        public ModifiableList(IEnumerable<T> collection) : base(collection)
        {
        }

        public ModifiableList()
        {
        }

        public new void Add(T t)
        {
            if(activeEnumerators == 0)
                base.Add(t);
            else
                pendingAdditions.Add(t);
        }

        public new IEnumerator<T> GetEnumerator()
        {
            ++activeEnumerators;

            foreach(T t in ((IList<T>)this))
                yield return t;

            --activeEnumerators;

            AddRange(pendingAdditions);
            pendingAdditions.Clear();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ModifiableList<int> ints = new ModifiableList<int>(new int[] { 2, 4, 6, 8 });

            foreach(int i in ints)
                ints.Add(i * 2);

            foreach(int i in ints)
                Console.WriteLine(i * 2);
        }
    }
}

How to create an AVD for Android 4.0

Another solution, for those of us without an internet connection to our development machine is:

Create a folder called system-images in the top level of your SDK directory (next to platforms and tools). Create subdirs android-14 and android-15 (as applicable). Extract the complete armeabi-v7a folder to these directory; sysimg_armv7a-15_r01.zip (from, e.g. google's repository) goes to android-15, sysimg_armv7a-14_r02.zip to android-14.

I've not tried this procedure offline, I finally relented and used my broadband allowance at home, but these are the target locations for these large sysimg's, for future reference.

I've tried creating the image subdirs where they were absent in 14 and 15 but while this allowed the AVD to create an image (for 15 but not 14) it hadn't shown the Android logo after 15 minutes.

How can I make a countdown with NSTimer?

Swift4

    @IBOutlet weak var actionButton: UIButton!
    @IBOutlet weak var timeLabel: UILabel!
    var timer:Timer?
    var timeLeft = 60

override func viewDidLoad() {
    super.viewDidLoad()
    setupTimer()
}

func setupTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
}

@objc func onTimerFires() {
    timeLeft -= 1
    timeLabel.text = "\(timeLeft) seconds left"

    if timeLeft <= 0 {
        actionButton.isEnabled = true
        actionButton.setTitle("enabled", for: .normal)
        timer?.invalidate()
        timer = nil
    }
}

@IBAction func btnClicked(_ sender: UIButton) {
    print("API Fired")
}

show more/Less text with just HTML and JavaScript

With some HTML changes, you can absolutely achieve this with CSS:

Lorem ipsum dolor sit amet
<p id="textarea">
    <!-- This is where I want to additional text-->
    All that delicious text is in here!
</p>
<!-- the show/hide controls inside of the following
     list, for ease of selecting with CSS -->
<ul class="controls">
    <li class="show"><a href="#textarea">Show</a></li>
    <li class="hide"><a href="#">Hide</a></li>
</ul>

<p>Here is some more text</p>

Coupled with the CSS:

#textarea {
    display: none; /* hidden by default */
}

#textarea:target {
    display: block; /* shown when a link targeting this id is clicked */
}

#textarea + ul.controls {
    list-style-type: none; /* aesthetics only, adjust to taste, irrelevant to demo */
}

/* hiding the hide link when the #textarea is not targeted,
   hiding the show link when it is selected: */
#textarea + ul.controls .hide,
#textarea:target + ul.controls .show {
    display: none;
}

/* Showing the hide link when the #textarea is targeted,
   showing the show link when it's not: */
#textarea:target + ul.controls .hide,
#textarea + ul.controls .show {
    display: inline-block;
}

JS Fiddle demo.

Or, you could use a label and an input of type="checkbox":

Lorem ipsum dolor sit amet
<input id="textAreaToggle" type="checkbox" />
<p id="textarea">
    <!-- This is where I want to additional text-->
    All that delicious text is in here!
</p>
<label for="textAreaToggle">textarea</label>

<p>Here is some more text</p>

With the CSS:

#textarea {
    /* hide by default: */
    display: none;
}

/* when the checkbox is checked, show the neighbouring #textarea element: */
#textAreaToggle:checked + #textarea {
    display: block;
}

/* position the checkbox off-screen: */
input[type="checkbox"] {
    position: absolute;
    left: -1000px;
}

/* Aesthetics only, adjust to taste: */
label {
    display: block;
}

/* when the checkbox is unchecked (its default state) show the text
   'Show ' in the label element: */
#textAreaToggle + #textarea + label::before {
    content: 'Show ';
}

/* when the checkbox is checked 'Hide ' in the label element; the
   general-sibling combinator '~' is required for a bug in Chrome: */
#textAreaToggle:checked ~ #textarea + label::before {
    content: 'Hide ';
}

JS Fiddle demo.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

What is the difference between a static and a non-static initialization code block

You will not write code into a static block that needs to be invoked anywhere in your program. If the purpose of the code is to be invoked then you must place it in a method.

You can write static initializer blocks to initialize static variables when the class is loaded but this code can be more complex..

A static initializer block looks like a method with no name, no arguments, and no return type. Since you never call it it doesn't need a name. The only time its called is when the virtual machine loads the class.

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

Could not find folder 'tools' inside SDK

In my case i was using Ubuntu. Where the was two directories one was /android-sdks and /android-sdk-linux. I used the second one it works for me :)

How do you execute an arbitrary native command from a string?

Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).

http://connect.microsoft.com/PowerShell/feedback/details/376207/

They suggest using --% as a way to force PowerShell to stop trying to interpret the text to the right.

For example:

MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj

How to insert a new line in Linux shell script?

Use this echo statement

 echo -e "Hai\nHello\nTesting\n"

The output is

Hai
Hello
Testing

Date minus 1 year?

You can use strtotime:

$date = strtotime('2010-01-01 -1 year');

The strtotime function returns a unix timestamp, to get a formatted string you can use date:

echo date('Y-m-d', $date); // echoes '2009-01-01'

How to fix Git error: object file is empty?

Let's go simple.. only case you uploaded source to remote git repo

  1. Backup your .git
  2. check your git

    git fsck --full
    
  3. remove empty object file (all)

    rm .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e
    
  4. check your git again.

    git fsck --full
    
  5. pull your source from remote git

    git pull origin master
    

How to empty/destroy a session in rails?

session in rails is a hash object. Hence any function available for clearing hash will work with sessions.

session.clear

or if specific keys have to be destroyed:

session.delete(key)

Tested in rails 3.2

added

People have mentioned by session={} is a bad idea. Regarding session.clear, Lobati comments- It looks like you're probably better off using reset_session [than session.clear], as it does some other cleaning up beyond what session.clear does. Internally, reset_session calls session.destroy, which itself calls clear as well some other stuff.

Way to ng-repeat defined number of times instead of repeating over array?

This is really UGLY, but it works without a controller for either an integer or variable:

integer:

<span ng-repeat="_ in ((_ = []) && (_.length=33) && _) track by $index">{{$index}}</span>

variable:

<span ng-repeat="_ in ((_ = []) && (_.length=myVar) && _) track by $index">{{$index}}</span>

Setting background color for a JFrame

Resurrecting a thread from stasis.

In 2018 this solution works for Swing/JFrame in NetBeans (should work in any IDE :):

this.getContentPane().setBackground(Color.GREEN);

Expression ___ has changed after it was checked

I couldnt comment on @Biranchi s post since I dont have enough reputation, but it fixed the problem for me.

One thing to note! If adding changeDetection: ChangeDetectionStrategy.OnPush on the component didn't work, and its a child component (dumb component) try adding it to the parent also.

This fixed the bug, but I wonder what are the side effects of this.

How can I execute PHP code from the command line?

You can use:

 echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php

The short tag "< ?=" can be helpful too:

 echo '<?= function_exists("foo") ? "yes" : "no";' | php
 echo '<?= 8+7+9 ;' | php

The closing tag "?>" is optional, but don't forget the final ";"!

How do I use tools:overrideLibrary in a build.gradle file?

use this code in manifest.xml

<uses-sdk
android:minSdkVersion="16"
android:maxSdkVersion="17"
tools:overrideLibrary="x"/>

nvarchar(max) vs NText

Wanted to add my experience with converting. I had many text fields in ancient Linq2SQL code. This was to allow text columns present in indexes to be rebuilt ONLINE.

First I've known about the benefits for years, but always assumed that converting would mean some scary long queries where SQL Server would have to rebuild the table and copy everything over, bringing down my websites and raising my heartrate.

I was also concerned that the Linq2SQL could cause errors if it was doing some kind of verification of the column type.

Happy to report though, that the ALTER commands returned INSTANTLY - so they are definitely only changing table metadata. There may be some offline work happening to bring <8000 character data back to be in-table, but the ALTER command was instant.

I ran the following to find all columns needing conversion:

SELECT concat('ALTER TABLE dbo.[', table_name, '] ALTER COLUMN [', column_name, '] VARCHAR(MAX)'), table_name, column_name
FROM information_schema.columns where data_type = 'TEXT' order by table_name, column_name

SELECT concat('ALTER TABLE dbo.[', table_name, '] ALTER COLUMN [', column_name, '] NVARCHAR(MAX)'), table_name, column_name
FROM information_schema.columns where data_type = 'NTEXT' order by table_name, column_name

This gave me a nice list of queries, which I just selected and copied to a new window. Like I said - running this was instant.

enter image description here

Linq2SQL is pretty ancient - it uses a designer that you drag tables onto. The situation may be more complex for EF Code first but I haven't tackled that yet.

How to query data out of the box using Spring data JPA by both Sort and Pageable?

In my case, to use Pageable and Sorting at the same time I used like below. In this case I took all elements using pagination and sorting by id by descending order:

modelRepository.findAll(PageRequest.of(page, 10, Sort.by("id").descending()))

Like above based on your requirements you can sort data with 2 columns as well.

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The formula is

minSdkVersion <= targetSdkVersion <= compileSdkVersion

minSdkVersion - is a marker that defines a minimum Android version on which application will be able to install. Also it is used by Lint to prevent calling API that doesn’t exist. Also it has impact on Build Time. So you can use build flavors to override minSdkVersion to maximum during the development. It will help to make build faster using all improvements that the Android team provides for us. For example some features Java 8 are available only from specific version of minSdkVersion.

targetSdkVersion - If AndroidOS version is >= targetSdkVersion it says Android system to turn on specific(new) behavior changes. *Please note that some of new behaviors will be turned on by default even if thought targetSdkVersion is <, you should read official doc.

For example:

  • Starting in Android 6.0 (API level 23) Runtime Permissions were introduced. If you set targetSdkVersion to 22 or lower your application does not ask a user for some permission in run time.

  • Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).

  • Starting in Android 9 (API level 28), Web-based data directories separated by process. If targetSdkVersion is 28+ and you create several WebView in different processes you will get java.lang.RuntimeException

compileSdkVersion - actually it is SDK Platform version and tells Gradle which Android SDK use to compile. When you want to use new features or debug .java files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion - level 28. compileSdkVersion is not included in your APK: it is purely used at compile time. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version

You can read more about it here. Also I would recommend you to take a look at the example of migration to Android 8.0.

[buildToolsVersion]

Laravel Controller Subfolder routing

In my case I had a prefix that had to be added for each route in the group, otherwise response would be that the UserController class was not found.

Route::prefix('/user')->group(function() {
    Route::post('/login', [UserController::class, 'login'])->prefix('/user');
    Route::post('/register', [UserController::class, 'register'])->prefix('/user');
});

Visual Studio C# IntelliSense not automatically displaying

Sometimes i've found Intellisense to be slow. Hit the . and wait for a minute and see if it appears after a delay. If so, then I believe there may be a cache that can be deleted to get it to rescan.

PHP - Merging two arrays into one array (also Remove Duplicates)

It will merger two array and remove duplicate

<?php
 $first = 'your first array';
 $second = 'your second array';
 $result = array_merge($first,$second);
 print_r($result);
 $result1= array_unique($result);
 print_r($result1);
 ?>

Try this link link1

How to select specific columns in laravel eloquent

Table::where('id', 1)->get(['name','surname']);

How to add many functions in ONE ng-click?

You can call multiple functions with ';'

ng-click="edit($index); open()"

How to override equals method in Java

tl;dr

record Person ( String name , int age ) {}  
if( 
    new Person( "Carol" , 27 )              // Compiler auto-generates implicitly the constructor.
    .equals(                                // Compiler auto-generates implicitly the `equals` method.
        new Person( "Carol" , 42 ) 
    ) 
)                                           // Returns `false`, as the name matches but the age differs.
{ … }

Details

While your specific problem is solved (using == for equality test between int primitive values), there is an alternative that eliminates the need to write that code.

record

Java 16 brings the record feature.

A record is a brief way to write a class whose main purpose is to transparently and immutably carry data. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString.

equals method provided automatically

The default implicit equals method compares each and every member field that you declared for the record. The members can be objects or primitives, both types are automatically compared in the default equals method.

For example, if you have a Person record carrying two fields, name & age, both of those fields are automatically compared to determine equality between a pair of Person objects.

public record Person ( String name , int age ) {}

Try it.

Person alice = new Person( "Alice" , 23 ) ;
Person alice2 = new Person( "Alice" , 23 ) ;
Person bob = new Person( "Bob" , 19 ) ;

boolean samePerson1 = alice.equals( alice2 ) ;  // true.
boolean samePerson2 = alice.equals( bob ) ;  // false.

You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals, be sure to override hashCode for consistent logic, as you would for a conventional Java class. And, think twice: Whenever adding methods to a record, reconsider if a record structure is really appropriate to that problem domain.

Tip: A record can be defined within another class, and even locally within a method.

Why isn't .ico file defined when setting window's icon?

Try this:

from tkinter import *
import os
import sys

root = Tk()
root.iconbitmap(os.path.join(sys.path[0], '<your-ico-file>'))

root.mainloop()

Note: replace <your-ico-file> with the name of the ico file you are using otherwise it won't work.

I have tried this in Python 3. It worked.

In Android EditText, how to force writing uppercase?

Xamarin equivalent of ErlVolton's answer:

editText.SetFilters(editText.GetFilters().Append(new InputFilterAllCaps()).ToArray());

Missing visible-** and hidden-** in Bootstrap v4

i like the bootstrap3 style as the device width of bootstrap4
so i modify the css as below
<pre>
.visible-xs, .visible-sm, .visible-md, .visible-lg { display:none !important; }
.visible-xs-block, .visible-xs-inline, .visible-xs-inline-block,
.visible-sm-block, .visible-sm-inline, .visible-sm-inline-block,
.visible-md-block, .visible-md-inline, .visible-md-inline-block,
.visible-lg-block, .visible-lg-inline, .visible-lg-inline-block { display:none !important; }
@media (max-width:575px) {
table.visible-xs                { display:table !important; }
tr.visible-xs                   { display:table-row !important; }
th.visible-xs, td.visible-xs    { display:table-cell !important; }

.visible-xs                 { display:block !important; }
.visible-xs-block { display:block !important; }
.visible-xs-inline { display:inline !important; }
.visible-xs-inline-block { display:inline-block !important; }
}

@media (min-width:576px) and (max-width:767px) {
table.visible-sm { display:table !important; }
tr.visible-sm { display:table-row !important; }
th.visible-sm,
td.visible-sm { display:table-cell !important; }

.visible-sm { display:block !important; }
.visible-sm-block { display:block !important; }
.visible-sm-inline { display:inline !important; }
.visible-sm-inline-block { display:inline-block !important; }
}

@media (min-width:768px) and (max-width:991px) {
table.visible-md { display:table !important; }
tr.visible-md { display:table-row !important; }
th.visible-md,
td.visible-md { display:table-cell !important; }

.visible-md { display:block !important; }
.visible-md-block { display:block !important; }
.visible-md-inline { display:inline !important; }
.visible-md-inline-block { display:inline-block !important; }
}

@media (min-width:992px) and (max-width:1199px) {
table.visible-lg { display:table !important; }
tr.visible-lg { display:table-row !important; }
th.visible-lg,
td.visible-lg { display:table-cell !important; }

.visible-lg { display:block !important; }
.visible-lg-block { display:block !important; }
.visible-lg-inline { display:inline !important; }
.visible-lg-inline-block { display:inline-block !important; }
}

@media (min-width:1200px) {
table.visible-xl { display:table !important; }
tr.visible-xl { display:table-row !important; }
th.visible-xl,
td.visible-xl { display:table-cell !important; }

.visible-xl { display:block !important; }
.visible-xl-block { display:block !important; }
.visible-xl-inline { display:inline !important; }
.visible-xl-inline-block { display:inline-block !important; }
}

@media (max-width:575px)                        { .hidden-xs{display:none !important;} }
@media (min-width:576px) and (max-width:767px)  { .hidden-sm{display:none !important;} }
@media (min-width:768px) and (max-width:991px)  { .hidden-md{display:none !important;} }
@media (min-width:992px) and (max-width:1199px) { .hidden-lg{display:none !important;} }
@media (min-width:1200px)                       { .hidden-xl{display:none !important;} }
</pre>

Onchange open URL via select - jQuery

If you don't want the url to put it on option's value, i'll give u example :

<select class="abc">
    <option value="0" href="hello">Hell</option>
    <option value="1" href="dello">Dell</option>
    <option value="2" href="cello">Cell</option>
</select>

    $("select").bind('change',function(){
        alert($(':selected',this).attr('href'));
    })

How can I remove jenkins completely from linux

if you are ubuntu user than try this:

sudo apt-get remove jenkins
sudo apt-get remove --auto-remove jenkins

'apt-get remove' command is use to remove package.

What is AF_INET, and why do I need it?

AF_INET is an address family that is used to designate the type of addresses that your socket can communicate with (in this case, Internet Protocol v4 addresses). When you create a socket, you have to specify its address family, and then you can only use addresses of that type with the socket. The Linux kernel, for example, supports 29 other address families such as UNIX (AF_UNIX) sockets and IPX (AF_IPX), and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).

For the most part, sticking with AF_INET for socket programming over a network is the safest option. There is also AF_INET6 for Internet Protocol v6 addresses.

Hope this helps,

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

It's the last selected DOM node index. Chrome assigns an index to each DOM node you select. So $0 will always point to the last node you selected, while $1 will point to the node you selected before that. Think of it like a stack of most recently selected nodes.

As an example, consider the following

<div id="sunday"></div>
<div id="monday"></div>
<div id="tuesday"></div>

Now you opened the devtools console and selected #sunday, #monday and #tuesday in the mentioned order, you will get ids like:

$0 -> <div id="tuesday"></div> 
$1 -> <div id="monday"></div>
$2 -> <div id="sunday"></div>

Note: It Might be useful to know that the node is selectable in your scripts (or console), for example one popular use for this is angular element selector, so you can simply pick your node, and run this:

angular.element($0).scope()

Voila you got access to node scope via console.

transparent navigation bar ios

Swift 5 applying only to the current view controller

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Make the navigation bar background clear
    navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    navigationController?.navigationBar.shadowImage = UIImage()
    navigationController?.navigationBar.isTranslucent = true
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    // Restore the navigation bar to default
    navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
    navigationController?.navigationBar.shadowImage = nil
}

Launch Image does not show up in my iOS App

  • Make sure your images are accurate size according to Apple guidelines.
  • Make sure, You will select only one option , either launch screen file or Launch Image Source. You can find these two options in Project build settings -> General

My suggestion to you is to select Launch Image Source as Image.Assets. Create splash image assets there in Image.assests folder.

Reference image for right configuration: enter image description here

docker : invalid reference format

In powershell you should use ${pwd} vs $(pwd)

How to enumerate a range of numbers starting at 1

from itertools import count, izip

def enumerate(L, n=0):
    return izip( count(n), L)

# if 2.5 has no count
def count(n=0):
    while True:
        yield n
        n+=1

Now h = list(enumerate(xrange(2000, 2005), 1)) works.

Why are hexadecimal numbers prefixed with 0x?

Short story: The 0 tells the parser it's dealing with a constant (and not an identifier/reserved word). Something is still needed to specify the number base: the x is an arbitrary choice.

Long story: In the 60's, the prevalent programming number systems were decimal and octal — mainframes had 12, 24 or 36 bits per byte, which is nicely divisible by 3 = log2(8).

The BCPL language used the syntax 8 1234 for octal numbers. When Ken Thompson created B from BCPL, he used the 0 prefix instead. This is great because

  1. an integer constant now always consists of a single token,
  2. the parser can still tell right away it's got a constant,
  3. the parser can immediately tell the base (0 is the same in both bases),
  4. it's mathematically sane (00005 == 05), and
  5. no precious special characters are needed (as in #123).

When C was created from B, the need for hexadecimal numbers arose (the PDP-11 had 16-bit words) and all of the points above were still valid. Since octals were still needed for other machines, 0x was arbitrarily chosen (00 was probably ruled out as awkward).

C# is a descendant of C, so it inherits the syntax.

How to use a ViewBag to create a dropdownlist?

@Html.DropDownListFor(m => m.Departments.id, (SelectList)ViewBag.Department, "Select", htmlAttributes: new { @class = "form-control" })

When to use <span> instead <p>?

The <p> tag is a paragraph, and as such, it is a block element (as is, for instance, h1 and div), whereas span is an inline element (as, for instance, b and a)

Block elements by default create some whitespace above and below themselves, and nothing can be aligned next to them, unless you set a float attribute to them.

Inline elements deal with spans of text inside a paragraph. They typically have no margins, and as such, you cannot, for instance, set a width to it.

Reverse Contents in Array

#include "stdafx.h"
#include <iostream>
using namespace std;

void main()
{
    int n, i;
    cout << "n = ";
    cin >> n;
    int *a = new int[n];
    int *b = new int[n];
    for (i = 0; i < n; i++)
    {
        cout << "a[" << i << "]= ";
        cin >> a[i];
    }
    for (i = 0; i < n; i++)
    {
        b[i] = a[n - 1 - i];
    }
    for (i = 0; i < n; i++)
    {
        cout << b[i];
    }
}

"Sources directory is already netbeans project" error when opening a project from existing sources

  1. copy an existing netbeans project folder in to your new project and manually edit the xml project name.

  2. reinstall netbeans

  3. copy/move all files/folders (except nbproject/ folder) to a new folder for your project, with a new name.

What does -z mean in Bash?

test -z returns true if the parameter is empty (see man sh or man test).

delete map[key] in go?

delete(sessions, "anykey")

These days, nothing will crash.

How to install toolbox for MATLAB

first, you need to find the toolbox that you need. There are many people developing 3rd party toolboxes for Matlab, so there isn't just one single place where you can find "the image processing toolbox". That said, a good place to start looking is the Matlab Central which is a Mathworks-run site for exchanging all kinds of Matlab-related material.

Once you find a toolbox you want, it will be in some compressed format, and its developers might have a "readme" file that details on how to install it. If it isn't the case, a generic way to attempt installation is to place the toolbox in any directory on your drive, and then add it to Matlab path, e.g., going to File -> Set Path... -> Add Folder or Add with Subfolders (I'm writing for memory but this is definitely close).

Otherwise, you can extract all .m files in your working directory, if you don't want to use downloaded toolbox in more than one project.

How do I mock a service that returns promise in AngularJS Jasmine unit test?

Honestly.. you are going about this the wrong way by relying on inject to mock a service instead of module. Also, calling inject in a beforeEach is an anti-pattern as it makes mocking difficult on a per test basis.

Here is how I would do this...

module(function ($provide) {
  // By using a decorator we can access $q and stub our method with a promise.
  $provide.decorator('myOtherService', function ($delegate, $q) {

    $delegate.makeRemoteCallReturningPromise = function () {
      var dfd = $q.defer();
      dfd.resolve('some value');
      return dfd.promise;
    };
  });
});

Now when you inject your service it will have a properly mocked method for usage.

How to Troubleshoot Intermittent SQL Timeout Errors

Performance problems boil down to CPU, IO, or Lock contention. It sounds like you have ruled out IO. I would guess CPU is not a problem since this is a database, not a number cruncher. So, that leaves lock contention.

If you can execute a sp_who2 while the queries are timing out, you can use the BlkBy column to trace back to the holding the lock that everyone else is waiting on. Since this is only happening a few times a day, you may have trouble catching enough data if you are running this manually, so I suggest you rig up an automated system to dump this output on a regular basis, or maybe to be triggered by the application timeout exceptions. You can also use the Activity Monitor to watch the degradation of query responsiveness in real-time, as suggested by peer.

Once you find the long-running query and the application that executes it, you can immediately resolve the domino of timeouts by reducing the timeout for that single application below all the others (right now, it must be longer). Then, you should inspect the code to determine a better solution. You could reduce the time the lock is held by committing the transaction sooner within a sproc, or reduce the lock required by the reading query with hints such as NOLOCK or UPDLOCK.

Here's some more reading on sp_who2: http://sqlserverplanet.com/dba/using-sp_who2/

And query hints: http://msdn.microsoft.com/en-us/library/ms181714.aspx http://msdn.microsoft.com/en-us/library/ms187373.aspx

Owl Carousel Won't Autoplay

Setting autoPlay: true didn't work for me. But on setting autoPlay: 5000 it worked.

Remove Fragment Page from ViewPager in Android

You could just override the destroyItem method

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    fragmentManager.beginTransaction().remove((Fragment) object).commitNowAllowingStateLoss();
}

How do I get the name of the current executable in C#?

To get the path and the name

System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

Is there Java HashMap equivalent in PHP?

Arrays in PHP can have Key Value structure.

How to name and retrieve a stash by name in git?

If you are just looking for a lightweight way to save some or all of your current working copy changes and then reapply them later at will, consider a patch file:

# save your working copy changes
git diff > some.patch

# re-apply it later
git apply some.patch

Every now and then I wonder if I should be using stashes for this and then I see things like the insanity above and I'm content with what I'm doing :)

python NameError: global name '__file__' is not defined

If you're exec'ing a file via command line, you can use this hack

import traceback

def get_this_filename():
    try:
        raise NotImplementedError("No error")
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        filename = traceback.extract_tb(exc_traceback)[-1].filename
    return filename

This worked for me in the UnrealEnginePython console, calling py.exec myfile.py

Testing the type of a DOM element in JavaScript

You can use typeof(N) to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.

In that case, use the elem.tagName or elem.nodeName property.

if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.

C# declare empty string array

Try this

string[] arr = new string[] {};

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

How to evaluate a math expression given in string form?

It is possible to convert any expression string in infix notation to a postfix notation using Djikstra's shunting-yard algorithm. The result of the algorithm can then serve as input to the postfix algorithm with returns the result of the expression.

I wrote an article about it here, with an implementation in java

How to generate unique id in MySQL?

Use UUID function.

I don't know the source of your procedures in PHP that generates unique values. If it is library function they should guarantee that your value is really unique. Check in documentation. You should, hovewer, use this function all the time. If you, for example, use PHP function to generate unique value, and then you decide to use MySQL function, you can generate value that already exist. In this case putting UNIQUE INDEX on the column is also a good idea.

MySQL Error: #1142 - SELECT command denied to user

You need to grant SELECT permissions to the MySQL user who is connecting to MySQL

same question as here Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

see answers of the link ;)

Convert PDF to PNG using ImageMagick

Reducing the image size before output results in something that looks sharper, in my case:

convert -density 300 a.pdf -resize 25% a.png

Best XML Parser for PHP

Have a look at PHP's available XML extensions.

The main difference between XML Parser and SimpleXML is that the latter is not a pull parser. SimpleXML is built on top of the DOM extensions and will load the entire XML file into memory. XML Parser like XMLReader will only load the current node into memory. You define handlers for specific nodes which will get triggered when the Parser encounters it. That is faster and saves on memory. You pay for that with not being able to use XPath.

Personally, I find SimpleXml quite limiting (hence simple) in what it offers over DOM. You can switch between DOM and SimpleXml easily though, but I usually dont bother and go the DOM route directly. DOM is an implementation of the W3C DOM API, so you might be familiar with it from other languages, for instance JavaScript.

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

Protractor : How to wait for page complete after click a button?

In this case, you can used:

Page Object:

    waitForURLContain(urlExpected: string, timeout: number) {
        try {
            const condition = browser.ExpectedConditions;
            browser.wait(condition.urlContains(urlExpected), timeout);
        } catch (e) {
            console.error('URL not contain text.', e);
        };
    }

Page Test:

page.waitForURLContain('abc#/efg', 30000);

Getting activity from context in android

Never ever use getApplicationContext() with views.

It should always be activity's context, as the view is attached to activity. Also, you may have a custom theme set, and when using application's context, all theming will be lost. Read more about different versions of contexts here.

how to check for null with a ng-if values in a view with angularjs?

You can also use ng-template, I think that would be more efficient while run time :)

<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
    <div>2</div>
</ng-template>

Cheers

Access props inside quotes in React JSX

For People, looking for answers w.r.t to 'map' function and dynamic data, here is a working example.

<img src={"http://examole.com/randomview/images" + each_actor['logo']} />

This gives the URL as "http://examole.com/randomview/images/2/dp_pics/182328.jpg" (random example)

Disable button in WPF?

This should do it:

<StackPanel>
    <TextBox x:Name="TheTextBox" />
    <Button Content="Click Me">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="IsEnabled" Value="True" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
                        <Setter Property="IsEnabled" Value="False" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</StackPanel>

"Char cannot be dereferenced" error

If Character.isLetter(ch) looks a bit wordy/ugly you can use a static import.

import static java.lang.Character.*;


if(isLetter(ch)) {

} else if(isDigit(ch)) {

} 

Generate ER Diagram from existing MySQL database, created for CakePHP

CakePHP was intended to be used as Ruby on Rails framework clone, done in PHP, so any reverse-engineering of underlying database is pointless. EER diagrams should be reverse-engineered from Model layer.

Such tools do exist for Ruby Here you can see Redmine database EER diagrams reverse-engineered from Models. Not from database. http://redminecookbook.com/Redmine-erd-diagrams.html

With following tools: http://rails-erd.rubyforge.org/ http://railroady.prestonlee.com/

How to set text size in a button in html

Belated. If need any fancy button than anyone can try this.

_x000D_
_x000D_
#startStopBtn {_x000D_
    font-size: 30px;_x000D_
    font-weight: bold;_x000D_
    display: inline-block;_x000D_
    margin: 0 auto;_x000D_
    color: #dcfbb4;_x000D_
    background-color: green;_x000D_
    border: 0.4em solid #d4f7da;_x000D_
    border-radius: 50%;_x000D_
    transition: all 0.3s;_x000D_
    box-sizing: border-box;_x000D_
    width: 4em;_x000D_
    height: 4em;_x000D_
    line-height: 3em;_x000D_
    cursor: pointer;_x000D_
    box-shadow: 0 0 0 rgba(0,0,0,0.1), inset 0 0 0 rgba(0,0,0,0.1);_x000D_
    text-align: center;_x000D_
}_x000D_
#startStopBtn:hover{_x000D_
    box-shadow: 0 0 2em rgba(0,0,0,0.1), inset 0 0 1em rgba(0,0,0,0.1);_x000D_
    background-color: #29a074;_x000D_
  }
_x000D_
<div id="startStopBtn" onclick="startStop()" class=""> Go!</div>
_x000D_
_x000D_
_x000D_

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')
    or

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
    or
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 
END

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

Passing a dictionary to a function as keyword parameters

Here ya go - works just any other iterable:

d = {'param' : 'test'}

def f(dictionary):
    for key in dictionary:
        print key

f(d)

How to use the PI constant in C++

I just came across this article by Danny Kalev which has a great tip for C++14 and up.

template<typename T>
constexpr T pi = T(3.1415926535897932385);

I thought this was pretty cool (though I would use the highest precision PI in there I could), especially because templates can use it based on type.

template<typename T>
T circular_area(T r) {
  return pi<T> * r * r;
}
double darea= circular_area(5.5);//uses pi<double>
float farea= circular_area(5.5f);//uses pi<float>

Why is @font-face throwing a 404 error on woff files?

Run IIS Server Manager (run command : inetmgr) Open Mime Types and add following

File name extension: .woff

MIME type: application/octet-stream

How to remove all numbers from string?

Regex

   $words = preg_replace('#[0-9 ]*#', '', $words);

Cast to generic type in C#

As mentioned, you cannot cast it directly. One possible solution is to have those generic types inherit from a non-generic interface, in which case you can still invoke methods on it without reflection. Using reflection, you can pass the mapped object to any method expecting it, then the cast will be performed for you. So if you have a method called Accept expecting a MessageProcessor as a parameter, then you can find it and invoke it dynamically.

Disable pasting text into HTML form

I use this vanilla JS solution:

const element = document.getElementById('textfield')
element.addEventListener('paste', e =>  e.preventDefault())

jQuery Find and List all LI elements within a UL within a specific DIV

Are you thinking about something like this?

$('ul li').each(function(i)
{
   $(this).attr('rel'); // This is your rel value
});

How to comment a block in Eclipse?

Select the text you want to Block-comment/Block-uncomment.

To comment, Ctrl + 6

To uncomment, Ctrl + 8

How do I move a table into a schema in T-SQL

Short answer:

ALTER SCHEMA new_schema TRANSFER old_schema.table_name

I can confirm that the data in the table remains intact, which is probably quite important :)

Long answer as per MSDN docs,

ALTER SCHEMA schema_name 
   TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]

If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.

Windows-1252 to UTF-8 encoding

You can change the encoding of a file with an editor such as notepad++. Just go to Encoding and select what you want.

I always prefer the Windows 1252

Calculate the center point of multiple latitude/longitude coordinate pairs

I did this task in javascript like below

function GetCenterFromDegrees(data){
    // var data = [{lat:22.281610498720003,lng:70.77577162868579},{lat:22.28065743343672,lng:70.77624369747241},{lat:22.280860953131217,lng:70.77672113067706},{lat:22.281863655593973,lng:70.7762061465462}];
    var num_coords = data.length;
    var X = 0.0;
    var Y = 0.0;
    var Z = 0.0;

    for(i=0; i<num_coords; i++){
        var lat = data[i].lat * Math.PI / 180;
        var lon = data[i].lng * Math.PI / 180;
        var a = Math.cos(lat) * Math.cos(lon);
        var b = Math.cos(lat) * Math.sin(lon);
        var c = Math.sin(lat);

        X += a;
        Y += b;
        Z += c;
    }

    X /= num_coords;
    Y /= num_coords;
    Z /= num_coords;

    lon = Math.atan2(Y, X);
    var hyp = Math.sqrt(X * X + Y * Y);
    lat = Math.atan2(Z, hyp);

    var finalLat = lat * 180 / Math.PI;
    var finalLng =  lon * 180 / Math.PI; 

    var finalArray = Array();
    finalArray.push(finalLat);
    finalArray.push(finalLng);
    return finalArray;
}

Store an array in HashMap

Your life will be much easier if you can save a List as the value instead of an array in that Map.

JQUERY: Uncaught Error: Syntax error, unrecognized expression

Try this (ES5)

console.log($("#" +  d));

ES6

console.log($(`#${d}`));

Select distinct values from a large DataTable column

This will retrun you distinct Ids

 var distinctIds = datatable.AsEnumerable()
                    .Select(s=> new {
                        id = s.Field<string>("id"),                           
                     })
                    .Distinct().ToList();

Remove all the children DOM elements in div

while(node.firstChild) {
    node.removeChild(node.firstChild);
}

Disable html5 video autoplay

_x000D_
_x000D_
<video class="embed-responsive-item"  controls>_x000D_
   <source src="http://example.com/video.mp4" autostart="false">_x000D_
   Your browser does not support the video tag._x000D_
</video>
_x000D_
_x000D_
_x000D_

How to rotate the background image in the container?

Very easy method, you rotate one way, and the contents the other. Requires a square though

#element{
    background : url('someImage.jpg');
}
#element:hover{
    transform: rotate(-30deg);
}
#element:hover >*{
    transform: rotate(30deg);
}