Programs & Examples On #Applicationdomain

C# Collection was modified; enumeration operation may not execute

As others have pointed out, you are modifying a collection that you are iterating over and that's what's causing the error. The offending code is below:

foreach (KeyValuePair<int, int> kvp in rankings)
{
    .....

    if((double)(similarModules/modules.Count)>0.6)
    {
        rankings[kvp.Key] = rankings[kvp.Key] + 4;  // <--- This line is the problem
    }
    .....

What may not be obvious from the code above is where the Enumerator comes from. In a blog post from a few years back about Eric Lippert provides an example of what a foreach loop gets expanded to by the compiler. The generated code will look something like:

{
    IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator(); // <-- This
                                                       // is where the Enumerator
                                                       // comes from.
    try
    { 
        int m; // OUTSIDE THE ACTUAL LOOP in C# 4 and before, inside the loop in 5
        while(e.MoveNext())
        {
            // loop code goes here
        }
    }
    finally
    { 
      if (e != null) ((IDisposable)e).Dispose();
    }
}

If you look up the MSDN documentation for IEnumerable (which is what GetEnumerator() returns) you will see:

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Which brings us back to what the error message states and the other answers re-state, you're modifying the underlying collection.

How to Add Incremental Numbers to a New Column Using Pandas

df = df.assign(New_ID=[880 + i for i in xrange(len(df))])[['New_ID'] + df.columns.tolist()]

>>> df
   New_ID  ID   Fruit
0     880  F1   Apple
1     881  F2  Orange
2     882  F3  Banana

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

Optional query string parameters in ASP.NET Web API

if you want to pass multiple parameters then you can create model instead of passing multiple parameters.

in case you dont want to pass any parameter then you can skip as well in it, and your code will look neat and clean.

Alter SQL table - allow NULL column value

The following MySQL statement should modify your column to accept NULLs.

ALTER TABLE `MyTable`
ALTER COLUMN `Col3` varchar(20) DEFAULT NULL

Refresh Page C# ASP.NET

Call Page_load function:

Page_Load(sender, e);

How to convert Varchar to Double in sql?

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName, 
       CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info 
ORDER BY _totalBal DESC

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

Had the same issue then I used the connection string without ./ (like DESKTOP-E53DUML instead of this ./DESKTOP-E53DUML)

How can I generate random alphanumeric strings?

For both crypto & noncrypto, efficiently:

private static readonly Random _random = new Random();

public static string GenerateRandomString(int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") =>
    RandomString(_random.NextBytes, length, charset.ToCharArray());

public static string GenerateRandomCryptoString(int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
{
    using (var crypto = new System.Security.Cryptography.RNGCryptoServiceProvider())
        return RandomString(crypto.GetBytes, length, charset.ToCharArray());
}

private static string RandomString(Action<byte[]> fillRandomBuffer, int length, char[] charset)
{
    if (length < 0)
        throw new ArgumentOutOfRangeException(nameof(length), $"{nameof(length)} must be greater or equal to 0");
    if (charset is null)
        throw new ArgumentNullException(nameof(charset));
    if (charset.Length == 0)
        throw new ArgumentException($"{nameof(charset)} must contain at least 1 character", nameof(charset));

    var maxIdx = charset.Length;
    var chars = new char[length];
    var randomBuffer = new byte[length * 4];
    fillRandomBuffer(randomBuffer);

    for (var i = 0; i < length; i++)
        chars[i] = charset[BitConverter.ToUInt32(randomBuffer, i * 4) % maxIdx];

    return new string(chars);
}

Using generators & LINQ. Not the fastest option (especially because it doesn't generate all the bytes in one go) but pretty neat & extensible:

private static readonly Random _random = new Random();

public static string GenerateRandomString(int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") =>
    new string(_random.GetGenerator().RandomChars(charset.ToCharArray()).Take(length).ToArray());

public static string GenerateRandomCryptoString(int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
{
    using (var crypto = new System.Security.Cryptography.RNGCryptoServiceProvider())
        return new string(crypto.GetGenerator().RandomChars(charset.ToCharArray()).Take(length).ToArray());
}

public static IEnumerable<char> RandomChars(this Func<uint, IEnumerable<uint>> randomGenerator, char[] charset)
{
    if (charset is null)
        throw new ArgumentNullException(nameof(charset));
    if (charset.Length == 0)
        throw new ArgumentException($"{nameof(charset)} must contain at least 1 character", nameof(charset));

    return randomGenerator((uint)charset.Length).Select(r => charset[r]);
}

public static Func<uint, IEnumerable<uint>> GetGenerator(this Random random)
{
    if (random is null)
        throw new ArgumentNullException(nameof(random));

    return GeneratorFunc_Inner;

    IEnumerable<uint> GeneratorFunc_Inner(uint maxValue)
    {
        if (maxValue > int.MaxValue)
            throw new ArgumentOutOfRangeException(nameof(maxValue));

        return Generator_Inner();

        IEnumerable<uint> Generator_Inner()
        {
            var randomBytes = new byte[4];
            while (true)
            {
                random.NextBytes(randomBytes);
                yield return BitConverter.ToUInt32(randomBytes, 0) % maxValue;
            }
        }
    }
}

public static Func<uint, IEnumerable<uint>> GetGenerator(this System.Security.Cryptography.RNGCryptoServiceProvider random)
{
    if (random is null)
        throw new ArgumentNullException(nameof(random));

    return Generator_Inner;

    IEnumerable<uint> Generator_Inner(uint maxValue)
    {
        var randomBytes = new byte[4];
        while (true)
        {
            random.GetBytes(randomBytes);
            yield return BitConverter.ToUInt32(randomBytes, 0) % maxValue;
        }
    }
}

a simpler version using LINQ for only non-crypto strings:

private static readonly Random _random = new Random();

public static string RandomString(int length, string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") =>
    new string(_random.GenerateChars(charset).Take(length).ToArray()); 

public static IEnumerable<char> GenerateChars(this Random random, string charset)
{
    if (charset is null) throw new ArgumentNullException(nameof(charset));
    if (charset.Length == 0) throw new ArgumentException($"{nameof(charset)} must contain at least 1 character", nameof(charset));

    return random.Generator(charset.Length).Select(r => charset[r]);
}

public static IEnumerable<int> Generator(this Random random, int maxValue)
{
    if (random is null) throw new ArgumentNullException(nameof(random));

    return Generator_Inner();

    IEnumerable<int> Generator_Inner() { while (true) yield return random.Next(maxValue); }
}

org.hibernate.MappingException: Unknown entity: annotations.Users

Add the following code to hibernate.cfg.xml

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>

Assembly - JG/JNLE/JL/JNGE after CMP

Wikibooks has a fairly good summary of jump instructions. Basically, there's actually two stages:

cmp_instruction op1, op2

Which sets various flags based on the result, and

jmp_conditional_instruction address

which will execute the jump based on the results of those flags.

Compare (cmp) will basically compute the subtraction op1-op2, however, this is not stored; instead only flag results are set. So if you did cmp eax, ebx that's the same as saying eax-ebx - then deciding based on whether that is positive, negative or zero which flags to set.

More detailed reference here.

Regular Expression for password validation

Long, and could maybe be shortened. Supports special characters ?"-_.

\A(?=[-\?\"_a-zA-Z0-9]*?[A-Z])(?=[-\?\"_a-zA-Z0-9]*?[a-z])(?=[-\?\"_a-zA-Z0-9]*?[0-9])[-\?\"_a-zA-Z0-9]{8,15}\z

Prefer composition over inheritance?

To address this question from a different perspective for newer programmers:

Inheritance is often taught early when we learn object-oriented programming, so it's seen as an easy solution to a common problem.

I have three classes that all need some common functionality. So if I write a base class and have them all inherit from it, then they will all have that functionality and I'll only need to maintain it in once place.

It sounds great, but in practice it almost never, ever works, for one of several reasons:

  • We discover that there are some other functions that we want our classes to have. If the way that we add functionality to classes is through inheritance, we have to decide - do we add it to the existing base class, even though not every class that inherits from it needs that functionality? Do we create another base class? But what about classes that already inherit from the other base class?
  • We discover that for just one of the classes that inherits from our base class we want the base class to behave a little differently. So now we go back and tinker with our base class, maybe adding some virtual methods, or even worse, some code that says, "If I'm inherited type A, do this, but if I'm inherited type B, do that." That's bad for lots of reasons. One is that every time we change the base class, we're effectively changing every inherited class. So we're really changing class A, B, C, and D because we need a slightly different behavior in class A. As careful as we think we are, we might break one of those classes for reasons that have nothing to do with those classes.
  • We might know why we decided to make all of these classes inherit from each other, but it might not (probably won't) make sense to someone else who has to maintain our code. We might force them into a difficult choice - do I do something really ugly and messy to make the change I need (see the previous bullet point) or do I just rewrite a bunch of this.

In the end, we tie our code in some difficult knots and get no benefit whatsoever from it except that we get to say, "Cool, I learned about inheritance and now I used it." That's not meant to be condescending because we've all done it. But we all did it because no one told us not to.

As soon as someone explained "favor composition over inheritance" to me, I thought back over every time I tried to share functionality between classes using inheritance and realized that most of the time it didn't really work well.

The antidote is the Single Responsibility Principle. Think of it as a constraint. My class must do one thing. I must be able to give my class a name that somehow describes that one thing it does. (There are exceptions to everything, but absolute rules are sometimes better when we're learning.) It follows that I cannot write a base class called ObjectBaseThatContainsVariousFunctionsNeededByDifferentClasses. Whatever distinct functionality I need must be in its own class, and then other classes that need that functionality can depend on that class, not inherit from it.

At the risk of oversimplifying, that's composition - composing multiple classes to work together. And once we form that habit we find that it's much more flexible, maintainable, and testable than using inheritance.

How to create and add users to a group in Jenkins for authentication?

You could use Role Strategy plugin for that purpose. It works like a charm, just setup some roles and assign them. Even on project-specific level.

How to deal with floating point number precision in JavaScript?

If you don't want to think about having to call functions each time, you can create a Class that handles conversion for you.

class Decimal {
  constructor(value = 0, scale = 4) {
    this.intervalValue = value;
    this.scale = scale;
  }

  get value() {
    return this.intervalValue;
  }

  set value(value) {
    this.intervalValue = Decimal.toDecimal(value, this.scale);
  }

  static toDecimal(val, scale) {
    const factor = 10 ** scale;
    return Math.round(val * factor) / factor;
  }
}

Usage:

const d = new Decimal(0, 4);
d.value = 0.1 + 0.2;              // 0.3
d.value = 0.3 - 0.2;              // 0.1
d.value = 0.1 + 0.2 - 0.3;        // 0
d.value = 5.551115123125783e-17;  // 0
d.value = 1 / 9;                  // 0.1111

Of course, when dealing with Decimal there are caveats:

d.value = 1/3 + 1/3 + 1/3;   // 1
d.value -= 1/3;              // 0.6667
d.value -= 1/3;              // 0.3334
d.value -= 1/3;              // 0.0001

You'd ideally want to use a high scale (like 12), and then convert it down when you need to present it or store it somewhere. Personally, I did experiment with creating a UInt8Array and trying to create a precision value (much like the SQL Decimal type), but since Javascript doesn't let you overload operators, it just gets a bit tedious not being able to use basic math operators (+, -, /, *) and using functions instead like add(), substract(), mult(). For my needs, it's not worth it.

But if you do need that level of precision and are willing to endure the use of functions for math, then I recommend the decimal.js library.

XmlSerializer: remove unnecessary xsi and xsd namespaces

There is an alternative - you can provide a member of type XmlSerializerNamespaces in the type to be serialized. Decorate it with the XmlNamespaceDeclarations attribute. Add the namespace prefixes and URIs to that member. Then, any serialization that does not explicitly provide an XmlSerializerNamespaces will use the namespace prefix+URI pairs you have put into your type.

Example code, suppose this is your type:

[XmlRoot(Namespace = "urn:mycompany.2009")]
public class Person {
  [XmlAttribute] 
  public bool Known;
  [XmlElement]
  public string Name;
  [XmlNamespaceDeclarations]
  public XmlSerializerNamespaces xmlns;
}

You can do this:

var p = new Person
  { 
      Name = "Charley",
      Known = false, 
      xmlns = new XmlSerializerNamespaces()
  }
p.xmlns.Add("",""); // default namespace is emoty
p.xmlns.Add("c", "urn:mycompany.2009");

And that will mean that any serialization of that instance that does not specify its own set of prefix+URI pairs will use the "p" prefix for the "urn:mycompany.2009" namespace. It will also omit the xsi and xsd namespaces.

The difference here is that you are adding the XmlSerializerNamespaces to the type itself, rather than employing it explicitly on a call to XmlSerializer.Serialize(). This means that if an instance of your type is serialized by code you do not own (for example in a webservices stack), and that code does not explicitly provide a XmlSerializerNamespaces, that serializer will use the namespaces provided in the instance.

Can I bind an array to an IN() condition?

very clean way for postgres is using the postgres-array ("{}"):

$ids = array(1,4,7,9,45);
$param = "{".implode(', ',$ids)."}";
$cmd = $db->prepare("SELECT * FROM table WHERE id = ANY (?)");
$result = $cmd->execute(array($param));

Numpy matrix to array

ravel() and flatten() functions from numpy are two techniques that I would try here. I will like to add to the posts made by Joe, Siraj, bubble and Kevad.

Ravel:

A = M.ravel()
print A, A.shape
>>> [1 2 3 4] (4,)

Flatten:

M = np.array([[1], [2], [3], [4]])
A = M.flatten()
print A, A.shape
>>> [1 2 3 4] (4,)

numpy.ravel() is faster, since it is a library level function which does not make any copy of the array. However, any change in array A will carry itself over to the original array M if you are using numpy.ravel().

numpy.flatten() is slower than numpy.ravel(). But if you are using numpy.flatten() to create A, then changes in A will not get carried over to the original array M.

numpy.squeeze() and M.reshape(-1) are slower than numpy.flatten() and numpy.ravel().

%timeit M.ravel()
>>> 1000000 loops, best of 3: 309 ns per loop

%timeit M.flatten()
>>> 1000000 loops, best of 3: 650 ns per loop

%timeit M.reshape(-1)
>>> 1000000 loops, best of 3: 755 ns per loop

%timeit np.squeeze(M)
>>> 1000000 loops, best of 3: 886 ns per loop

How to disable phone number linking in Mobile Safari?

To disable phone number detection on part of a page, wrap the affected text in an anchor tag with href="#". If you do this, mobile Safari and UIWebView should leave it alone.

<a href="#"> 1234567 </a>

How do you get the process ID of a program in Unix or Linux using Python?

This is a simplified variation of Fernando's answer. This is for Linux and either Python 2 or 3. No external library is needed, and no external process is run.

import glob

def get_command_pid(command):
    for path in glob.glob('/proc/*/comm'):
        if open(path).read().rstrip() == command:
            return path.split('/')[2]

Only the first matching process found will be returned, which works well for some purposes. To get the PIDs of multiple matching processes, you could just replace the return with yield, and then get a list with pids = list(get_command_pid(command)).

Alternatively, as a single expression:

For one process:

next(path.split('/')[2] for path in glob.glob('/proc/*/comm') if open(path).read().rstrip() == command)

For multiple processes:

[path.split('/')[2] for path in glob.glob('/proc/*/comm') if open(path).read().rstrip() == command]

SQL Server Operating system error 5: "5(Access is denied.)"

An old post, but here is a step by step that worked for SQL Server 2014 running under windows 7:

  • Control Panel ->
  • System and Security ->
  • Administrative Tools ->
  • Services ->
  • Double Click SQL Server (SQLEXPRESS) -> right click, Properties
  • Select Log On Tab
  • Select "Local System Account" (the default was some obtuse Windows System account)
  • -> OK
  • right click, Stop
  • right click, Start

Voilá !

I think setting the logon account may have been an option in the installation, but if so it was not the default, and was easy to miss if you were not already aware of this issue.

Expected response code 220 but got code "", with message "" in Laravel

I was facing the same issue. After researching too much on Google and StackOverflow. I found a solution very simple

First, you need to set environment like this

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=example44
MAIL_ENCRYPTION=tls
[email protected]

you have to change your Gmail address and password

Now you have to on less secure apps by following this link https://myaccount.google.com/lesssecureapps

MySQL Workbench Dark Theme

Quoting Yoga...

For Mac users, the code_editor.xml file is in MBP HD/ Applications/MySQLWorkbench.app/Contents/Resources/data/

I just discovered by dumbfounded experimentation (i.e. first thing I tried, worked) that if I copy that file to...

/Users/your.username/Library/Application Support/MySQL/Workbench/code_editor.xml

...and then edit it there, it does indeed override. Just worked perfectly for me on Mac OS X Sierra and MySQL Workbench 6.3.

display:inline vs display:block

Display : block will take the whole line i.e without line break

Display :inline will take only exact space that it requires.

 #block
  {
   display : block;
   background-color:red;
   border:1px solid;
  }

 #inline
 {
  display : inline;
  background-color:red;
  border:1px solid;
 }

You can refer example in this fiddle http://jsfiddle.net/RJXZM/1/.

REST API Token-based Authentication

In the web a stateful protocol is based on having a temporary token that is exchanged between a browser and a server (via cookie header or URI rewriting) on every request. That token is usually created on the server end, and it is a piece of opaque data that has a certain time-to-live, and it has the sole purpose of identifying a specific web user agent. That is, the token is temporary, and becomes a STATE that the web server has to maintain on behalf of a client user agent during the duration of that conversation. Therefore, the communication using a token in this way is STATEFUL. And if the conversation between client and server is STATEFUL it is not RESTful.

The username/password (sent on the Authorization header) is usually persisted on the database with the intent of identifying a user. Sometimes the user could mean another application; however, the username/password is NEVER intended to identify a specific web client user agent. The conversation between a web agent and server based on using the username/password in the Authorization header (following the HTTP Basic Authorization) is STATELESS because the web server front-end is not creating or maintaining any STATE information whatsoever on behalf of a specific web client user agent. And based on my understanding of REST, the protocol states clearly that the conversation between clients and server should be STATELESS. Therefore, if we want to have a true RESTful service we should use username/password (Refer to RFC mentioned in my previous post) in the Authorization header for every single call, NOT a sension kind of token (e.g. Session tokens created in web servers, OAuth tokens created in authorization servers, and so on).

I understand that several called REST providers are using tokens like OAuth1 or OAuth2 accept-tokens to be be passed as "Authorization: Bearer " in HTTP headers. However, it appears to me that using those tokens for RESTful services would violate the true STATELESS meaning that REST embraces; because those tokens are temporary piece of data created/maintained on the server side to identify a specific web client user agent for the valid duration of a that web client/server conversation. Therefore, any service that is using those OAuth1/2 tokens should not be called REST if we want to stick to the TRUE meaning of a STATELESS protocol.

Rubens

How to get the version of ionic framework?

ionic -v

Ionic CLI update available: 5.2.4 ? 5.2.5
Run npm i -g ionic to update

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

SQL query, if value is null then return 1

You can use COALESCE:

SELECT  orderhed.ordernum, 
    orderhed.orderdate, 
    currrate.currencycode,  
    coalesce(currrate.currentrate, 1) as currentrate
FROM orderhed 
LEFT OUTER JOIN currrate 
    ON orderhed.company = currrate.company 
    AND orderhed.orderdate = currrate.effectivedate

Or even IsNull():

SELECT  orderhed.ordernum, 
    orderhed.orderdate, 
    currrate.currencycode,  
    IsNull(currrate.currentrate, 1) as currentrate
FROM orderhed 
LEFT OUTER JOIN currrate 
    ON orderhed.company = currrate.company 
    AND orderhed.orderdate = currrate.effectivedate

Here is an article to help decide between COALESCE and IsNull:

http://www.mssqltips.com/sqlservertip/2689/deciding-between-coalesce-and-isnull-in-sql-server/

static const vs #define

Defining constants by using preprocessor directive #define is not recommended to apply not only in C++, but also in C. These constants will not have the type. Even in C was proposed to use const for constants.

start/play embedded (iframe) youtube-video on click of an image

To start video

var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);

To stop video

var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);

You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters

works for both vimeo and youtube on FF & Chrome

Selenium and xPath - locating a link by containing text

I think the problem is here:

[contains(text()='Some text')]

To break this down,

  1. The [] are a conditional that operates on each individual node in that node set -- each span node in your case. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  2. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  3. contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order.

You should try to change this to

[text()[contains(.,'Some text')]]

  1. The outer [] are a conditional that operates on each individual node in that node set text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.

  2. The inner [] are a conditional that operates on each node in that node set.

  3. contains is a function that operates on a string. Here it is passed an individual text node (.).

How can I get the number of records affected by a stored procedure?

Turns out for me that SET NOCOUNT ON was set in the stored procedure script (by default on SQL Server Management Studio) and SqlCommand.ExecuteNonQuery(); always returned -1.

I just set it off: SET NOCOUNT OFF without needing to use @@ROWCOUNT.

More details found here : SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete

What's "tools:context" in Android layout files?

This attribute helps to get the best knowledge of the activity associated with your layout. This is also useful when you have to add onClick handlers on a view using QuickFix.

tools:context=".MainActivity"

How to Count Duplicates in List with LINQ

You can use "group by" + "orderby". See LINQ 101 for details

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
        group x by x into g
        let count = g.Count()
        orderby count descending
        select new {Value = g.Key, Count = count};
foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

In response to this post (now deleted):

If you have a list of some custom objects then you need to use custom comparer or group by specific property.

Also query can't display result. Show us complete code to get a better help.

Based on your latest update:

You have this line of code:

group xx by xx into g

Since xx is a custom object system doesn't know how to compare one item against another. As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:

Note that I use Foo.Name as a key - i.e. objects will be grouped based on value of Name property.

There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.

//Using extension methods
var q = list.GroupBy(x => x.Name)
            .Select(x => new {Count = x.Count(), 
                              Name = x.Key, 
                              ID = x.First().ID})
            .OrderByDescending(x => x.Count);

//Using LINQ
var q = from x in list
        group x by x.Name into g
        let count = g.Count()
        orderby count descending
        select new {Name = g.Key, Count = count, ID = g.First().ID};

foreach (var x in q)
{
    Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}

javascript regex - look behind alternative?

Let's suppose you want to find all int not preceded by unsigned:

With support for negative look-behind:

(?<!unsigned )int

Without support for negative look-behind:

((?!unsigned ).{9}|^.{0,8})int

Basically idea is to grab n preceding characters and exclude match with negative look-ahead, but also match the cases where there's no preceeding n characters. (where n is length of look-behind).

So the regex in question:

(?<!filename)\.js$

would translate to:

((?!filename).{8}|^.{0,7})\.js$

You might need to play with capturing groups to find exact spot of the string that interests you or you want't to replace specific part with something else.

What is the difference between float and double?

Here is what the standard C99 (ISO-IEC 9899 6.2.5 §10) or C++2003 (ISO-IEC 14882-2003 3.1.9 §8) standards say:

There are three floating point types: float, double, and long double. The type double provides at least as much precision as float, and the type long double provides at least as much precision as double. The set of values of the type float is a subset of the set of values of the type double; the set of values of the type double is a subset of the set of values of the type long double.

The C++ standard adds:

The value representation of floating-point types is implementation-defined.

I would suggest having a look at the excellent What Every Computer Scientist Should Know About Floating-Point Arithmetic that covers the IEEE floating-point standard in depth. You'll learn about the representation details and you'll realize there is a tradeoff between magnitude and precision. The precision of the floating point representation increases as the magnitude decreases, hence floating point numbers between -1 and 1 are those with the most precision.

Validating URL in Java

Using only standard API, pass the string to a URL object then convert it to a URI object. This will accurately determine the validity of the URL according to the RFC2396 standard.

Example:

public boolean isValidURL(String url) {

    try {
        new URL(url).toURI();
    } catch (MalformedURLException | URISyntaxException e) {
        return false;
    }

    return true;
}

What is "Advanced" SQL?

I think it's best highlighted with an example. If you feel you could write the following SQL statement quickly with little/no reference material, then I'd guess that you probably meet their Advanced SQL requirement:

DECLARE @date DATETIME
SELECT @date = '10/31/09'

SELECT
      t1.EmpName,
      t1.Region,
      t1.TourStartDate,
      t1.TourEndDate,
      t1.FOrdDate,
      FOrdType  = MAX(CASE WHEN o.OrderDate = t1.FOrdDate THEN o.OrderType  ELSE NULL END),
      FOrdTotal = MAX(CASE WHEN o.OrderDate = t1.FOrdDate THEN o.OrderTotal ELSE NULL END),
      t1.LOrdDate,
      LOrdType  = MAX(CASE WHEN o.OrderDate = t1.LOrdDate THEN o.OrderType  ELSE NULL END),
      LOrdTotal = MAX(CASE WHEN o.OrderDate = t1.LOrdDate THEN o.OrderTotal ELSE NULL END)
  FROM 
      (--Derived table t1 returns the tourdates, and the order dates
      SELECT
            e.EmpId,
            e.EmpName,
            et.Region,
            et.TourStartDate,
            et.TourEndDate,
            FOrdDate = MIN(o.OrderDate),
            LOrdDate = MAX(o.OrderDate)
        FROM #Employees e INNER JOIN #EmpTours et
          ON e.EmpId = et.EmpId INNER JOIN #Orders o
          ON e.EmpId = o.EmpId
       WHERE et.TourStartDate <= @date
         AND (et.TourEndDate > = @date OR et.TourEndDate IS NULL)
         AND o.OrderDate BETWEEN et.TourStartDate AND @date
       GROUP BY e.EmpId,e.EmpName,et.Region,et.TourStartDate,et.TourEndDate
      ) t1 INNER JOIN #Orders o
    ON t1.EmpId = o.EmpId
   AND (t1.FOrdDate = o.OrderDate OR t1.LOrdDate = o.OrderDate)
 GROUP BY t1.EmpName,t1.Region,t1.TourStartDate,t1.TourEndDate,t1.FOrdDate,t1.LOrdDate

(source of query)

And to be honest, that's a relatively simple query - just some inner joins and a subquery, along with a few common keywords (max, min, case).

Not an enclosing class error Android Studio

String user_email = email.getText().toString().trim();
firebaseAuth
    .createUserWithEmailAndPassword(user_email,user_password)
    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(task.isSuccessful()) {
                Toast.makeText(RegistraionActivity.this, "Registration sucessful", Toast.LENGTH_SHORT).show();
                startActivities(new Intent(RegistraionActivity.this,MainActivity.class));
            }else{
                Toast.makeText(RegistraionActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
            }
        }
    });

How can I remove jenkins completely from linux

First - stop Jenkins service:

sudo service jenkins stop

Next - delete:

sudo apt-get remove --purge jenkins

If you used separate server for Jenkins, some GCP or AWS - just delete this server. Here is a video how to uninstall Jenkins from GCP Compute Engine https://youtu.be/D2HUFAc_Trw

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

What's the difference between a null pointer and a void pointer?

They are two different concepts: "void pointer" is a type (void *). "null pointer" is a pointer that has a value of zero (NULL). Example:

void *pointer = NULL;

That's a NULL void pointer.

How do I convert a C# List<string[]> to a Javascript array?

JSON is valid JavaScript Object anyway, while you are printing JavaScript itself, you don't need to encode/decode JSON further once it is converted to JSON.

<script type="text/javascript">
    var addresses = @Html.Raw(Model.Addresses);
</script>

Following will be printed, and it is valid JavaScript Expression.

<script type="text/javascript">
    var addresses = [["123 Street St.","City","CA","12345"],["456 Street St.","City","UT","12345"],["789 Street St.","City","OR","12345"]];
</script>

How to Correctly Check if a Process is running and Stop it

If you don't need to display exact result "running" / "not runnuning", you could simply:

ps notepad -ErrorAction SilentlyContinue | kill -PassThru

If the process was not running, you'll get no results. If it was running, you'll receive get-process output, and the process will be stopped.

What is the difference between a generative and a discriminative algorithm?

Here's the most important part from the lecture notes of CS299 (by Andrew Ng) related to the topic, which really helps me understand the difference between discriminative and generative learning algorithms.

Suppose we have two classes of animals, elephant (y = 1) and dog (y = 0). And x is the feature vector of the animals.

Given a training set, an algorithm like logistic regression or the perceptron algorithm (basically) tries to find a straight line — that is, a decision boundary — that separates the elephants and dogs. Then, to classify a new animal as either an elephant or a dog, it checks on which side of the decision boundary it falls, and makes its prediction accordingly. We call these discriminative learning algorithm.

Here's a different approach. First, looking at elephants, we can build a model of what elephants look like. Then, looking at dogs, we can build a separate model of what dogs look like. Finally, to classify a new animal, we can match the new animal against the elephant model, and match it against the dog model, to see whether the new animal looks more like the elephants or more like the dogs we had seen in the training set. We call these generative learning algorithm.

Default SQL Server Port

The default port of SQL server is 1433.

Convert dictionary values into array

There is a ToArray() function on Values:

Foo[] arr = new Foo[dict.Count];    
dict.Values.CopyTo(arr, 0);

But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:

IEnumerable<Foo> foos = dict.Values;

How to reshape data from long to wide format

You can do this with the reshape() function, or with the melt() / cast() functions in the reshape package. For the second option, example code is

library(reshape)
cast(dat1, name ~ numbers)

Or using reshape2

library(reshape2)
dcast(dat1, name ~ numbers)

How to do a logical OR operation for integer comparison in shell scripting?

Sometimes you need to use double brackets, otherwise you get an error like too many arguments

if [[ $OUTMERGE == *"fatal"* ]] || [[ $OUTMERGE == *"Aborting"* ]]
  then
fi

How do I get the SharedPreferences from a PreferenceActivity in Android?

having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...

public class global {
    public static Activity globalContext = null;

and set it in the main activity create

@Override
public void onCreate(Bundle savedInstanceState) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
            global.sdcardPath,
            ""));
    super.onCreate(savedInstanceState);

    //Start 
    //Debug.startMethodTracing("appname.Trace1");

    global.globalContext = this;

also all preference keys should be language independent, I'm shocked nobody has mentioned that.

getText(R.string.yourPrefKeyName).toString()

now call it very simply like this in one line of code

global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);

.m2 , settings.xml in Ubuntu

As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned

$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml

Possible to access MVC ViewBag object from Javascript file?

For CoreMVC 3.1, that would be,

@using Newtonsoft.Json
var listInJs =  @Html.Raw(JsonConvert.SerializeObject(ViewBag.SomeGenericList));

How can I list ALL grants a user received?

Assuming you want to list grants on all objects a particular user has received:

select * from all_tab_privs_recd where grantee = 'your user'

This will not return objects owned by the user. If you need those, use all_tab_privs view instead.

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

You have to create either another page or generic handler with the code to generate your pdf. Then that event gets triggered and the person is redirected to that page.

HTML: Changing colors of specific words in a string of text

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
    Enter the competition by <span style="color:#FF0000">January 30, 2011</span> and you could win up to $$$$ — including amazing <span style="color:#0000A0">summer</span> trips!
</p>

The span elements are inline an thus don't break the flow of the paragraph, only style in between the tags.

How do I set the selected item in a drop down box

Simple and easy to understand example by using ternary operators to set selected value in php

<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $id=> $value) { ?>
  <option value="<?php echo $id;?>" <?php echo ($id==  '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>

Singular matrix issue with Numpy

The matrix you pasted

[[   1,    8,   50],
 [   8,   64,  400],
 [  50,  400, 2500]]

Has a determinant of zero. This is the definition of a Singular matrix (one for which an inverse does not exist)

http://en.wikipedia.org/wiki/Invertible_matrix

"Could not find a version that satisfies the requirement opencv-python"

It happened with me on Windows, pip was not able to install opencv-python==3.4.0.12.

Later found out that it was due to the Python version, Python 3.7 has some issue with not getting linked to https://github.com/skvark/opencv-python.

Downgraded to Python 3.6 and it worked with:

pip3 install opencv-python

How to get the cell value by column name not by index in GridView in asp.net

Header Row cells sometimes will not work. This will just return the column Index. It will help in a lot of different ways. I know this is not the answer he is requesting. But this will help for a lot people.

public static int GetColumnIndexByHeaderText(GridView gridView, string columnName)
    {      
        for (int i = 0; i < gridView.Columns.Count ; i++)
        {
            if (gridView.Columns[i].HeaderText.ToUpper() == columnName.ToUpper() )
            {
                return i;
            }
        }     
        return -1;
    }

Add one day to date in javascript

Just for the sake of adding functions to the Date prototype:

In a mutable fashion / style:

Date.prototype.addDays = function(n) {
   this.setDate(this.getDate() + n);
};

// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
   this.addDays(1);
};

Date.prototype.addMonths = function(n) {
   this.setMonth(this.getMonth() + n);
};

Date.prototype.addYears = function(n) {
   this.setFullYear(this.getFullYear() + n);
}

// etc...

var currentDate = new Date();
currentDate.nextDay();

Error : ORA-01704: string literal too long

What are you using when operate with CLOB?

In all events you can do it with PL/SQL

DECLARE
  str varchar2(32767);
BEGIN
  str := 'Very-very-...-very-very-very-very-very-very long string value';
  update t1 set col1 = str;
END;
/

Proof link on SQLFiddle

C++ int to byte array

Another useful way of doing it that I use is unions:

union byteint
{
    byte b[sizeof int];
    int i;
};
byteint bi;
bi.i = 1337;
for(int i = 0; i<4;i++)
    destination[i] = bi.b[i];

This will make it so that the byte array and the integer will "overlap"( share the same memory ). this can be done with all kinds of types, as long as the byte array is the same size as the type( else one of the fields will not be influenced by the other ). And having them as one object is also just convenient when you have to switch between integer manipulation and byte manipulation/copying.

Find the paths between two given nodes?

given the adjacency matrix:

{0, 1, 3, 4, 0, 0}

{0, 0, 2, 1, 2, 0}

{0, 1, 0, 3, 0, 0}

{0, 1, 1, 0, 0, 1}

{0, 0, 0, 0, 0, 6}

{0, 1, 0, 1, 0, 0}

the following Wolfram Mathematica code solve the problem to find all the simple paths between two nodes of a graph. I used simple recursion, and two global var to keep track of cycles and to store the desired output. the code hasn't been optimized just for the sake of code clarity. the "print" should be helpful to clarify how it works.

cycleQ[l_]:=If[Length[DeleteDuplicates[l]] == Length[l], False, True];
getNode[matrix_, node_]:=Complement[Range[Length[matrix]],Flatten[Position[matrix[[node]], 0]]];

builtTree[node_, matrix_]:=Block[{nodes, posAndNodes, root, pos},
    If[{node} != {} && node != endNode ,
        root = node;
        nodes = getNode[matrix, node];
        (*Print["root:",root,"---nodes:",nodes];*)

        AppendTo[lcycle, Flatten[{root, nodes}]];
        If[cycleQ[lcycle] == True,
            lcycle = Most[lcycle]; appendToTree[root, nodes];,
            Print["paths: ", tree, "\n", "root:", root, "---nodes:",nodes];
            appendToTree[root, nodes];

        ];
    ];

appendToTree[root_, nodes_] := Block[{pos, toAdd},
    pos = Flatten[Position[tree[[All, -1]], root]];
    For[i = 1, i <= Length[pos], i++,
        toAdd = Flatten[Thread[{tree[[pos[[i]]]], {#}}]] & /@ nodes;
        (* check cycles!*)            
        If[cycleQ[#] != True, AppendTo[tree, #]] & /@ toAdd;
    ];
    tree = Delete[tree, {#} & /@ pos];
    builtTree[#, matrix] & /@ Union[tree[[All, -1]]];
    ];
];

to call the code: initNode = 1; endNode = 6; lcycle = {}; tree = {{initNode}}; builtTree[initNode, matrix];

paths: {{1}} root:1---nodes:{2,3,4}

paths: {{1,2},{1,3},{1,4}} root:2---nodes:{3,4,5}

paths: {{1,3},{1,4},{1,2,3},{1,2,4},{1,2,5}} root:3---nodes:{2,4}

paths: {{1,4},{1,2,4},{1,2,5},{1,3,4},{1,2,3,4},{1,3,2,4},{1,3,2,5}} root:4---nodes:{2,3,6}

paths: {{1,2,5},{1,3,2,5},{1,4,6},{1,2,4,6},{1,3,4,6},{1,2,3,4,6},{1,3,2,4,6},{1,4,2,5},{1,3,4,2,5},{1,4,3,2,5}} root:5---nodes:{6}

RESULTS:{{1, 4, 6}, {1, 2, 4, 6}, {1, 2, 5, 6}, {1, 3, 4, 6}, {1, 2, 3, 4, 6}, {1, 3, 2, 4, 6}, {1, 3, 2, 5, 6}, {1, 4, 2, 5, 6}, {1, 3, 4, 2, 5, 6}, {1, 4, 3, 2, 5, 6}}

...Unfortunately I cannot upload images to show the results in a better way :(

http://textanddatamining.blogspot.com

In Java, how to find if first character in a string is upper case without regex

If you have to check it out manually you can do int a = s.charAt(0)

If the value of a is between 65 to 90 it is upper case.

How to convert JSON to CSV format and store in a variable

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JSON to CSV</title>
    <script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
</head>
<body>
    <h1>This page does nothing....</h1>

    <script type="text/javascript">
        var json3 = {
          "count": 2,
          "items": [{
              "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
              "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
              "link": "http://wik.io/info/US/309201303",
              "timestamp": 1326439500,
              "image": null,
              "embed": null,
              "language": null,
              "user": null,
              "user_image": null,
              "user_link": null,
              "user_id": null,
              "geo": null,
              "source": "wikio",
              "favicon": "http://wikio.com/favicon.ico",
              "type": "blogs",
              "domain": "wik.io",
              "id": "2388575404943858468"
            },
            {
              "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
              "description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
              "link": "http://wik.io/info/US/309198933",
              "timestamp": 1326439320,
              "image": null,
              "embed": null,
              "language": null,
              "user": null,
              "user_image": null,
              "user_link": null,
              "user_id": null,
              "geo": null,
              "source": "wikio",
              "favicon": "http://wikio.com/favicon.ico",
              "type": "blogs",
              "domain": "wik.io",
              "id": "16209851193593872066"
            }
          ]
        };

        const items = json3.items
        const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
        const header = Object.keys(items[0])
        let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
        csv.unshift(header.join(','))
        csv = csv.join('\r\n')

        var link = document.createElement("a");    
        link.id="lnkDwnldLnk";
        document.body.appendChild(link);
        blob = new Blob([csv], { type: 'text/csv' }); 
        var csvUrl = window.webkitURL.createObjectURL(blob);
        var filename = 'UserExport.csv';
        jQuery("#lnkDwnldLnk")
        .attr({
            'download': filename,
            'href': csvUrl
        });
        jQuery('#lnkDwnldLnk')[0].click();
        document.body.removeChild(link);
    </script>
</body>
</html>

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

I was getting the following errors:

Failed to decode downloaded font: [...]/fonts/glyphicons-halflings-regular.woff2
OTS parsing error: invalid version tag

which was fixed after downloading the raw file directly from:
https://github.com/twbs/bootstrap/blob/master/fonts/glyphicons-halflings-regular.woff2

The problem was that there was a proxy error when downloading the file (it contained the HTML error message).

Split output of command by columns using Bash?

Bash's set will parse all output into position parameters.

For instance, with set $(free -h) command, echo $7 will show "Mem:"

Android: How to open a specific folder via Intent and show its content in a file browser?

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, DocumentsContract.Document.MIME_TYPE_DIR);
startActivity(intent);

Will open files app home screen enter image description here

Show div when radio button selected

$('input[name=test]').click(function () {
    if (this.id == "watch-me") {
        $("#show-me").show('slow');
    } else {
        $("#show-me").hide('slow');
    }
});

http://jsfiddle.net/2SsAk/2/

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

if you are using tomcat you may try this

<servlet-mapping>

    <http-method>POST</http-method>

</servlet-mapping>

in addition to <servlet-name> and <url-mapping>

Moment JS start and end of given month

var d = new moment();
var startMonth = d.clone().startOf('month');
var endMonth = d.clone().endOf('month');
console.log(startMonth, endMonth);

doc

How to delete items from a dictionary while iterating over it?

Iterate over a copy instead, such as the one returned by items():

for k, v in list(mydict.items()):

Cloning a private Github repo

As everyone aware about the process of cloning, I would like to add few more things here. Don't worry about special character or writing "@" as "%40" see character encoding

$ git clone https://username:[email protected]/user/repo   

This line can do the job

  1. Suppose if I have a password containing special character ( I don't know what to replace for '@' in my password)
  2. What if I want to use other temporary password other than my original password

To solve this issue I encourage to use GitHub Developer option to generate Access token. I believe Access token is secure and you wont find any special character.

creating-a-personal-access-token

Now I will write the below code to access my repository.

$ git clone https://username:[email protected]/user/repo

I am just replacing my original password with Access-token, Now I am not worried if some one see my access credential , I can regenerate the token when ever I feel.

Make sure you have checked repo Full control of private repositories here is the snap short

if block inside echo statement?

You will want to use the a ternary operator which acts as a shortened IF/Else statement:

echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

How to limit text width

use css property word-wrap: break-word;

see example here: http://jsfiddle.net/emgRF/

jQuery calculate sum of values in all text fields

Similarly along the lines of these answers written as a plugin:

$.fn.sum = function () {
    var sum = 0;
    this.each(function () {
        sum += 1*($(this).val());
    });
    return sum;
};

For the record 1 * x is faster than Number(x) in Chrome

Referencing Row Number in R

These are present by default as rownames when you create a data.frame.

R> df = data.frame('a' = rnorm(10), 'b' = runif(10), 'c' = letters[1:10])
R> df
            a          b c
1   0.3336944 0.39746731 a
2  -0.2334404 0.12242856 b
3   1.4886706 0.07984085 c
4  -1.4853724 0.83163342 d
5   0.7291344 0.10981827 e
6   0.1786753 0.47401690 f
7  -0.9173701 0.73992239 g
8   0.7805941 0.91925413 h
9   0.2469860 0.87979229 i
10  1.2810961 0.53289335 j

and you can access them via the rownames command.

R> rownames(df)
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

if you need them as numbers, simply coerce to numeric by adding as.numeric, as in as.numeric(rownames(df)).

You don't need to add them, as if you know what you are looking for (say item df$c == 'i', you can use the which command:

R> which(df$c =='i')
[1] 9

or if you don't know the column

R> which(df == 'i', arr.ind=T)
     row col
[1,]   9   3

you may access the element using df[9, 'c'], or df$c[9].

If you wanted to add them you could use df$rownumber <- as.numeric(rownames(df)), though this may be less robust than df$rownumber <- 1:nrow(df) as there are cases when you might have assigned to rownames so they will no longer be the default index numbers (the which command will continue to return index numbers even if you do assign to rownames).

Can I get JSON to load into an OrderedDict?

Some great news! Since version 3.6 the cPython implementation has preserved the insertion order of dictionaries (https://mail.python.org/pipermail/python-dev/2016-September/146327.html). This means that the json library is now order preserving by default. Observe the difference in behaviour between python 3.5 and 3.6. The code:

import json
data = json.loads('{"foo":1, "bar":2, "fiddle":{"bar":2, "foo":1}}')
print(json.dumps(data, indent=4))

In py3.5 the resulting order is undefined:

{
    "fiddle": {
        "bar": 2,
        "foo": 1
    },
    "bar": 2,
    "foo": 1
}

In the cPython implementation of python 3.6:

{
    "foo": 1,
    "bar": 2,
    "fiddle": {
        "bar": 2,
        "foo": 1
    }
}

The really great news is that this has become a language specification as of python 3.7 (as opposed to an implementation detail of cPython 3.6+): https://mail.python.org/pipermail/python-dev/2017-December/151283.html

So the answer to your question now becomes: upgrade to python 3.6! :)

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

What is an instance variable in Java?

Instance variable is the variable declared inside a class, but outside a method: something like:

class IronMan {

    /** These are all instance variables **/
    public String realName;
    public String[] superPowers;
    public int age;

    /** Getters and setters here **/
}

Now this IronMan Class can be instantiated in another class to use these variables. Something like:

class Avengers {

    public static void main(String[] a) {
        IronMan ironman = new IronMan();
        ironman.realName = "Tony Stark";
        // or
        ironman.setAge(30);
    }

}

This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.

Permission denied error while writing to a file in Python

If you are executing the python script via terminal pass --user to provide admin permissions.

Worked for me!

If you are using windows run the file as admin.

If you are executing via cmd, run cmd as admin and execute the python script.

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

First we install the Microsoft.EntityFrameworkCore.SqlServer NuGet Package:

PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer

Then, after importing the namespace with

using Microsoft.EntityFrameworkCore;

we add the database context:

services.AddDbContext<AspDbContext>(options =>
    options.UseSqlServer(config.GetConnectionString("optimumDB")));

Difference between arguments and parameters in Java

There are different points of view. One is they are the same. But in practice, we need to differentiate formal parameters (declarations in the method's header) and actual parameters (values passed at the point of invocation). While phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".

CSS: How to position two elements on top of each other, without specifying a height?

Due to absolute positioning removing the elements from the document flow position: absolute is not the right tool for the job. Depending on the exact layout you want to create you will be successful using negative margins, position:relative or maybe even transform: translate. Show us a sample of what you want to do we can help you better.

Send XML data to webservice using php curl

If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you

How do I parse an ISO 8601-formatted date?

An another way is to use specialized parser for ISO-8601 is to use isoparse function of dateutil parser:

from dateutil import parser

date = parser.isoparse("2008-09-03T20:56:35.450686+01:00")
print(date)

Output:

2008-09-03 20:56:35.450686+01:00

This function is also mentioned in the documentation for the standard Python function datetime.fromisoformat:

A more full-featured ISO 8601 parser, dateutil.parser.isoparse is available in the third-party package dateutil.

Entity Framework Queryable async

There is a massive difference in the example you have posted, the first version:

var urls = await context.Urls.ToListAsync();

This is bad, it basically does select * from table, returns all results into memory and then applies the where against that in memory collection rather than doing select * from table where... against the database.

The second method will not actually hit the database until a query is applied to the IQueryable (probably via a linq .Where().Select() style operation which will only return the db values which match the query.

If your examples were comparable, the async version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async functionality.

However the major difference (and benefit) is that the async version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).

What is deserialize and serialize in JSON?

Explanation of Serialize and Deserialize using Python

In python, pickle module is used for serialization. So, the serialization process is called pickling in Python. This module is available in Python standard library.

Serialization using pickle

import pickle

#the object to serialize
example_dic={1:"6",2:"2",3:"f"}

#where the bytes after serializing end up at, wb stands for write byte
pickle_out=open("dict.pickle","wb")
#Time to dump
pickle.dump(example_dic,pickle_out)
#whatever you open, you must close
pickle_out.close()

The PICKLE file (can be opened by a text editor like notepad) contains this (serialized data):

€}q (KX 6qKX 2qKX fqu.

Deserialization using pickle

import pickle

pickle_in=open("dict.pickle","rb")
get_deserialized_data_back=pickle.load(pickle_in)

print(get_deserialized_data_back)

Output:

{1: '6', 2: '2', 3: 'f'}

jQuery change method on input type="file"

I could not get IE8+ to work by adding a jQuery event handler to the file input type. I had to go old-school and add the the onchange="" attribute to the input tag:

<input type='file' onchange='getFilename(this)'/>

function getFileName(elm) {
   var fn = $(elm).val();
   ....
}

EDIT:

function getFileName(elm) {
   var fn = $(elm).val();
   var filename = fn.match(/[^\\/]*$/)[0]; // remove C:\fakename
   alert(filename);
}

Find the last element of an array while using a foreach loop in PHP

You can dirctly get last index by:

$numItems = count($arr);

echo $arr[$numItems-1];

How to change the default docker registry from docker.io to my private registry?

if you are using the fedora distro, you can change the file

/etc/containers/registries.conf

Adding domain docker.io

Executing a stored procedure within a stored procedure

Inline Stored procedure we using as per our need. Example like different Same parameter with different values we have to use in queries..

Create Proc SP1
(
 @ID int,
 @Name varchar(40)
 -- etc parameter list, If you don't have any parameter then no need to pass.
 )

  AS
  BEGIN

  -- Here we have some opereations

 -- If there is any Error Before Executing SP2 then SP will stop executing.

  Exec SP2 @ID,@Name,@SomeID OUTPUT 

 -- ,etc some other parameter also we can use OutPut parameters like 

 -- @SomeID is useful for some other operations for condition checking insertion etc.

 -- If you have any Error in you SP2 then also it will stop executing.

 -- If you want to do any other operation after executing SP2 that we can do here.

END

Difference between no-cache and must-revalidate

With Jeffrey Fox's interpretation about no-cache, i've tested under chrome 52.0.2743.116 m, the result shows that no-cache has the same behavior as must-revalidate, they all will NOT use local cache when server is unreachable, and, they all will use cache while tap browser's Back/Forward button when server is unreachable. As above, i think max-age=0, must-revalidate is identical to no-cache, at least in implementation.

Search of table names

I know this is an old thread, but if you prefer case-insensitive searching:

SELECT * FROM INFORMATION_SCHEMA.TABLES 
WHERE Lower(TABLE_NAME) LIKE Lower('%%')

How to read numbers separated by space using scanf

It should be as simple as using a list of receiving variables:

scanf("%i %i %i", &var1, &var2, &var3);

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

do just

<dependency>
   <groupId>javax.el</groupId>
   <artifactId>javax.el-api</artifactId>
   <version>2.2.4</version>
</dependency>

C++ - Hold the console window open?

hey first of all to include c++ functions you should use

include<iostream.h> instead of stdio .h

and to hold the output screen there is a simple command getch();
here, is an example:
   #include<iostream.h>
   #include<conio.h>
   void main()  \\or int main(); if you want
  {
    cout<<"c# is more advanced than c++";
    getch();
  }

thank you

Convert pem key to ssh-rsa format

No need to compile stuff. You can do the same with ssh-keygen:

ssh-keygen -f pub1key.pub -i

will read the public key in openssl format from pub1key.pub and output it in OpenSSH format.

Note: In some cases you will need to specify the input format:

ssh-keygen -f pub1key.pub -i -mPKCS8

From the ssh-keygen docs (From man ssh-keygen):

-m key_format Specify a key format for the -i (import) or -e (export) conversion options. The supported key formats are: “RFC4716” (RFC 4716/SSH2 public or private key), “PKCS8” (PEM PKCS8 public key) or “PEM” (PEM public key). The default conversion format is “RFC4716”.

Cause of No suitable driver found for

Not sure if it's worth anything, but I had a similar problem where I was getting a "java.sql.SQLException: No suitable driver found" error. I found this thread while researching a solution.

The way I ended up solving my problem was to forgo using java.sql.DriverManager to get a connection and instead built up an instance of org.hsqldb.jdbc.jdbcDataSource and used that.

The root cause of my problem (I believe) had to do with the classloader hierarchy and the fact that the JRE was running Java 5. Even though I could successfully load the jdbcDriver class, the classloader behind java.sql.DriverManager was higher up, to the point that it couldn't see the hsqldb.jar I needed.

Anyway, just putting this note here in case someone else stumbles by with a similar problem.

Convert string into Date type on Python

from datetime import datetime

a = datetime.strptime(f, "%Y-%m-%d")

Change color and appearance of drop down arrow

The <select> element is generated by the application and styling is not part of the CSS/HTML spec.

You would have to fake it with your own DIV and overlay it on top of the existing one, or build your own control emulating the same functionality.

How to open generated pdf using jspdf in new window

  1. Search in jspdf.js this:

    if(type == 'datauri') {
        document.location.href ='data:application/pdf;base64,' + Base64.encode(buffer);
    }
    
  2. Add :

    if(type == 'datauriNew') {   
        window.open('data:application/pdf;base64,' + Base64.encode(buffer));
    }
    
  3. call this option 'datauriNew' Saludos ;)

Spring MVC Missing URI template variable

This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.

Example: Suppose you defined in the REST definition

@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")

Then during the definition of the function, it should be

public ResponseEntity<List> getData(@PathVariable String appId)

This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:

public ResponseEntity<List> getData(@PathVariable String ID)

Issue with background color in JavaFX 8

Try this one in your css document,

-fx-background-color : #ffaadd;

or

-fx-base : #ffaadd; 

Also, you can set background color on your object with this code directly.

yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));

How to convert this var string to URL in Swift

you need to do:

let fileUrl = URL(string: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)

depending on your needs. See URL docs

Before Swift 3, URL was called NSURL.

What does ||= (or-equals) mean in Ruby?

This is the default assignment notation

for example: x ||= 1
this will check to see if x is nil or not. If x is indeed nil it will then assign it that new value (1 in our example)

more explicit:
if x == nil
x = 1
end

How can I add or update a query string parameter?

Based on @amateur's answer (and now incorporating the fix from @j_walker_dev comment), but taking into account the comment about hash tags in the url I use the following:

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  } else {
    var hash =  '';
    if( uri.indexOf('#') !== -1 ){
        hash = uri.replace(/.*#/, '#');
        uri = uri.replace(/#.*/, '');
    }
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";    
    return uri + separator + key + "=" + value + hash;
  }
}

Edited to fix [?|&] in regex which should of course be [?&] as pointed out in the comments

Edit: Alternative version to support removing URL params as well. I have used value === undefined as the way to indicate removal. Could use value === false or even a separate input param as wanted.

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
  if( value === undefined ) {
    if (uri.match(re)) {
        return uri.replace(re, '$1$2');
    } else {
        return uri;
    }
  } else {
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    } else {
    var hash =  '';
    if( uri.indexOf('#') !== -1 ){
        hash = uri.replace(/.*#/, '#');
        uri = uri.replace(/#.*/, '');
    }
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";    
    return uri + separator + key + "=" + value + hash;
  }
  }  
}

See it in action at https://jsfiddle.net/bp3tmuxh/1/

Getting the Username from the HKEY_USERS values

The proper way to do this requires leveraging the SAM registry hive (on Windows 10, this requires NT AUTHORITY\SYSTEM privileges). The information you require is in the the key: HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\Users\Names.

Each subkey is the username, and the default value in each subkey is a binary integer. This value (converted to decimal) actually corresponds to the last chunk of the of the SID.

Take "Administrator" for example, by default it is associated with the integer 0x1f4 (or 500).

So, in theory you could take the build a list of SIDS based on the subkey names of the HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList key and/or HKEY_USERS key, parse out the the value after the last hyphen (-), and compare that to the info from the SAM hive.

If you don't have NT AUTHORITY\SYSTEM privileges, the next best way to approach this may be to follow the other method described in the answers here.

reference: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/81d92bba-d22b-4a8c-908a-554ab29148ab

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

As we recently posted on the React blog, in the vast majority of cases you don't need getDerivedStateFromProps at all.

If you just want to compute some derived data, either:

  1. Do it right inside render
  2. Or, if re-calculating it is expensive, use a memoization helper like memoize-one.

Here's the simplest "after" example:

import memoize from "memoize-one";

class ExampleComponent extends React.Component {
  getDerivedData = memoize(computeDerivedState);

  render() {
    const derivedData = this.getDerivedData(this.props.someValue);
    // ...
  }
}

Check out this section of the blog post to learn more.

Inserting the same value multiple times when formatting a string

incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}

You may like to have a read of this to get an understanding: String Formatting Operations.

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

Execute a large SQL script (with GO commands)

Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-2D00-the-easy-way

Sample code:

public static void Main()    
{        
  string scriptDirectory = "c:\\temp\\sqltest\\";
  string sqlConnectionString = "Integrated Security=SSPI;" +
  "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)";
  DirectoryInfo di = new DirectoryInfo(scriptDirectory);
  FileInfo[] rgFiles = di.GetFiles("*.sql");
  foreach (FileInfo fi in rgFiles)
  {
        FileInfo fileInfo = new FileInfo(fi.FullName);
        string script = fileInfo.OpenText().ReadToEnd();
        using (SqlConnection connection = new SqlConnection(sqlConnectionString))
        {
            Server server = new Server(new ServerConnection(connection));
            server.ConnectionContext.ExecuteNonQuery(script);
        }
   }
}

If that won't work for you, see Phil Haack's library which handles that: http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx

Fastest way to write huge data in text file Java

try memory mapped files (takes 300 m/s to write 174MB in my m/c, core 2 duo, 2.5GB RAM) :

byte[] buffer = "Help I am trapped in a fortune cookie factory\n".getBytes();
int number_of_lines = 400000;

FileChannel rwChannel = new RandomAccessFile("textfile.txt", "rw").getChannel();
ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, buffer.length * number_of_lines);
for (int i = 0; i < number_of_lines; i++)
{
    wrBuf.put(buffer);
}
rwChannel.close();

What is the minimum I have to do to create an RPM file?

If make config works for your program or you have a shell script which copies your two files to the appropriate place you can use checkinstall. Just go to the directory where your makefile is in and call it with the parameter -R (for RPM) and optionally with the installation script.

How to use regex in file find

Just little elaboration of regex for search a directory and file

Find a directroy with name like book

find . -name "*book*" -type d

Find a file with name like book word

find . -name "*book*" -type f

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

jQuery '.each' and attaching '.click' event

One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.

For example:

HTML:

<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>

<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>

JS:

$( ".selected" ).each(function(index) {
    $(this).on("click", function(){
        // For the boolean value
        var boolKey = $(this).data('selected');
        // For the mammal value
        var mammalKey = $(this).attr('id'); 
    });
});

How does the JPA @SequenceGenerator annotation work

I have MySQL schema with autogen values. I use strategy=GenerationType.IDENTITY tag and seems to work fine in MySQL I guess it should work most db engines as well.

CREATE TABLE user (
    id bigint NOT NULL auto_increment,
    name varchar(64) NOT NULL default '',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

User.java:

// mark this JavaBean to be JPA scoped class
@Entity
@Table(name="user")
public class User {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;    // primary key (autogen surrogate)

    @Column(name="name")
    private String name;

    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name=name; }
}

printing all contents of array in C#

You may try this:

foreach(var item in yourArray)
{
    Console.WriteLine(item.ToString());
}

Also you may want to try something like this:

yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));

EDIT: to get output in one line [based on your comment]:

 Console.WriteLine("[{0}]", string.Join(", ", yourArray));
 //output style:  [8, 1, 8, 8, 4, 8, 6, 8, 8, 8]

EDIT(2019): As it is mentioned in other answers it is better to use Array.ForEach<T> method and there is no need to do the ToList step.

Array.ForEach(yourArray, Console.WriteLine);

Execute JavaScript using Selenium WebDriver in C#

The shortest code

ChromeDriver drv = new ChromeDriver();

drv.Navigate().GoToUrl("https://stackoverflow.com/questions/6229769/execute-javascript-using-selenium-webdriver-in-c-sharp");

drv.ExecuteScript("return alert(document.title);");


How to duplicate a git repository? (without forking)

I have noticed some of the other answers here use a bare clone and then mirror push to the new repository, however this does not work for me and when I open the new repository after that, the files look mixed up and not as I expect.

Here is a solution that definitely works for copying the files, although it does not preserve the original repository's revision history.

  1. git clone the repository onto your local machine.
  2. cd into the project directory and then run rm -rf .git to remove all the old git metadata including commit history, etc.
  3. Initialize a fresh git repository by running git init.
  4. Run git add . ; git commit -am "Initial commit" - Of course you can call this commit what you want.
  5. Set the origin to your new repository git remote add origin https://github.com/user/repo-name (replace the url with the url to your new repository)
  6. Push it to your new repository with git push origin master.

ConfigurationManager.AppSettings - How to modify and save?

Perhaps you should look at adding a Settings File. (e.g. App.Settings) Creating this file will allow you to do the following:

string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";

This means you can edit and then change items, where the items are strongly typed, and best of all... you don't have to touch any xml before you deploy!

The result is a Application or User contextual setting.

Have a look in the "add new item" menu for the setting file.

How do I perform an IF...THEN in an SQL SELECT?

 SELECT
   CASE 
      WHEN OBSOLETE = 'N' or InStock = 'Y' THEN 'TRUE' 
      ELSE 'FALSE' 
   END AS Salable,
   * 
FROM PRODUCT

Rails 4 LIKE query - ActiveRecord adds quotes

ActiveRecord is clever enough to know that the parameter referred to by the ? is a string, and so it encloses it in single quotes. You could as one post suggests use Ruby string interpolation to pad the string with the required % symbols. However, this might expose you to SQL-injection (which is bad). I would suggest you use the SQL CONCAT() function to prepare the string like so:

"name LIKE CONCAT('%',?,'%') OR postal_code LIKE CONCAT('%',?,'%')", search, search)

Does MS Access support "CASE WHEN" clause if connect with ODBC?

I have had to use a multiple IIF statement to create a similar result in ACCESS SQL.

IIf([refi type] Like "FHA ST*","F",IIf([refi type]="VA IRRL","V"))

All remaining will stay Null.

How do I change the figure size with subplots?

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

How do I enable the column selection mode in Eclipse?

First of all your mouse key must be focus in editor to enable Toggle Block Selection Mode

enter image description here

Click on toggleButton as shown in figure and it will enable Vertical selection. After selection toggle it again.

How to initialize a dict with keys from a list and empty value in Python?

nobody cared to give a dict-comprehension solution ?

>>> keys = [1,2,3,5,6,7]
>>> {key: None for key in keys}
{1: None, 2: None, 3: None, 5: None, 6: None, 7: None}

How do I specify the exit code of a console application in .NET?

If you are going to use the method suggested by David, you should also take a look at the [Flags] Attribute.

This allows you to do bit wise operations on enums.

[Flags]
enum ExitCodes : int
{
  Success = 0,
  SignToolNotInPath = 1,
  AssemblyDirectoryBad = 2,
  PFXFilePathBad = 4,
  PasswordMissing = 8,
  SignFailed = 16,
  UnknownError = 32
}

Then

(ExitCodes.SignFailed | ExitCodes.UnknownError)

would be 16 + 32. :)

Maven: repository element was not specified in the POM inside distributionManagement?

Review the pom.xml file inside of target/checkout/. Chances are, the pom.xml in your trunk or master branch does not have the distributionManagement tag.

Custom sort function in ng-repeat

To include the direction along with the orderBy function:

ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"

where

defaultSortDirection = 0; // 0 = Ascending, 1 = Descending

Authorize a non-admin developer in Xcode / Mac OS

Finally, I was able to get rid of it using DevToolsSecurity -enable on Terminal. Thanks to @joar_at_work!

FYI: I'm on Xcode 4.3, and pressed the disable button when it launched for the first time, don't ask why, just assume my dog made me do it :)

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

I think the issue with the deployment descriptor and dependencies that you are using.

I was having the same issue that I resolved by doing these things. Update your POM.XML

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.17</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>1.17</version>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>jsr311-api</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

    </dependencies>

Also, add this code inside your build tag under the POM.XML only Since Container needs to know that where is your resource file configured.

<build>
        <finalName>HatchWaysAppAPI</finalName>
        <sourceDirectory>src/main/resources</sourceDirectory>
        <plugins>

            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

        </plugins>
    </build>

Change your resource folder according to your requirement.

Your Web.xml should be like this.

<servlet>
        <servlet-name>HatchWaysAppAPI Maven Webapp</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.hatchwaysapi.mainController</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>HatchWaysAppAPI Maven Webapp</servlet-name>
        <url-pattern>/v1/*</url-pattern>
    </servlet-mapping>

Note This configuration only for the maven if you not using maven than ignore Pom.XML just do config of the Web.xml.

C++ class forward declaration

The forward declaration is an "incomplete type", the only thing you can do with such a type is instantiate a pointer to it, or reference it in a function declaration (i.e. and argument or return type in a function prototype). In line 52 in your code, you are attempting to instantiate an object.

At that point the compiler has no knowledge of the object's size nor its constructor, so cannot instantiate an object.

PHP cURL vs file_get_contents

file_get_contents() is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.

fopen() with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

How to set null to a GUID property

You can use typeof(Guid), "00000000-0000-0000-0000-000000000000" for DefaultValue of the property.

Is there a concise way to iterate over a stream with indices in Java 8?

Since guava 21, you can use

Streams.mapWithIndex()

Example (from official doc):

Streams.mapWithIndex(
    Stream.of("a", "b", "c"),
    (str, index) -> str + ":" + index)
) // will return Stream.of("a:0", "b:1", "c:2")

CGContextDrawImage draws image upside down when passed UIImage.CGImage

If anyone is interested in a no-brainer solution for drawing an image in a custom rect in a context:

 func drawImage(image: UIImage, inRect rect: CGRect, context: CGContext!) {

    //flip coords
    let ty: CGFloat = (rect.origin.y + rect.size.height)
    CGContextTranslateCTM(context, 0, ty)
    CGContextScaleCTM(context, 1.0, -1.0)

    //draw image
    let rect__y_zero = CGRect(origin: CGPoint(x: rect.origin.x, y:0), size: rect.size)
    CGContextDrawImage(context, rect__y_zero, image.CGImage)

    //flip back
    CGContextScaleCTM(context, 1.0, -1.0)
    CGContextTranslateCTM(context, 0, -ty)

}

The image will be scaled to fill the rect.

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

The issue is that even though we add a folder to skip list it will be deleted if it does not exist.

The solution is to add both the destination and the source folder with full path.

I will try to explain the different scenarios and what happens below, based on my experience.

Starting folder structure:

d:\Temp\source\1.txt
d:\Temp\source\2\2.txt

Command:

robocopy D:\Temp\source D:\Temp\dest /MIR

This will copy over all the files and folders that are missing and deletes all the files and folders that cannot be found in the source

Let's add a new folder and then add it to the command to skip it.

New structure:

d:\Temp\source\1.txt
d:\Temp\source\2\2.txt
d:\Temp\source\3\3.txt

Command:

robocopy D:\Temp\source D:\Temp\dest /MIR /XD "D:\Temp\source\3"        

If I add /XD with the source folder and run the command it all seems good the command it wont copy it over.

Now add a folder to the destination to get this setup:

d:\Temp\source\1.txt
d:\Temp\source\2\2.txt
d:\Temp\source\3\3.txt

d:\Temp\dest\1.txt
d:\Temp\dest\2\2.txt
d:\Temp\dest\3\4.txt

If I run the command it is still fine, 4.txt stays there 3.txt is not copied over. All is fine.

But, if I delete the source folder "d:\Temp\source\3" then the destination folder and the file are deleted even though it is on the skip list

                       1    D:\Temp\source\
    *EXTRA Dir        -1    D:\Temp\dest\3\
      *EXTRA File                  4        4.txt
                       1    D:\Temp\source\2\

If I change the command to skip the destination folder instead then the folder is not deleted, when the folder is missing from the source.

robocopy D:\Temp\source D:\Temp\dest /MIR /XD "D:\Temp\dest\3"

On the other hand if the folder exists and there are files it will copy them over and delete them:

                       1    D:\Temp\source\3\
          *EXTRA File                  4        4.txt
100%        New File                   4        3.txt

To make sure the folder is always skipped and no files are copied over even if the source or destination folder is missing we have to add both to the skip list:

robocopy D:\Temp\source D:\Temp\dest /MIR /XD "d:\Temp\source\3" "D:\Temp\dest\3"

After this no matters if the source folder is missing or the destination folder is missing, robocopy will leave it as it is.

Bootstrap 4: Multilevel Dropdown Inside Navigation

I found this multidrop-down menu which work great in all device.

Also, have hover style

It supports multi-level submenus with bootstrap 4.

_x000D_
_x000D_
$( document ).ready( function () {_x000D_
    $( '.navbar a.dropdown-toggle' ).on( 'click', function ( e ) {_x000D_
        var $el = $( this );_x000D_
        var $parent = $( this ).offsetParent( ".dropdown-menu" );_x000D_
        $( this ).parent( "li" ).toggleClass( 'show' );_x000D_
_x000D_
        if ( !$parent.parent().hasClass( 'navbar-nav' ) ) {_x000D_
            $el.next().css( { "top": $el[0].offsetTop, "left": $parent.outerWidth() - 4 } );_x000D_
        }_x000D_
        $( '.navbar-nav li.show' ).not( $( this ).parents( "li" ) ).removeClass( "show" );_x000D_
        return false;_x000D_
    } );_x000D_
} );
_x000D_
.navbar-light .navbar-nav .nav-link {_x000D_
    color: rgb(64, 64, 64);_x000D_
}_x000D_
.btco-menu li > a {_x000D_
    padding: 10px 15px;_x000D_
    color: #000;_x000D_
}_x000D_
_x000D_
.btco-menu .active a:focus,_x000D_
.btco-menu li a:focus ,_x000D_
.navbar > .show > a:focus{_x000D_
    background: transparent;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
.dropdown-menu .show > .dropdown-toggle::after{_x000D_
    transform: rotate(-90deg);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded btco-menu">_x000D_
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
        <span class="navbar-toggler-icon"></span>_x000D_
    </button>_x000D_
    <a class="navbar-brand" href="#">Navbar</a>_x000D_
    <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
        <ul class="navbar-nav">_x000D_
            <li class="nav-item active">_x000D_
                <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
            </li>_x000D_
            <li class="nav-item">_x000D_
                <a class="nav-link" href="#">Features</a>_x000D_
            </li>_x000D_
            <li class="nav-item">_x000D_
                <a class="nav-link" href="#">Pricing</a>_x000D_
            </li>_x000D_
            <li class="nav-item dropdown">_x000D_
                <a class="nav-link dropdown-toggle" href="https://bootstrapthemes.co" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown link</a>_x000D_
                <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
                    <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
                    <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
                    <li><a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
                        <ul class="dropdown-menu">_x000D_
                            <li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
                            <li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
                            <li><a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
                                <ul class="dropdown-menu">_x000D_
                                    <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                                    <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                                </ul>_x000D_
                            </li>_x000D_
                            <li><a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
                                <ul class="dropdown-menu">_x000D_
                                    <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                                    <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                                </ul>_x000D_
                            </li>_x000D_
                        </ul>_x000D_
                    </li>_x000D_
                </ul>_x000D_
            </li>_x000D_
        </ul>_x000D_
    </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

.jar error - could not find or load main class

Had this problem couldn't find the answer so i went looking on other threads, I found that i was making my app with 1.8 but for some reason my jre was out dated even though i remember updating it. I downloaded the lastes jre 8 and the jar file runs perfectly. Hope this helps.

How can I change all input values to uppercase using Jquery?

use css :

input.upper { text-transform: uppercase; }

probably best to use the style, and convert serverside. There's also a jQuery plugin to force uppercase: http://plugins.jquery.com/plugin-tags/uppercase

Difference between onLoad and ng-init in angular

Works for me.

<div ng-show="$scope.showme === true">Hello World</div>
<div ng-repeat="a in $scope.bigdata" ng-init="$scope.showme = true">{{ a.title }}</div>

android - How to get view from context?

first use this:

LayoutInflater inflater = (LayoutInflater) Read_file.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Read file is current activity in which you want your context.

View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));

then you can use this to find any element in layout.

ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);

Change limit for "Mysql Row size too large"

I also encountered the same problem. I solve the problem by executing the following sql:

ALTER ${table} ROW_FORMAT=COMPRESSED;

But, I think u should know about the Row Storage.
There are two kinds of columns: variable-length column(such as VARCHAR, VARBINARY, and BLOB and TEXT types) and fixed-length column. They are stored in different types of pages.

Variable-length columns are an exception to this rule. Columns such as BLOB and VARCHAR that are too long to fit on a B-tree page are stored on separately allocated disk pages called overflow pages. We call such columns off-page columns. The values of these columns are stored in singly-linked lists of overflow pages, and each such column has its own list of one or more overflow pages. In some cases, all or a prefix of the long column value is stored in the B-tree, to avoid wasting storage and eliminating the need to read a separate page.

and when purpose of setting ROW_FORMAT is

When a table is created with ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED, InnoDB can store long variable-length column values (for VARCHAR, VARBINARY, and BLOB and TEXT types) fully off-page, with the clustered index record containing only a 20-byte pointer to the overflow page.

Wanna know more about DYNAMIC and COMPRESSED Row Formats

Text overwrite in visual studio 2010

press your keyboard Insert Key

Laravel 5: Retrieve JSON array from $request

 $postbody='';
 // Check for presence of a body in the request
 if (count($request->json()->all())) {
     $postbody = $request->json()->all();
 }

This is how it's done in laravel 5.2 now.

From milliseconds to hour, minutes, seconds and milliseconds

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class MyTest {

    public static void main(String[] args) {
        long seconds = 360000;

        long days = TimeUnit.SECONDS.toDays(seconds);
        long hours = TimeUnit.SECONDS.toHours(seconds - TimeUnit.DAYS.toSeconds(days));

        System.out.println("days: " + days);
        System.out.println("hours: " + hours);
    }
}

ToString() function in Go

When you have own struct, you could have own convert-to-string function.

package main

import (
    "fmt"
)

type Color struct {
    Red   int `json:"red"`
    Green int `json:"green"`
    Blue  int `json:"blue"`
}

func (c Color) String() string {
    return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}

func main() {
    c := Color{Red: 123, Green: 11, Blue: 34}
    fmt.Println(c) //[123, 11, 34]
}

Pandas: Convert Timestamp to datetime.date

Use the .date method:

In [11]: t = pd.Timestamp('2013-12-25 00:00:00')

In [12]: t.date()
Out[12]: datetime.date(2013, 12, 25)

In [13]: t.date() == datetime.date(2013, 12, 25)
Out[13]: True

To compare against a DatetimeIndex (i.e. an array of Timestamps), you'll want to do it the other way around:

In [21]: pd.Timestamp(datetime.date(2013, 12, 25))
Out[21]: Timestamp('2013-12-25 00:00:00')

In [22]: ts = pd.DatetimeIndex([t])

In [23]: ts == pd.Timestamp(datetime.date(2013, 12, 25))
Out[23]: array([ True], dtype=bool)

Add text at the end of each line

  1. You can also achieve this using the backreference technique

    sed -i.bak 's/\(.*\)/\1:80/' foo.txt
    
  2. You can also use with awk like this

    awk '{print $0":80"}' foo.txt > tmp && mv tmp foo.txt
    

Setting selected option in laravel form

You can do it like this.

<select class="form-control" name="resoureceName">

  <option>Select Item</option>

  @foreach ($items as $item)
    <option value="{{ $item->id }}" {{ ( $item->id == $existingRecordId) ? 'selected' : '' }}> {{ $item->name }} </option>
  @endforeach    </select>

SHA-256 or MD5 for file integrity

The underlying MD5 algorithm is no longer deemed secure, thus while md5sum is well-suited for identifying known files in situations that are not security related, it should not be relied on if there is a chance that files have been purposefully and maliciously tampered. In the latter case, the use of a newer hashing tool such as sha256sum is highly recommended.

So, if you are simply looking to check for file corruption or file differences, when the source of the file is trusted, MD5 should be sufficient. If you are looking to verify the integrity of a file coming from an untrusted source, or over from a trusted source over an unencrypted connection, MD5 is not sufficient.

Another commenter noted that Ubuntu and others use MD5 checksums. Ubuntu has moved to PGP and SHA256, in addition to MD5, but the documentation of the stronger verification strategies are more difficult to find. See the HowToSHA256SUM page for more details.

How to enable production mode?

In environment.ts file set production to true

export const environment = {
  production: true
};

AngularJS - Create a directive that uses ng-model

Creating an isolate scope is undesirable. I would avoid using the scope attribute and do something like this. scope:true gives you a new child scope but not isolate. Then use parse to point a local scope variable to the same object the user has supplied to the ngModel attribute.

app.directive('myDir', ['$parse', function ($parse) {
    return {
        restrict: 'EA',
        scope: true,
        link: function (scope, elem, attrs) {
            if(!attrs.ngModel) {return;}
            var model = $parse(attrs.ngModel);
            scope.model = model(scope);
        }
    };
}]);

how to convert image to byte array in java?

BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.

if you want the data from DataBufferByte, use:

public byte[] extractBytes (String ImageName) throws IOException {
 // open image
 File imgPath = new File(ImageName);
 BufferedImage bufferedImage = ImageIO.read(imgPath);

 // get DataBufferBytes from Raster
 WritableRaster raster = bufferedImage .getRaster();
 DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

 return ( data.getData() );
}

now you can process these bytes by hiding text in lsb for example, or process it the way you want.

How do I rename a column in a SQLite database table?

Recently I had to do that in SQLite3 with a table named points with the colunms id, lon, lat. Erroneusly, when the table was imported, the values for latitude where stored in the lon column and viceversa, so an obvious fix would be to rename those columns. So the trick was:

create table points_tmp as select id, lon as lat, lat as lon from points;
drop table points;
alter table points_tmp rename to points;

I hope this would be useful for you!

How to pass data in the ajax DELETE request other than headers

I was able to successfully pass through the data attribute in the ajax method. Here is my code

$.ajax({
     url: "/api/Gigs/Cancel",
     type: "DELETE",
     data: {
             "GigId": link.attr('data-gig-id')
           }

  })

The link.attr method simply returned the value of 'data-gig-id' .

How to download/upload files from/to SharePoint 2013 using CSOM?

I would suggest reading some Microsoft documentation on what you can do with CSOM. This might be one example of what you are looking for, but there is a huge API documented in msdn.

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume there is a list item with ID=1. 
ListItem listItem = announcementsList.Items.GetById(1); 

// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!"; 
listItem.Update(); 

context.ExecuteQuery(); 

From: http://msdn.microsoft.com/en-us/library/fp179912.aspx

Is there an XSL "contains" directive?

Sure there is! For instance:

<xsl:if test="not(contains($hhref, '1234'))">
  <li>
    <a href="{$hhref}" title="{$pdate}">
      <xsl:value-of select="title"/>
    </a>
  </li>
</xsl:if>

The syntax is: contains(stringToSearchWithin, stringToSearchFor)

How to prevent SIGPIPEs (or handle them properly)

I'm super late to the party, but SO_NOSIGPIPE isn't portable, and might not work on your system (it seems to be a BSD thing).

A nice alternative if you're on, say, a Linux system without SO_NOSIGPIPE would be to set the MSG_NOSIGNAL flag on your send(2) call.

Example replacing write(...) by send(...,MSG_NOSIGNAL) (see nobar's comment)

char buf[888];
//write( sockfd, buf, sizeof(buf) );
send(    sockfd, buf, sizeof(buf), MSG_NOSIGNAL );

MySQL my.cnf file - Found option without preceding group

I had this problem when I installed MySQL 8.0.15 with the community installer. The my.ini file that came with the installer did not work correctly after it had been edited. I did a full manual install by downloading that zip folder. I was able to create my own my.ini file containing only the parameters that I was concerned about and it worked.

  1. download zip file from MySQL website
  2. unpack the folder into C:\program files\MySQL\MySQL8.0
  3. within the MySQL8.0 folder that you unpacked the zip folder into, create a text file and save it as my.ini
  4. include the parameters in that my.ini file that you are concerned about. so something like this(just ensure that there is already a folder created for the datadir or else initialization won't work):

    [mysqld]
    basedire=C:\program files\MySQL\MySQL8.0
    datadir=D:\MySQL\Data
    ....continue with whatever parameters you want to include
    
  5. initialize the data directory by running these two commands in the command prompt:

    cd C:\program files\MySQL\MySQL8.0\bin
    mysqld --default-file=C:\program files\MySQL\MySQL8.0\my.ini --initialize
    
  6. install the MySQL server as a service by running these two commands:

    cd C:\program files\MySQL\MySQL8.0\bin
    mysqld --install --default-file=C:\program files\MySQL\MySQL8.0\my.ini
    
  7. finally, start the server for the first time by running these two commands:

    cd C:\program files\MySQL\MySQL8.0\bin
    mysqld --console
    

How can I make setInterval also work when a tab is inactive in Chrome?

Heavily influenced by Ruslan Tushov's library, I've created my own small library. Just add the script in the <head> and it will patch setInterval and setTimeout with ones that use WebWorker.

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

The problem is due to older version of ojdbc - ojdbc14.

Place the latest version of ojdbc jar file in your application or shared library. (Only one version should be there and it should be the latest one) As of today - ojdbc6.jar

Check the application libraries and shared libraries on server.

Generate sha256 with OpenSSL and C++

I think that you only have to replace SHA1 function with SHA256 function with tatk code from link in Your post

How to get current value of RxJS Subject or Observable?

A Subject or Observable doesn't have a current value. When a value is emitted, it is passed to subscribers and the Observable is done with it.

If you want to have a current value, use BehaviorSubject which is designed for exactly that purpose. BehaviorSubject keeps the last emitted value and emits it immediately to new subscribers.

It also has a method getValue() to get the current value.

Combine [NgStyle] With Condition (if..else)

[ngStyle] with condition based if and else case.

<label for="file" [ngStyle]="isPreview ? {'cursor': 'default'} : {'cursor': 'pointer'}">Attachment

Re-order columns of table in Oracle

I followed the solution above from Jonas and it worked well until I needed to add a second column. What I found is that when making the columns visible again Oracle does not necessarily set them visible in the order listed in the statement.

To demonstrate this follow Jonas' example above. As he showed, once the steps are complete the table is in the order that you'd expect. Things then break down when you add another column as shown below:

Example (continued from Jonas'):

Add another column which is to be inserted before column C.

ALTER TABLE t ADD (b2 INT);

Use the technique demonstrated above to move the newly added B2 column before column C.

ALTER TABLE t MODIFY (c INVISIBLE, d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY (c VISIBLE, d VISIBLE, e VISIBLE);

DESCRIBE t;

Name
----
A
B
B2
D
E
C

As shown above column C has moved to the end. It seems that the ALTER TABLE statement above processed the columns in the order D, E, C rather than in the order specified in the statement (perhaps in physical table order). To ensure that the column is placed where desired it is necessary to make the columns visible one by one in the desired order.

ALTER TABLE t MODIFY (c INVISIBLE, d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY c VISIBLE;
ALTER TABLE t MODIFY d VISIBLE;
ALTER TABLE t MODIFY e VISIBLE;

DESCRIBE t;

Name
----
A
B
B2
C
D
E

Create Table from JSON Data with angularjs and ng-repeat

Angular 2 or 4:

There's no more ng-repeat, it's *ngFor now in recent Angular versions!

<table style="padding: 20px; width: 60%;">
    <tr>
      <th  align="left">id</th>
      <th  align="left">status</th>
      <th  align="left">name</th>
    </tr>
    <tr *ngFor="let item of myJSONArray">
      <td>{{item.id}}</td>
      <td>{{item.status}}</td>
      <td>{{item.name}}</td>
    </tr>
</table>

Used this simple JSON:

[{"id":1,"status":"active","name":"A"},
{"id":2,"status":"live","name":"B"},
{"id":3,"status":"active","name":"C"},
{"id":6,"status":"deleted","name":"D"},
{"id":4,"status":"live","name":"E"},
{"id":5,"status":"active","name":"F"}]

What is a daemon thread in Java?

Daemon threads are generally known as "Service Provider" thread. These threads should not be used to execute program code but system code. These threads run parallel to your code but JVM can kill them anytime. When JVM finds no user threads, it stops it and all daemon threads terminate instantly. We can set non-daemon thread to daemon using :

setDaemon(true)

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

For me, it works when I double checked the parent´s "group ID" and "artifact ID" that in my case were the wrong ones and that was the problem.

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

First, open Device Manager by searching for it in the Windows search bar.

Then, click ports and right click the port the Arduino is connected to. Then, go to Port settingsAdvanced. Next, select any port that is not in use and is not the port the Arduino is currently connected to. Then click OK and unplug + replug your Arduino. This works most of the time with any Arduino board.

How to check if Receiver is registered in Android?

i put this code in my parent activity

List registeredReceivers = new ArrayList<>();

@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
    registeredReceivers.add(System.identityHashCode(receiver));
    return super.registerReceiver(receiver, filter);
}

@Override
public void unregisterReceiver(BroadcastReceiver receiver) {
    if(registeredReceivers.contains(System.identityHashCode(receiver)))
    super.unregisterReceiver(receiver);
}

What is the boundary in multipart/form-data?

multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.

The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).

The payload passed looks something like this:

Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW

    -----WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name=”file”; filename=”captcha”
    Content-Type:

    -----WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name=”action”

    submit
    -----WebKitFormBoundary7MA4YWxkTrZu0gW--

On the webservice side, it's consumed in @Consumes("multipart/form-data") form.

Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.

See RFC1341 sec7.2 The Multipart Content-Type

Wait till a Function with animations is finished until running another Function

Is this what you mean man: http://jsfiddle.net/LF75a/

You will have one function fire the next function and so on, i.e. add another function call and then add your functionONe at the bottom of it.

Please lemme know if I missed anything, hope it fits the cause :)

or this: Call a function after previous function is complete

Code:

function hulk()
{
  // do some stuff...
}
function simpsons()
{
  // do some stuff...
  hulk();
}
function thor()
{
  // do some stuff...
  simpsons();
}

Convert number of minutes into hours & minutes using PHP

<?php

function convertToHoursMins($time, $format = '%02d:%02d') {
    if ($time < 1) {
        return;
    }
    $hours = floor($time / 60);
    $minutes = ($time % 60);
    return sprintf($format, $hours, $minutes);
}

echo convertToHoursMins(250, '%02d hours %02d minutes'); // should output 4 hours 17 minutes

java: How can I do dynamic casting of a variable from one type to another?

I recently felt like I had to do this too, but then found another way which possibly makes my code look neater, and uses better OOP.

I have many sibling classes that each implement a certain method doSomething(). In order to access that method, I would have to have an instance of that class first, but I created a superclass for all my sibling classes and now I can access the method from the superclass.

Below I show two ways alternative ways to "dynamic casting".

// Method 1.
mFragment = getFragmentManager().findFragmentByTag(MyHelper.getName(mUnitNum));
switch (mUnitNum) {
case 0:
    ((MyFragment0) mFragment).sortNames(sortOptionNum);
    break;
case 1:
    ((MyFragment1) mFragment).sortNames(sortOptionNum);
    break;
case 2:
    ((MyFragment2) mFragment).sortNames(sortOptionNum);
    break;
}

and my currently used method,

// Method 2.
mSuperFragment = (MySuperFragment) getFragmentManager().findFragmentByTag(MyHelper.getName(mUnitNum));
mSuperFragment.sortNames(sortOptionNum);

Find the most common element in a list

def mostCommonElement(list):
  count = {} // dict holder
  max = 0 // keep track of the count by key
  result = None // holder when count is greater than max
  for i in list:
    if i not in count:
      count[i] = 1
    else:
      count[i] += 1
    if count[i] > max:
      max = count[i]
      result = i
  return result

mostCommonElement(["a","b","a","c"]) -> "a"

Principal Component Analysis (PCA) in Python

This will may be the simplest answer one can find for the PCA including easily understandable steps. Let say we want to retain 2 principal dimensions from the 144 which provides maximum information.

Firstly, convert your 2-D array to a dataframe:

import pandas as pd

# Here X is your array of size (26424 x 144)
data = pd.DataFrame(X)

Then, there are two methods one can go with:

Method 1: Manual calculation

Step 1: Apply column standardization on X

from sklearn import preprocessing

scalar = preprocessing.StandardScaler()
standardized_data = scalar.fit_transform(data)

Step 2: Find Co-variance matrix S of original matrix X

sample_data = standardized_data
covar_matrix = np.cov(sample_data)

Step 3: Find eigen values and eigen vectors of S (here 2D, so 2 of each)

from scipy.linalg import eigh

# eigh() function will provide eigen-values and eigen-vectors for a given matrix.
# eigvals=(low value, high value) takes eigen value numbers in ascending order
values, vectors = eigh(covar_matrix, eigvals=(142,143))

# Converting the eigen vectors into (2,d) shape for easyness of further computations
vectors = vectors.T

Step 4: Transform the data

# Projecting the original data sample on the plane formed by two principal eigen vectors by vector-vector multiplication.

new_coordinates = np.matmul(vectors, sample_data.T)
print(new_coordinates.T)

This new_coordinates.T will be of size (26424 x 2) with 2 principal components.

Method 2: Using Scikit-Learn

Step 1: Apply column standardization on X

from sklearn import preprocessing

scalar = preprocessing.StandardScaler()
standardized_data = scalar.fit_transform(data)

Step 2: Initializing the pca

from sklearn import decomposition

# n_components = numbers of dimenstions you want to retain
pca = decomposition.PCA(n_components=2)

Step 3: Using pca to fit the data

# This line takes care of calculating co-variance matrix, eigen values, eigen vectors and multiplying top 2 eigen vectors with data-matrix X.
pca_data = pca.fit_transform(sample_data)

This pca_data will be of size (26424 x 2) with 2 principal components.

How to pass data between fragments

That depends on how the fragment is structured. If you can have some of the methods on the Fragment Class B static and also the target TextView object static, you can call the method directly on Fragment Class A. This is better than a listener as the method is performed instantaneously, and we don't need to have an additional task that performs listening throughout the activity. See example below:

Fragment_class_B.setmyText(String yourstring);

On Fragment B you can have the method defined as:

public static void setmyText(final String string) {
myTextView.setText(string);
}

Just don't forget to have myTextView set as static on Fragment B, and properly import the Fragment B class on Fragment A.

Just did the procedure on my project recently and it worked. Hope that helped.

How do I call Objective-C code from Swift?

See Apple's guide to Using Swift with Cocoa and Objective-C. This guide covers how to use Objective-C and C code from Swift and vice versa and has recommendations for how to convert a project or mix and match Objective-C/C and Swift parts in an existing project.

The compiler automatically generates Swift syntax for calling C functions and Objective-C methods. As seen in the documentation, this Objective-C:

UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];

turns into this Swift code:

let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped)

Xcode also does this translation on the fly — you can use Open Quickly while editing a Swift file and type an Objective-C class name, and it'll take you to a Swift-ified version of the class header. (You can also get this by cmd-clicking on an API symbol in a Swift file.) And all the API reference documentation in the iOS 8 and OS X v10.10 (Yosemite) developer libraries is visible in both Objective-C and Swift forms (e.g. UIView).

Handling identity columns in an "Insert Into TABLE Values()" statement?

You have 2 choices:

1) Either specify the column name list (without the identity column).

2) SET IDENTITY_INSERT tablename ON, followed by insert statements that provide explicit values for the identity column, followed by SET IDENTITY_INSERT tablename OFF.

If you are avoiding a column name list, perhaps this 'trick' might help?:

-- Get a comma separated list of a table's column names
SELECT STUFF(
(SELECT 
',' + COLUMN_NAME AS [text()]
FROM 
INFORMATION_SCHEMA.COLUMNS
WHERE 
TABLE_NAME = 'TableName'
Order By Ordinal_position
FOR XML PATH('')
), 1,1, '')

javax.naming.NoInitialContextException - Java

We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext.

In a standalone application, you can specify that as below

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");

Context ctx = new InitialContext(env);

But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext as below

System.getProperty(Context.PROVIDER_URL);

and

these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work

InitialContext ctx = new InitialContext();

iOS application: how to clear notifications?

Most likely because Notification Center is a relatively new feature, Apple didn't necessarily want to push a whole new paradigm for clearing notifications. So instead, they multi-purposed [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0]; to clear said notifications. It might seem a bit weird, and Apple might provide a more intuitive way to do this in the future, but for the time being it's the official way.

Myself, I use this snippet:

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];

which never fails to clear all of the app's notifications from Notification Center.

How can I select item with class within a DIV?

Try this

$("#mydiv div.myclass")

IsNothing versus Is Nothing

You should absolutely avoid using IsNothing()

Here are 4 reasons from the article IsNothing() VS Is Nothing

  1. Most importantly, IsNothing(object) has everything passed to it as an object, even value types! Since value types cannot be Nothing, it’s a completely wasted check.
    Take the following example:

    Dim i As Integer
    If IsNothing(i) Then
       ' Do something 
    End If
    

    This will compile and run fine, whereas this:

    Dim i As Integer
    If i Is Nothing Then
        '   Do something 
    End If
    

    Will not compile, instead the compiler will raise the error:

    'Is' operator does not accept operands of type 'Integer'.
    Operands must be reference or nullable types.

  2. IsNothing(object) is actually part of part of the Microsoft.VisualBasic.dll.
    This is undesirable as you have an unneeded dependency on the VisualBasic library.

  3. Its slow - 33.76% slower in fact (over 1000000000 iterations)!

  4. Perhaps personal preference, but IsNothing() reads like a Yoda Condition. When you look at a variable you're checking it's state, with it as the subject of your investigation.

    i.e. does it do x? --- NOT Is xing a property of it?

    So I think If a IsNot Nothing reads better than If Not IsNothing(a)

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

I just killed the Oracle processes and re-initiate JBoss. All was fine :)

How can I make my match non greedy in vim?

Plugin eregex.vim handles Perl-style non-greedy operators *? and +?

Parsing JSON using C

Do you need to parse arbitrary JSON structures, or just data that's specific to your application. If the latter, you can make it a lot lighter and more efficient by not having to generate any hash table/map structure mapping JSON keys to values; you can instead just store the data directly into struct fields or whatever.

Getting around the Max String size in a vba function?

Excel only shows 255 characters but in fact if more than 255 characters are saved, to see the complete string, consult it in the immediate window

Press Crl + G and type ?RunWhat in the immediate window and press Enter

How to import data from text file to mysql database

It should be as simple as...

LOAD DATA INFILE '/tmp/mydata.txt' INTO TABLE PerformanceReport;

By default LOAD DATA INFILE uses tab delimited, one row per line, so should take it in just fine.

Twitter Bootstrap 3: How to center a block

It's new in the Bootstrap 3.0.1 release, so make sure you have the latest (10/29)...

Demo: http://bootply.com/91632

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
    <div class="center-block" style="width:200px;background-color:#ccc;">...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fill DataTable from SQL Server database

Try with following:

public DataTable fillDataTable(string table)
    {
        string query = "SELECT * FROM dstut.dbo." +table;

        SqlConnection sqlConn = new SqlConnection(conSTR);
        sqlConn.Open();
        SqlCommand cmd = new SqlCommand(query, sqlConn);
        SqlDataAdapter da=new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        sqlConn.Close();
        return dt;
    }

Hope it is helpful.

Visualizing branch topology in Git

Use git log --graph or gitk. (Both also accept --all, which will show all the branches instead of just the current one.)

For branch names and a compact view, try:

git log --graph --decorate --oneline