Programs & Examples On #C# 4.0

C# 4.0 introduced features like dynamic objects, COM interoperability improvements, generic co- and contra-variance, optional and named parameters. Use this tag if your question specifically pertains to C# 4.0 specific features. The C# tag should be used if your question is not specific to C# 4.0 features.

C# Create New T()

Just for completion, the best solution here is often to require a factory function argument:

T GetObject<T>(Func<T> factory)
{  return factory(); }

and call it something like this:

string s = GetObject(() => "result");

You can use that to require or make use of available parameters, if needed.

Convert from List into IEnumerable format

You can use the extension method AsEnumerable in Assembly System.Core and System.Linq namespace :

List<Book> list = new List<Book>();
return list.AsEnumerable();

This will, as said on this MSDN link change the type of the List in compile-time. This will give you the benefits also to only enumerate your collection we needed (see MSDN example for this).

ASP.Net MVC - Read File from HttpPostedFileBase without save

An alternative is to use StreamReader.

public void FunctionName(HttpPostedFileBase file)
{
    string result = new StreamReader(file.InputStream).ReadToEnd();
}

What and When to use Tuple?

This is the most important thing to know about the Tuple type. Tuple is a class, not a struct. It thus will be allocated upon the managed heap. Each class instance that is allocated adds to the burden of garbage collection.

Note: The properties Item1, Item2, and further do not have setters. You cannot assign them. The Tuple is immutable once created in memory.

C#: Dynamic runtime cast

This should work:

public static dynamic Cast(dynamic obj, Type castTo)
{
    return Convert.ChangeType(obj, castTo);
}

Edit

I've written the following test code:

var x = "123";
var y = Cast(x, typeof(int));
var z = y + 7;
var w = Cast(z, typeof(string)); // w == "130"

It does resemble the kind of "typecasting" one finds in languages like PHP, JavaScript or Python (because it also converts the value to the desired type). I don't know if that's a good thing, but it certainly works... :-)

Check if list<t> contains any of another list

Here is a sample to find if there are match elements in another list

List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};

if (nums1.Any(x => nums2.Any(y => y == x)))
{
    Console.WriteLine("There are equal elements");
}
else
{
    Console.WriteLine("No Match Found!");
}

How to get first record in each group using Linq

The awnser of @Alireza is totally correct, but you must notice that when using this code

var res = from element in list
          group element by element.F1
              into groups
              select groups.OrderBy(p => p.F2).First();

which is simillar to this code because you ordering the list and then do the grouping so you are getting the first row of groups

var res = (from element in list)
          .OrderBy(x => x.F2)
          .GroupBy(x => x.F1)
          .Select()

Now if you want to do something more complex like take the same grouping result but take the first element of F2 and the last element of F3 or something more custom you can do it by studing the code bellow

 var res = (from element in list)
          .GroupBy(x => x.F1)
          .Select(y => new
           {
             F1 = y.FirstOrDefault().F1;
             F2 = y.First().F2;
             F3 = y.Last().F3;
           });

So you will get something like

   F1            F2             F3 
 -----------------------------------
   Nima          1990           12
   John          2001           2
   Sara          2010           4

How to create a custom attribute in C#

You start by writing a class that derives from Attribute:

public class MyCustomAttribute: Attribute
{
    public string SomeProperty { get; set; }
}

Then you could decorate anything (class, method, property, ...) with this attribute:

[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{

}

and finally you would use reflection to fetch it:

var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
    var myAttribute = customAttributes[0];
    string value = myAttribute.SomeProperty;
    // TODO: Do something with the value
}

You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:

/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute

Important things to know about attributes:

  • Attributes are metadata.
  • They are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted
  • The only way to make any sense and usage of custom attributes is to use Reflection. So if you don't use reflection at runtime to fetch them and decorate something with a custom attribute don't expect much to happen.
  • The time of creation of the attributes is non-deterministic. They are instantiated by the CLR and you have absolutely no control over it.

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Dynamically adding properties to an ExpandoObject

dynamic x = new ExpandoObject();
x.NewProp = string.Empty;

Alternatively:

var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);

.NET NewtonSoft JSON deserialize map to a different property name

If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me

Usage:

var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new CustomContractResolver();
this.DataContext = JsonConvert.DeserializeObject<CountResponse>(jsonString, settings);

Logic:

public class CustomContractResolver : DefaultContractResolver
{
    private Dictionary<string, string> PropertyMappings { get; set; }

    public CustomContractResolver()
    {
        this.PropertyMappings = new Dictionary<string, string> 
        {
            {"Meta", "meta"},
            {"LastUpdated", "last_updated"},
            {"Disclaimer", "disclaimer"},
            {"License", "license"},
            {"CountResults", "results"},
            {"Term", "term"},
            {"Count", "count"},
        };
    }

    protected override string ResolvePropertyName(string propertyName)
    {
        string resolvedName = null;
        var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
        return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
    }
}

Fastest way to Remove Duplicate Value from a list<> by lambda

You can use this extension method for enumerables containing more complex types:

IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)
{
    var knownKeys = new HashSet<TKey>();
    return source.Where(element => knownKeys.Add(keySelector(element)));
}

how to set default culture info for entire c# application

With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.

EPPlus - Read Excel Table

Not sure why but none of the above solution work for me. So sharing what worked:

public void readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
            }
        }
    }
}

Only Add Unique Item To List

//HashSet allows only the unique values to the list
HashSet<int> uniqueList = new HashSet<int>();

var a = uniqueList.Add(1);
var b = uniqueList.Add(2);
var c = uniqueList.Add(3);
var d = uniqueList.Add(2); // should not be added to the list but will not crash the app

//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1,"Happy");
dict.Add(2, "Smile");
dict.Add(3, "Happy");
dict.Add(2, "Sad"); // should be failed // Run time error "An item with the same key has already been added." App will crash

//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<string, int> dictRev = new Dictionary<string, int>();

dictRev.Add("Happy", 1);
dictRev.Add("Smile", 2);
dictRev.Add("Happy", 3); // should be failed // Run time error "An item with the same key has already been added." App will crash
dictRev.Add("Sad", 2);

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

The main concept of partial view is returning the HTML code rather than going to the partial view it self.

[HttpGet]
public ActionResult Calendar(int year)
{
    var dates = new List<DateTime>() { /* values based on year */ };
    HolidayViewModel model = new HolidayViewModel {
        Dates = dates
    };
    return PartialView("HolidayPartialView", model);
}

this action return the HTML code of the partial view ("HolidayPartialView").

To refresh partial view replace the existing item with the new filtered item using the jQuery below.

$.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });

How to update value of a key in dictionary in c#?

Try this simple function to add an dictionary item if it does not exist or update when it exists:

    public void AddOrUpdateDictionaryEntry(string key, int value)
    {
        if (dict.ContainsKey(key))
        {
            dict[key] = value;
        }
        else
        {
            dict.Add(key, value);
        }
    }

This is the same as dict[key] = value.

Deserialize JSON string to c# object

I believe you are looking for this:

string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

how to check if string value is in the Enum list?

You can use the Enum.TryParse method:

Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
    // You now have the value in age 
}

C# 4.0 optional out/ref arguments

As already mentioned, this is simply not allowed and I think it makes a very good sense. However, to add some more details, here is a quote from the C# 4.0 Specification, section 21.1:

Formal parameters of constructors, methods, indexers and delegate types can be declared optional:

fixed-parameter:
    attributesopt parameter-modifieropt type identifier default-argumentopt
default-argument:
    = expression

  • A fixed-parameter with a default-argument is an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter.
  • A required parameter cannot appear after an optional parameter in a formal-parameter-list.
  • A ref or out parameter cannot have a default-argument.

Avoid Adding duplicate elements to a List C#

You can use Enumerable.Except to get distinct items from lines3 which is not in lines2:

lines2.AddRange(lines3.Except(lines2));

If lines2 contains all items from lines3 then nothing will be added. BTW internally Except uses Set<string> to get distinct items from second sequence and to verify those items present in first sequence. So, it's pretty fast.

Moq, SetupGet, Mocking a property

But while mocking read-only properties means properties with getter method only you should declare it as virtual otherwise System.NotSupportedException will be thrown because it is only supported in VB as moq internally override and create proxy when we mock anything.

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

I had the same problem. It turned out that I didn't specify a default page and I didn't have any page that is named after the default page convention (default.html, defult.aspx etc). As a result, ASP.NET doesn't allow the user to browse the directory (not a problem in Visual Studio built-in web server that allows you to view the directory) and shows the error message. To fix it, I added one default page in Web.Config and it worked.

<system.webServer>
    <defaultDocument>
        <files>
            <add value="myDefault.aspx"/>
        </files>
    </defaultDocument>
</system.webServer>

Interop type cannot be embedded

Expanding on Jon's correct answer.

The problem here is that your are combining the new "Embed Interop Types" (or NoPIA) feature with use of a class type. The "Embed Interop Types" feature works by essentially statically linking in all of the types from a PIA (Primary Interop Assembly) into the referencing assembly removing the overhead of deploying it.

This feature works great for most types in a PIA but it does have restrictions. One of them is that you cannot embed classes (it's a servicing issue). Misha has a detailed blog article on why this is not allowed

Label word wrapping

Ironically, turning off AutoSize by setting it to false allowed me to get the label control dimensions to size it both vertically and horizontally which effectively allows word-wrapping to occur.

Redirect from asp.net web api post action

    [HttpGet]
    public RedirectResult Get()
    {
        return RedirectPermanent("https://www.google.com");
    }

How to encode the plus (+) symbol in a URL

The + character has a special meaning in a URL => it means whitespace - . If you want to use the literal + sign, you need to URL encode it to %2b:

body=Hi+there%2bHello+there

Here's an example of how you could properly generate URLs in .NET:

var uriBuilder = new UriBuilder("https://mail.google.com/mail");

var values = HttpUtility.ParseQueryString(string.Empty);
values["view"] = "cm";
values["tf"] = "0";
values["to"] = "[email protected]";
values["su"] = "some subject";
values["body"] = "Hi there+Hello there";

uriBuilder.Query = values.ToString();

Console.WriteLine(uriBuilder.ToString());

The result

https://mail.google.com:443/mail?view=cm&tf=0&to=someemail%40somedomain.com&su=some+subject&body=Hi+there%2bHello+there

Connecting to Oracle Database through C#?

Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:

  • Install Oracle Client , and add bin location to Path environment varaible of windows OR
  • Copy oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version), oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll

How do I check if a property exists on a dynamic anonymous type in c#?

This is working for me-:

  public static bool IsPropertyExist(dynamic dynamicObj, string property)
       {
           try
           {
               var value=dynamicObj[property].Value;
               return true;
           }
           catch (RuntimeBinderException)
           {

               return false;
           }

       }

compare two list and return not matching items using linq

Well, you already have good answers, but they're most Lambda. A more LINQ approach would be like

var NotSentMessages =
                from msg in MsgList
                where !SentList.Any(x => x.MsgID == msg.MsgID)
                select msg;

What are the true benefits of ExpandoObject?

It's all about programmer convenience. I can imagine writing quick and dirty programs with this object.

Parallel.ForEach vs Task.Factory.StartNew

In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:

public static double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result; 
}

Execution of this method takes about 0.5sec.

I called it 200 times using Parallel:

Parallel.For(0, 200, (int i) =>
{
    SumRootN(10);
});

Then I called it 200 times using the old-fashioned way:

List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
{
    Task t = new Task(() => SumRootN(10));
    t.Start();
    tasks.Add(t);
}

Task.WaitAll(tasks.ToArray()); 

First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.

Using DataContractSerializer to serialize, but can't deserialize back

Other solution is:

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

One remark: sometimes it happens that raw xml contains e.g.:

<?xml version="1.0" encoding="utf-16"?>

then of course you can't use UTF8 encoding used in other examples..

How to get first object out from List<Object> using Linq

You also can use this:

var firstOrDefault = lstComp.FirstOrDefault();
if(firstOrDefault != null) 
{
    //doSmth
}

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

HttpListener Access Denied

Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?

You can't, it has to start with elevated privileges. You can restart it with the runas verb, which will prompt the user to switch to admin mode

static void RestartAsAdmin()
{
    var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
    Process.Start(startInfo);
    Environment.Exit(0);
}

EDIT: actually, that's not true; HttpListener can run without elevated privileges, but you need to give permission for the URL on which you want to listen. See Darrel Miller's answer for details.

Error Message: Type or namespace definition, or end-of-file expected

  1. Make sure you have System.Web referenced
  2. Get rid of the two } at the end.

What is the difference between task and thread?

Thread

The bare metal thing, you probably don't need to use it, you probably can use a LongRunning task and take the benefits from the TPL - Task Parallel Library, included in .NET Framework 4 (february, 2002) and above (also .NET Core).

Tasks

Abstraction above the Threads. It uses the thread pool (unless you specify the task as a LongRunning operation, if so, a new thread is created under the hood for you).

Thread Pool

As the name suggests: a pool of threads. Is the .NET framework handling a limited number of threads for you. Why? Because opening 100 threads to execute expensive CPU operations on a Processor with just 8 cores definitely is not a good idea. The framework will maintain this pool for you, reusing the threads (not creating/killing them at each operation), and executing some of them in parallel, in a way that your CPU will not burn.

OK, but when to use each one?

In resume: always use tasks.

Task is an abstraction, so it is a lot easier to use. I advise you to always try to use tasks and if you face some problem that makes you need to handle a thread by yourself (probably 1% of the time) then use threads.

BUT be aware that:

  • I/O Bound: For I/O bound operations (database calls, read/write files, APIs calls, etc) avoid using normal tasks, use LongRunning tasks (or threads if you need to). Because using tasks would lead you to a thread pool with a few threads busy and a lot of another tasks waiting for its turn to take the pool.
  • CPU Bound: For CPU bound operations just use the normal tasks (that internally will use the thread pool) and be happy.

Sending JSON object to Web API

Change:

 data: JSON.stringify({ model: source })

To:

 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

How to make all controls resize accordingly proportionally when window is maximized?

Well, it's fairly simple to do.

On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.

Here's the code:

private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            myCanvas.Width = e.NewSize.Width;
            myCanvas.Height = e.NewSize.Height;

            double xChange = 1, yChange = 1;

            if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width/e.PreviousSize.Width);

            if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

            foreach (FrameworkElement fe in myCanvas.Children )
            {   
                /*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */            
                if (fe is Grid == false)
                {
                    fe.Height = fe.ActualHeight * yChange;
                    fe.Width = fe.ActualWidth * xChange;

                    Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
                    Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);

                }
            }
        }

How to create my json string by using C#?

No real need for the JSON.NET package. You could use JavaScriptSerializer. The Serialize method will turn a managed type instance into a JSON string.

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);

How to backup Sql Database Programmatically in C#

 private void BackupManager_Load(object sender, EventArgs e)
        {
            txtFileName.Text = "DB_Backup_" + DateTime.Now.ToString("dd-MMM-yy");
        }

        private void btnDBBackup_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtFileName.Text.Trim()))
            {
                BackUp();
            }
            else
            {
                MessageBox.Show("Please Enter Backup File Name", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtFileName.Focus();
                return;
            }
        }

        private void BackUp()
        {
            try
            {

                progressBar1.Value = 0;

                for (progressBar1.Value = 0; progressBar1.Value < 100; progressBar1.Value++)
                {

                }

                pl.DbName = "Inventry";
                pl.Path = @"D:/" + txtFileName.Text.Trim() + ".bak";

                for (progressBar1.Value = 100; progressBar1.Value < 200; progressBar1.Value++)
                {

                }

                bl.DbBackUp(pl);
                for (progressBar1.Value = 200; progressBar1.Value < 300; progressBar1.Value++)
                {

                }

                for (progressBar1.Value = 300; progressBar1.Value < 400; progressBar1.Value++)
                {

                }

                for (progressBar1.Value = 400; progressBar1.Value < progressBar1.Maximum; progressBar1.Value++)
                {

                }
                if (progressBar1.Value == progressBar1.Maximum)
                {
                    MessageBox.Show("Backup Saved Successfully...!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                progressBar1.Value = 0;
            }
        }

Better naming in Tuple classes than "Item1", "Item2"

MichaelMocko Answered is great,

but I want to add a few things which I had to figure out

(string first, string middle, string last) LookupName(long id)

above Line will give you compile-time error if you are using .net framework < 4.7

So if you have a project that is using .net framework < 4.7 and still you want to use ValueTuple than workAround would be installing this NuGet package

Update:

Example of returning Named tuple from a method and using it

public static (string extension, string fileName) GetFile()
{
    return ("png", "test");
}

Using it

var (extension, fileName) = GetFile();

Console.WriteLine(extension);
Console.WriteLine(fileName);

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

Because default parameters are resolved at compile time, not runtime. So the default values does not belong to the object being called, but to the reference type that it is being called through.

Datetime in C# add days

DateTime is immutable. That means you cannot change it's state and have to assign the result of an operation to a variable.

endDate = endDate.AddDays(addedDays);

Redirect to Action in another controller

Try switching them:

return RedirectToAction("Account", "Login");

I tried it and it worked.

How to add and get Header values in WebApi

As someone already pointed out how to do this with .Net Core, if your header contains a "-" or some other character .Net disallows, you can do something like:

public string Test([FromHeader]string host, [FromHeader(Name = "Content-Type")] string contentType)
{
}

Iterating over JSON object in C#

dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
    Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName, 
        item.slug, item.imageUrl);
}

or

var list = JsonConvert.DeserializeObject<List<MyItem>>(json);

public class MyItem
{
    public string id;
    public string displayName;
    public string name;
    public string slug;
    public string imageUrl;
}

What is the 'dynamic' type in C# 4.0 used for?

The dynamic keyword was added, together with many other new features of C# 4.0, to make it simpler to talk to code that lives in or comes from other runtimes, that has different APIs.

Take an example.

If you have a COM object, like the Word.Application object, and want to open a document, the method to do that comes with no less than 15 parameters, most of which are optional.

To call this method, you would need something like this (I'm simplifying, this is not actual code):

object missing = System.Reflection.Missing.Value;
object fileName = "C:\\test.docx";
object readOnly = true;
wordApplication.Documents.Open(ref fileName, ref missing, ref readOnly,
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing);

Note all those arguments? You need to pass those since C# before version 4.0 did not have a notion of optional arguments. In C# 4.0, COM APIs have been made easier to work with by introducing:

  1. Optional arguments
  2. Making ref optional for COM APIs
  3. Named arguments

The new syntax for the above call would be:

wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);

See how much easier it looks, how much more readable it becomes?

Let's break that apart:

                                    named argument, can skip the rest
                                                   |
                                                   v
wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);
                                 ^                         ^
                                 |                         |
                               notice no ref keyword, can pass
                               actual parameter values instead

The magic is that the C# compiler will now inject the necessary code, and work with new classes in the runtime, to do almost the exact same thing that you did before, but the syntax has been hidden from you, now you can focus on the what, and not so much on the how. Anders Hejlsberg is fond of saying that you have to invoke different "incantations", which is a sort of pun on the magic of the whole thing, where you typically have to wave your hand(s) and say some magic words in the right order to get a certain type of spell going. The old API way of talking to COM objects was a lot of that, you needed to jump through a lot of hoops in order to coax the compiler to compile the code for you.

Things break down in C# before version 4.0 even more if you try to talk to a COM object that you don't have an interface or class for, all you have is an IDispatch reference.

If you don't know what it is, IDispatch is basically reflection for COM objects. With an IDispatch interface you can ask the object "what is the id number for the method known as Save", and build up arrays of a certain type containing the argument values, and finally call an Invoke method on the IDispatch interface to call the method, passing all the information you've managed to scrounge together.

The above Save method could look like this (this is definitely not the right code):

string[] methodNames = new[] { "Open" };
Guid IID = ...
int methodId = wordApplication.GetIDsOfNames(IID, methodNames, methodNames.Length, lcid, dispid);
SafeArray args = new SafeArray(new[] { fileName, missing, missing, .... });
wordApplication.Invoke(methodId, ... args, ...);

All this for just opening a document.

VB had optional arguments and support for most of this out of the box a long time ago, so this C# code:

wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);

is basically just C# catching up to VB in terms of expressiveness, but doing it the right way, by making it extendable, and not just for COM. Of course this is also available for VB.NET or any other language built on top of the .NET runtime.

You can find more information about the IDispatch interface on Wikipedia: IDispatch if you want to read more about it. It's really gory stuff.

However, what if you wanted to talk to a Python object? There's a different API for that than the one used for COM objects, and since Python objects are dynamic in nature as well, you need to resort to reflection magic to find the right methods to call, their parameters, etc. but not the .NET reflection, something written for Python, pretty much like the IDispatch code above, just altogether different.

And for Ruby? A different API still.

JavaScript? Same deal, different API for that as well.

The dynamic keyword consists of two things:

  1. The new keyword in C#, dynamic
  2. A set of runtime classes that knows how to deal with the different types of objects, that implement a specific API that the dynamic keyword requires, and maps the calls to the right way of doing things. The API is even documented, so if you have objects that comes from a runtime not covered, you can add it.

The dynamic keyword is not, however, meant to replace any existing .NET-only code. Sure, you can do it, but it was not added for that reason, and the authors of the C# programming language with Anders Hejlsberg in the front, has been most adamant that they still regard C# as a strongly typed language, and will not sacrifice that principle.

This means that although you can write code like this:

dynamic x = 10;
dynamic y = 3.14;
dynamic z = "test";
dynamic k = true;
dynamic l = x + y * z - k;

and have it compile, it was not meant as a sort of magic-lets-figure-out-what-you-meant-at-runtime type of system.

The whole purpose was to make it easier to talk to other types of objects.

There's plenty of material on the internet about the keyword, proponents, opponents, discussions, rants, praise, etc.

I suggest you start with the following links and then google for more:

Permission is only granted to system app

Path In Android Studio in mac:

Android Studio -> Preferences -> Editor -> Inspections

Expand Android -> Expand Lint -> Expand Correctness

Uncheck the checkbox for Using system app permission

Click on "APPLY" -> "OK"

SQL Server add auto increment primary key to existing table

No - you have to do it the other way around: add it right from the get go as INT IDENTITY - it will be filled with identity values when you do this:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY

and then you can make it the primary key:

ALTER TABLE dbo.YourTable
   ADD CONSTRAINT PK_YourTable
   PRIMARY KEY(ID)

or if you prefer to do all in one step:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY
       CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

VIM Disable Automatic Newline At End Of File

I've added a tip on the Vim wiki for a similar (though different) problem:

http://vim.wikia.com/wiki/Do_not_auto-add_a_newline_at_EOF

How to center absolute div horizontally using CSS?

You need to set left: 0 and right: 0.

This specifies how far to offset the margin edges from the sides of the window.

Like 'top', but specifies how far a box's right margin edge is offset to the [left/right] of the [right/left] edge of the box's containing block.

Source: http://www.w3.org/TR/CSS2/visuren.html#position-props

Note: The element must have a width smaller than the window or else it will take up the entire width of the window.

If you could use media queries to specify a minimum margin, and then transition to auto for larger screen sizes.


_x000D_
_x000D_
.container {_x000D_
  left:0;_x000D_
  right:0;_x000D_
_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
_x000D_
  position: absolute;_x000D_
  width: 40%;_x000D_
_x000D_
  outline: 1px solid black;_x000D_
  background: white;_x000D_
}
_x000D_
<div class="container">_x000D_
  Donec ullamcorper nulla non metus auctor fringilla._x000D_
  Maecenas faucibus mollis interdum._x000D_
  Sed posuere consectetur est at lobortis._x000D_
  Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor._x000D_
  Sed posuere consectetur est at lobortis._x000D_
</div>
_x000D_
_x000D_
_x000D_

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

Bash script processing limited number of commands in parallel

See parallel. Its syntax is similar to xargs, but it runs the commands in parallel.

How to filter input type="file" dialog by specific file type?

See http://www.w3schools.com/tags/att_input_accept.asp:

The accept attribute is supported in all major browsers, except Internet Explorer and Safari. Definition and Usage

The accept attribute specifies the types of files that the server accepts (that can be submitted through a file upload).

Note: The accept attribute can only be used with <input type="file">.

Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.

Syntax <input accept="audio/*|video/*|image/*|MIME_type" />

Tip: To specify more than one value, separate the values with a comma (e.g. <input accept="audio/*,video/*,image/*" />.

Function passed as template argument

Yes, it is valid.

As for making it work with functors as well, the usual solution is something like this instead:

template <typename F>
void doOperation(F f)
{
  int temp=0;
  f(temp);
  std::cout << "Result is " << temp << std::endl;
}

which can now be called as either:

doOperation(add2);
doOperation(add3());

See it live

The problem with this is that if it makes it tricky for the compiler to inline the call to add2, since all the compiler knows is that a function pointer type void (*)(int &) is being passed to doOperation. (But add3, being a functor, can be inlined easily. Here, the compiler knows that an object of type add3 is passed to the function, which means that the function to call is add3::operator(), and not just some unknown function pointer.)

Best way to get whole number part of a Decimal number

By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).

If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:

Math.Truncate(number)

and return the value as... A DECIMAL or a DOUBLE.

edit: Truncate is definitely the correct function!

Calculating the area under a curve given a set of coordinates, without knowing the function

You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.

Python script that calculates Simpsons rule:

def integrate(y_vals, h):
    i = 1
    total = y_vals[0] + y_vals[-1]
    for y in y_vals[1:-1]:
        if i % 2 == 0:
            total += 2 * y
        else:
            total += 4 * y
        i += 1
    return total * (h / 3.0)

h is the offset (or gap) between y values, and y_vals is an array of well, y values.

Example (In same file as above function):

y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

Check if string ends with one of the strings from a list

There is two ways: regular expressions and string (str) methods.

String methods are usually faster ( ~2x ).

import re, timeit
p = re.compile('.*(.mp3|.avi)$', re.IGNORECASE)
file_name = 'test.mp3'
print(bool(t.match(file_name))
%timeit bool(t.match(file_name)

792 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

file_name = 'test.mp3'
extensions = ('.mp3','.avi')
print(file_name.lower().endswith(extensions))
%timeit file_name.lower().endswith(extensions)

274 ns ± 4.22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

How to split the screen with two equal LinearLayouts?

Just putting it out there:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF0000"
    android:weightSum="4"
    android:padding="5dp"> <!-- to show what the parent is -->
    <LinearLayout
        android:background="#0000FF"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="2" />
    <LinearLayout
        android:background="#00FF00"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1" />
</LinearLayout>

Can git undo a checkout of unstaged files

I believe if a file is modified but not yet added (staged), it is purely "private".
Meaning it cannot be restored by GIT if overwritten with the index or the HEAD version (unless you have a copy of your current work somewhere).

A "private" content is one only visible in your current directory, but not registered in any way in Git.

Note: As explained in other answers, you can recover your changes if you use an IDE (with local history) or have an open editor (ctrl+Z).

Where can I find MySQL logs in phpMyAdmin?

Open your PHPMyAdmin, don't select any database and look for Binary Log tab . You can select different logs from a drop down list and press GO Button to view them.

Composer: The requested PHP extension ext-intl * is missing from your system

For php.ini 5.6 version (check version using php -v)

;extension=php_intl.dll ; remove semicolon and keep like this extension=php_intl.dll

For php.ini 7.* version

;extension=intl ; remove semicolon and keep like this extension=intl

Note - After That Make Sure to Restart Your Xampp,Wamp Server in you Local Machine.

Android: how to convert whole ImageView to Bitmap?

Just thinking out loud here (with admittedly little expertise working with graphics in Java) maybe something like this would work?:

ImageView iv = (ImageView)findViewById(R.id.imageview);
Bitmap bitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
iv.draw(canvas);

Out of curiosity, what are you trying to accomplish? There may be a better way to achieve your goal than what you have in mind.

How to insert an item into a key/value pair object?

You could use an OrderedDictionary, but I would question why you would want to do that.

Iterating through a string word by word

Using nltk.

from nltk.tokenize import sent_tokenize, word_tokenize
sentences = sent_tokenize("This is a string.")
words_in_each_sentence = word_tokenize(sentences)

You may use TweetTokenizer for parsing casual text with emoticons and such.

Is Fortran easier to optimize than C for heavy calculations?

There is another item where Fortran is different than C - and potentially faster. Fortran has better optimization rules than C. In Fortran, the evaluation order of an expressions is not defined, which allows the compiler to optimize it - if one wants to force a certain order, one has to use parentheses. In C the order is much stricter, but with "-fast" options, they are more relaxed and "(...)" are also ignored. I think Fortran has a way which lies nicely in the middle. (Well, IEEE makes the live more difficult as certain evaluation-order changes require that no overflows occur, which either has to be ignored or hampers the evaluation).

Another area of smarter rules are complex numbers. Not only that it took until C 99 that C had them, also the rules govern them is better in Fortran; since the Fortran library of gfortran is partially written in C but implements the Fortran semantics, GCC gained the option (which can also be used with "normal" C programs):

-fcx-fortran-rules Complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there is no checking whether the result of a complex multiplication or division is "NaN + I*NaN", with an attempt to rescue the situation in that case.

The alias rules mentioned above is another bonus and also - at least in principle - the whole-array operations, which if taken properly into account by the optimizer of the compiler, can lead faster code. On the contra side are that certain operation take more time, e.g. if one does an assignment to an allocatable array, there are lots of checks necessary (reallocate? [Fortran 2003 feature], has the array strides, etc.), which make the simple operation more complex behind the scenes - and thus slower, but makes the language more powerful. On the other hand, the array operations with flexible bounds and strides makes it easier to write code - and the compiler is usually better optimizing code than a user.

In total, I think both C and Fortran are about equally fast; the choice should be more which language does one like more or whether using the whole-array operations of Fortran and its better portability are more useful -- or the better interfacing to system and graphical-user-interface libraries in C.

How to open child forms positioned within MDI parent in VB.NET?

Try adding a button on mdi parent and add this code' to set your mdi child inside the mdi parent. change the yourchildformname to your MDI Child's form name and see if this works.

    Dim NewMDIChild As New yourchildformname()
    'Set the Parent Form of the Child window.
    NewMDIChild.MdiParent = Me
    'Display the new form.
    NewMDIChild.Show()

formGroup expects a FormGroup instance

There are a few issues in your code

  • <div [formGroup]="form"> outside of a <form> tag
  • <form [formGroup]="form"> but the name of the property containing the FormGroup is loginForm therefore it should be <form [formGroup]="loginForm">
  • [formControlName]="dob" which passes the value of the property dob which doesn't exist. What you need is to pass the string dob like [formControlName]="'dob'" or simpler formControlName="dob"

Plunker example

Convert double/float to string

Go and look at the printf() implementation with "%f" in some C library.

Does functional programming replace GoF design patterns?

Some patterns are easier to implement in a language supporting FP. For example, Strategy can be implemented using nicely using closures. However depending on context, you may prefer to implement Strategy using a class-based approach, say where the strategies themselves are quite complicated and/or share structure that you want to model using Template Method.

In my experience developing in a multi-paradigm language (Ruby), the FP implementation works well in simple cases, but where the context is more complicated the GoF OOP based approach is a better fit.

The FP approach does not replace the OOP approach, it complements it.

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

  1. Declare the variable
  2. Set it by your command and add dynamic parts like use parameter values of sp(here @IsMonday and @IsTuesday are sp params)
  3. execute the command

    declare  @sql varchar (100)
    set @sql ='select * from #td1'
    
    if (@IsMonday+@IsTuesday !='')
    begin
    set @sql= @sql+' where PickupDay in ('''+@IsMonday+''','''+@IsTuesday+''' )'
    end
    exec( @sql)
    

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

I encountered an issue like this using the Maven Release Plugin. Resolving using relative paths (i.e. for the parent pom in the child module ../parent/pom.xml) did not seem to work in this scenario, it keeps looking for the released parent pom in the Nexus repository. Moving the parent pom to the parent folder of the module resolved this.

Add / remove input field dynamically with jQuery

you can do it as follow:

 $("#addButton").click(function () {

    if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
    }   

    var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
          '<input type="text" name="textbox' + counter + 
          '" id="textbox' + counter + '" value="" >');

    newTextBoxDiv.appendTo("#TextBoxesGroup");


    counter++;
     });

     $("#removeButton").click(function () {
    if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   

    counter--;

        $("#TextBoxDiv" + counter).remove();

     });

refer live demo http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/

How to filter array when object key value is in array

This is a fast solution with a temporary object.

_x000D_
_x000D_
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }],_x000D_
    empid = [1, 4, 5],_x000D_
    object = {},_x000D_
    result;_x000D_
_x000D_
records.forEach(function (a) {_x000D_
    object[a.empid] = a;_x000D_
});_x000D_
_x000D_
result = empid.map(function (a) {_x000D_
    return object[a];_x000D_
});_x000D_
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
_x000D_
_x000D_
_x000D_

How can I exit from a javascript function?

if ( condition ) {
    return;
}

The return exits the function returning undefined.

The exit statement doesn't exist in javascript.

The break statement allows you to exit a loop, not a function. For example:

var i = 0;
while ( i < 10 ) {
    i++;
    if ( i === 5 ) {
        break;
    }
}

This also works with the for and the switch loops.

Check if a time is between two times (time DataType)

This should also work (even in SQL-Server 2005):

SELECT *
FROM dbo.MyTable
WHERE Created >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, Created - 1), 0))
  AND Created <  DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, Created), 0))

DEMO

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

Git pull is actually a combo tool: it runs git fetch (getting the changes) and git merge (merging them with your current copy)

Are you sure you are on the correct branch?

Rounding float in Ruby

you can use this for rounding to a precison..

//to_f is for float

salary= 2921.9121
puts salary.to_f.round(2) // to 2 decimal place                   

puts salary.to_f.round() // to 3 decimal place          

VBA array sort function?

I posted some code in answer to a related question on StackOverflow:

Sorting a multidimensionnal array in VBA

The code samples in that thread include:

  1. A vector array Quicksort;
  2. A multi-column array QuickSort;
  3. A BubbleSort.

Alain's optimised Quicksort is very shiny: I just did a basic split-and-recurse, but the code sample above has a 'gating' function that cuts down on redundant comparisons of duplicated values. On the other hand, I code for Excel, and there's a bit more in the way of defensive coding - be warned, you'll need it if your array contains the pernicious 'Empty()' variant, which will break your While... Wend comparison operators and trap your code in an infinite loop.

Note that quicksort algorthms - and any recursive algorithm - can fill the stack and crash Excel. If your array has fewer than 1024 members, I'd use a rudimentary BubbleSort.

Public Sub QuickSortArray(ByRef SortArray As Variant, _
                                Optional lngMin As Long = -1, _ 
                                Optional lngMax As Long = -1, _ 
                                Optional lngColumn As Long = 0)
On Error Resume Next
'Sort a 2-Dimensional array
' Sample Usage: sort arrData by the contents of column 3 ' ' QuickSortArray arrData, , , 3
' 'Posted by Jim Rech 10/20/98 Excel.Programming
'Modifications, Nigel Heffernan:
' ' Escape failed comparison with empty variant ' ' Defensive coding: check inputs
Dim i As Long Dim j As Long Dim varMid As Variant Dim arrRowTemp As Variant Dim lngColTemp As Long

If IsEmpty(SortArray) Then Exit Sub End If
If InStr(TypeName(SortArray), "()") < 1 Then 'IsArray() is somewhat broken: Look for brackets in the type name Exit Sub End If
If lngMin = -1 Then lngMin = LBound(SortArray, 1) End If
If lngMax = -1 Then lngMax = UBound(SortArray, 1) End If
If lngMin >= lngMax Then ' no sorting required Exit Sub End If

i = lngMin j = lngMax
varMid = Empty varMid = SortArray((lngMin + lngMax) \ 2, lngColumn)
' We send 'Empty' and invalid data items to the end of the list: If IsObject(varMid) Then ' note that we don't check isObject(SortArray(n)) - varMid might pick up a valid default member or property i = lngMax j = lngMin ElseIf IsEmpty(varMid) Then i = lngMax j = lngMin ElseIf IsNull(varMid) Then i = lngMax j = lngMin ElseIf varMid = "" Then i = lngMax j = lngMin ElseIf varType(varMid) = vbError Then i = lngMax j = lngMin ElseIf varType(varMid) > 17 Then i = lngMax j = lngMin End If

While i <= j
While SortArray(i, lngColumn) < varMid And i < lngMax i = i + 1 Wend
While varMid < SortArray(j, lngColumn) And j > lngMin j = j - 1 Wend

If i <= j Then
' Swap the rows ReDim arrRowTemp(LBound(SortArray, 2) To UBound(SortArray, 2)) For lngColTemp = LBound(SortArray, 2) To UBound(SortArray, 2) arrRowTemp(lngColTemp) = SortArray(i, lngColTemp) SortArray(i, lngColTemp) = SortArray(j, lngColTemp) SortArray(j, lngColTemp) = arrRowTemp(lngColTemp) Next lngColTemp Erase arrRowTemp
i = i + 1 j = j - 1
End If

Wend
If (lngMin < j) Then Call QuickSortArray(SortArray, lngMin, j, lngColumn) If (i < lngMax) Then Call QuickSortArray(SortArray, i, lngMax, lngColumn)

End Sub

How to iterate through a list of dictionaries in Jinja template?

As a sidenote to @Navaneethan 's answer, Jinja2 is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.

Data:

parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]

in Jinja2 iteration:

{% for dict_item in parent_dict %}
   This example has {{dict_item['A']}} and {{dict_item['B']}}:
       with the content --
       {% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}

The rendered output:

This example has val1 and val2:
    with the content --
    1.1 and 2.2.

This example has val3 and val4:
   with the content --
   3.3 and 4.4.

How to Remove Line Break in String

str = Replace(str, vbLf, "")

This code takes all the line break's out of the code

if you just want the last one out:

If Right(str, 1) = vbLf Then str = Left(str, Len(str) - 1)

is the way how you tryed OK.


Update:

line feed = ASCII 10, form feed = ASCII 12 and carriage return = ASCII 13. Here we see clearly what we all know: the PC comes from the (electric) typewriter

vbLf is Chr (10) and means that the cursor jumps one line lower (typewriter: turn the roller) vbCr is Chr (13) means the cursor jumps to the beginning (typewriter: pull back the roll)

In DOS, a line break is always VBCrLf or Chr (13) & Chr (10), in files anyway, but e.g. also with the text boxes in VB.

In an Excel cell, on the other hand, a line break is only VBLf, the second line then starts at the first position even without vbCr. With vbCrLf then go one cell deeper.

So it depends on where you read and get your String from. if you want to remove all the vbLf (Char(10)) and vbCr (Char(13)) in your tring, you can do it like that:

strText = Replace(Replace(strText, Chr(10), ""), Chr(13), "")

If you only want t remove the Last one, you can test on do it like this:

If Right(str, 1) = vbLf or Right(str, 1) = vbCr Then str = Left(str, Len(str) - 1)

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

jQuery: how to change title of document during .ready()?

<script type="text/javascript">
$(document).ready(function() {

    $(this).attr("title", "sometitle");

});
</script>

Set today's date as default date in jQuery UI datepicker

$("#date").datepicker.regional[""].dateFormat = 'dd/mm/yy';
$("#date").datepicker("setDate", new Date());

Always work for me

Tab separated values in awk

Should this not work?

echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk '{print $1}'

How can we stop a running java process through Windows cmd?

When I ran taskkill to stop the javaw.exe process it would say it had terminated but remained running. The jqs process (java qucikstart) needs to be stopped also. Running this batch file took care of the issue.

taskkill /f /im jqs.exe
taskkill /f /im javaw.exe
taskkill /f /im java.exe

Insert line after first match using sed

A POSIX compliant one using the s command:

sed '/CLIENTSCRIPT="foo"/s/.*/&\
CLIENTSCRIPT2="hello"/' file

In C/C++ what's the simplest way to reverse the order of bits in a byte?

#define BITS_SIZE 8

int
reverseBits ( int a )
{
  int rev = 0;
  int i;

  /* scans each bit of the input number*/
  for ( i = 0; i < BITS_SIZE - 1; i++ )
  {
    /* checks if the bit is 1 */
    if ( a & ( 1 << i ) )
    {
      /* shifts the bit 1, starting from the MSB to LSB
       * to build the reverse number 
      */
      rev |= 1 << ( BITS_SIZE - 1 ) - i;
    }
  }

  return rev;
}

How to write PNG image to string with the PIL?

For Python3 it is required to use BytesIO:

from io import BytesIO
from PIL import Image, ImageDraw

image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "This text is drawn on image")

byte_io = BytesIO()

image.save(byte_io, 'PNG')

Read more: http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image

How to get package name from anywhere?

Create a java module to be initially run when starting your app. This module would be extending the android Application class and would initialize any global app variables and also contain app-wide utility routines -

public class MyApplicationName extends Application {

    private final String PACKAGE_NAME = "com.mysite.myAppPackageName";

    public String getPackageName() { return PACKAGE_NAME; }
}

Of course, this could include logic to obtain the package name from the android system; however, the above is smaller, faster and cleaner code than obtaining it from android.

Be sure to place an entry in your AndroidManifest.xml file to tell android to run your application module before running any activities -

<application 
    android:name=".MyApplicationName" 
    ...
>

Then, to obtain the package name from any other module, enter

MyApp myApp = (MyApp) getApplicationContext();
String myPackage = myApp.getPackageName();

Using an application module also gives you a context for modules that need but don't have a context.

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.

location / {
    root /path/to/root/of/static/files;
    try_files $uri $uri/ @apachesite;

    expires max;
    access_log off;
}

location @apachesite {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.

MySQL query String contains

You probably are looking for find_in_set function:

Where find_in_set($needle,'column') > 0

This function acts like in_array function in PHP

How do I mount a host directory as a volume in docker compose

If you would like to mount a particular host directory (/disk1/prometheus-data in the following example) as a volume in the volumes section of the Docker Compose YAML file, you can do it as below, e.g.:

version: '3'

services:
  prometheus:
    image: prom/prometheus
    volumes:
      - prometheus-data:/prometheus

volumes:
  prometheus-data:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: /disk1/prometheus-data

By the way, in prometheus's Dockerfile, You may find the VOLUME instruction as below, which marks it as holding externally mounted volumes from native host, etc. (Note however: this instruction is not a must though to mount a volume into a container.):

Dockerfile

...
VOLUME ["/prometheus"]
...

Refs:

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

Format in other syntax is possible in this way

[DateTime]::Today.AddDays(-1).ToString("yyyyMMdd")

what exactly is device pixel ratio?

Boris Smus's article High DPI Images for Variable Pixel Densities has a more accurate definition of device pixel ratio: the number of device pixels per CSS pixel is a good approximation, but not the whole story.

Note that you can get the DPR used by a device with window.devicePixelRatio.

Javascript - check array for value

If you don't care about legacy browsers:

if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )

if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:

if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )

Spring MVC Controller redirect using URL parameters instead of in response

@RequestMapping(path="/apps/add", method=RequestMethod.POST)
public String addApps(String appUrl, Model model, final RedirectAttributes redirectAttrs) {
    if (!validate(appUrl)) {
       redirectAttrs.addFlashAttribute("error", "Validation failed");
    }
    return "redirect:/apps/add"
} 

@RequestMapping(path="/apps/add", method=RequestMethod.GET)
public String addAppss(Model model) {
    String error = model.asMap().get("error");
}

How to create a custom-shaped bitmap marker with Android map API v2

From lambda answer, I have made something closer to the requirements.

boolean imageCreated = false;

Bitmap bmp = null;
Marker currentLocationMarker;
private void doSomeCustomizationForMarker(LatLng currentLocation) {
    if (!imageCreated) {
        imageCreated = true;
        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        bmp = Bitmap.createBitmap(400, 400, conf);
        Canvas canvas1 = new Canvas(bmp);

        Paint color = new Paint();
        color.setTextSize(30);
        color.setColor(Color.WHITE);

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inMutable = true;

        Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),
                R.drawable.messi,opt);
        Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 320, 320, true);
        canvas1.drawBitmap(resized, 40, 40, color);

        canvas1.drawText("Le Messi", 30, 40, color);

        currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation)
                .icon(BitmapDescriptorFactory.fromBitmap(bmp))
                // Specifies the anchor to be at a particular point in the marker image.
                .anchor(0.5f, 1));
    } else {
        currentLocationMarker.setPosition(currentLocation);
    }

}

How to select data from 30 days?

Try this : Using this you can select date by last 30 days,

SELECT DATEADD(DAY,-30,GETDATE())

ssh: check if a tunnel is alive

#!/bin/bash

# Check do we have tunnel to example.com server
lsof -i tcp@localhost:6000 > /dev/null

# If exit code wasn't 0 then tunnel doesn't exist.
if [ $? -eq 1 ]
then
  echo ' > You missing ssh tunnel. Creating one..'
  ssh -L 6000:localhost:5432 example.com
fi

echo ' > DO YOUR STUFF < '

How do I parse an ISO 8601-formatted date?

What is the exact error you get? Is it like the following?

>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
ValueError: time data did not match format:  data=2008-08-12T12:20:30.656234Z  fmt=%Y-%m-%dT%H:%M:%S.Z

If yes, you can split your input string on ".", and then add the microseconds to the datetime you got.

Try this:

>>> def gt(dt_str):
        dt, _, us= dt_str.partition(".")
        dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
        us= int(us.rstrip("Z"), 10)
        return dt + datetime.timedelta(microseconds=us)

>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

In Python 3 the dict.values() method returns a dictionary view object, not a list like it does in Python 2. Dictionary views have a length, can be iterated, and support membership testing, but don't support indexing.

To make your code work in both versions, you could use either of these:

{names[i]:value for i,value in enumerate(d.values())}

    or

values = list(d.values())
{name:values[i] for i,name in enumerate(names)}

By far the simplest, fastest way to do the same thing in either version would be:

dict(zip(names, d.values()))

Note however, that all of these methods will give you results that will vary depending on the actual contents of d. To overcome that, you may be able use an OrderedDict instead, which remembers the order that keys were first inserted into it, so you can count on the order of what is returned by the values() method.

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.

Sometimes using image = array(img).reshape(a,b,c,d) will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is

np.expand_dims(img, axis=0)

It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

Benefits of inline functions in C++?

Why not make all functions inline by default? Because it's an engineering trade off. There are at least two types of "optimization": speeding up the program and reducing the size (memory footprint) of the program. Inlining generally speeds things up. It gets rid of the function call overhead, avoiding pushing then pulling parameters from the stack. However, it also makes the memory footprint of the program bigger, because every function call must now be replaced with the full code of the function. To make things even more complicated, remember that the CPU stores frequently used chunks of memory in a cache on the CPU for ultra-rapid access. If you make the program's memory image big enough, your program won't be able to use the cache efficiently, and in the worst case inlining could actually slow your program down. To some extent the compiler can calculate what the trade offs are, and may be able to make better decisions than you can, just looking at the source code.

What is the difference between bindParam and bindValue?

Here are some I can think about :

  • With bindParam, you can only pass variables ; not values
  • with bindValue, you can pass both (values, obviously, and variables)
  • bindParam works only with variables because it allows parameters to be given as input/output, by "reference" (and a value is not a valid "reference" in PHP) : it is useful with drivers that (quoting the manual) :

support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.

With some DB engines, stored procedures can have parameters that can be used for both input (giving a value from PHP to the procedure) and ouput (returning a value from the stored proc to PHP) ; to bind those parameters, you've got to use bindParam, and not bindValue.

Shared folder between MacOSX and Windows on Virtual Box

Using a Windows 10 guest, after I performed steps 1 through 3 from @xinampc's answer, I had to open a new File Explorer and navigated to This PC > CD Drive (D:) VirtualBox Guest Additions to run VBoxWindowsAdditions. After I ran that and went through the command prompts, Windows rebooted and I was able to see VBOXSVR under Network.

Display last git commit comment

git show

is the fastest to type, but shows you the diff as well.

git log -1

is fast and simple.

git log -1 --pretty=%B

if you need just the commit message and nothing else.

python: [Errno 10054] An existing connection was forcibly closed by the remote host

This can be caused by the two sides of the connection disagreeing over whether the connection timed out or not during a keepalive. (Your code tries to reused the connection just as the server is closing it because it has been idle for too long.) You should basically just retry the operation over a new connection. (I'm surprised your library doesn't do this automatically.)

Warning: comparison with string literals results in unspecified behaviour

You want to use strcmp() == 0 to compare strings instead of a simple ==, which will just compare if the pointers are the same (which they won't be in this case).

args[i] is a pointer to a string (a pointer to an array of chars null terminated), as is "&" or "<".

The expression argc[i] == "&" checks if the two pointers are the same (point to the same memory location).

The expression strcmp( argc[i], "&") == 0 will check if the contents of the two strings are the same.

Binding arrow keys in JS/jQuery

A terse solution using plain Javascript (thanks to Sygmoral for suggested improvements):

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
    }
};

Also see https://stackoverflow.com/a/17929007/1397061.

Custom format for time command

You could use the date command to get the current time before and after performing the work to be timed and calculate the difference like this:

#!/bin/bash

# Get time as a UNIX timestamp (seconds elapsed since Jan 1, 1970 0:00 UTC)
T="$(date +%s)"

# Do some work here
sleep 2

T="$(($(date +%s)-T))"
echo "Time in seconds: ${T}"

printf "Pretty format: %02d:%02d:%02d:%02d\n" "$((T/86400))" "$((T/3600%24))" "$((T/60%60))" "$((T%60))""

Notes: $((...)) can be used for basic arithmetic in bash – caution: do not put spaces before a minus - as this might be interpreted as a command-line option.

See also: http://tldp.org/LDP/abs/html/arithexp.html

EDIT:
Additionally, you may want to take a look at sed to search and extract substrings from the output generated by time.

EDIT:

Example for timing with milliseconds (actually nanoseconds but truncated to milliseconds here). Your version of date has to support the %N format and bash should support large numbers.

# UNIX timestamp concatenated with nanoseconds
T="$(date +%s%N)"

# Do some work here
sleep 2

# Time interval in nanoseconds
T="$(($(date +%s%N)-T))"
# Seconds
S="$((T/1000000000))"
# Milliseconds
M="$((T/1000000))"

echo "Time in nanoseconds: ${T}"
printf "Pretty format: %02d:%02d:%02d:%02d.%03d\n" "$((S/86400))" "$((S/3600%24))" "$((S/60%60))" "$((S%60))" "${M}"

DISCLAIMER:
My original version said

M="$((T%1000000000/1000000))"

but this was edited out because it apparently did not work for some people whereas the new version reportedly did. I did not approve of this because I think that you have to use the remainder only but was outvoted.
Choose whatever fits you.

How to add days to the current date?

can try this

select (CONVERT(VARCHAR(10),GETDATE()+360,110)) as Date_Result

C++ performance vs. Java/C#

I don't know either...my Java programs are always slow. :-) I've never really noticed C# programs being particularly slow, though.

In Python, how do I split a string and keep the separators?

You can also split a string with an array of strings instead of a regular expression, like this:

def tokenizeString(aString, separators):
    #separators is an array of strings that are being used to split the string.
    #sort separators in order of descending length
    separators.sort(key=len)
    listToReturn = []
    i = 0
    while i < len(aString):
        theSeparator = ""
        for current in separators:
            if current == aString[i:i+len(current)]:
                theSeparator = current
        if theSeparator != "":
            listToReturn += [theSeparator]
            i = i + len(theSeparator)
        else:
            if listToReturn == []:
                listToReturn = [""]
            if(listToReturn[-1] in separators):
                listToReturn += [""]
            listToReturn[-1] += aString[i]
            i += 1
    return listToReturn
    

print(tokenizeString(aString = "\"\"\"hi\"\"\" hello + world += (1*2+3/5) '''hi'''", separators = ["'''", '+=', '+', "/", "*", "\\'", '\\"', "-=", "-", " ", '"""', "(", ")"]))

In MS DOS copying several files to one file

copy *.csv new.csv

No need for /b as csv isn't a binary file type.

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I was also facing this issue

Error- Windows cannot find 'http://127.0.01:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

After some research work, I found out that my HTTPPORT ie. 8080 was occupied by Apace HTTP Server and hence connection by OracleServiceXE could not be established.

What I did to solve this issue was :

  1. Go to Windows -> Services, found out Apache2.4 and manually stopped it to free my 8080 port.
  2. Clicked on Start Database, and I received message :

The OracleServiceXE service is starting.............. The OracleServiceXE service was started successfully.

  1. Manually entered http://127.0.0.1:8080/apex/f?p=4950 url to my browser which auto redirected me to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303

That's it my issue got resolved.

In order to remember this new url and make sure that next time whenever I hit Get Started I should be redirected to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303 instead of http://127.0.0.1:8080/apex/f?p=4950, what I did was :

  1. Browse to Directory:\OracleDatabase\app\oracle\product\11.2.0\server and search for Get_Started.html.
  2. Right Click on Get_Started.html and select Properties
  3. Modify your url and click Apply

Hope this Helps.

mysql: see all open connections to a given database?

In query browser right click on database and select processlist

Sort array by firstname (alphabetically) in Javascript

underscorejs offers the very nice _.sortBy function:

_.sortBy([{a:1},{a:3},{a:2}], "a")

or you can use a custom sort function:

_.sortBy([{a:"b"},{a:"c"},{a:"a"}], function(i) {return i.a.toLowerCase()})

How do you determine a processing time in Python?

If all you want is the time between two points in code (and it seems that's what you want) I have written tic() toc() functions ala Matlab's implementation. The basic use case is:

tic()

''' some code that runs for an interesting amount of time '''

toc()

# OUTPUT:
# Elapsed time is: 32.42123 seconds

Super, incredibly easy to use, a sort of fire-and-forget kind of code. It's available on Github's Gist https://gist.github.com/tyleha/5174230

Accessing certain pixel RGB value in openCV

uchar * value = img2.data; //Pointer to the first pixel data ,it's return array in all values 
int r = 2;
for (size_t i = 0; i < img2.cols* (img2.rows * img2.channels()); i++)
{

        if (r > 2) r = 0;

        if (r == 0) value[i] = 0;
        if (r == 1)value[i] =  0;
        if (r == 2)value[i] = 255;

        r++;
}

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

Open a good text editor (I'd recommend TextMate, but the free TextWrangler or vi or nano will do too), and open:

/etc/apache2/httpd.conf

Find the line:

"#LoadModule php5_module        libexec/apache2/libphp5.so"

And uncomment it (remove the #).

Download and install the latest MySQL version from mysql.com. Choose the x86_64 version for Intel (unless your Intel Mac is the original Macbook Pro or Macbook, which are not 64 bit chips. In those cases, use the 32 bit x86 version).

Install all the MySQL components. Using the pref pane, start MySQL.

In the Sharing System Pref, turn on (or if it was already on, turn off/on) Web Sharing.

You should now have Apache/PHP/MySQL running.

In 10.4 and 10.5 it was necessary to modify the php.ini file to point to the correct location of mysql.sock. There are reports that this is fixed in 10.6, but that doesn't appear to be the case for all of us, given some of the comments below.

Maximum execution time in phpMyadmin

'ZERO' for unlimited time.

C:\Apache24\htdocs\phpmyadmin\libraries\Config.class.php

/**
 * maximum execution time in seconds (0 for no limit)
 *
 * @global integer $cfg['ExecTimeLimit']
 */
$cfg['ExecTimeLimit'] = 0;

You could also import the large file right from MySQL as query or a PHP query.

500,000 rows just took me 18 seconds to import on local server, using this method.

(create table first) - then:

LOAD DATA LOCAL INFILE 'Path_To_Your_File.csv' 
INTO TABLE Your_Table_Name 
FIELDS TERMINATED BY ',' 
LINES TERMINATED BY '\n' 

Changing column names of a data frame

I use this:

colnames(dataframe)[which(names(dataframe) == "columnName")] <- "newColumnName"

Tomcat 7: How to set initial heap size correctly?

Just came across this and I've implemented Nathan's solution:

add the line (changing the values as required):

export JAVA_OPTS="-Xms512M -Xmx1024M"

to /usr/share/tomcat7/bin/setenv.sh

If that file doesn't exists then create it and

chown root:root it
chmod 755 it

And then restart tomcat and check it with

ps aux | grep logging

Which should just pick up the instance and show the java parms

How to create an executable .exe file from a .m file

If you have MATLAB Compiler installed, there's a GUI option for compiling. Try entering

deploytool

in the command line. Mathworks does a pretty good job documenting how to use it in this video tutorial: http://www.mathworks.com/products/demos/compiler/deploytool/index.html

Also, if you want to include user input such as choosing a file or directory, look into

uigetfile % or uigetdir if you need every file in a directory

for use in conjunction with

guide

Remove the newline character in a list read from a file

You could actually put the newlines to good use by reading the entire file into memory as a single long string and then use them to split that into the list of grades.

with open("grades.dat") as input:
    grades = [line.split(",") for line in input.read().splitlines()]
etc...

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

I use this website and this pattern do leap year validation as well.

<input type="text" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" required />

Consistency of hashCode() on a Java string

As said above, in general you should not rely on the hash code of a class remaining the same. Note that even subsequent runs of the same application on the same VM may produce different hash values. AFAIK the Sun JVM's hash function calculates the same hash on every run, but that's not guaranteed.

Note that this is not theoretical. The hash function for java.lang.String was changed in JDK1.2 (the old hash had problems with hierarchical strings like URLs or file names, as it tended to produce the same hash for strings which only differed at the end).

java.lang.String is a special case, as the algorithm of its hashCode() is (now) documented, so you can probably rely on that. I'd still consider it bad practice. If you need a hash algorithm with special, documented properties, just write one :-).

HTML5 Canvas vs. SVG vs. div

To add to this, I've been doing a diagram application, and initially started out with canvas. The diagram consists of many nodes, and they can get quite big. The user can drag elements in the diagram around.

What I found was that on my Mac, for very large images, SVG is superior. I have a MacBook Pro 2013 13" Retina, and it runs the fiddle below quite well. The image is 6000x6000 pixels, and has 1000 objects. A similar construction in canvas was impossible to animate for me when the user was dragging objects around in the diagram.

On modern displays you also have to account for different resolutions, and here SVG gives you all of this for free.

Fiddle: http://jsfiddle.net/knutsi/PUcr8/16/

Fullscreen: http://jsfiddle.net/knutsi/PUcr8/16/embedded/result/

var wiggle_factor = 0.0;
nodes = [];

// create svg:
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('style', 'border: 1px solid black');
svg.setAttribute('width', '6000');
svg.setAttribute('height', '6000');

svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink",
    "http://www.w3.org/1999/xlink");

document.body.appendChild(svg);


function makeNode(wiggle) {
    var node = document.createElementNS("http://www.w3.org/2000/svg", "g");
    var node_x = (Math.random() * 6000);
    var node_y = (Math.random() * 6000);
    node.setAttribute("transform", "translate(" + node_x + ", " + node_y +")");

    // circle:
    var circ = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    circ.setAttribute( "id","cir")
    circ.setAttribute( "cx", 0 + "px")
    circ.setAttribute( "cy", 0 + "px")
    circ.setAttribute( "r","100px");
    circ.setAttribute('fill', 'red');
    circ.setAttribute('pointer-events', 'inherit')

    // text:
    var text = document.createElementNS("http://www.w3.org/2000/svg", "text");
    text.textContent = "This is a test! ÅÆØ";

    node.appendChild(circ);
    node.appendChild(text);

    node.x = node_x;
    node.y = node_y;

    if(wiggle)
        nodes.push(node)
    return node;
}

// populate with 1000 nodes:
for(var i = 0; i < 1000; i++) {
    var node = makeNode(true);
    svg.appendChild(node);
}

// make one mapped to mouse:
var bnode = makeNode(false);
svg.appendChild(bnode);

document.body.onmousemove=function(event){
    bnode.setAttribute("transform","translate(" +
        (event.clientX + window.pageXOffset) + ", " +
        (event.clientY + window.pageYOffset) +")");
};

setInterval(function() {
    wiggle_factor += 1/60;
    nodes.forEach(function(node) {

        node.setAttribute("transform", "translate(" 
                          + (Math.sin(wiggle_factor) * 200 + node.x) 
                          + ", " 
                          + (Math.sin(wiggle_factor) * 200 + node.y) 
                          + ")");        
    })
},1000/60);

Update Tkinter Label from variable

The window is only displayed once the mainloop is entered. So you won't see any changes you make in your while True block preceding the line root.mainloop().


GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.

from tkinter import *

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

t = Entry(root, textvariable = var)
t.pack()

root.mainloop() # the window is now displayed

I like the following reference: tkinter 8.5 reference: a GUI for Python


Here is a working example of what you were trying to do:

from tkinter import *
from time import sleep

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

for i in range(6):
    sleep(1) # Need this to slow the changes down
    var.set('goodbye' if i%2 else 'hello')
    root.update_idletasks()

root.update Enter event loop until all pending events have been processed by Tcl.

Mockito: InvalidUseOfMatchersException

It might help some one in the future: Mockito doesn't support mocking of 'final' methods (right now). It gave me the same InvalidUseOfMatchersException.

The solution for me was to put the part of the method that didn't have to be 'final' in a separate, accessible and overridable method.

Review the Mockito API for your use case.

SHA1 vs md5 vs SHA256: which to use for a PHP login?

Here is the comparison between MD5 and SHA1. You can get a clear idea about which one is better.

enter image description here

How to prevent robots from automatically filling up a form?

What if - the Bot does not find any form at all?

3 examples:

  1. Insert your form using AJAX
  • If you are OK with users having JS disabled and not being able to see/ submit a form, you can notify them and have them enable Javascript first using a noscript statement:
<noscript>
  <p class="error">
    ERROR: The form could not be loaded. Please enable JavaScript in your browser to fully enjoy our services.
  </p>
</noscript>
  • Create a form.html and place your form inside a <div id="formContainer"> element.

  • Inside the page where you need to call that form use an empty <div id="dynamicForm"></div> and this jQuery: $("#dynamicForm").load("form.html #formContainer");

  1. Build your form entirely using JS

_x000D_
_x000D_
// THE FORM
var $form = $("<form/>", {
  appendTo : $("#formContainer"),
  class    : "myForm",
  submit   : AJAXSubmitForm
});

// EMAIL INPUT
$("<input/>",{
  name        : "Email", // Needed for serialization
  placeholder : "Your Email",
  appendTo    : $form,
  on          : {        // Yes, the jQuery's on() Method 
    input : function() {
      console.log( this.value );
    }
  }
});

// MESSAGE TEXTAREA
$("<textarea/>",{
  name        : "Message", // Needed for serialization
  placeholder : "Your message",
  appendTo    : $form
});

// SUBMIT BUTTON
$("<input/>",{
  type        : "submit",
  value       : "Send",
  name        : "submit",
  appendTo    : $form
});

function AJAXSubmitForm(event) {
  event.preventDefault(); // Prevent Default Form Submission
  // do AJAX instead:
  var serializedData = $(this).serialize();
  alert( serializedData );
  $.ajax({
    url: '/mail.php',
    type: "POST",
    data: serializedData,
    success: function (data) {
      // log the data sent back from PHP
      console.log( data );
    }
  });
}
_x000D_
.myForm input,
.myForm textarea{
  font: 14px/1 sans-serif;
  box-sizing: border-box;
  display:block;
  width:100%;
  padding: 8px;
  margin-bottom:12px;
}
.myForm textarea{
  resize: vertical;
  min-height: 120px;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formContainer"></div>
_x000D_
_x000D_
_x000D_

  1. Bot-bait input
  • Bots like (really like) saucy input elements like:
<input 
  type="text"
  name="email"
  id="email"
  placeholder="Your email"
  autocomplete="nope"
  tabindex="-1"
They wll be happy to enter some value such as
`[email protected]`
  • After using the above HTML you can also use CSS to not display the input:
input[name=email]{ /* bait input */
  /* do not use display:none or visibility:hidden
     that will not fool the bot*/
  position:absolute;
  left:-2000px;
}
  • Now that your input is not visible to the user expect in PHP that your $_POST["email"] should be empty (without any value)! Otherwise don't submit the form.
  • Finally,all you need to do is create another input like <input name="sender" type="text" placeholder="Your email"> after (!) the "bot-bait" input for the actual user Email address.

Acknowledgments:

Developer.Mozilla - Turning off form autocompletition
StackOverflow - Ignore Tabindex

Two constructors

To call one constructor from another you need to use this() and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.

How to add element in Python to the end of list using list.insert?

list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]

Time complexity, append O(1), insert O(n)

How to list all the files in android phone by using adb shell?

Some Android phones contain Busybox. Was hard to find.

To see if busybox was around:

ls -lR / | grep busybox

If you know it's around. You need some read/write space. Try you flash drive, /sdcard

cd /sdcard
ls -lR / >lsoutput.txt

upload to your computer. Upload the file. Get some text editor. Search for busybox. Will see what directory the file was found in.

busybox find /sdcard -iname 'python*'

to make busybox easier to access, you could:

cd /sdcard
ln -s /where/ever/busybox/is  busybox
/sdcard/busybox find /sdcard -iname 'python*'

Or any other place you want. R

What is the Java equivalent for LINQ?

There's a very good library that you can use for this.

Located here: https://github.com/nicholas22/jpropel-light

Lambdas won't be available until Java 8 though, so using it is a bit different and doesn't feel as natural.

jQuery Datepicker close datepicker after selected date

Answer above did not work for me on Chrome. The change event was been fired after I clicked out of the field somewhere, which did not help because the datepicker window is also closed too when you click out of the field.

I did use this code and it worked pretty well. You can place it after calling .datepicker();

HTML

<input type="text" class="datepicker-input" placeholder="click to show datepicker" />

JavaScript

$(".datepicker-input").each(function() {
    $(this).datepicker();
});

$(".datepicker-input").click(function() {
    $(".datepicker-days .day").click(function() {
        $('.datepicker').hide();
    });
});

jQuery set checkbox checked

Worked for me:

$checkbok.prop({checked: true});

Removing carriage return and new-line from the end of a string in c#

This is what I got to work for me.

s.Replace("\r","").Replace("\n","")

How to calculate the number of occurrence of a given character in each row of a column of strings?

s <- "aababacababaaathhhhhslsls jsjsjjsaa ghhaalll"
p <- "a"
s2 <- gsub(p,"",s)
numOcc <- nchar(s) - nchar(s2)

May not be the efficient one but solve my purpose.

How to query DATETIME field using only date in Microsoft SQL Server?

you can try this

select * from test where DATEADD(dd, 0, DATEDIFF(dd, 0, date)) = '03/19/2014';

Maintain image aspect ratio when changing height

Most of images with intrinsic dimensions, that is a natural size, like a jpeg image. If the specified size defines one of both the width and the height, the missing value is determined using the intrinsic ratio... - see MDN.

But that doesn't work as expected if the images that are being set as direct flex items with the current Flexible Box Layout Module Level 1, as far as I know.

See these discussions and bug reports might be related:

  • Flexbugs #14 - Chrome/Flexbox Intrinsic Sizing not implemented correctly.
  • Firefox Bug 972595 - Flex containers should use "flex-basis" instead of "width" for computing intrinsic widths of flex items
  • Chromium Issue 249112 - In Flexbox, allow intrinsic aspect ratios to inform the main-size calculation.

As a workaround, you could wrap each <img> with a <div> or a <span>, or so.

jsFiddle

_x000D_
_x000D_
.slider {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.slider>div {_x000D_
  min-width: 0; /* why? see below. */_x000D_
}_x000D_
_x000D_
.slider>div>img {_x000D_
  max-width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<div class="slider">_x000D_
  <div><img src="https://picsum.photos/400/300?image=0" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=1" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=2" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=3" /></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

4.5 Implied Minimum Size of Flex Items

To provide a more reasonable default minimum size for flex items, this specification introduces a new auto value as the initial value of the min-width and min-height properties defined in CSS 2.1.


Alternatively, you can use CSS table layout instead, which you'll get similar results as flexbox, it will work on more browsers, even for IE8.

jsFiddle

_x000D_
_x000D_
.slider {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.slider>div {_x000D_
  display: table-cell;_x000D_
  vertical-align: top;_x000D_
}_x000D_
_x000D_
.slider>div>img {_x000D_
  max-width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<div class="slider">_x000D_
  <div><img src="https://picsum.photos/400/300?image=0" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=1" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=2" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=3" /></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to step through Python code to help debug issues?

Programmatically stepping and tracing through python code is possible too (and its easy!). Look at the sys.settrace() documentation for more details. Also here is a tutorial to get you started.

How can I add new keys to a dictionary?

your_dict = {}

To add new key:

  1. your_dict[key]=value

  2. your_dict.update(key=value)

How to write trycatch in R

Since I just lost two days of my life trying to solve for tryCatch for an irr function, I thought I should share my wisdom (and what is missing). FYI - irr is an actual function from FinCal in this case where got errors in a few cases on a large data set.

  1. Set up tryCatch as part of a function. For example:

    irr2 <- function (x) {
      out <- tryCatch(irr(x), error = function(e) NULL)
      return(out)
    }
    
  2. For the error (or warning) to work, you actually need to create a function. I originally for error part just wrote error = return(NULL) and ALL values came back null.

  3. Remember to create a sub-output (like my "out") and to return(out).

Custom sort function in ng-repeat

Actually the orderBy filter can take as a parameter not only a string but also a function. From the orderBy documentation: https://docs.angularjs.org/api/ng/filter/orderBy):

function: Getter function. The result of this function will be sorted using the <, =, > operator.

So, you could write your own function. For example, if you would like to compare cards based on a sum of opt1 and opt2 (I'm making this up, the point is that you can have any arbitrary function) you would write in your controller:

$scope.myValueFunction = function(card) {
   return card.values.opt1 + card.values.opt2;
};

and then, in your template:

ng-repeat="card in cards | orderBy:myValueFunction"

Here is the working jsFiddle

The other thing worth noting is that orderBy is just one example of AngularJS filters so if you need a very specific ordering behaviour you could write your own filter (although orderBy should be enough for most uses cases).

Setting action for back button in navigation controller

For a form that requires user input like this, I would recommend invoking it as a "modal" instead of part of your navigation stack. That way they have to take care of business on the form, then you can validate it and dismiss it using a custom button. You can even design a nav bar that looks the same as the rest of your app but gives you more control.

Temporary table in SQL server causing ' There is already an object named' error

In Azure Data warehouse also this occurs sometimes, because temporary tables created for a user session.. I got the same issue fixed by reconnecting the database,

printf format specifiers for uint32_t and size_t

Sounds like you're expecting size_t to be the same as unsigned long (possibly 64 bits) when it's actually an unsigned int (32 bits). Try using %zu in both cases.

I'm not entirely certain though.

How to timeout a thread

Indeed rather use ExecutorService instead of Timer, here's an SSCCE:

package com.stackoverflow.q2275443;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Test {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new Task());

        try {
            System.out.println("Started..");
            System.out.println(future.get(3, TimeUnit.SECONDS));
            System.out.println("Finished!");
        } catch (TimeoutException e) {
            future.cancel(true);
            System.out.println("Terminated!");
        }

        executor.shutdownNow();
    }
}

class Task implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
        return "Ready!";
    }
}

Play a bit with the timeout argument in Future#get() method, e.g. increase it to 5 and you'll see that the thread finishes. You can intercept the timeout in the catch (TimeoutException e) block.

Update: to clarify a conceptual misunderstanding, the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep(). Inside your long running task, you should be checking if the thread is not interrupted as follows:

while (!Thread.interrupted()) {
    // Do your long running task here.
}

require_once :failed to open stream: no such file or directory

You will need to link to the file relative to the file that includes eventManager.php (Page A)

Change your code from
require_once('../includes/dbconn.inc');

To
require_once('../mysite/php/includes/dbconn.inc');

Converting RGB to grayscale/intensity

Heres some code in c to convert rgb to grayscale. The real weighting used for rgb to grayscale conversion is 0.3R+0.6G+0.11B. these weights arent absolutely critical so you can play with them. I have made them 0.25R+ 0.5G+0.25B. It produces a slightly darker image.

NOTE: The following code assumes xRGB 32bit pixel format

unsigned int *pntrBWImage=(unsigned int*)..data pointer..;  //assumes 4*width*height bytes with 32 bits i.e. 4 bytes per pixel
unsigned int fourBytes;
        unsigned char r,g,b;
        for (int index=0;index<width*height;index++)
        {
            fourBytes=pntrBWImage[index];//caches 4 bytes at a time
            r=(fourBytes>>16);
            g=(fourBytes>>8);
            b=fourBytes;

            I_Out[index] = (r >>2)+ (g>>1) + (b>>2); //This runs in 0.00065s on my pc and produces slightly darker results
            //I_Out[index]=((unsigned int)(r+g+b))/3;     //This runs in 0.0011s on my pc and produces a pure average
        }

css label width not taking effect

give the style

display:inline-block;

hope this will help'

PHP to search within txt file and echo the whole line

And a PHP example, multiple matching lines will be displayed:

<?php
$file = 'somefile.txt';
$searchfor = 'name';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}

Difference between BYTE and CHAR in column datatypes

One has exactly space for 11 bytes, the other for exactly 11 characters. Some charsets such as Unicode variants may use more than one byte per char, therefore the 11 byte field might have space for less than 11 chars depending on the encoding.

See also http://www.joelonsoftware.com/articles/Unicode.html

Excel Define a range based on a cell value

Old post but this is exactly what I needed, simple question, how to change it to count column rather than Row. Thankyou in advance. Novice to Excel.

=SUM(A1:INDIRECT(CONCATENATE("A",C5)))

I.e My data is A1 B1 C1 D1 etc rather then A1 A2 A3 A4.

Remove final character from string

What you are trying to do is an extension of string slicing in Python:

Say all strings are of length 10, last char to be removed:

>>> st[:9]
'abcdefghi'

To remove last N characters:

>>> N = 3
>>> st[:-N]
'abcdefg'

Restoring MySQL database from physical files

With MySql 5.1 (Win7). To recreate DBs (InnoDbs) I've replaced all contents of following dirs (my.ini params):

datadir="C:/ProgramData/MySQL/MySQL Server 5.1/Data/"
innodb_data_home_dir="C:/MySQL Datafiles/"

After that I started MySql Service and all works fine.

LINQ to SQL - Left Outer Join with multiple join conditions

Can be written using composite join key. Also if there is need to select properties from both left and right sides the LINQ can be written as

var result = context.Periods
    .Where(p => p.companyid == 100)
    .GroupJoin(
        context.Facts,
        p => new {p.id, otherid = 17},
        f => new {id = f.periodid, f.otherid},
        (p, f) => new {p, f})
    .SelectMany(
        pf => pf.f.DefaultIfEmpty(),
        (pf, f) => new MyJoinEntity
        {
            Id = pf.p.id,
            Value = f.value,
            // and so on...
        });

https with WCF error: "Could not find base address that matches scheme https"

Make sure SSL is enabled for your server!

I got this error when trying to use a HTTPS configuration file on my local box which doesn't have that certificate. I was trying to do local testing - by converting some of the bindings from HTTPS to HTTP. I thought it would be easier to do this than try to install a self signed certificate for local testing.

Turned out I was getting this error becasue I didn't have SSL enabled on my local IIS even though I wasn't intending on actually using it.

There was something in the configuration for HTTPS. Creating a self signed cert in IIS7 allowed HTTP to then work :-)

How do I finish the merge after resolving my merge conflicts?

Whenever You merge two branches using command git merge brancha branchb , There are two possibilities:

  1. One branch (lets say brancha) can be reached by the other branch (lets say branchb) by following its commits history.In this case git simply fast-forward the head to point to the recent branch (in this case branchb).

    2.But if the two branches have diverged at some older point then git creates a new snapshot and add a new commit that points to it. So in case there is no conflict between the branches you are merging, git smoothly creates a new commit.

Run git log to see the commit after you have merged two non-conflicting branches.

Now coming back to the interesting case when there are merge conflicts between the merging branches. I quote this from the page https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

Git hasn’t automatically created a new merge commit. It has paused the process while you resolve the conflict. If you want to see which files are unmerged at any point after a merge conflict, you can run git status


So in case there are merge conflicts, you need to resolve the conflict then add the changes you have made to the staging area using git add filename and then commit the changes by using the command git commit which was paused by git because of the conflict.I hope this explains your query. Also do visit the link above for a detailed understanding. In case of any query please comment below , I'll be happy to help.

Multiple aggregations of the same column using pandas GroupBy.agg()

Would something like this work:

In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]: 
              func2     func1
dummy                        
1     -4.263768e-16 -0.188565

Using JQuery to open a popup window and print

Are you sure you can't alter the HTML in the popup window?

If you can, add a <script> tag at the end of the popup's HTML, and call window.print() inside it. Then it won't be called until the HTML has loaded.

Setting the correct encoding when piping stdout in Python

An arguable sanitized version of Craig McQueen's answer.

import sys, codecs
class EncodedOut:
    def __init__(self, enc):
        self.enc = enc
        self.stdout = sys.stdout
    def __enter__(self):
        if sys.stdout.encoding is None:
            w = codecs.getwriter(self.enc)
            sys.stdout = w(sys.stdout)
    def __exit__(self, exc_ty, exc_val, tb):
        sys.stdout = self.stdout

Usage:

with EncodedOut('utf-8'):
    print u'ÅÄÖåäö'

Laravel 5 Class 'form' not found

Use Form, not form. The capitalization counts.

What is the best practice for creating a favicon on a web site?

I used https://iconifier.net I uploaded my image, downloaded images zip file, added images to my server, followed the directions on the site including adding the links to my index.html and it worked. My favicon now shows on my iPhone in Safari when 'Add to home screen'

Is Spring annotation @Controller same as @Service?

No, they are pretty different from each other.

Both are different specializations of @Component annotation (in practice, they're two different implementations of the same interface) so both can be discovered by the classpath scanning (if you declare it in your XML configuration)

@Service annotation is used in your service layer and annotates classes that perform service tasks, often you don't use it but in many case you use this annotation to represent a best practice. For example, you could directly call a DAO class to persist an object to your database but this is horrible. It is pretty good to call a service class that calls a DAO. This is a good thing to perform the separation of concerns pattern.

@Controller annotation is an annotation used in Spring MVC framework (the component of Spring Framework used to implement Web Application). The @Controller annotation indicates that a particular class serves the role of a controller. The @Controller annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations.

So looking at the Spring MVC architecture you have a DispatcherServlet class (that you declare in your XML configuration) that represent a front controller that dispatch all the HTTP Request towards the appropriate controller classes (annotated by @Controller). This class perform the business logic (and can call the services) by its method. These classes (or its methods) are typically annotated also with @RequestMapping annotation that specify what HTTP Request is handled by the controller and by its method.

For example:

@Controller
@RequestMapping("/appointments")
public class AppointmentsController {

    private final AppointmentBook appointmentBook;

    @Autowired
    public AppointmentsController(AppointmentBook appointmentBook) {
        this.appointmentBook = appointmentBook;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Appointment> get() {
        return appointmentBook.getAppointmentsForToday();
    }

This class is a controller.

This class handles all the HTTP Request toward "/appointments" "folder" and in particular the get method is the method called to handle all the GET HTTP Request toward the folder "/appointments".

I hope that now it is more clear for you.

How to set the DefaultRoute to another Route in React Router

You can use Redirect instead of DefaultRoute

<Redirect from="/" to="searchDashboard" />

Update 2019-08-09 to avoid problem with refresh use this instead, thanks to Ogglas

<Redirect exact from="/" to="searchDashboard" />

Is it possible to animate scrollTop with jQuery?

You can use the jQuery animation for scroll page with a specific duration:

$("html, body").animate({scrollTop: "1024px"}, 5000);

where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.

Search for all files in project containing the text 'querystring' in Eclipse

Just noticed that quick search has been included into eclipse 4.13 as a built-in function by typing Ctrl+Alt+Shift+L (or Cmd+Alt+Shift+L on Mac)

https://www.eclipse.org/eclipse/news/4.13/platform.php#quick-text-search

Convert String to SecureString

no fancy linq, not adding all the chars by hand, just plain and simple:

var str = "foo";
var sc = new SecureString();
foreach(char c in str) sc.appendChar(c);

How to update and order by using ms sql

WITH    q AS
        (
        SELECT  TOP 10 *
        FROM    messages
        WHERE   status = 0
        ORDER BY
                priority DESC
        )
UPDATE  q
SET     status = 10

Non-alphanumeric list order from os.listdir()

You can use the builtin sorted function to sort the strings however you want. Based on what you describe,

sorted(os.listdir(whatever_directory))

Alternatively, you can use the .sort method of a list:

lst = os.listdir(whatever_directory)
lst.sort()

I think should do the trick.

Note that the order that os.listdir gets the filenames is probably completely dependent on your filesystem.

How to merge lists into a list of tuples?

You can use map lambda

a = [2,3,4]
b = [5,6,7]
c = map(lambda x,y:(x,y),a,b)

This will also work if there lengths of original lists do not match

Bitwise operation and usage

One typical usage:

| is used to set a certain bit to 1

& is used to test or clear a certain bit

  • Set a bit (where n is the bit number, and 0 is the least significant bit):

    unsigned char a |= (1 << n);

  • Clear a bit:

    unsigned char b &= ~(1 << n);

  • Toggle a bit:

    unsigned char c ^= (1 << n);

  • Test a bit:

    unsigned char e = d & (1 << n);

Take the case of your list for example:

x | 2 is used to set bit 1 of x to 1

x & 1 is used to test if bit 0 of x is 1 or 0

Is there a php echo/print equivalent in javascript

this is an another way:

<html>
<head>
    <title>Echo</title>
    <style type="text/css">
    #result{
        border: 1px solid #000000;
        min-height: 250px;
        max-height: 100%;
        padding: 5px;
        font-family: sans-serif;
        font-size: 12px;
    }
    </style>
    <script type="text/javascript" lang="ja">
    function start(){
        function echo(text){
            lastResultAreaText = document.getElementById('result').innerHTML;
            resultArea = document.getElementById('result');
            if(lastResultAreaText==""){
                resultArea.innerHTML=text;
            }
            else{
                resultArea.innerHTML=lastResultAreaText+"</br>"+text;
            }
        }

        echo("Hello World!");
        }
    </script>
</head>
<body onload="start()">
<pre id="result"></pre> 
</body>

How do I count the number of rows and columns in a file using bash?

awk 'BEGIN{FS=","}END{print "COLUMN NO: "NF " ROWS NO: "NR}' file

You can use any delimiter as field separator and can find numbers of ROWS and columns

jQuery Scroll to Div

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Check this link: http://css-tricks.com/snippets/jquery/smooth-scrolling/ for a demo, I've used it before and it works quite nicely.

How to write both h1 and h2 in the same line?

In many cases,

display:inline;

is enough.

But in some cases, you have to add following:

clear:none;

Implementing Singleton with an Enum (in Java)

In this Java best practices book by Joshua Bloch, you can find explained why you should enforce the Singleton property with a private constructor or an Enum type. The chapter is quite long, so keeping it summarized:

Making a class a Singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type. Recommended approach is implement Singletons by simply make an enum type with one element:

// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.

While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

openssl s_client using a proxy

Even with openssl v1.1.0 I had some problems passing our proxy, e.g. s_client: HTTP CONNECT failed: 400 Bad Request That forced me to write a minimal Java-class to show the SSL-Handshake

    public static void main(String[] args) throws IOException, URISyntaxException {
    HttpHost proxy = new HttpHost("proxy.my.company", 8080);
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
    CloseableHttpClient httpclient = HttpClients.custom()
            .setRoutePlanner(routePlanner)
            .build();
    URI uri = new URIBuilder()
            .setScheme("https")
            .setHost("www.myhost.com")
            .build();
    HttpGet httpget = new HttpGet(uri);
    httpclient.execute(httpget);
}

With following dependency:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
        <type>jar</type>
    </dependency>

you can run it with Java SSL Logging turned on

This should produce nice output like

trustStore provider is :
init truststore
adding as trusted cert:
  Subject: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
  Issuer:  CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
  Algorithm: RSA; Serial number: 0xc3517
  Valid from Mon Jun 21 06:00:00 CEST 1999 until Mon Jun 22 06:00:00 CEST 2020

adding as trusted cert:
  Subject: CN=SecureTrust CA, O=SecureTrust Corporation, C=US
  Issuer:  CN=SecureTrust CA, O=SecureTrust Corporation, C=US
(....)

Resizing an image in an HTML5 canvas

I've put up some algorithms to do image interpolation on html canvas pixel arrays that might be useful here:

https://web.archive.org/web/20170104190425/http://jsperf.com:80/pixel-interpolation/2

These can be copy/pasted and can be used inside of web workers to resize images (or any other operation that requires interpolation - I'm using them to defish images at the moment).

I haven't added the lanczos stuff above, so feel free to add that as a comparison if you'd like.

Quick unix command to display specific lines in the middle of a file?

# print line number 52
sed -n '52p' # method 1
sed '52!d' # method 2
sed '52q;d' # method 3,  efficient on large files 

method 3 efficient on large files

fastest way to display specific lines

How to install JQ on Mac by command-line?

You can install any application/packages with brew on mac. If you want to know the exact command just search your package on https://brewinstall.org and you will get the set of commands needed to install that package.

First open terminal and install brew

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null

Now Install jq

brew install jq

How to render html with AngularJS templates

Use-

<span ng-bind-html="myContent"></span>

You need to tell angular to not escape it.

Why does git say "Pull is not possible because you have unmerged files"?

If you dont want any of your local branch changes i think this is the best approach

git clean -df
git reset --hard
git checkout REMOTE_BRANCH_NAME
git pull origin REMOTE_BRANCH_NAME

ssh : Permission denied (publickey,gssapi-with-mic)

I had the same problem. In my case, macOS doesn't load my SSH keys, but I fix it with:

ssh-add <SSH private key>
ssh-add <SSH public key>

I couldn't connect to a Droplet on DigitalOcean, but the subsequent commands work for me.

You can go to the forum here.

How to stop docker under Linux

The output of ps aux looks like you did not start docker through systemd/systemctl.

It looks like you started it with:

sudo dockerd -H gridsim1103:2376

When you try to stop it with systemctl, nothing should happen as the resulting dockerd process is not controlled by systemd. So the behavior you see is expected.

The correct way to start docker is to use systemd/systemctl:

systemctl enable docker
systemctl start docker

After this, docker should start on system start.

EDIT: As you already have the docker process running, simply kill it by pressing CTRL+C on the terminal you started it. Or send a kill signal to the process.

RegExp matching string not starting with my

^(?!my)\w+$

should work.

It first ensures that it's not possible to match my at the start of the string, and then matches alphanumeric characters until the end of the string. Whitespace anywhere in the string will cause the regex to fail. Depending on your input you might want to either strip whitespace in the front and back of the string before passing it to the regex, or use add optional whitespace matchers to the regex like ^\s*(?!my)(\w+)\s*$. In this case, backreference 1 will contain the name of the variable.

And if you need to ensure that your variable name starts with a certain group of characters, say [A-Za-z_], use

^(?!my)[A-Za-z_]\w*$

Note the change from + to *.

Where is Maven's settings.xml located on Mac OS?

It doesn't exist at first. You have to create it in your home folder, /Users/usename/.m2/ (or ~/.m2)

For example :

alt text

Maven Installation OSX Error Unsupported major.minor version 51.0

I solved it putting a old version of maven (2.x), using brew:

brew uninstall maven
brew tap homebrew/versions 
brew install maven2

text-align: right; not working for <label>

Label is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div element is a block element so its width is by default 100%.

You will have to place the text-align: right; on the div element in your case, or applying display: block; to your label

Another option is to set a width for each label and then use text-align. The display: block method will not be necessary using this.

Check if table exists without using "select from"

None of the options except SELECT doesn't allow database name as used in SELECT, so I wrote this:

SELECT COUNT(*) AS cnt FROM information_schema.TABLES 
WHERE CONCAT(table_schema,".",table_name)="db_name.table_name";

Start thread with member function

Some users have already given their answer and explained it very well.

I would like to add few more things related to thread.

  1. How to work with functor and thread. Please refer to below example.

  2. The thread will make its own copy of the object while passing the object.

    #include<thread>
    #include<Windows.h>
    #include<iostream>
    
    using namespace std;
    
    class CB
    {
    
    public:
        CB()
        {
            cout << "this=" << this << endl;
        }
        void operator()();
    };
    
    void CB::operator()()
    {
        cout << "this=" << this << endl;
        for (int i = 0; i < 5; i++)
        {
            cout << "CB()=" << i << endl;
            Sleep(1000);
        }
    }
    
    void main()
    {
        CB obj;     // please note the address of obj.
    
        thread t(obj); // here obj will be passed by value 
                       //i.e. thread will make it own local copy of it.
                        // we can confirm it by matching the address of
                        //object printed in the constructor
                        // and address of the obj printed in the function
    
        t.join();
    }
    

Another way of achieving the same thing is like:

void main()
{
    thread t((CB()));

    t.join();
}

But if you want to pass the object by reference then use the below syntax:

void main()
{
    CB obj;
    //thread t(obj);
    thread t(std::ref(obj));
    t.join();
}

How to insert an item at the beginning of an array in PHP?

Use array_unshift($array, $item);

$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);

will give you

Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
)

How do I capture all of my compiler's output to a file?

Try make 2> file. Compiler warnings come out on the standard error stream, not the standard output stream. If my suggestion doesn't work, check your shell manual for how to divert standard error.

Get column index from column name in python pandas

To modify DSM's answer a bit, get_loc has some weird properties depending on the type of index in the current version of Pandas (1.1.5) so depending on your Index type you might get back an index, a mask, or a slice. This is somewhat frustrating for me because I don't want to modify the entire columns just to extract one variable's index. Much simpler is to avoid the function altogether:

list(df.columns).index('pear')

Very straightforward and probably fairly quick.

PostgreSQL: role is not permitted to log in

try to run

sudo su - postgres
psql
ALTER ROLE 'dbname'

Correct way to use Modernizr to detect IE?

Well, after doing more research on this topic I ended up using following solution for targeting IE 10+. As IE10&11 are the only browsers which support the -ms-high-contrast media query, that is a good option without any JS:

@media screen and (-ms-high-contrast: active), screen and (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
}

Works perfectly.

How to send a HTTP OPTIONS request from the command line?

The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)

OPTIONS /path

You can send an OPTIONS request with curl like this:

curl -i -X OPTIONS http://example.org/path

You may also use -v instead of -i to see more output.

OPTIONS *

To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:

curl -i --request-target "*" -X OPTIONS http://example.org

how to compare two elements in jquery

Every time you call the jQuery() function, a new object is created and returned. So even equality checks on the same selectors will fail.

<div id="a">test</div>

$('#a') == $('#a') // false

The resulting jQuery object contains an array of matching elements, which are basically native DOM objects like HTMLDivElement that always refer to the same object, so you should check those for equality using the array index as Darin suggested.

$('#a')[0] == $('#a')[0] // true

JSON order mixed up

JavaScript objects, and JSON, have no way to set the order for the keys. You might get it right in Java (I don't know how Java objects work, really) but if it's going to a web client or another consumer of the JSON, there is no guarantee as to the order of keys.

Group By Multiple Columns

Ok got this as:

var query = (from t in Transactions
             group t by new {t.MaterialID, t.ProductID}
             into grp
                    select new
                    {
                        grp.Key.MaterialID,
                        grp.Key.ProductID,
                        Quantity = grp.Sum(t => t.Quantity)
                    }).ToList();

AttributeError("'str' object has no attribute 'read'")

Ok, this is an old thread but. I had a same issue, my problem was I used json.load instead of json.loads

This way, json has no problem with loading any kind of dictionary.

Official documentation

json.load - Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.

json.loads - Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

Drop all tables command

I had the same problem with SQLite and Android. Here is my Solution:

List<String> tables = new ArrayList<String>();
Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
    String tableName = cursor.getString(1);
    if (!tableName.equals("android_metadata") &&
            !tableName.equals("sqlite_sequence"))
        tables.add(tableName);
    cursor.moveToNext();
}
cursor.close();

for(String tableName:tables) {
    db.execSQL("DROP TABLE IF EXISTS " + tableName);
}

setTimeout / clearTimeout problems

Practical example Using Jquery for a dropdown menu ! On mouse over on #IconLoggedinUxExternal shows div#ExternalMenuLogin and set time out to hide the div#ExternalMenuLogin

On mouse over on div#ExternalMenuLogin it cancels the timeout. On mouse out on div#ExternalMenuLogin it sets the timeout.

The point here is always to invoke clearTimeout before set the timeout, as so, avoiding double calls

var ExternalMenuLoginTO;
$('#IconLoggedinUxExternal').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
    $("#ExternalMenuLogin").show()
});

$('#IconLoggedinUxExternal').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )    
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,1000
    );
    $("#ExternalMenuLogin").show()
});

$('#ExternalMenuLogin').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
});
$('#ExternalMenuLogin').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,500
    );
});

JavaScript unit test tools for TDD

google-js-test:

JavaScript testing framework released by Google: https://github.com/google/gjstest

  • Extremely fast test startup and execution time, without having to run a browser.
  • Clean, readable output in the case of both passing and failing tests.
  • A browser-based test runner that can simply be refreshed whenever JS is changed.
  • Style and semantics that resemble Google Test for C++.
  • A built-in mocking framework that requires minimal boilerplate code (e.g. no $tearDown or $verifyAll) with style and semantics based on the Google C++ Mocking Framework.

There are currently no binaries for Windows

How do I create a SQL table under a different schema?

Try running CREATE TABLE [schemaname].[tableName]; GO;

This assumes the schemaname exists in your database. Please use CREATE SCHEMA [schemaname] if you need to create a schema as well.

EDIT: updated to note SQL Server 11.03 requiring this be the only statement in the batch.

If table exists drop table then create it, if it does not exist just create it

Well... Huh. For years nobody mentioned one subtle thing.

Despite DROP TABLE IF EXISTS `bla`; CREATE TABLE `bla` ( ... ); seems reasonable, it leads to a situation when old table is already gone and new one has not been yet created: some client may try to access subject table right at this moment.

The better way is to create brand new table and swap it with an old one (table contents are lost):

CREATE TABLE `bla__new` (id int); /* if not ok: terminate, report error */
RENAME TABLE `bla__new` to `bla`; /* if ok: terminate, report success */
RENAME TABLE `bla` to `bla__old`, `bla__new` to `bla`;
DROP TABLE IF EXISTS `bla__old`;
  • You should check the result of CREATE ... and do not continue in case of error, because failure means that other thread didn't finish the same script: either because it crashed in the middle or just didn't finish yet -- it's a good idea to inspect things by yourself.
  • Then, you should check the result of first RENAME ... and do not continue in case of success: whole operation is successfully completed; even more, running next RENAME ... can (and will) be unsafe if another thread has already started same sequence (it's better to cover this case than not to cover, see locking note below).
  • Second RENAME ... atomically replaces table definition, refer to MySQL manual for details.
  • At last, DROP ... just cleans up the old table, obviously.

Wrapping all statements with something like SELECT GET_LOCK('__upgrade', -1); ... DO RELEASE_LOCK('__upgrade'); allows to just invoke all statements sequentially without error checking, but I don't think it's a good idea: complexity increases and locking functions in MySQL aren't safe for statement-based replication.

If the table data should survive table definition upgrade... For general case it's far more complex story about comparing table definitions to find out differences and produce proper ALTER ... statement, which is not always possible automatically, e.g. when columns are renamed.

Side note 1: You can deal with views using the same approach, in this case CREATE/DROP TABLE merely transforms to CREATE/DROP VIEW while RENAME TABLE remains unchanged. In fact you can even turn table into view and vice versa.

CREATE VIEW `foo__new` as ...; /* if not ok: terminate, report error */
RENAME TABLE `foo__new` to `foo`; /* if ok: terminate, report success */
RENAME TABLE `foo` to `foo__old`, `foo__new` to `foo`;
DROP VIEW IF EXISTS `foo__old`;

Side note 2: MariaDB users should be happy with CREATE OR REPLACE TABLE/VIEW, which already cares about subject problem and it's fine points.

Selenium C# WebDriver: Wait until element is present

I confused an anonymous function with a predicate. Here's a little helper method:

   WebDriverWait wait;
    private void waitForById(string id)
    {
        if (wait == null)
            wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));

        //wait.Until(driver);
        wait.Until(d => d.FindElement(By.Id(id)));
    }

How do I open port 22 in OS X 10.6.7

I'm using OSX 10.11.6 and this article works for me.

enter image description here

Select random lines from a file

# Function to sample N lines randomly from a file
# Parameter $1: Name of the original file
# Parameter $2: N lines to be sampled 
rand_line_sampler() {
    N_t=$(awk '{print $1}' $1 | wc -l) # Number of total lines

    N_t_m_d=$(( $N_t - $2 - 1 )) # Number oftotal lines minus desired number of lines

    N_d_m_1=$(( $2 - 1)) # Number of desired lines minus 1

    # vector to have the 0 (fail) with size of N_t_m_d 
    echo '0' > vector_0.temp
    for i in $(seq 1 1 $N_t_m_d); do
            echo "0" >> vector_0.temp
    done

    # vector to have the 1 (success) with size of desired number of lines
    echo '1' > vector_1.temp
    for i in $(seq 1 1 $N_d_m_1); do
            echo "1" >> vector_1.temp
    done

    cat vector_1.temp vector_0.temp | shuf > rand_vector.temp

    paste -d" " rand_vector.temp $1 |
    awk '$1 != 0 {$1=""; print}' |
    sed 's/^ *//' > sampled_file.txt # file with the sampled lines

    rm vector_0.temp vector_1.temp rand_vector.temp
}

rand_line_sampler "parameter_1" "parameter_2"

go to link on button click - jquery

you can get the current url with window.location.href but I think you will need the jQuery query plugin to manipulate the query string: http://plugins.jquery.com/project/query-object

Java Program to test if a character is uppercase/lowercase/number/vowel

If it weren't a homework, you could use existing methods such as Character.isDigit(char), Character.isUpperCase(char) and Character.isLowerCase(char) which are a bit "smarter", because they don't operate only in ASCII, but also in various charsets.

static final char[] VOWELS = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };

static boolean isVowel(char ch) {
    for (char vowel : VOWELS) {
        if (vowel == ch) {
            return true;
        }
    }
    return false;
}

static boolean isDigit(char ch) {
    return ch >= '0' && ch <= '9';
}

static boolean isLowerCase(char ch) {
    return ch >= 'a' && ch <= 'z';
}

static boolean isUpperCase(char ch) {
    return ch >= 'A' && ch <= 'Z';
}

What is the difference between JOIN and UNION?

JOIN:

A join is used for displaying columns with the same or different names from different tables. The output displayed will have all the columns shown individually. That is, the columns will be aligned next to each other.

UNION:

The UNION set operator is used for combining data from two tables which have columns with the same datatype. When a UNION is performed the data from both tables will be collected in a single column having the same datatype.

For example:

See the two tables shown below:

Table t1
Articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2

Table t2
manufacturer_id manufacturer
1 ABC Gmbh
2 DEF Co KG

Now for performing a JOIN type the query is shown below.

SELECT articleno, article, manufacturer
FROM t1 JOIN t2 ON (t1.manufacturer_id =
t2.manufacturer_id);

articelno article manufacturer
1 hammer ABC GmbH
2 screwdriver DEF Co KG

That is a join.

UNION means that you have to tables or resultset with the same amount and type of columns and you add this to tables/resultsets together. Look at this example:

Table year2006
Articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2

Table year2007
Articleno article price manufacturer_id
1 hammer 6 $ 3
2 screwdriver 7 $ 4

SELECT articleno, article, price, manufactruer_id
FROM year2006
UNION
SELECT articleno, article, price, manufacturer_id
FROM year2007

articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2
1 hammer 6 $ 3
2 screwdriver 7 $ 4

How to read from stdin with fgets()?

You have a wrong idea of what fgets returns. Take a look at this: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

It returns null when it finds an EOF character. Try running the program above and pressing CTRL+D (or whatever combination is your EOF character), and the loop will exit succesfully.

How do you want to detect the end of the input? Newline? Dot (you said sentence xD)?

Get list of certificates from the certificate store in C#

Try this:

//using System.Security.Cryptography.X509Certificates;
public static X509Certificate2 selectCert(StoreName store, StoreLocation location, string windowTitle, string windowMsg)
{

    X509Certificate2 certSelected = null;
    X509Store x509Store = new X509Store(store, location);
    x509Store.Open(OpenFlags.ReadOnly);

    X509Certificate2Collection col = x509Store.Certificates;
    X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, windowTitle, windowMsg, X509SelectionFlag.SingleSelection);

    if (sel.Count > 0)
    {
        X509Certificate2Enumerator en = sel.GetEnumerator();
        en.MoveNext();
        certSelected = en.Current;
    }

    x509Store.Close();

    return certSelected;
}

How does the @property decorator work in Python?

This following:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x

    def _x_set(self, value):
        self._x = value

    def _x_del(self):
        del self._x

    x = property(_x_get, _x_set, _x_del, 
                    "I'm the 'x' property.")

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x

    def _x_set(self, value):
        self._x = value

    def _x_del(self):
        del self._x

    x = property(_x_get, doc="I'm the 'x' property.")
    x = x.setter(_x_set)
    x = x.deleter(_x_del)

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x
    x = property(_x_get, doc="I'm the 'x' property.")

    def _x_set(self, value):
        self._x = value
    x = x.setter(_x_set)

    def _x_del(self):
        del self._x
    x = x.deleter(_x_del)

Which is the same as :

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

Use custom build output folder when using create-react-app

Félix's answer is correct and upvoted, backed-up by Dan Abramov himself.

But for those who would like to change the structure of the output itself (within the build folder), one can run post-build commands with the help of postbuild, which automatically runs after the build script defined in the package.json file.

The example below changes it from static/ to user/static/, moving files and updating file references on relevant files (full gist here):

package.json

{
  "name": "your-project",
  "version": "0.0.1",
  [...]
  "scripts": {
    "build": "react-scripts build",
    "postbuild": "./postbuild.sh",
    [...]
  },
}

postbuild.sh

#!/bin/bash

# The purpose of this script is to do things with files generated by
# 'create-react-app' after 'build' is run.
# 1. Move files to a new directory called 'user'
#    The resulting structure is 'build/user/static/<etc>'
# 2. Update reference on generated files from
#    static/<etc>
#     to
#    user/static/<etc>
#
# More details on: https://github.com/facebook/create-react-app/issues/3824

# Browse into './build/' directory
cd build
# Create './user/' directory
echo '1/4 Create "user" directory'
mkdir user
# Find all files, excluding (through 'grep'):
# - '.',
# - the newly created directory './user/'
# - all content for the directory'./static/'
# Move all matches to the directory './user/'
echo '2/4 Move relevant files'
find . | grep -Ev '^.$|^.\/user$|^.\/static\/.+' | xargs -I{} mv -v {} user
# Browse into './user/' directory
cd user
# Find all files within the folder (not subfolders)
# Replace string 'static/' with 'user/static/' on all files that match the 'find'
# ('sed' requires one to create backup files on OSX, so we do that)
echo '3/4 Replace file references'
find . -type f -maxdepth 1 | LC_ALL=C xargs -I{} sed -i.backup -e 's,static/,user/static/,g' {}
# Delete '*.backup' files created in the last process
echo '4/4 Clean up'
find . -name '*.backup' -type f -delete
# Done

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

For Java 8: You can use inbuilt java.time.format.DateTimeFormatter to reduce any chance of typos, like

DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;

ISO_ZONED_DATE_TIME represents 2011-12-03T10:15:30+01:00[Europe/Paris] is one of the bundled standard DateTime formats provided by Oracle link

PHP: check if any posted vars are empty - form: all fields required

Personally I extract the POST array and then have if(!$login || !$password) then echo fill out the form :)

How do I call paint event?

The Invalidate() Method will cause a repaint.

MSDN Link

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

You can use ExtendedXmlSerializer. If you have a class:

public class TestClass
{
    public Dictionary<int, string> Dictionary { get; set; }
}

and create instance of this class:

var obj = new TestClass
{
    Dictionary = new Dictionary<int, string>
    {
        {1, "First"},
        {2, "Second"},
        {3, "Other"},
    }
};

You can serialize this object using ExtendedXmlSerializer:

var serializer = new ConfigurationContainer()
    .UseOptimizedNamespaces() //If you want to have all namespaces in root element
    .Create();

var xml = serializer.Serialize(
    new XmlWriterSettings { Indent = true }, //If you want to formated xml
    obj);

Output xml will look like:

<?xml version="1.0" encoding="utf-8"?>
<TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples">
  <Dictionary>
    <sys:Item>
      <Key>1</Key>
      <Value>First</Value>
    </sys:Item>
    <sys:Item>
      <Key>2</Key>
      <Value>Second</Value>
    </sys:Item>
    <sys:Item>
      <Key>3</Key>
      <Value>Other</Value>
    </sys:Item>
  </Dictionary>
</TestClass>

You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer

'node' is not recognized as an internal or external command

Node is missing from the SYSTEM PATH, try this in your command line

SET PATH=C:\Program Files\Nodejs;%PATH%

and then try running node

To set this system wide you need to set in the system settings - cf - http://banagale.com/changing-your-system-path-in-windows-vista.htm

To be very clean, create a new system variable NODEJS

NODEJS="C:\Program Files\Nodejs"

Then edit the PATH in system variables and add %NODEJS%

PATH=%NODEJS%;...

JFrame in full screen Java

One way is to use the Extended State. This asks the underlying OS to maximize the JFrame.

setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);

Other approach would be to manually maximize the screen for you requirement.

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(100, 100, (int) dim.getWidth(), (int) dim.getHeight());
setLocationRelativeTo(null);

But this has pitfalls in Ubuntu OS. The work around I found was this.

if (SystemHelper.isUnix()) {
    getContentPane().setPreferredSize(
    Toolkit.getDefaultToolkit().getScreenSize());
    pack();
    setResizable(false);
    show();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Point p = new Point(0, 0);
            SwingUtilities.convertPointToScreen(p, getContentPane());
            Point l = getLocation();
            l.x -= p.x;
            l.y -= p.y;
            setLocation(p);
        }
    });
}

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(100, 100, (int) dim.getWidth(), (int) dim.getHeight());
setLocationRelativeTo(null);

In Fedora the above problem is not present. But there are complications involved with Gnome or KDE. So better be careful. Hope this helps.

How do I pass multiple parameters into a function in PowerShell?

The correct answer has already been provided, but this issue seems prevalent enough to warrant some additional details for those wanting to understand the subtleties.

I would have added this just as a comment, but I wanted to include an illustration--I tore this off my quick reference chart on PowerShell functions. This assumes function f's signature is f($a, $b, $c):

Syntax pitfalls of a function call

Thus, one can call a function with space-separated positional parameters or order-independent named parameters. The other pitfalls reveal that you need to be cognizant of commas, parentheses, and white space.

For further reading, see my article Down the Rabbit Hole: A Study in PowerShell Pipelines, Functions, and Parameters. The article contains a link to the quick reference/wall chart as well.

The multi-part identifier could not be bound

What worked for me was to change my WHERE clause into a SELECT subquery

FROM:

    DELETE FROM CommentTag WHERE [dbo].CommentTag.NoteId = [dbo].FetchedTagTransferData.IssueId

TO:

    DELETE FROM CommentTag WHERE [dbo].CommentTag.NoteId = (SELECT NoteId FROM FetchedTagTransferData)

De-obfuscate Javascript code to make it readable again

Try this: http://jsbeautifier.org/

I tested with your code and worked as good as possible. =D

HSL to RGB color conversion

I needed a really light weight one, Its not 100%, but it gets close enough for some usecases.

float3 Hue(float h, float s, float l)
{
    float r = max(cos(h * 2 * UNITY_PI) * 0.5 + 0.5, 0);
    float g = max(cos((h + 0.666666) * 2 * UNITY_PI) * 0.5 + 0.5, 0);
    float b = max(cos((h + 0.333333) * 2 * UNITY_PI) * 0.5 + 0.5, 0);
    float gray = 0.2989 * r + 0.5870 * g + 0.1140 * b;
    return lerp(gray, float3(r, g, b), s) * smoothstep(0, 0.5, l) + 1 * smoothstep(0.5, 1, l);
}

SVN undo delete before commit

1) do

svn revert . --recursive

2) parse output for errors like

"Failed to revert 'dir1/dir2' -- try updating instead."

3) call svn up for each of error directories:

svn up dir1/dir2

How to load external webpage in WebView

try this

webviewlayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/help_webview"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:scrollbars="none"
/>

In your Activity:

WebView webView;
setContentView(R.layout.webviewlayout);
webView = (WebView)findViewById(R.id.help_webview);
webView.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com");

Update

Add webView.setWebViewClient(new WebViewController()); to your Activity.

WebViewController class:

public class WebViewController extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

How to extract request http headers from a request using NodeJS connect

If you use Express 4.x, you can use the req.get(headerName) method as described in Express 4.x API Reference

IsNullOrEmpty with Object

I found that DataGridViewTextBox values and some JSON objects don't equal Null but instead are "{}" values. Comparing them to Null doesn't work but using these do the trick:

if (cell.Value is System.DBNull)

if (cell.Value == System.DBNull.Value)

A good excerpt I found concerning the difference between Null and DBNull:

Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.

You can learn more about the DBNull class here.

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

SQL how to increase or decrease one for a int column in one command

UPDATE Orders Order
SET Order.Quantity =  Order.Quantity - 1
WHERE SomeCondition(Order)

As far as I know there is no build-in support for INSERT-OR-UPDATE in SQL. I suggest to create a stored procedure or use a conditional query to achiev this. Here you can find a collection of solutions for different databases.

PHP PDO: charset, set names?

$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);

How to get the caller's method name in the called method?

I found a way if you're going across classes and want the class the method belongs to AND the method. It takes a bit of extraction work but it makes its point. This works in Python 2.7.13.

import inspect, os

class ClassOne:
    def method1(self):
        classtwoObj.method2()

class ClassTwo:
    def method2(self):
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 4)
        print '\nI was called from', calframe[1][3], \
        'in', calframe[1][4][0][6: -2]

# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()

# start the program
os.system('cls')
classoneObj.method1()

Android, How to create option Menu

Replace return super.onCreateOptionsMenu(menu); with return true; in your onCreateOptionsMenu method This will help

And you should also have the onCreate method in your activity

Getting All Variables In Scope

Although everyone answer "No" and I know that "No" is the right answer but if you really need to get local variables of a function there is a restricted way.

Consider this function:

var f = function() {
    var x = 0;
    console.log(x);
};

You can convert your function to a string:

var s = f + '';

You will get source of function as a string

'function () {\nvar x = 0;\nconsole.log(x);\n}'

Now you can use a parser like esprima to parse function code and find local variable declarations.

var s = 'function () {\nvar x = 0;\nconsole.log(x);\n}';
s = s.slice(12); // to remove "function () "
var esprima = require('esprima');
var result = esprima.parse(s);

and find objects with:

obj.type == "VariableDeclaration"

in the result (I have removed console.log(x) below):

{
    "type": "Program",
    "body": [
        {
            "type": "VariableDeclaration",
            "declarations": [
                {
                    "type": "VariableDeclarator",
                    "id": {
                        "type": "Identifier",
                        "name": "x"
                    },
                    "init": {
                        "type": "Literal",
                        "value": 0,
                        "raw": "0"
                    }
                }
            ],
            "kind": "var"
        }
    ]
}

I have tested this in Chrome, Firefox and Node.

But the problem with this method is that you just have the variables defined in the function itself. For example for this one:

var g = function() {
    var y = 0;
    var f = function() {
        var x = 0;
        console.log(x);
    };
}

you just have access to the x and not y. But still you can use chains of caller (arguments.callee.caller.caller.caller) in a loop to find local variables of caller functions. If you have all local variable names so you have scope variables. With the variable names you have access to values with a simple eval.

VB.NET - Remove a characters from a String

The String class has a Replace method that will do that.

Dim clean as String
clean = myString.Replace(",", "")

What are OLTP and OLAP. What is the difference between them?

Very short answer :

Different databases have different uses. I'm not a database expert. Rule of thumb:

  • if you are doing analytics (ex. aggregating historical data) use OLAP
  • if you are doing transactions (ex. adding/removing orders on an e-commerce cart) use OLTP

Short answer:

Let's consider two example scenarios:

Scenario 1:

You are building an online store/website, and you want to be able to:

  • store user data, passwords, previous transactions...
  • store actual products, their associated prices

You want to be able to find data for a particular user, change its name... basically perform INSERT, UPDATE, DELETE operations on user data. Same with products, etc.

You want to be able to make transactions, possibly involving a user buying a product (that's a relation). Then OLTP is probably a good fit.

Scenario 2:

You have an online store/website, and you want to compute things like

  • the "total money spent by all users"
  • "what is the most sold product"

This falls into the analytics/business intelligence domain, and therefore OLAP is probably more suited.

If you think in terms of "It would be nice to know how/what/how much"..., and that involves all "objects" of one or more kind (ex. all the users and most of the products to know the total spent) then OLAP is probably better suited.

Longer answer:

Of course things are not so simple. That's why we have to use short tags like OLTPand OLAP in the first place. Each database should be evaluated independently in the end.

So what could be the fundamental difference between OLAP and OLTP?

Well, databases have to store data somewhere. It shouldn't be surprising that the way the data is stored heavily reflects the possible use of said data. Data is usually stored on a hard drive. Let's think of a hard drive as a really wide sheet of paper, where we can read and write things. There are two ways to organize our reads and writes so that they can be efficient and fast.

One way is to make a book that is a bit like a phone book. On each page of the book, we store the information regarding a particular user. Now that's nice, we can find the information for a particular user very easily! Just jump to the page! We can even have a special page at the beginning to tell us on which page the users are if we want. But on the other hand, if we want to find, say, how much money all of our users spent then we would have to read every page, i.e. the whole book! That would be a row-based book/database (OLTP). The optional page at the beginning would be the index.

Another way to use our big sheet of paper is to make an accounting book. I'm no accountant, but let's imagine that we would have a page for "expenditures", "purchases"... That's nice because now we can query things like "give me the total revenue" very quickly (just read the "purchases" page). We can also ask for more involved things like "give me the top ten products sold" and still have acceptable performance. But now consider how painful it would be to find the expenditures for a particular user. You would have to go through the whole list of everyone's expenditures and filter the ones of that particular user, then sum them. Which basically amounts to "read the whole book" again. That would be a column-based database (OLAP).

It follows that:

  • OLTP databases are meant to be used to do many small transactions, and usually serve as a "single source of truth".

  • OLAP databases on the other hand are more suited for analytics, data mining, fewer queries but they are usually bigger (they operate on more data).

It's a bit more involved than that of course and that's a 20 000 feet overview of how databases differ, but it allows me not to get lost in a sea of acronyms.

Speaking of acronyms:

  • OLTP = Online transaction processing
  • OLAP = Online analytical processing

To read a bit further, here are some relevant links which heavily inspired my answer: