Programs & Examples On #System.reflection

System.Reflection is a namespace of the .NET framework. It contains types that retrieve information about assemblies, modules, members, parameters, and other entities in managed code by examining their metadata.

Simple InputBox function

It would be something like this

function CustomInputBox([string] $title, [string] $message, [string] $defaultText) 
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript" 
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" ) 
$_userInput = $inputObject.eval("getInput") 

return $_userInput
}

Then you can call the function similar to this.

$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null ) 
{
 echo "Input was [$userInput]"
}
else
{
 echo "User cancelled the form!"
}

This is the most simple way to do this that I can think of.

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

if you're working with some kind of subversion: delete the project and re-download it, it worked for me :S

How to properly set Column Width upon creating Excel file? (Column properties)

I have change all columns width in my case as

            worksheet.Columns[1].ColumnWidth = 7;
            worksheet.Columns[2].ColumnWidth = 15;
            worksheet.Columns[3].ColumnWidth = 15;
            worksheet.Columns[4].ColumnWidth = 15;
            worksheet.Columns[5].ColumnWidth = 18;
            worksheet.Columns[6].ColumnWidth = 8;
            worksheet.Columns[7].ColumnWidth = 13;
            worksheet.Columns[8].ColumnWidth = 17;
            worksheet.Columns[9].ColumnWidth = 17;

Note: Columns in worksheet start with 1 not from 0 as in Arrary.

Exception of type 'System.OutOfMemoryException' was thrown.

If you're using IIS Express, select Show All Application from IIS Express in the task bar notification area, then select Stop All.

Now re-run your application.

Loading DLLs at runtime in C#

You need to create an instance of the type that expose the Output method:

static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var class1Type = DLL.GetType("DLL.Class1");

        //Now you can use reflection or dynamic to call the method. I will show you the dynamic way

        dynamic c = Activator.CreateInstance(class1Type);
        c.Output(@"Hello");

        Console.ReadLine();
     }

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

How to Bold entire row 10 example:

workSheet.Cells[10, 1].EntireRow.Font.Bold = true;    

More formally:

Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[10, 1] as Xl.Range;
rng.EntireRow.Font.Bold = true;

How to Bold Specific Cell 'A10' for example:

workSheet.Cells[10, 1].Font.Bold = true;

Little more formal:

int row = 1;
int column = 1;  /// 1 = 'A' in Excel

Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[row, column] as Xl.Range;
rng.Font.Bold = true;

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

In my case, it was Blend SDK missed out on TeamCity machine. This caused the error due incorrect way of assembly resolving then.

Non-static method requires a target

I face this error on testing WebAPI in Postman tool.

After building the code, If we remove any line (For Example: In my case when I remove one Commented line this error was occur...) in debugging mode then the "Non-static method requires a target" error will occur.

Again, I tried to send the same request. This time code working properly. And I get the response properly in Postman.

I hope it will use to someone...

Exception from HRESULT: 0x800A03EC Error

Adding one more possible issue causing this: the formula was wrong because I was using the wrong list separator according to my locale. Using CultureInfo.CurrentCulture.TextInfo.ListSeparator; corrected the issue.

Note that the exception was thrown on the following line of code...

The module was expected to contain an assembly manifest

Check if the manifest is a valid xml file. I had the same problem by doing a DOS copy command at the end of the build, and it turns out that for some reason I can not understand "copy" was adding a strange character (->) at the end of the manifest files. The problem was solved by adding "/b" switch to force binary copy.

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

The event is probably raised before the elements are fully loaded or the references are still unset, hence the exceptions. Try only setting properties if the reference is not null and IsLoaded is true.

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();

Extension methods must be defined in a non-generic static class

if you do not intend to have static functions just get rid of the "this" keyword in the arguments.

Best way to get application folder path

Root directory:

DriveInfo cDrive = new DriveInfo(System.Environment.CurrentDirectory);
var driverPath = cDrive.RootDirectory;

Getting assembly name

You can use the AssemblyName class to get the assembly name, provided you have the full name for the assembly:

AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().FullName).Name

or

AssemblyName.GetAssemblyName(e.Source).Name

MSDN Reference - AssemblyName Class

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

Could not load file or assembly 'System.Data.SQLite'

Manual load related System.Data.SQLite assembly can resolve this.

Changed gatapia's Code as below:

    public static void LoadSQLLiteAssembly()
    {
        Uri dir = new Uri(Assembly.GetExecutingAssembly().CodeBase);
        FileInfo fi = new FileInfo(dir.AbsolutePath);
        string appropriateFile = Path.Combine(fi.Directory.FullName, GetAppropriateSQLLiteAssembly());
        Assembly.LoadFrom(appropriateFile);
    }

    private static string GetAppropriateSQLLiteAssembly()
    {
        string pa = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
        string arch = ((String.IsNullOrEmpty(pa) || String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? "32" : "64");
        return "System.Data.SQLite.x" + arch + ".DLL";
    }

XmlSerializer giving FileNotFoundException at constructor

Like Martin Sherburn said, this is normal behavior. The constructor of the XmlSerializer first tries to find an assembly named [YourAssembly].XmlSerializers.dll which should contain the generated class for serialization of your type. Since such a DLL has not been generated yet (they are not by default), a FileNotFoundException is thrown. When that happenes, XmlSerializer's constructor catches that exception, and the DLL is generated automatically at runtime by the XmlSerializer's constructor (this is done by generating C# source files in the %temp% directory of your computer, then compiling them using the C# compiler). Additional constructions of an XmlSerializer for the same type will just use the already generated DLL.

UPDATE: Starting from .NET 4.5, XmlSerializer no longer performs code generation nor does it perform compilation with the C# compiler in order to create a serializer assembly at runtime, unless explicitly forced to by setting a configuration file setting (useLegacySerializerGeneration). This change removes the dependency on csc.exe and improves startup performance. Source: .NET Framework 4.5 Readme, section 1.3.8.1.

The exception is handled by XmlSerializer's constructor. There is no need to do anything yourself, you can just click 'Continue' (F5) to continue executing your program and everything will be fine. If you're bothered by the exceptions stopping the execution of your program and popping up an exception helper, you either have 'Just My Code' turned off, or you have the FileNotFoundException set to break execution when thrown, instead of when 'User-unhandled'.

To enable 'Just My Code', go to Tools >> Options >> Debugging >> General >> Enable Just My Code. To turn off breaking of execution when FileNotFound is thrown, go to Debug >> Exceptions >> Find >> enter 'FileNotFoundException' >> untick the 'Thrown' checkbox from System.IO.FileNotFoundException.

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

I had an issue with automap. In the bin folder, the file automap.4net.dll was there, but for some reason the automap.xml and automap.dll weren't. Copying them to the bin directory solved the issue.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

If you can copy the whole exception it would be much more better, but once I faced with this Exception and this is because the function calling from your dll file which I guess is Aspose.dll hasn't been signed well. I think it would be the possible duplicate of this

FYI, in order to find out if your dll hasn't been signed well you should right-click on that and go to the signiture and it will tell you if it has been electronically signed well or not.

How can I find the method that called the current method?

Obviously this is a late answer, but I have a better option if you can use .NET 4.5 or newer:

internal static void WriteInformation<T>(string text, [CallerMemberName]string method = "")
{
    Console.WriteLine(DateTime.Now.ToString() + " => " + typeof(T).FullName + "." + method + ": " + text);
}

This will print the current Date and Time, followed by "Namespace.ClassName.MethodName" and ending with ": text".
Sample output:

6/17/2016 12:41:49 PM => WpfApplication.MainWindow..ctor: MainWindow initialized

Sample use:

Logger.WriteInformation<MainWindow>("MainWindow initialized");

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyVersion pretty much stays internal to .NET, while AssemblyFileVersion is what Windows sees. If you go to the properties of an assembly sitting in a directory and switch to the version tab, the AssemblyFileVersion is what you'll see up top. If you sort files by version, this is what's used by Explorer.

The AssemblyInformationalVersion maps to the "Product Version" and is meant to be purely "human-used".

AssemblyVersion is certainly the most important, but I wouldn't skip AssemblyFileVersion, either. If you don't provide AssemblyInformationalVersion, the compiler adds it for you by stripping off the "revision" piece of your version number and leaving the major.minor.build.

How do I get the path of the assembly the code is in?

The only solution that worked for me when using CodeBase and UNC Network shares was:

System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);

It also works with normal URIs too.

Non-static variable cannot be referenced from a static context

  • The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.

  • Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class

  • As a corollary to the above

    1. variables within a method can not be static
    2. static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
  • The lifetime of a static field/method is equivalent to the lifetime of your application

E.g. Say, car has the property colour, and exhibits the behaviour 'motion'. An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.

Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.

HTH

Uncaught TypeError: .indexOf is not a function

I ran across this error recently using a javascript library which changes the parameters of a function based on conditions.

You can test an object to see if it has the function. I would only do this in scenarios where you don't control what is getting passed to you.

if( param.indexOf != undefined ) {
   // we have a string or other object that 
   // happens to have a function named indexOf
}

You can test this in your browser console:

> (3).indexOf == undefined;
true

> "".indexOf == undefined;
false

How can I show/hide component with JSF?

Use the "rendered" attribute available on most if not all tags in the h-namespace.

<h:outputText value="Hi George" rendered="#{Person.name == 'George'}" />

UIView bottom border?

Swift 4 extension with border width and color. Works great!

@IBDesignable
final class SideBorders: UIView {
@IBInspectable var topColor: UIColor = UIColor.clear
@IBInspectable var topWidth: CGFloat = 0

@IBInspectable var rightColor: UIColor = UIColor.clear
@IBInspectable var rightWidth: CGFloat = 0

@IBInspectable var bottomColor: UIColor = UIColor.clear
@IBInspectable var bottomWidth: CGFloat = 0

@IBInspectable var leftColor: UIColor = UIColor.clear
@IBInspectable var leftWidth: CGFloat = 0

override func draw(_ rect: CGRect) {
    let topBorder = CALayer()
    topBorder.backgroundColor = topColor.cgColor
    topBorder.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: topWidth)
    self.layer.addSublayer(topBorder)

    let rightBorder = CALayer()
    rightBorder.backgroundColor = rightColor.cgColor
    rightBorder.frame = CGRect(x: self.frame.size.width - rightWidth, y: 0, width: rightWidth, height: self.frame.size.height)
    self.layer.addSublayer(rightBorder)

    let bottomBorder = CALayer()
    bottomBorder.backgroundColor = bottomColor.cgColor
    bottomBorder.frame = CGRect(x: 0, y: self.frame.size.height - bottomWidth, width: self.frame.size.width, height: bottomWidth)
    self.layer.addSublayer(bottomBorder)

    let leftBorder = CALayer()
    leftBorder.backgroundColor = leftColor.cgColor
    leftBorder.frame = CGRect(x: 0, y: self.frame.size.height - leftWidth, width: self.frame.size.width, height: leftWidth)
    self.layer.addSublayer(leftBorder)
}

}

Limiting number of displayed results when using ngRepeat

Another (and I think better) way to achieve this is to actually intercept the data. limitTo is okay but what if you're limiting to 10 when your array actually contains thousands?

When calling my service I simply did this:

TaskService.getTasks(function(data){
    $scope.tasks = data.slice(0,10);
});

This limits what is sent to the view, so should be much better for performance than doing this on the front-end.

Import/Index a JSON file into Elasticsearch

I just made sure that I am in the same directory as the json file and then simply ran this

curl -s -H "Content-Type: application/json" -XPOST localhost:9200/product/default/_bulk?pretty --data-binary @product.json

So if you too make sure you are at the same directory and run it this way. Note: product/default/ in the command is something specific to my environment. you can omit it or replace it with whatever is relevant to you.

How can I exclude $(this) from a jQuery selector?

You can also use the jQuery .siblings() method:

HTML

<div class="content">
  <a href="#">A</a>
  <a href="#">B</a>
  <a href="#">C</a>
</div>

Javascript

$(".content").on('click', 'a', function(e) {
  e.preventDefault();
  $(this).siblings().hide('slow');
});

Working demo: http://jsfiddle.net/wTm5f/

HTML5 Canvas Rotate Image

This is the simplest code to draw a rotated and scaled image:

function drawImage(ctx, image, x, y, w, h, degrees){
  ctx.save();
  ctx.translate(x+w/2, y+h/2);
  ctx.rotate(degrees*Math.PI/180.0);
  ctx.translate(-x-w/2, -y-h/2);
  ctx.drawImage(image, x, y, w, h);
  ctx.restore();
}

Best way to do a PHP switch with multiple values per case?

Nowadays you can do...

switch ([$group1, $group2]){
    case ["users", "location"]:
    case ["users", "online"]:
        Ju_le_do_the_thing();
        break;
    case ["forum", $group2]:
        Foo_the_bar();
        break;
}

List<T> OrderBy Alphabetical Order

people.OrderBy(person => person.lastname).ToList();

How to add fonts to create-react-app based projects?

I was making mistakes like this.

@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i&amp;subset=cyrillic,cyrillic-ext,latin-ext";
@import "https://use.fontawesome.com/releases/v5.3.1/css/all.css";

It works properly this way

@import url(https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i&amp;subset=cyrillic,cyrillic-ext,latin-ext);
@import url(https://use.fontawesome.com/releases/v5.3.1/css/all.css);

How to install latest version of git on CentOS 7.x/6.x

To build and install modern Git on CentOS 6:

yum install -y curl-devel expat-devel gettext-devel openssl-devel zlib-devel gcc perl-ExtUtils-MakeMaker
export GIT_VERSION=2.6.4
mkdir /root/git
cd /root/git
wget "https://www.kernel.org/pub/software/scm/git/git-${GIT_VERSION}.tar.gz"
tar xvzf "git-${GIT_VERSION}.tar.gz"
cd git-${GIT_VERSION}
make prefix=/usr/local all
make prefix=/usr/local install
yum remove -y git
git --version # should be GIT_VERSION

Pull request vs Merge request

GitLab's "merge request" feature is equivalent to GitHub's "pull request" feature. Both are means of pulling changes from another branch or fork into your branch and merging the changes with your existing code. They are useful tools for code review and change management.

An article from GitLab discusses the differences in naming the feature:

Merge or pull requests are created in a git management application and ask an assigned person to merge two branches. Tools such as GitHub and Bitbucket choose the name pull request since the first manual action would be to pull the feature branch. Tools such as GitLab and Gitorious choose the name merge request since that is the final action that is requested of the assignee. In this article we'll refer to them as merge requests.

A "merge request" should not be confused with the git merge command. Neither should a "pull request" be confused with the git pull command. Both git commands are used behind the scenes in both pull requests and merge requests, but a merge/pull request refers to a much broader topic than just these two commands.

Where can I get a list of Ansible pre-defined variables?

Note the official docs on connection configuration variables or "behavioral" variables - which aren't listed in host vars, appears to be List of Behavioral Inventory Parameters in the Inventory documentation.

P.S. The sudo option is undocumented there (yes its sudo not ansible_sudo as you'd expect ...) and probably a couple more aren't, but thats best doc I've found on em.

How to perform a sum of an int[] array

Once is out (March 2014) you'll be able to use streams:

int sum = IntStream.of(a).sum();

or even

int sum = IntStream.of(a).parallel().sum();

Convert Unix timestamp into human readable date using MySQL

Since I found this question not being aware, that mysql always stores time in timestamp fields in UTC but will display (e.g. phpmyadmin) in local time zone I would like to add my findings.

I have an automatically updated last_modified field, defined as:

`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Looking at it with phpmyadmin, it looks like it is in local time, internally it is UTC

SET time_zone = '+04:00'; // or '+00:00' to display dates in UTC or 'UTC' if time zones are installed.
SELECT last_modified, UNIX_TIMESTAMP(last_modified), from_unixtime(UNIX_TIMESTAMP(last_modified), '%Y-%c-%d %H:%i:%s'), CONVERT_TZ(last_modified,@@session.time_zone,'+00:00') as UTC FROM `table_name`

In any constellation, UNIX_TIMESTAMP and 'as UTC' are always displayed in UTC time.

Run this twice, first without setting the time_zone.

setAttribute('display','none') not working

Try this:

setAttribute("hidden", true);

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

Deep copy in ES6 using the spread syntax

function deepclone(obj) {
    let newObj = {};

    if (typeof obj === 'object') {
        for (let key in obj) {
            let property = obj[key],
                type = typeof property;
            switch (type) {
                case 'object':
                    if( Object.prototype.toString.call( property ) === '[object Array]' ) {
                        newObj[key] = [];
                        for (let item of property) {
                            newObj[key].push(this.deepclone(item))
                        }
                    } else {
                        newObj[key] = deepclone(property);
                    }
                    break;
                default:
                    newObj[key] = property;
                    break;

            }
        }
        return newObj
    } else {
        return obj;
    }
}

How to run C program on Mac OS X using Terminal?

Answer is chmod 755 hello - it makes file executable... It is funny, so no-one answered it. I had same problem on MacOS, which is now solved.

nano hello.c make hello chmod 755 hello Then you run it by ./hello

clang --version Apple LLVM version 8.0.0 (clang-800.0.42.1) Target: x86_64-apple-darwin15.6.0

nothing was installed, nano make (clang) chmod - all inside MacOS already

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

I accidentally removed and then unpack back folder from where I tried to install pod.
It was like this: 1) cd in your project folder 2) zip your project 3) remove project folder 4) unzip folder back 5) from now even you have this folder you should go to this folder again from the terminal

jquery equivalent for JSON.stringify

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

Getting String value from enum in Java

You can use values() method:

For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.

inline conditionals in angular.js

For checking a variable content and have a default text, you can use:

<span>{{myVar || 'Text'}}</span>

What is the difference between WCF and WPF?

WCF = Windows COMMUNICATION Foundation

WPF = Windows PRESENTATION Foundation.

WCF deals with communication (in simple terms - sending and receiving data as well as formatting and serialization involved), WPF deals with presentation (UI)

Should I use the Reply-To header when sending emails as a service to others?

I tested dkarp's solution with gmail and it was filtered to spam. Use the Reply-To header instead (or in addition, although gmail apparently doesn't need it). Here's how linkedin does it:

Sender: [email protected]
From: John Doe via LinkedIn <[email protected]>
Reply-To: John Doe <[email protected]>
To: My Name <[email protected]>

Once I switched to this format, gmail is no longer filtering my messages as spam.

How to find the parent element using javascript

Using plain javascript:

element.parentNode

In jQuery:

element.parent()

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

Best way to get child nodes

Don't let white space fool you. Just test this in a console browser.

Use native javascript. Here is and example with two 'ul' sets with the same class. You don't need to have your 'ul' list all in one line to avoid white space just use your array count to jump over white space.

How to get around white space with querySelector() then childNodes[] js fiddle link: https://jsfiddle.net/aparadise/56njekdo/

var y = document.querySelector('.list');
var myNode = y.childNodes[11].style.backgroundColor='red';

<ul class="list">
    <li>8</li>
    <li>9</li>
    <li>100</li>
</ul>

<ul class="list">
    <li>ABC</li>
    <li>DEF</li>
    <li>XYZ</li>
</ul>

What's the difference between subprocess Popen and call (how can I use them)?

There are two ways to do the redirect. Both apply to either subprocess.Popen or subprocess.call.

  1. Set the keyword argument shell = True or executable = /path/to/the/shell and specify the command just as you have it there.

  2. Since you're just redirecting the output to a file, set the keyword argument

    stdout = an_open_writeable_file_object
    

    where the object points to the output file.

subprocess.Popen is more general than subprocess.call.

Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

call does block. While it supports all the same arguments as the Popen constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call returns a code representing the process' exit status.

returncode = call(*args, **kwargs) 

is basically the same as calling

returncode = Popen(*args, **kwargs).wait()

call is just a convenience function. It's implementation in CPython is in subprocess.py:

def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

As you can see, it's a thin wrapper around Popen.

How to preview git-pull without doing fetch?

What about cloning the repo elsewhere, and doing git log on both the real checkout and the fresh clone to see if you got the same thing.

How do I select an element with its name attribute in jQuery?

$('[name="ElementNameHere"]').doStuff();

jQuery supports CSS3 style selectors, plus some more.

See more

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I used an approach described by Eric Daugherty: I created a special servlet that always answers with 403 code and put its mapping before the general one.

Mapping fragment:

  <servlet>
    <servlet-name>generalServlet</servlet-name>
    <servlet-class>project.servlet.GeneralServlet</servlet-class>
  </servlet>
 <servlet>
    <servlet-name>specialServlet</servlet-name>
    <servlet-class>project.servlet.SpecialServlet</servlet-class>
 </servlet>
 <servlet-mapping>
    <servlet-name>specialServlet</servlet-name>
    <url-pattern>/resources/restricted/*</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
    <servlet-name>generalServlet</servlet-name>
    <url-pattern>/resources/*</url-pattern>
 </servlet-mapping>

And the servlet class:

public class SpecialServlet extends HttpServlet {
    public SpecialServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}

Can you center a Button in RelativeLayout?

Summarized

Adding:

android:layout_centerInParent="true"

just works on RelativeLayout, if one of the following attributes is also set for the view:

android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"

which alignes the child view to the parent view. The "center" is based on the axis of the alignement you have chosen:

left/right -> vertical

top/bottom -> horizontal

Setting the gravity of childs/content inside the view:

android:gravity="center"

is centering the child inside the parent view in any case, if there is no alignment set. Optional you can choose:

<!-- Axis to Center -->
android:gravity="center_horizontal"
android:gravity="center_vertical"

<!-- Alignment to set-->
android:gravity="top"
android:gravity="bottom"
android:gravity="left"
android:gravity="right"
android:gravity="fill"
...

Then there is:

android:layout_gravity="center"

which is centering the view itself inside it's parent

And at last you can add the following attribute to the parents view:

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

How to run specific test cases in GoogleTest

You could use advanced options to run Google tests.

To run only some unit tests you could use --gtest_filter=Test_Cases1* command line option with value that accepts the * and ? wildcards for matching with multiple tests. I think it will solve your problem.

UPD:

Well, the question was how to run specific test cases. Integration of gtest with your GUI is another thing, which I can't really comment, because you didn't provide details of your approach. However I believe the following approach might be a good start:

  1. Get all testcases by running tests with --gtest_list_tests
  2. Parse this data into your GUI
  3. Select test cases you want ro run
  4. Run test executable with option --gtest_filter

How do I print output in new line in PL/SQL?

Pass the string and replace space with line break, it gives you desired result.

select replace('shailendra kumar',' ',chr(10)) from dual;

Append data frames together in a for loop

You should try this:

df_total = data.frame()
for (i in 1:7){
    # vector output
    model <- #some processing

    # add vector to a dataframe
    df <- data.frame(model)
    df_total <- rbind(df_total,df)
}

How to deserialize a JObject to .NET object

From the documentation I found this

JObject o = new JObject(
   new JProperty("Name", "John Smith"),
   new JProperty("BirthDate", new DateTime(1983, 3, 20))
);

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

Console.WriteLine(p.Name);

The class definition for Person should be compatible to the following:

class Person {
    public string Name { get; internal set; }
    public DateTime BirthDate { get; internal set; }
}

Edit

If you are using a recent version of JSON.net and don't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.

Enabling CORS in Cloud Functions for Firebase

One additional piece of info, just for the sake of those googling this after some time: If you are using firebase hosting, you can also set up rewrites, so that for example a url like (firebase_hosting_host)/api/myfunction redirects to the (firebase_cloudfunctions_host)/doStuff function. That way, since the redirection is transparent and server-side, you don't have to deal with cors.

You can set that up with a rewrites section in firebase.json:

"rewrites": [
        { "source": "/api/myFunction", "function": "doStuff" }
]

javascript clear field value input

do like

<input name="name" id="name" type="text" value="Name" 
   onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>

and js

function fillField(input,val) {
      if(input.value == "")
         input.value=val;
};

function clearField(input,val) {
      if(input.value == val)
         input.value="";
};

update

here is a demo fiddle of the same

.NET / C# - Convert char[] to string

Another alternative

char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );

Debug.Assert( s.Equals( "Rock-&-Roll" ) );

struct in class

You should define the struct out of the class like this:

#include <iostream>
using namespace std;
struct X
{
        int v;
};
class E
{
public: 
      X var;
};

int main(){

E object;
object.var.v=10; 

return 0;
}

C library function to perform sort

Use qsort() in <stdlib.h>.

@paxdiablo The qsort() function conforms to ISO/IEC 9899:1990 (``ISO C90'').

Where does PostgreSQL store the database?

I'd bet you're asking this question because you've tried pg_ctl start and received the following error:

pg_ctl: no database directory specified and environment variable PGDATA unset

In other words, you're looking for the directory to put after -D in your pg_ctl start command.

In this case, the directory you're looking for contains these files.

PG_VERSION      pg_dynshmem     pg_multixact
pg_snapshots    pg_tblspc       postgresql.conf
base            pg_hba.conf     pg_notify   
pg_stat         pg_twophase     postmaster.opts
global          pg_ident.conf   pg_replslot
pg_stat_tmp     pg_xlog         postmaster.pid
pg_clog         pg_logical      pg_serial
pg_subtrans     postgresql.auto.conf    server.log

You can locate it by locating any of the files and directories above using the search provided with your OS.

For example in my case (a HomeBrew install on Mac OS X), these files are located in /usr/local/var/postgres. To start the server I type:

pg_ctl -D /usr/local/var/postgres -w start

... and it works.

Adding IN clause List to a JPA Query

public List<DealInfo> getDealInfos(List<String> dealIds) {
        String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
        TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
        query.setParameter("inclList", dealIds);
        return query.getResultList();
    }

Works for me with JPA 2, Jboss 7.0.2

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Correct Method is

.PopupPanel
{
    border: solid 1px black;
    position: fixed;
    left: 50%;
    top: 50%;
    background-color: white;
    z-index: 100;
    height: 400px;
    margin-top: -200px;

    width: 600px;
    margin-left: -300px;
}

Java synchronized method lock on object, or method?

This example (although not pretty one) can provide more insight into locking mechanism. If incrementA is synchronized, and incrementB is not synchronized, then incrementB will be executed ASAP, but if incrementB is also synchronized then it has to 'wait' for incrementA to finish, before incrementB can do its job.

Both methods are called onto single instance - object, in this example it is: job, and 'competing' threads are aThread and main.

Try with 'synchronized' in incrementB and without it and you will see different results.If incrementB is 'synchronized' as well then it has to wait for incrementA() to finish. Run several times each variant.

class LockTest implements Runnable {
    int a = 0;
    int b = 0;

    public synchronized void incrementA() {
        for (int i = 0; i < 100; i++) {
            this.a++;
            System.out.println("Thread: " + Thread.currentThread().getName() + "; a: " + this.a);
        }
    }

    // Try with 'synchronized' and without it and you will see different results
    // if incrementB is 'synchronized' as well then it has to wait for incrementA() to finish

    // public void incrementB() {
    public synchronized void incrementB() {
        this.b++;
        System.out.println("*************** incrementB ********************");
        System.out.println("Thread: " + Thread.currentThread().getName() + "; b: " + this.b);
        System.out.println("*************** incrementB ********************");
    }

    @Override
    public void run() {
        incrementA();
        System.out.println("************ incrementA completed *************");
    }
}

class LockTestMain {
    public static void main(String[] args) throws InterruptedException {
        LockTest job = new LockTest();
        Thread aThread = new Thread(job);
        aThread.setName("aThread");
        aThread.start();
        Thread.sleep(1);
        System.out.println("*************** 'main' calling metod: incrementB **********************");
        job.incrementB();
    }
}

How to remove the URL from the printing page?

On Chrome 57 the following worked for me, if you have control of the HTML page that needs to be printed (in my case I needed to print a small 3x1 inch label):

  • remove the HTML title element from header (either temporarily using jquery or permanently if that page does not really need a title)
  • set the @page margin to 0 as mentioned by @Chamika Sandamal

This resulted in printing a page that only contained the body text, no URLs, no page #s etc.

A free tool to check C/C++ source code against a set of coding standards?

Try nsiqcppstyle. It's a Python based coding style checker for C/C++. It's easy to extend to add your own rules.

Circular (or cyclic) imports in Python

There are a lot of great answers here. While there are usually quick solutions to the problem, some of which feel more pythonic than others, if you have the luxury of doing some refactoring, another approach is to analyze the organization of your code, and try to remove the circular dependency. You may find, for example, that you have:

File a.py

from b import B

class A:
    @staticmethod
    def save_result(result):
        print('save the result')

    @staticmethod
    def do_something_a_ish(param):
        A.save_result(A.use_param_like_a_would(param))

    @staticmethod
    def do_something_related_to_b(param):
        B.do_something_b_ish(param)

File b.py

from a import A

class B:
    @staticmethod
    def do_something_b_ish(param):
        A.save_result(B.use_param_like_b_would(param))

In this case, just moving one static method to a separate file, say c.py:

File c.py

def save_result(result):
    print('save the result')

will allow removing the save_result method from A, and thus allow removing the import of A from a in b:

Refactored File a.py

from b import B
from c import save_result

class A:
    @staticmethod
    def do_something_a_ish(param):
        A.save_result(A.use_param_like_a_would(param))

    @staticmethod
    def do_something_related_to_b(param):
        B.do_something_b_ish(param)

Refactored File b.py

from c import save_result

class B:
    @staticmethod
    def do_something_b_ish(param):
        save_result(B.use_param_like_b_would(param))

In summary, if you have a tool (e.g. pylint or PyCharm) that reports on methods that can be static, just throwing a staticmethod decorator on them might not be the best way to silence the warning. Even though the method seems related to the class, it might be better to separate it out, especially if you have several closely related modules that might need the same functionality and you intend to practice DRY principles.

How do I get the time of day in javascript/Node.js?

Check out the moment.js library. It works with browsers as well as with Node.JS. Allows you to write

moment().hour();

or

moment().hours();

without prior writing of any functions.

Big-oh vs big-theta

I'm a mathematician and I have seen and needed big-O O(n), big-Theta T(n), and big-Omega O(n) notation time and again, and not just for complexity of algorithms. As people said, big-Theta is a two-sided bound. Strictly speaking, you should use it when you want to explain that that is how well an algorithm can do, and that either that algorithm can't do better or that no algorithm can do better. For instance, if you say "Sorting requires T(n(log n)) comparisons for worst-case input", then you're explaining that there is a sorting algorithm that uses O(n(log n)) comparisons for any input; and that for every sorting algorithm, there is an input that forces it to make O(n(log n)) comparisons.

Now, one narrow reason that people use O instead of O is to drop disclaimers about worst or average cases. If you say "sorting requires O(n(log n)) comparisons", then the statement still holds true for favorable input. Another narrow reason is that even if one algorithm to do X takes time T(f(n)), another algorithm might do better, so you can only say that the complexity of X itself is O(f(n)).

However, there is a broader reason that people informally use O. At a human level, it's a pain to always make two-sided statements when the converse side is "obvious" from context. Since I'm a mathematician, I would ideally always be careful to say "I will take an umbrella if and only if it rains" or "I can juggle 4 balls but not 5", instead of "I will take an umbrella if it rains" or "I can juggle 4 balls". But the other halves of such statements are often obviously intended or obviously not intended. It's just human nature to be sloppy about the obvious. It's confusing to split hairs.

Unfortunately, in a rigorous area such as math or theory of algorithms, it's also confusing not to split hairs. People will inevitably say O when they should have said O or T. Skipping details because they're "obvious" always leads to misunderstandings. There is no solution for that.

Creating a DateTime in a specific Time Zone in c#

Using TimeZones class makes it easy to create timezone specific date.

TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(TimeZones.Paris.Id));

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

UITableViewCell Selected Background Color on Multiple Selection

Swift 3

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
     selectedCell.contentView.backgroundColor = UIColor.darkGray
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
     let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
     selectedCell.contentView.backgroundColor = UIColor.clear
}

Convert String[] to comma separated string in java

StringBuilder sb = new StringBuilder();
for (String n : name) { 
    if (sb.length() > 0) sb.append(',');
    sb.append("'").append(n).append("'");
}
return sb.toString();

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

For iOS greater than or equal to 8

Under the target's General tab, in the Embedded Binaries section add the framework. This will copy the framework into the compiled so that it can be linked to at runtime.

enter image description here

Why is this happening? : because the framework you are linking to is compiled as a dynamically linked framework and thus is linked to at runtime.

** Note:** Embedding custom frameworks is only supported in iOS > 8 and thus an alternative solution that works on older versions of iOS follows.

For iOS less than 8

If you influence this framework (have access to the source code/build process) you may change this framework to be statically linked rather than dynamically linked. This will cause the code to be included in your compiled app rather than linked to at runtime and thus the framework will not have to be embedded.

** How:** Under the framework's Build Setting tab, in the Linking section, change the Mach-O Type to Static Library. You should now not need to include the framework under embedded binaries.

Static Framework

Including Assets: To include things such as images, audio, or xib/nib files I recommend creating a bundle (essentially a directory, more info here bit.ly/ios_bundle) and then load the assets from the bundle using NSBundle.

How to initialize std::vector from C-style array?

Don't forget that you can treat pointers as iterators:

w_.assign(w, w + len);

Where do I find some good examples for DDD?

.NET DDD Sample from Domain-Driven Design Book by Eric Evans can be found here: http://dddsamplenet.codeplex.com

Cheers,

Jakub G

How can we programmatically detect which iOS version is device running on?

Update

From iOS 8 we can use the new isOperatingSystemAtLeastVersion method on NSProcessInfo

   NSOperatingSystemVersion ios8_0_1 = (NSOperatingSystemVersion){8, 0, 1};
   if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:ios8_0_1]) {
      // iOS 8.0.1 and above logic
   } else {
      // iOS 8.0.0 and below logic
   }

Beware that this will crash on iOS 7, as the API didn't exist prior to iOS 8. If you're supporting iOS 7 and below, you can safely perform the check with

if ([NSProcessInfo instancesRespondToSelector:@selector(isOperatingSystemAtLeastVersion:)]) {
  // conditionally check for any version >= iOS 8 using 'isOperatingSystemAtLeastVersion'
} else {
  // we're on iOS 7 or below
}

Original answer iOS < 8

For the sake of completeness, here's an alternative approach proposed by Apple itself in the iOS 7 UI Transition Guide, which involves checking the Foundation Framework version.

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
   // Load resources for iOS 6.1 or earlier
} else {
   // Load resources for iOS 7 or later
}

Reliable way for a Bash script to get the full path to itself

Try this:

cd $(dirname $([ -L $0 ] && readlink -f $0 || echo $0))

Correct way to write line to file?

If you are writing a lot of data and speed is a concern you should probably go with f.write(...). I did a quick speed comparison and it was considerably faster than print(..., file=f) when performing a large number of writes.

import time    

start = start = time.time()
with open("test.txt", 'w') as f:
    for i in range(10000000):
        # print('This is a speed test', file=f)
        # f.write('This is a speed test\n')
end = time.time()
print(end - start)

On average write finished in 2.45s on my machine, whereas print took about 4 times as long (9.76s). That being said, in most real-world scenarios this will not be an issue.

If you choose to go with print(..., file=f) you will probably find that you'll want to suppress the newline from time to time, or replace it with something else. This can be done by setting the optional end parameter, e.g.;

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)

Whichever way you choose I'd suggest using with since it makes the code much easier to read.

Update: This difference in performance is explained by the fact that write is highly buffered and returns before any writes to disk actually take place (see this answer), whereas print (probably) uses line buffering. A simple test for this would be to check performance for long writes as well, where the disadvantages (in terms of speed) for line buffering would be less pronounced.

start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")

The performance difference now becomes much less pronounced, with an average time of 2.20s for write and 3.10s for print. If you need to concatenate a bunch of strings to get this loooong line performance will suffer, so use-cases where print would be more efficient are a bit rare.

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:

Returned identity values not always correct

.bashrc: Permission denied

.bashrc is not meant to be executed but sourced. Try this instead:

. ~/.bashrc

Cheers!

IE6/IE7 css border on select element

To do a border along one side of a select in IE use IE's filters:

select.required { border-left:2px solid red; filter: progid:DXImageTransform.Microsoft.dropshadow(OffX=-2, OffY=0,color=#FF0000) }

I put a border on one side only of all my inputs for required status.

There is probably an effects that do a better job for an all-round border ...

http://msdn.microsoft.com/en-us/library/ms532853(v=VS.85).aspx

Get today date in google appScript

The Date object is used to work with dates and times.

Date objects are created with new Date()

var now = new Date();

now - Current date and time object.

function changeDate() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
    var date = new Date();
    sheet.getRange(5, 2).setValue(date); 
}

Fatal Error :1:1: Content is not allowed in prolog

Someone should mark Johannes Weiß's comment as the answer to this question. That is exactly why xml documents can't just be loaded in a DOM Document class.

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

Change "on" color of a Switch

Based on a combination of a few of the answers here this is what worked for me.

<Switch
    android:trackTintMode="src_over"
    android:thumbTint="@color/white"
    android:trackTint="@color/shadow"
    android:checked="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

How can I center a div within another div?

This will work fine I think, though you might need to reset "top:200px;" according to your needs:

#main_content {
    top: 160px;
    left: 160px;
    width: 800px;
    min-height: 500px;
    height: auto;
    background-color: #2185C5;
    position: relative;
    border: 2px solid #CCCCCC;
}

#container {
    width: 100px;
    height: 20px;;
    margin: 0 auto;
    padding-top: 10px;
    position: relative;
    top: 200px;
    border: 2px solid #CCCCCC;
}

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

One of the following solutions will work for you:

  1. npm config set python c:\Python\27\python.exe or set PYTHON=D:\Python\bin\Python.exe
  2. npm config set python D:\Library\Python\Python27\python.exe
  3. Let npm configure everything for you (takes forever to complete) npm --add-python-to-path='true' --debug install --global windows-build-tools (Must be executed via "Run As Administrator" PowerShell)

If not... Try to install the required package on your own (I did so, and it was node-sass, after installing it manually, the whole npm install was successfully completed

How to give a pandas/matplotlib bar graph custom colors

For a more detailed answer on creating your own colormaps, I highly suggest visiting this page

If that answer is too much work, you can quickly make your own list of colors and pass them to the color parameter. All the colormaps are in the cm matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.

from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color

array([[ 0.865006,  0.316822,  0.226055,  1.      ],
       [ 0.851384,  0.30226 ,  0.239636,  1.      ],
       [ 0.832299,  0.283913,  0.257383,  1.      ],
       [ 0.817341,  0.270954,  0.27039 ,  1.      ],
       [ 0.796607,  0.254728,  0.287264,  1.      ],
       [ 0.775059,  0.239667,  0.303526,  1.      ],
       [ 0.758422,  0.229097,  0.315266,  1.      ],
       [ 0.735683,  0.215906,  0.330245,  1.      ],
       .....

Then we can use this to plot, using the data from the original post:

import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))

enter image description here

TypeError: 'bool' object is not callable

You do cls.isFilled = True. That overwrites the method called isFilled and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.

The solution is use a different name for the variable than you do for the method.

Writing file to web server - ASP.NET

There are methods like WriteAllText in the File class for common operations on files.

Use the MapPath method to get the physical path for a file in your web application.

File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

Tip for RxJS

I'll often have member variables of type Observable<string>, and I won't be initializing it until ngOnInit (using Angular). The compiler then assumes it to be uninitialized becasue it isn't 'definitely assigned in the constructor' - and the compiler is never going to understand ngOnInit.

You can use the ! assertion operator on the definition to avoid the error:

favoriteColor!: Observable<string>;

An uninitialized observable can cause all kinds of runtime pain with errors like 'you must provide a stream but you provided null'. The ! is fine if you definitely know it's going to be set in something like ngOnInit, but there may be cases where the value is set in some other less deterministic way.

So an alternative I'll sometimes use is :

public loaded$: Observable<boolean> = uninitialized('loaded');

Where uninitialized is defined globally somewhere as:

export const uninitialized = (name: string) => throwError(name + ' not initialized');

Then if you ever use this stream without it being defined it will immediately throw a runtime error.

How do I wrap text in a span?

Try

_x000D_
_x000D_
.test {
white-space:pre-wrap;
}
_x000D_
<a class="test" href="#">
    Notes

    <span>
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
    </span>
</a>
_x000D_
_x000D_
_x000D_

How to connect to local instance of SQL Server 2008 Express

Haha, oh boy, I figured it out. Somehow, someway, I did not install the Database Engine when I installed SQL Server 2008. I have no idea how I missed that, but that's what happened.

Why do we use __init__ in Python classes?

class Dog(object):

    # Class Object Attribute
    species = 'mammal'

    def __init__(self,breed,name):
        self.breed = breed
        self.name = name

In above example we use species as a global since it will be always same(Kind of constant you can say). when you call __init__ method then all the variable inside __init__ will be initiated(eg:breed,name).

class Dog(object):
    a = '12'

    def __init__(self,breed,name,a):
        self.breed = breed
        self.name = name
        self.a= a

if you print the above example by calling below like this

Dog.a
12

Dog('Lab','Sam','10')
Dog.a
10

That means it will be only initialized during object creation. so anything which you want to declare as constant make it as global and anything which changes use __init__

How to fill 100% of remaining height?

I added this for pages that were too short.

html:

<section id="secondary-foot"></section>

css:

section#secondary-foot {
    height: 100%;
    background-color: #000000;
    position: fixed;
    width: 100%;
}

Unzipping files in Python

import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

That's pretty much it!

Capturing a single image from my webcam in Java or Python

On windows it is easy to interact with your webcam with pygame:

from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')

I haven't tried using pygame on linux (all my linux boxen are servers without X), but this link might be helpful http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux

Create excel ranges using column numbers in vba?

Range.EntireColumn

Yes! You can use Range.EntireColumn MSDN

dim column : column = 4

dim column_range : set column_range = Sheets(1).Cells(column).EntireColumn

Range("ColumnName:ColumnName")

If you were after a specific column, you could create a hard coded column range with the syntax e.g. Range("D:D").

However, I'd use entire column as it provides more flexibility to change that column at a later time.

Worksheet.Columns

Worksheet.Columns provides Range access to a column within a worksheet. MSDN

If you would like access to the first column of the first sheet. You would call the Columns function on the worksheet.

dim column_range: set column_range = Sheets(1).Columns(1)

The Columns property is also available on any Range MSDN

EntireRow can also be useful if you have a range for a single cell but would like to reach other cells on the row, akin to a LOOKUP

dim id : id = 12345


dim found : set found = Range("A:A").Find(id)

if not found is Nothing then
    'Get the fourth cell from the match
    MsgBox found.EntireRow.Cells(4)
end if

Finding child element of parent pure javascript

The children property returns an array of elements, like so:

parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]

There are alternatives to querySelector, like document.getElementsByClassName('parent')[0] if you so desire.


Edit: Now that I think about it, you could just use querySelectorAll to get decendents of parent having a class name of child1:

children = document.querySelectorAll('.parent .child1');

The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.

mysql datetime comparison

I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :

[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...

How to use onClick with divs in React.js

This also works:

I just changed with this.state.color==='white'?'black':'white'.

You can also pick the color from drop-down values and update in place of 'black';

(CodePen)

Single selection in RecyclerView

This is how the Adapter class looks like :

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewHolder>{

Context context;
ArrayList<RouteDetailsFromFirestore> routeDetailsFromFirestoreArrayList_;
public int  lastSelectedPosition=-1;


public MyRecyclerViewAdapter(Context context, ArrayList<RouteDetailsFromFirestore> routeDetailsFromFirestoreArrayList)
{
    this.context = context;
    this.routeDetailsFromFirestoreArrayList_ = routeDetailsFromFirestoreArrayList;
}

@NonNull
@Override
public MyRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
{
    // LayoutInflater layoutInflater = LayoutInflater.from(mainActivity_.getBaseContext());
    LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
    View view = layoutInflater.inflate(R.layout.route_details, viewGroup, false);
    return new MyRecyclerViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final MyRecyclerViewHolder myRecyclerViewHolder, final int i) {

    /* This is the part where the appropriate checking and unchecking of radio button happens appropriately */
    myRecyclerViewHolder.mRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b) {
                if (lastSelectedPosition != -1) {
     /* Getting the reference to the previously checked radio button and then unchecking it.lastSelectedPosition has the index of the previously selected radioButton */  
                    //RadioButton rb = (RadioButton) ((MainActivity) context).linearLayoutManager.getChildAt(lastSelectedPosition).findViewById(R.id.rbRadioButton);
                    RadioButton rb = (RadioButton) ((MainActivity) myRecyclerViewHolder.mRadioButton.getContext()).linearLayoutManager.getChildAt(lastSelectedPosition).findViewById(R.id.rbRadioButton);
                    rb.setChecked(false);
                }
                    lastSelectedPosition = i;
                    /* Checking the currently selected radio button */
                    myRecyclerViewHolder.mRadioButton.setChecked(true);
                }
        }
    });
}

@Override
public int getItemCount() {
    return routeDetailsFromFirestoreArrayList_.size();
}
} // End of Adapter Class

Inside MainActivity.java we call the ctor of Adapter class like this. The context passed is of MainActivity to the Adapter ctor :

myRecyclerViewAdapter = new MyRecyclerViewAdapter(MainActivity.this, routeDetailsList);

Loading custom configuration files

The config file is just an XML file, you can open it by:

private static XmlDocument loadConfigDocument()
{
    XmlDocument doc = null;
    try
    {
        doc = new XmlDocument();
        doc.Load(getConfigFilePath());
        return doc;
    }
    catch (System.IO.FileNotFoundException e)
    {
        throw new Exception("No configuration file found.", e);
    }
    catch (Exception ex)
    {
        return null;
    }
}

and later retrieving values by:

    // retrieve appSettings node

    XmlNode node =  doc.SelectSingleNode("//appSettings");

initialize a vector to zeros C++/C++11

You don't need initialization lists for that:

std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);

How to get the selected date value while using Bootstrap Datepicker?

You can try this

$('#startdate').val()

or

$('#startdate').data('date')

Convert comma separated string to array in PL/SQL

declare
seprator varchar2(1):=',';
dosweeklist varchar2(4000):='a,b,c';
begin
for i in (SELECT  SUBSTR(dosweeklist,
                         case when level=1 then 1 else INSTR(dosweeklist,seprator,1,LEVEL-1)+1 end,
                         NVL(NULLIF(INSTR(dosweeklist,seprator,1,LEVEL),0),length(dosweeklist)+1) - case when level=1 then 1 else INSTR(dosweeklist,seprator,1,LEVEL-1)+1 end) dat 
          FROM dual
          CONNECT BY LEVEL <= LENGTH(dosweeklist) - LENGTH(REPLACE(dosweeklist,seprator,'')) +1)
loop
dbms_output.put_line(i.dat);
end loop;
end;
/

so select query only in for loop can do the trick, by replacing dosweeklist as your delimited string and seprator as your delimited character.

Lets see output

a

b

c

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

How to check if a word is an English word with Python?

For a semantic web approach, you could run a sparql query against WordNet in RDF format. Basically just use urllib module to issue GET request and return results in JSON format, parse using python 'json' module. If it's not English word you'll get no results.

As another idea, you could query Wiktionary's API.

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it!

Quantile-Quantile Plot using SciPy

I came up with this. Maybe you can improve it. Especially the method of generating the quantiles of the distribution seems cumbersome to me.

You could replace np.random.normal with any other distribution from np.random to compare data against other distributions.

#!/bin/python

import numpy as np

measurements = np.random.normal(loc = 20, scale = 5, size=100000)

def qq_plot(data, sample_size):
    qq = np.ones([sample_size, 2])
    np.random.shuffle(data)
    qq[:, 0] = np.sort(data[0:sample_size])
    qq[:, 1] = np.sort(np.random.normal(size = sample_size))
    return qq

print qq_plot(measurements, 1000)

A Simple AJAX with JSP example

I have used jQuery AJAX to make AJAX requests.

Check the following code:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#call').click(function ()
            {
                $.ajax({
                    type: "post",
                    url: "testme", //this is my servlet
                    data: "input=" +$('#ip').val()+"&output="+$('#op').val(),
                    success: function(msg){      
                            $('#output').append(msg);
                    }
                });
            });

        });
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    input:<input id="ip" type="text" name="" value="" /><br></br>
    output:<input id="op" type="text" name="" value="" /><br></br>
    <input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
    <div id="output"></div>
</body>

How to resolve "local edit, incoming delete upon update" message

Short version:

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update
$ touch foo bar
$ svn revert foo bar
$ rm foo bar

If the conflict is about directories instead of files then replace touch with mkdir and rm with rm -r.


Note: the same procedure also work for the following situation:

$ svn st
!     C foo
      >   local delete, incoming delete upon update
!     C bar
      >   local delete, incoming delete upon update

Long version:

This happens when you edit a file while someone else deleted the file and commited first. As a good svn citizen you do an update before a commit. Now you have a conflict. Realising that deleting the file is the right thing to do you delete the file from your working copy. Instead of being content svn now complains that the local files are missing and that there is a conflicting update which ultimately wants to see the files deleted. Good job svn.

Should svn resolve not work, for whatever reason, you can do the following:

Initial situation: Local files are missing, update is conflicting.

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update

Recreate the conflicting files:

$ touch foo bar

If the conflict is about directories then replace touch with mkdir.

New situation: Local files to be added to the repository (yeah right, svn, whatever you say), update still conflicting.

$ svn st
A  +  C foo
      >   local edit, incoming delete upon update
A  +  C bar
      >   local edit, incoming delete upon update

Revert the files to the state svn likes them (that means deleted):

$ svn revert foo bar

New situation: Local files not known to svn, update no longer conflicting.

$ svn st
?       foo
?       bar

Now we can delete the files:

$ rm foo bar

If the conflict is about directories then replace rm with rm -r.

svn no longer complains:

$ svn st

Done.

rails 3 validation on uniqueness on multiple attributes

Dont work for me, need to put scope in plural

validates_uniqueness_of :teacher_id, :scopes => [:semester_id, :class_id]

How to open a workbook specifying its path

You can also open a required file through a prompt, This helps when you want to select file from different path and different file.

Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant

NewFile = Application.GetOpenFilename("microsoft excel files (*.xlsm*), *.xlsm*")

If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub

Detecting a mobile browser

Feature detection is much better than trying to figure out which device you are on and very hard to keep up with new devices coming out all the time, a library like Modernizr lets you know if a particular feature is available or not.

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

Add labels to each argument in your plot call corresponding to the series it is graphing, i.e. label = "series 1"

Then simply add Pyplot.legend() to the bottom of your script and the legend will display these labels.

How to get Tensorflow tensor dimensions (shape) as int values?

In later versions (tested with TensorFlow 1.14) there's a more numpy-like way to get the shape of a tensor. You can use tensor.shape to get the shape of the tensor.

tensor_shape = tensor.shape
print(tensor_shape)

What is the JSF resource library for and how should it be used?

Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.

Real world examples

To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency or UIViewRoot#addComponentResource()) the following way:

<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />

It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.

Easier identifying

This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.

Also, when you're using a custom ResourceHandler, you can also apply more finer grained control over resources coming from a specific library when library is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler and GraphicResourceHandler; check the createResource() method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource or GraphicResource for the purpose.

Noted should be that RichFaces did it wrong. It didn't use any library at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.

Your own webapp

Your own webapp does not necessarily need a resource library. You'd best just omit it.

<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />

Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml template file:

<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />

And a /WEB-INF/templates/admin.xhtml template file:

<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />

For a real world example, check the OmniFaces showcase source code.

Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):

<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />

Library versioning

Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)* pattern to denote the resource library version.

WebContent
 |-- resources
 |    `-- default
 |         `-- 1_0
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

When using this markup:

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

This will generate the following HTML with the library version as v parameter:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_0" alt="" />

So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler will automatically serve the resource from the highest version number, according to numerical ordering rules.

So, when copying/renaming resources/default/1_0/* folder into resources/default/1_1/* like follows:

WebContent
 |-- resources
 |    `-- default
 |         |-- 1_0
 |         |    :
 |         |
 |         `-- 1_1
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

Then the last markup example would generate the following HTML:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_1" alt="" />

This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.

Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler. See also How to use JSF versioning for resources in jar.

See also:

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

you have to add vm argument while running the program. This should be like

-Dwebdriver.firefox.bin=/custom/path/of/firefox/exe

In IntelliJ IDE much simpler Goto Run ? Edit Configurations... In VM options add the above.

IntelliJ Run Configurations

Eclipse also have the options to give vm argument while running. This way I am using portable Firefox with selenium.

How to build an APK file in Eclipse?

Right click on the project in Eclipse -> Android tools -> Export without signed key. Connect your device. Mount it by sdk/tools.

Execute external program

borrowed this shamely from here

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

System.out.printf("Output of running %s is:", Arrays.toString(args));

while ((line = br.readLine()) != null) {
  System.out.println(line);
}

More information here

Other issues on how to pass commands here and here

What are the differences between Visual Studio Code and Visual Studio?

Visual Studio Code is an editor while Visual Studio is an IDE.

Visual Studio Code is cross-platform and fast, while Visual Studio is not fast.

Note that Visual Studio for Mac is available now but is a different product compared to Visual Studio (Windows). It's based on Xamarin Studio and lacks support for some older .NET project types. It does successfully build solutions created in Visual Studio 2017. Visual Studio for Mac has a more limited UI (for example, no customizable toolbar). So for cross-platform work, Visual Studio Code may still be preferable.

HTML/CSS: Making two floating divs the same height

As far as I know, you can't do this using current implementations of CSS. To make two column, equal height-ed you need JS.

Converting XML to JSON using Python?

You can use the xmljson library to convert using different XML JSON conventions.

For example, this XML:

<p id="1">text</p>

translates via the BadgerFish convention into this:

{
  'p': {
    '@id': 1,
    '$': 'text'
  }
}

and via the GData convention into this (attributes are not supported):

{
  'p': {
    '$t': 'text'
  }
}

... and via the Parker convention into this (attributes are not supported):

{
  'p': 'text'
}

It's possible to convert from XML to JSON and from JSON to XML using the same conventions:

>>> import json, xmljson
>>> from lxml.etree import fromstring, tostring
>>> xml = fromstring('<p id="1">text</p>')
>>> json.dumps(xmljson.badgerfish.data(xml))
'{"p": {"@id": 1, "$": "text"}}'
>>> xmljson.parker.etree({'ul': {'li': [1, 2]}})
# Creates [<ul><li>1</li><li>2</li></ul>]

Disclosure: I wrote this library. Hope it helps future searchers.

best way to get folder and file list in Javascript

Why to invent the wheel?

There is a very popular NPM package, that let you do things like that easy.

var recursive = require("recursive-readdir");

recursive("some/path", function (err, files) {
  // `files` is an array of file paths
  console.log(files);
});

Lear more:

C# guid and SQL uniqueidentifier

// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(GentEFONRFFConnection);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("your Procedure Name", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@orgid", SqlDbType.UniqueIdentifier).Value = orgid;
myCommand.Parameters.Add("@statid", SqlDbType.UniqueIdentifier).Value = statid;
myCommand.Parameters.Add("@read", SqlDbType.Bit).Value = read;
myCommand.Parameters.Add("@write", SqlDbType.Bit).Value = write;
// Mark the Command as a SPROC

myCommand.ExecuteNonQuery();

myCommand.Dispose();
myConnection.Close();

Path of assets in CSS files in Symfony 2

I offen manage css/js plugin with composer which install it under vendor. I symlink those to the web/bundles directory, that's let composer update bundles as needed.

exemple:

1 - symlink once at all (use command fromweb/bundles/

ln -sf vendor/select2/select2/dist/ select2

2 - use asset where needed, in twig template :

{{ asset('bundles/select2/css/fileinput.css) }}

Regards.

To delay JavaScript function call using jQuery

function sample() {
    alert("This is sample function");
}

$(function() {
    $("#button").click(function() {
        setTimeout(sample, 2000);
    });

});

jsFiddle.

If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().

Single Result from Database by using mySQLi

If you assume just one result you could do this as in Edwin suggested by using specific users id.

$someUserId = 'abc123';

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);

$stmt->execute();

$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.

OR as "Your Common Sense" which selects just one user.

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");

$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

Nothing really different from the above except for PHP v.5

Why does jQuery or a DOM method such as getElementById not find the element?

As @FelixKling pointed out, the most likely scenario is that the nodes you are looking for do not exist (yet).

However, modern development practices can often manipulate document elements outside of the document tree either with DocumentFragments or simply detaching/reattaching current elements directly. Such techniques may be used as part of JavaScript templating or to avoid excessive repaint/reflow operations while the elements in question are being heavily altered.

Similarly, the new "Shadow DOM" functionality being rolled out across modern browsers allows elements to be part of the document, but not query-able by document.getElementById and all of its sibling methods (querySelector, etc.). This is done to encapsulate functionality and specifically hide it.

Again, though, it is most likely that the element you are looking for simply is not (yet) in the document, and you should do as Felix suggests. However, you should also be aware that that is increasingly not the only reason that an element might be unfindable (either temporarily or permanently).

Connect to SQL Server database from Node.js

I am not sure did you see this list of MS SQL Modules for Node JS

Share your experience after using one if possible .

Good Luck

Why does 'git commit' not save my changes?

I had an issue where I was doing commit --amend even after issuing a git add . and it still wasn't working. Turns out I made some .vimrc customizations and my editor wasn't working correctly. Fixing these errors so that vim returns the correct code resolved the issue.

"Press Any Key to Continue" function in C

Use the C Standard Library function getchar() instead as getch() is not a standard function, being provided by Borland TURBO C for MS-DOS/Windows only.

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");  
getchar();    
 

Here, getchar() expects you to press the return key so the printf statement should be press ENTER to continue. Even if you press another key, you still need to press ENTER:

printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");  
getchar();    

If you are using Windows then you can use getch()

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();   
//if you press any character it will continue ,  
//but this is not a standard c function.

char ch;
printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");    
//here also if you press any other key will wait till pressing ENTER
scanf("%c",&ch); //works as getchar() but here extra variable is required.      

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

You have Qwt which is mature. There is a 3D version lurking somewhere. However, I have never been satisfied with the aesthetic result.

It may be worth waiting for Qt3D to come out to write something better yourself easily.

How to see which flags -march=native will activate?

You can use the -Q --help=target options:

gcc -march=native -Q --help=target ...

The -v option may also be of use.

You can see the documentation on the --help option here.

Add a reference column migration in Rails 4

Another syntax of doing the same thing is:

rails g migration AddUserToUpload user:belongs_to

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

it should vary with the architecture because it represents the size of any object. So on a 32-bit system size_t will likely be at least 32-bits wide. On a 64-bit system it will likely be at least 64-bit wide.

pandas dataframe create new columns and fill with calculated values from same df

You can do this easily manually for each column like this:

df['A_perc'] = df['A']/df['sum']

If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):

ds.div(ds['sum'], axis=0)

And if you want this in one step added to the same dataframe:

>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
          A         B         C         D       sum    A_perc    B_perc  \
1  0.151722  0.935917  1.033526  0.941962  3.063127  0.049532  0.305543   
2  0.033761  1.087302  1.110695  1.401260  3.633017  0.009293  0.299283   
3  0.761368  0.484268  0.026837  1.276130  2.548603  0.298739  0.190013   

     C_perc    D_perc  sum_perc  
1  0.337409  0.307517         1  
2  0.305722  0.385701         1  
3  0.010530  0.500718         1  

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

for the maven users, comment the scope provided in the following dependency:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <!--<scope>provided</scope>-->
    </dependency>

UPDATE

As feed.me mentioned you have to uncomment the provided part depending on what kind of app you are deploying.

Here is a useful link with the details: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#build-tool-plugins-maven-packaging

WP -- Get posts by category?

Create a taxonomy field category (field name = post_category) and import it in your template as shown below:

<?php
          $categ = get_field('post_category');  
          $args = array( 'posts_per_page' => 6,
         'category_name' => $categ->slug );
          $myposts = get_posts( $args );
          foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
            //your code here
          <?php endforeach; 
          wp_reset_postdata();?>

Get specific ArrayList item

We print the value using mainList.get(index) where index starts with '0'. For Example: mainList.get(2) prints the 3rd element in the list.

List all files and directories in a directory + subdirectories

the logical and ordered way:

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace DirLister
{
class Program
{
    public static void Main(string[] args)
    {
        //with reflection I get the directory from where this program is running, thus listing all files from there and all subdirectories
        string[] st = FindFileDir(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
        using ( StreamWriter sw = new StreamWriter("listing.txt", false ) )
        {
            foreach(string s in st)
            {
                //I write what I found in a text file
                sw.WriteLine(s);
            }
        }
    }

    private static string[] FindFileDir(string beginpath)
    {
        List<string> findlist = new List<string>();

        /* I begin a recursion, following the order:
         * - Insert all the files in the current directory with the recursion
         * - Insert all subdirectories in the list and rebegin the recursion from there until the end
         */
        RecurseFind( beginpath, findlist );

        return findlist.ToArray();
    }

    private static void RecurseFind( string path, List<string> list )
    {
        string[] fl = Directory.GetFiles(path);
        string[] dl = Directory.GetDirectories(path);
        if ( fl.Length>0 || dl.Length>0 )
        {
            //I begin with the files, and store all of them in the list
            foreach(string s in fl)
                list.Add(s);
            //I then add the directory and recurse that directory, the process will repeat until there are no more files and directories to recurse
            foreach(string s in dl)
            {
                list.Add(s);
                RecurseFind(s, list);
            }
        }
    }
}
}

Access elements in json object like an array

var coordinates = [jsonObject[3][0], 
                   jsonObject[3][0],
                   jsonObject[4][1], 
                   jsonObject[4][1]];

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

Can constructors be async?

I would use something like this.

 public class MyViewModel
    {
            public MyDataTable Data { get; set; }
            public MyViewModel()
               {
                   loadData(() => GetData());
               }
               private async void loadData(Func<DataTable> load)
               {
                  try
                  {
                      MyDataTable = await Task.Run(load);
                  }
                  catch (Exception ex)
                  {
                       //log
                  }
               }
               private DataTable GetData()
               {
                    DataTable data;
                    // get data and return
                    return data;
               }
    }

This is as close to I can get for constructors.

What is a LAMP stack?

For anyone still looking into this in order to learn specifically what a stack is, the term "stack" is referring to a "solution stack." A solution stack is simply a complete set of software to address a given problem, usually by combining to provide the platform or infrastructure necessary. This term is the parent of both "server stack" and "web stack." Accordingly, a LAMP stack is a specific and complete set of software specifically aimed at serving dynamic content over the web.

Some extra reading:

https://www.techopedia.com/definition/28154/solution-stack https://en.wikipedia.org/wiki/Solution_stack

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

To do it in a generic JPA way using getter annotations, the example below works for me with Hibernate 3.5.4 and Oracle 11g. Note that the mapped getter and setter (getOpenedYnString and setOpenedYnString) are private methods. Those methods provide the mapping but all programmatic access to the class is using the getOpenedYn and setOpenedYn methods.

private String openedYn;

@Transient
public Boolean getOpenedYn() {
  return toBoolean(openedYn);
}

public void setOpenedYn(Boolean openedYn) {
  setOpenedYnString(toYesNo(openedYn));
}

@Column(name = "OPENED_YN", length = 1)
private String getOpenedYnString() {
  return openedYn;
}

private void setOpenedYnString(String openedYn) {
  this.openedYn = openedYn;
}

Here's the util class with static methods toYesNo and toBoolean:

public class JpaUtil {

    private static final String NO = "N";
    private static final String YES = "Y";

    public static String toYesNo(Boolean value) {
        if (value == null)
            return null;
        else if (value)
            return YES;
        else
            return NO;
    }

    public static Boolean toBoolean(String yesNo) {
        if (yesNo == null)
            return null;
        else if (YES.equals(yesNo))
            return true;
        else if (NO.equals(yesNo))
            return false;
        else
            throw new RuntimeException("unexpected yes/no value:" + yesNo);
    }
}

C# loop - break vs. continue

break causes the program counter to jump out of the scope of the innermost loop

for(i = 0; i < 10; i++)
{
    if(i == 2)
        break;
}

Works like this

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto BREAK;
}
BREAK:;

continue jumps to the end of the loop. In a for loop, continue jumps to the increment expression.

for(i = 0; i < 10; i++)
{
    if(i == 2)
        continue;

    printf("%d", i);
}

Works like this

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto CONTINUE;

    printf("%d", i);

    CONTINUE:;
}

Importing a CSV file into a sqlite3 database table using Python

My 2 cents (more generic):

import csv, sqlite3
import logging

def _get_col_datatypes(fin):
    dr = csv.DictReader(fin) # comma is default delimiter
    fieldTypes = {}
    for entry in dr:
        feildslLeft = [f for f in dr.fieldnames if f not in fieldTypes.keys()]
        if not feildslLeft: break # We're done
        for field in feildslLeft:
            data = entry[field]

            # Need data to decide
            if len(data) == 0:
                continue

            if data.isdigit():
                fieldTypes[field] = "INTEGER"
            else:
                fieldTypes[field] = "TEXT"
        # TODO: Currently there's no support for DATE in sqllite

    if len(feildslLeft) > 0:
        raise Exception("Failed to find all the columns data types - Maybe some are empty?")

    return fieldTypes


def escapingGenerator(f):
    for line in f:
        yield line.encode("ascii", "xmlcharrefreplace").decode("ascii")


def csvToDb(csvFile, outputToFile = False):
    # TODO: implement output to file

    with open(csvFile,mode='r', encoding="ISO-8859-1") as fin:
        dt = _get_col_datatypes(fin)

        fin.seek(0)

        reader = csv.DictReader(fin)

        # Keep the order of the columns name just as in the CSV
        fields = reader.fieldnames
        cols = []

        # Set field and type
        for f in fields:
            cols.append("%s %s" % (f, dt[f]))

        # Generate create table statement:
        stmt = "CREATE TABLE ads (%s)" % ",".join(cols)

        con = sqlite3.connect(":memory:")
        cur = con.cursor()
        cur.execute(stmt)

        fin.seek(0)


        reader = csv.reader(escapingGenerator(fin))

        # Generate insert statement:
        stmt = "INSERT INTO ads VALUES(%s);" % ','.join('?' * len(cols))

        cur.executemany(stmt, reader)
        con.commit()

    return con

How to read a HttpOnly cookie using JavaScript

Httponly cookies' purpose is being inaccessible by script, so you CAN NOT.

php var_dump() vs print_r()

The var_dump function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.

The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.

Example:

$obj = (object) array('qualitypoint', 'technologies', 'India');

var_dump($obj) will display below output in the screen.

object(stdClass)#1 (3) {
 [0]=> string(12) "qualitypoint"
 [1]=> string(12) "technologies"
 [2]=> string(5) "India"
}

And, print_r($obj) will display below output in the screen.

stdClass Object ( 
 [0] => qualitypoint
 [1] => technologies
 [2] => India
)

More Info

What's the best CRLF (carriage return, line feed) handling strategy with Git?

Almost four years after asking this question, I have finally found an answer that completely satisfies me!

See the details in github:help's guide to Dealing with line endings.

Git allows you to set the line ending properties for a repo directly using the text attribute in the .gitattributes file. This file is committed into the repo and overrides the core.autocrlf setting, allowing you to ensure consistent behaviour for all users regardless of their git settings.

And thus

The advantage of this is that your end of line configuration now travels with your repository and you don't need to worry about whether or not collaborators have the proper global settings.

Here's an example of a .gitattributes file

# Auto detect text files and perform LF normalization
*        text=auto

*.cs     text diff=csharp
*.java   text diff=java
*.html   text diff=html
*.css    text
*.js     text
*.sql    text

*.csproj text merge=union
*.sln    text merge=union eol=crlf

*.docx   diff=astextplain
*.DOCX   diff=astextplain

# absolute paths are ok, as are globs
/**/postinst* text eol=lf

# paths that don't start with / are treated relative to the .gitattributes folder
relative/path/*.txt text eol=lf

There is a convenient collection of ready to use .gitattributes files for the most popular programming languages. It's useful to get you started.

Once you've created or adjusted your .gitattributes, you should perform a once-and-for-all line endings re-normalization.

Note that the GitHub Desktop app can suggest and create a .gitattributes file after you open your project's Git repo in the app. To try that, click the gear icon (in the upper right corner) > Repository settings ... > Line endings and attributes. You will be asked to add the recommended .gitattributes and if you agree, the app will also perform a normalization of all the files in your repository.

Finally, the Mind the End of Your Line article provides more background and explains how Git has evolved on the matters at hand. I consider this required reading.

You've probably got users in your team who use EGit or JGit (tools like Eclipse and TeamCity use them) to commit their changes. Then you're out of luck, as @gatinueta explained in this answer's comments:

This setting will not satisfy you completely if you have people working with Egit or JGit in your team, since those tools will just ignore .gitattributes and happily check in CRLF files https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372

One trick might be to have them commit their changes in another client, say SourceTree. Our team back then preferred that tool to Eclipse's EGit for many use cases.

Who said software is easy? :-/

Git fails when pushing commit to github

The Problem to push mostly is because of the size of the files that need to be pushed. I was trying to push some libraries of just size 2 mb, then too the push was giving error of RPC with result 7. The line is of 4 mbps and is working fine. Some subsequent tries to the push got me success. If such error comes, wait for few minutes and keep on trying.

I also found out that there are some RPC failures if the github is down or is getting unstable network at their side.

So keeping up trying after some intervals is the only option!

How do I copy a string to the clipboard?

You can also use ctypes to tap into the Windows API and avoid the massive pywin32 package. This is what I use (excuse the poor style, but the idea is there):

import ctypes

# Get required functions, strcpy..
strcpy = ctypes.cdll.msvcrt.strcpy
ocb = ctypes.windll.user32.OpenClipboard    # Basic clipboard functions
ecb = ctypes.windll.user32.EmptyClipboard
gcd = ctypes.windll.user32.GetClipboardData
scd = ctypes.windll.user32.SetClipboardData
ccb = ctypes.windll.user32.CloseClipboard
ga = ctypes.windll.kernel32.GlobalAlloc    # Global memory allocation
gl = ctypes.windll.kernel32.GlobalLock     # Global memory Locking
gul = ctypes.windll.kernel32.GlobalUnlock
GMEM_DDESHARE = 0x2000

def Get():
  ocb(None) # Open Clip, Default task

  pcontents = gcd(1) # 1 means CF_TEXT.. too lazy to get the token thingy...

  data = ctypes.c_char_p(pcontents).value

  #gul(pcontents) ?
  ccb()

  return data

def Paste(data):
  ocb(None) # Open Clip, Default task

  ecb()

  hCd = ga(GMEM_DDESHARE, len(bytes(data,"ascii")) + 1)

  pchData = gl(hCd)

  strcpy(ctypes.c_char_p(pchData), bytes(data, "ascii"))

  gul(hCd)

  scd(1, hCd)

  ccb()

Postgres password authentication fails

pg_hba.conf entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf in order to get proper help.

Change this line:

host    all             all             <my-ip-address>/32        md5

To reflect your local network settings. So, if your IP is 192.168.16.78 (class C) with a mask of 255.255.255.0, then put this:

host    all             all             192.168.16.0/24        md5

Make sure your WINDOWS MACHINE is in that network 192.168.16.0 and try again.

what is the most efficient way of counting occurrences in pandas?

When you want to count the frequency of categorical data in a column in pandas dataFrame use: df['Column_Name'].value_counts()

-Source.

Maintain the aspect ratio of a div with CSS

I used a new solution.

.squares{
  width: 30vw
  height: 30vw

To main aspect ratio

.aspect-ratio
  width: 10vw
  height: 10vh

However, this is relative to the entire viewport. So, if you need a div that is 30% of the viewport width, you can use 30vw instead, and since you know the width, you reuse them in height using calc and vw unit.

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

Initially I also had problem getting FLAG_ACTIVITY_CLEAR_TOP to work. Eventually I got it to work by using the value of it (0x04000000). So looks like there's an Eclipse/compiler issue. But unfortunately the surviving activity is restarted, which is not what I want. So looks like there's no easy solution.

how do I set height of container DIV to 100% of window height?

I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
 html {height: 50%; border: solid red 3px; }_x000D_
 body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
 div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
 _x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
 <div id="container">_x000D_
  <p>&lt;html&gt; is red</p>_x000D_
  <p>&lt;body&gt; is green</p>_x000D_
  <p>&lt;div&gt; is blue</p>_x000D_
 </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.

About CSS units: w3schools: CSS units

A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."

How to open the Google Play Store directly from my Android application?

If you want to open Google Play store from your app then use this command directy: market://details?gotohome=com.yourAppName, it will open your app's Google Play store pages.

Show all apps by a specific publisher

Search for apps that using the Query on its title or description

Reference: https://tricklio.com/market-details-gotohome-1/

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

When should you use 'friend' in C++?

The short answer would be: use friend when it actually improves encapsulation. Improving readability and usability (operators << and >> are the canonical example) is also a good reason.

As for examples of improving encapsulation, classes specifically designed to work with the internals of other classes (test classes come to mind) are good candidates.

Chrome:The website uses HSTS. Network errors...this page will probably work later

I recently had the same issue while trying to access domains using CloudFlare Origin CA.

The only way I found to workaround/avoid HSTS cert exception on Chrome (Windows build) was following the short instructions in https://support.opendns.com/entries/66657664.

The workaround:
Add to Chrome shortcut the flag --ignore-certificate-errors, then reopen it and surf to your website.

Reminder:
Use it only for development purposes.

enter image description here

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

You have to pass the route parameters to the route method, for example:

<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>

It's because, both routes have a {nickname} in the route declaration. I've used $nickname for example but make sure you change the $nickname to appropriate value/variable, for example, it could be something like the following:

<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>

Shell Scripting: Using a variable to define a path

Don't use spaces...

(Incorrect)

SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'

(Correct)

SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'

Difference between $(this) and event.target?

'this' refers to the DOM object to which the event listener has been attached. 'event.target' refers to the DOM object for which the event listener got triggered. A natural question arises as, why the event listener is triggering for other DOM objects. This is because event listener attached parent triggers for child object too.

How to upgrade PowerShell version from 2.0 to 3.0

As of today, Windows PowerShell 5.1 is the latest version. It can be installed as part of Windows Management Framework 5.1. It was released in January 2017.

Quoting from the official Microsoft download page here.

Some of the new and updated features in this release include:

  • Constrained file copying to/from JEA endpoints
  • JEA support for Group Managed Service Accounts and Conditional Access Policies
  • PowerShell console support for VT100 and redirecting stdin with interactive input
  • Support for catalog signed modules in PowerShell Get
  • Specifying which module version to load in a script
  • Package Management cmdlet support for proxy servers
  • PowerShellGet cmdlet support for proxy servers
  • Improvements in PowerShell Script Debugging
  • Improvements in Desired State Configuration (DSC)
  • Improved PowerShell usage auditing using Transcription and Logging
  • New and updated cmdlets based on community feedback

How change default SVN username and password to commit changes?

For Windows (7), the same folder is located at,

%APPDATA%\Subversion\auth

Type in the above in the Run(Win key + R) dialog box and hit Enter,

To check the existing username open the below file as a text file,

%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx

How do I determine file encoding in OS X?

A brute-force way to check the encoding might just be to check the file in a hex editor or similar. (or write a program to check) Look at the binary data in the file. The UTF-8 format is fairly easy to recognize. All ASCII characters are single bytes with values below 128 (0x80) Multibyte sequences follow the pattern shown in the wiki article

If you can find a simpler way to get a program to verify the encoding for you, that's obviously a shortcut, but if all else fails, this would do the trick.

move column in pandas dataframe

You can also do this as a one-liner:

df.drop(columns=['b', 'x']).assign(b=df['b'], x=df['x'])

Is there a job scheduler library for node.js?

This won't be suitable for everyone, but if your application is already setup to take commands via a socket, you can use netcat to issue a commands via cron proper.

echo 'mycommand' | nc -U /tmp/myapp.sock

Android EditText view Floating Hint in Material Design

Yes, as of May 29, 2015 this functionality is now provided in the Android Design Support Library

This library includes support for

  • Floating labels
  • Floating action button
  • Snackbar
  • Navigation drawer
  • and more

c# dictionary one key many values

Here's my approach to achieve this behavior.

For a more comprehensive solution involving ILookup<TKey, TElement>, check out my other answer.

public abstract class Lookup<TKey, TElement> : KeyedCollection<TKey, ICollection<TElement>>
{
  protected override TKey GetKeyForItem(ICollection<TElement> item) =>
    item
    .Select(b => GetKeyForItem(b))
    .Distinct()
    .SingleOrDefault();

  protected abstract TKey GetKeyForItem(TElement item);

  public void Add(TElement item)
  {
    var key = GetKeyForItem(item);
    if (Dictionary != null && Dictionary.TryGetValue(key, out var collection))
      collection.Add(item);
    else
      Add(new List<TElement> { item });
  }

  public void Remove(TElement item)
  {
    var key = GetKeyForItem(item);
    if (Dictionary != null && Dictionary.TryGetValue(key, out var collection))
    {
      collection.Remove(item);
      if (collection.Count == 0)
        Remove(key);
    }
  }
}

Usage:

public class Item
{
  public string Key { get; }
  public string Value { get; set; }
  public Item(string key, string value = null) { Key = key; Value = value; }
}

public class Lookup : Lookup<string, Item>
{
  protected override string GetKeyForItem(Item item) => item.Key;
}

static void Main(string[] args)
{
  var toRem = new Item("1", "different");
  var single = new Item("2", "single");
  var lookup = new Lookup()
  {
    new Item("1", "hello"),
    new Item("1", "hello2"),
    new Item(""),
    new Item("", "helloo"),
    toRem,
    single
  };

  lookup.Remove(toRem);
  lookup.Remove(single);
}

Note: the key must be immutable (or remove and re-add upon key-change).

How do I remove whitespace from the end of a string in Python?

>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.

Genymotion error at start 'Unable to load virtualbox'

I have spend all day to solve this error since none of the answers worked for me.

I found out that oracle virtual box doesn't install the network adapter correctly in windows 8.1

Solution:

  1. Delete all previous virtual box adapters
  2. Go to device manager and click "Action" > "Add legacy hardware"
  3. Install the oracle virtual box adapters manually (my path was C:\Program Files\Oracle\VirtualBox\drivers\network\netadp\VBoxNetAdp.inf)

Now that virtual box adapters is installed correctly, it needs to be setup correctly. (the following solution is like many other solution in here)

  1. Start Oracle VM VirtualBox and go to "File" > "Preferences" > "Network" > "Host-only Network"
  2. Click edit
  3. Set IPv4 192.168.56.1 mask 255.255.255.0
  4. Click DHCP Server tab and set server adr: 192.168.56.100 server Mask: 255.255.255.0 low address bound: 192.168.56.101 upper adress bound 192.168.56.254
  5. Now click OK and start genymotion

Class Not Found Exception when running JUnit test

For me I had to put the project x/src/test/java/ at the bottom of the "order and export" in the "java build path"

enter image description here

Unsafe JavaScript attempt to access frame with URL

From a child document of different origin you are not allowed access to the top window's location.hash property, but you are allowed to set the location property itself.

This means that given that the top windows location is http://example.com/page/, instead of doing

parent.location.hash = "#foobar";

you do need to know the parents location and do

parent.location = "http://example.com/page/#foobar";

Since the resource is not navigated this will work as expected, only changing the hash part of the url.

If you are using this for cross-domain communication, then I would recommend using easyXDM instead.

How to add google-services.json in Android?

This error indicates your package_name in your google-services.json might be wrong. I personally had this issue when I used

buildTypes {
    ...

    debug {
        applicationIdSuffix '.debug'
    }
}

in my build.gradle. So, when I wanted to debug, the name of the application was ("all of a sudden") app.something.debug instead of app.something. I was able to run the debug when I changed the said package_name...

Converting a String to DateTime

I just found an elegant way:

Convert.ChangeType("2020-12-31", typeof(DateTime));

Convert.ChangeType("2020/12/31", typeof(DateTime));

Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));

Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));

Convert.ChangeType("11/?????/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));

Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"

Oracle SQL update based on subquery between two tables

As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.

However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.

How do I make a semi transparent background?

This is simple and sort. Use hsla css function like below

.transparent {
   background-color: hsla(0,0%,4%,.4);
}

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

Give a Format String value of C2 for the value's properties as shown in figure below.

enter image description here

How do you specify table padding in CSS? ( table, not cell padding )

table {
    background: #fff;
    box-shadow: 0 0 0 10px #fff;
    margin: 10px;
    width: calc(100% - 20px); 
}

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

How do I mount a remote Linux folder in Windows through SSH?

I don't think you can mount a Linux folder as a network drive under windows having only access to ssh. I can suggest you to use WinSCP that allows you to transfer file through ssh and it's free.

EDIT: well, sorry. Vinko posted before me and now i've learned a new thing :)

How to open local file on Jupyter?

To start Jupyter Notebook in Windows:

  • open a Windows cmd (win + R and return cmd)
  • change directory to the desired file path (cd file-path)
  • give command jupyter notebook

You can further navigate from the UI of Jupyter notebook after you launch it (if you are not directly launching the right file.)
OR you can directly drag and drop the file to the cmd, to open the file.

C:\Users\kushalatreya>jupyter notebook "C:\Users\kushalatreya\Downloads\Material\PythonCourseFolder\PythonCourse-DataTypes.ipynb"

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

You need to add JQuery js before adding bootstrap js file, because BootStrap use jqueries function. So make sure to load first jquery js and then bootstap js file.

<!-- JQuery Core JavaScript -->
<script src="app/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="app/js/bootstrap.min.js"></script>

How to auto import the necessary classes in Android Studio with shortcut?

Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:

Select Insert imports on paste value to All

Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*

Screenshot

Using %f with strftime() in Python to get microseconds

If you want speed, try this:

def _timestamp(prec=0):
    t = time.time()
    s = time.strftime("%H:%M:%S", time.localtime(t))
    if prec > 0:
        s += ("%.9f" % (t % 1,))[1:2+prec]
    return s

Where prec is precision -- how many decimal places you want. Please note that the function does not have issues with leading zeros in fractional part like some other solutions presented here.

Unable to Connect to GitHub.com For Cloning

You can try to clone using the HTTPS protocol. Terminal command:

git clone https://github.com/RestKit/RestKit.git

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors(); in the configure method. The method looks like that:

protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests() // authorize
                .anyRequest().authenticated() // all requests are authenticated
                .and()
                .httpBasic();

        http.cors();
}

How to stop VBA code running?

This is an old post, but given the title of this question, the END option should be described in more detail. This can be used to stop ALL PROCEDURES (not just the subroutine running). It can also be used within a function to stop other Subroutines (which I find useful for some add-ins I work with).

As Microsoft states:

Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables*. I noticed that the END method is not described in much detail. This can be used to stop ALL PROCEDURES (not just the subroutine running).

Here is an illustrative example:

Sub RunSomeMacros()

    Call FirstPart
    Call SecondPart

    'the below code will not be executed if user clicks yes during SecondPart.
    Call ThirdPart
    MsgBox "All of the macros have been run."

End Sub

Private Sub FirstPart()
    MsgBox "This is the first macro"

End Sub

Private Sub SecondPart()
    Dim answer As Long
    answer = MsgBox("Do you want to stop the macros?", vbYesNo)

    If answer = vbYes Then
        'Stops All macros!
        End
    End If

    MsgBox "You clicked ""NO"" so the macros are still rolling..."
End Sub

Private Sub ThirdPart()
    MsgBox "Final Macro was run."
End Sub

Access Controller method from another controller in Laravel 5

You can use a static method in PrintReportController and then call it from the SubmitPerformanceController like this;

namespace App\Http\Controllers;

class PrintReportController extends Controller
{

    public static function getPrintReport()
    {
      return "Printing report";
    }


}



namespace App\Http\Controllers;

use App\Http\Controllers\PrintReportController;

class SubmitPerformanceController extends Controller
{


    public function index()
    {

     echo PrintReportController::getPrintReport();

    }

}

How do you automatically set text box to Uppercase?

The answers with the text-transformation:uppercase styling will not send uppercased data to the server on submit - what you might expect. You can do something like this instead:

For your input HTML use onkeydown:

<input name="yourInput" onkeydown="upperCaseF(this)"/>

In your JavaScript:

function upperCaseF(a){
    setTimeout(function(){
        a.value = a.value.toUpperCase();
    }, 1);
}

With upperCaseF() function on every key press down, the value of the input is going to turn into its uppercase form.

I also added a 1ms delay so that the function code block triggers after the keydown event occured.

UPDATE

Per remommendation from Dinei, you can use oninput event instead of onkeydown and get rid of setTimeout.

For your input HTML use oninput:

<input name="yourInput" oninput="this.value = this.value.toUpperCase()"/>

How to restore PostgreSQL dump file into Postgres databases?

1.open the terminal.

2.backup your database with following command

your postgres bin - /opt/PostgreSQL/9.1/bin/

your source database server - 192.168.1.111

your backup file location and name - /home/dinesh/db/mydb.backup

your source db name - mydatabase

/opt/PostgreSQL/9.1/bin/pg_dump --host '192.168.1.111' --port 5432 --username "postgres" --no-password --format custom --blobs --file "/home/dinesh/db/mydb.backup" "mydatabase"

3.restore mydb.backup file into destination.

your destination server - localhost

your destination database name - mydatabase

create database for restore the backup.

/opt/PostgreSQL/9.1/bin/psql -h 'localhost' -p 5432 -U postgres -c "CREATE DATABASE mydatabase"

restore the backup.

/opt/PostgreSQL/9.1/bin/pg_restore --host 'localhost' --port 5432 --username "postgres" --dbname "mydatabase" --no-password --clean "/home/dinesh/db/mydb.backup"

URL rewriting with PHP

PHP is not what you are looking for, check out mod_rewrite

How to change DataTable columns order

I know this is a really old question.. and it appears it was answered.. But I got here with the same question but a different reason for the question, and so a slightly different answer worked for me. I have a nice reusable generic datagridview that takes the datasource supplied to it and just displays the columns in their default order. I put aliases and column order and selection at the dataset's tableadapter level in designer. However changing the select query order of columns doesn't seem to impact the columns returned through the dataset. I have found the only way to do this in the designer, is to remove all the columns selected within the tableadapter, adding them back in the order you want them selected.

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

I think you have put command like java -VERSION. This is in capital letters You need to put all command in lowercase letters

javac -version
java -version

All characters must be in lowercase letter

Find unused code

Yes, ReSharper does this. Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used.

How do I get column datatype in Oracle with PL-SQL with low privileges?

The best solution that I've found for such case is

select column_name, data_type||
case
when data_precision is not null and nvl(data_scale,0)>0 then '('||data_precision||','||data_scale||')'
when data_precision is not null and nvl(data_scale,0)=0 then '('||data_precision||')'
when data_precision is null and data_scale is not null then '(*,'||data_scale||')'
when char_length>0 then '('||char_length|| case char_used 
                                                         when 'B' then ' Byte'
                                                         when 'C' then ' Char'
                                                         else null 
                                           end||')'
end||decode(nullable, 'N', ' NOT NULL')
from user_tab_columns
where table_name = 'TABLE_NAME'
and column_name = 'COLUMN_NAME';

@Aaron Stainback, thank you for correction!

How to apply a CSS class on hover to dynamically generated submit buttons?

Add the below code

input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;
}

If you need only for these button then you can add id name

#paginate input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;
}

DEMO

Making text background transparent but not text itself

opacity will make both text and background transparent. Use a semi-transparent background-color instead, by using a rgba() value for example. Works on IE8+

How to automatically indent source code?

Also, there's the handy little "increase indent" and "decrease indent" buttons. If you highlight a block of code and click those buttons the entire block will indent.

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

Send email using the GMail SMTP server from a PHP page

SwiftMailer can send E-Mail using external servers.

here is an example that shows how to use a Gmail server:

require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";

//Connect to localhost on port 25
$swift =& new Swift(new Swift_Connection_SMTP("localhost"));


//Connect to an IP address on a non-standard port
$swift =& new Swift(new Swift_Connection_SMTP("217.147.94.117", 419));


//Connect to Gmail (PHP5)
$swift = new Swift(new Swift_Connection_SMTP(
    "smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS));

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

What does /p mean in set /p?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Two ways I've used it... first:

SET /P variable=

When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

And second:

SET /P variable=<%temp%\filename.txt

Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

vim - How to delete a large block of text without counting the lines?

There are several possibilities, what's best depends on the text you work on.

Two possibilities come to mind:

  • switch to visual mode (V, S-V, ...), select the text with cursor movement and press d
  • delete a whole paragraph with: dap

Example: Communication between Activity and Service using Messaging

For sending data to a service you can use:

Intent intent = new Intent(getApplicationContext(), YourService.class);
intent.putExtra("SomeData","ItValue");
startService(intent);

And after in service in onStartCommand() get data from intent.

For sending data or event from a service to an application (for one or more activities):

private void sendBroadcastMessage(String intentFilterName, int arg1, String extraKey) {
    Intent intent = new Intent(intentFilterName);
    if (arg1 != -1 && extraKey != null) {
        intent.putExtra(extraKey, arg1);
    }
    sendBroadcast(intent);
}

This method is calling from your service. You can simply send data for your Activity.

private void someTaskInYourService(){

    //For example you downloading from server 1000 files
    for(int i = 0; i < 1000; i++) {
        Thread.sleep(5000) // 5 seconds. Catch in try-catch block
        sendBroadCastMessage(Events.UPDATE_DOWNLOADING_PROGRESSBAR, i,0,"up_download_progress");
    }

For receiving an event with data, create and register method registerBroadcastReceivers() in your activity:

private void registerBroadcastReceivers(){
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int arg1 = intent.getIntExtra("up_download_progress",0);
            progressBar.setProgress(arg1);
        }
    };
    IntentFilter progressfilter = new IntentFilter(Events.UPDATE_DOWNLOADING_PROGRESS);
    registerReceiver(broadcastReceiver,progressfilter);

For sending more data, you can modify method sendBroadcastMessage();. Remember: you must register broadcasts in onResume() & unregister in onStop() methods!

UPDATE

Please don't use my type of communication between Activity & Service. This is the wrong way. For a better experience please use special libs, such us:

1) EventBus from greenrobot

2) Otto from Square Inc

P.S. I'm only using EventBus from greenrobot in my projects,

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

It is not the asker's problem in this instance but the first troubleshooting step for a generic "AttributeError: __exit__" should be making sure the brackets are there, e.g.

with SomeContextManager() as foo:
    #works because a new object is referenced...

not

with SomeContextManager as foo:
    #AttributeError because the class is referenced

Catches me out from time to time and I end up here -__-

Error sending json in POST to web API service

I had all my settings covered in the accepted answer. The problem I had was that I was trying to update the Entity Framework entity type "Task" like:

public IHttpActionResult Post(Task task)

What worked for me was to create my own entity "DTOTask" like:

public IHttpActionResult Post(DTOTask task)

iPhone Navigation Bar Title text color

After encountering the same problem (as others) of the label that moves when we insert a button in the navBar (in my case i have a spinner that i replace with a button when the date is loaded), the above solutions didn't work for me, so here is what worked and kept the label at the same place all the time:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
    // this will appear as the title in the navigation bar
    //CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
   CGRect frame = CGRectMake(0, 0, 180, 44);
    UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];



    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:20.0];
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor yellowColor];
    self.navigationItem.titleView = label;
    label.text = NSLocalizedString(@"Latest Questions", @"");
    [label sizeToFit];
}

return self;

In Java, remove empty elements from a list of Strings

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", "", "How"));
           Stream<String> stream = list .stream();
           Predicate<String> empty = empt->(empt.equals(""));
            Predicate<String> emptyRev = empty.negate();
           list=  stream.filter(emptyRev).collect(Collectors.toList());

OR

list =  list .stream().filter(empty->(!empty.equals(""))).collect(Collectors.toList());