Programs & Examples On #Code first

Code-first is a software implementation approach that favors programming against an API over other approaches that may rely more heavily on visual tools or require the presence of some external source that is inspected to generate program behavior, structure, or data.

ALTER TABLE DROP COLUMN failed because one or more objects access this column

The @SqlZim's answer is correct but just to explain why this possibly have happened. I've had similar issue and this was caused by very innocent thing: adding default value to a column

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int DEFAULT NULL;

But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.

So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int NULL,
  CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;

You'll still have to drop the constraint before dropping the column, but you will at least know its name up front.

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

There are some basics difference between ICollection and IEnumerable

  • IEnumerable - contains only GetEnumerator method to get Enumerator and allows looping
  • ICollection contains additional methods: Add, Remove, Contains, Count, CopyTo
  • ICollection is inherited from IEnumerable
  • With ICollection you can modify the collection by using the methods like add/remove. You don't have the liberty to do the same with IEnumerable.

Simple Program:

using System;
using System.Collections;
using System.Collections.Generic;

namespace StackDemo
{
    class Program 
    {
        static void Main(string[] args)
        {
            List<Person> persons = new List<Person>();
            persons.Add(new Person("John",30));
            persons.Add(new Person("Jack", 27));

            ICollection<Person> personCollection = persons;
            IEnumerable<Person> personEnumeration = persons;

            // IEnumeration
            // IEnumration Contains only GetEnumerator method to get Enumerator and make a looping
            foreach (Person p in personEnumeration)
            {                                   
               Console.WriteLine("Name:{0}, Age:{1}", p.Name, p.Age);
            }

            // ICollection
            // ICollection Add/Remove/Contains/Count/CopyTo
            // ICollection is inherited from IEnumerable
            personCollection.Add(new Person("Tim", 10));

            foreach (Person p in personCollection)
            {
                Console.WriteLine("Name:{0}, Age:{1}", p.Name, p.Age);        
            }
            Console.ReadLine();

        }
    }

    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Person(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }
    }
}

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

it may caused by Property which is not populated by model.. instead it is populated by Controller.. which may cause this error.. solution to this is assign the property before applying ModelState validation. and this second Assumption is . you may have already have Data in your Database and trying to update it it but now fetching it.

The model backing the <Database> context has changed since the database was created

Now it's:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer<YourDbContext>(null);
    base.OnModelCreating(modelBuilder);
}

in your YourDbContext.cs file.

CREATE DATABASE permission denied in database 'master' (EF code-first)

I have no prove for my solution, just assumptions.

In my case it is caused by domain name in connection string. I have an assumption that if DNS server is not available, it is not able to connect to database and thus the Entity Framework tries to create this database. But the permission is denied, which is correct.

Entity Framework Code First - two Foreign Keys from same table

I know it's a several years old post and you may solve your problem with above solution. However, i just want to suggest using InverseProperty for someone who still need. At least you don't need to change anything in OnModelCreating.

The below code is un-tested.

public class Team
{
    [Key]
    public int TeamId { get; set;} 
    public string Name { get; set; }

    [InverseProperty("HomeTeam")]
    public virtual ICollection<Match> HomeMatches { get; set; }

    [InverseProperty("GuestTeam")]
    public virtual ICollection<Match> GuestMatches { get; set; }
}


public class Match
{
    [Key]
    public int MatchId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

You can read more about InverseProperty on MSDN: https://msdn.microsoft.com/en-us/data/jj591583?f=255&MSPPError=-2147217396#Relationships

Nullable property to entity field, Entity Framework through Code First

The other option is to tell EF to allow the column to be null:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();            
        base.OnModelCreating(modelBuilder);
}

This code should be in the object that inherits from DbContext.

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

Getting only hour/minute of datetime

Just use Hour and Minute properties

var date = DateTime.Now;
date.Hour;
date.Minute;

Or you can easily zero the seconds using

var zeroSecondDate = date.AddSeconds(-date.Second);

Is object empty?

It might be a bit hacky. You can try this.

if (JSON.stringify(data).length === 2) {
   // Do something
}

Not sure if there is any disadvantage of this method.

Signed to unsigned conversion in C - is it always safe?

Referring to the bible:

  • Your addition operation causes the int to be converted to an unsigned int.
  • Assuming two's complement representation and equally sized types, the bit pattern does not change.
  • Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)
  • The rules are a little more complicated in the case of combining signed and unsigned of differing sizes.

XSLT string replace

The rouine is pretty good, however it causes my app to hang, so I needed to add the case:

  <xsl:when test="$text = '' or $replace = ''or not($replace)" >
    <xsl:value-of select="$text" />
    <!-- Prevent thsi routine from hanging -->
  </xsl:when>

before the function gets called recursively.

I got the answer from here: When test hanging in an infinite loop

Thank you!

horizontal line and right way to code it in html, css

_x000D_
_x000D_
hr {_x000D_
    display: block;_x000D_
    height: 1px;_x000D_
    border: 0;_x000D_
    border-top: 1px solid #ccc;_x000D_
    margin: 1em 0;_x000D_
    padding: 0;_x000D_
}
_x000D_
<div>Hello</div>_x000D_
<hr/>_x000D_
<div>World</div>
_x000D_
_x000D_
_x000D_

Here is how html5boilerplate does it:

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

How does Python manage int and long?

Python 2.7.9 auto promotes numbers. For a case where one is unsure to use int() or long().

>>> a = int("123")
>>> type(a)
<type 'int'>
>>> a = int("111111111111111111111111111111111111111111111111111")
>>> type(a)
<type 'long'>

Pretty printing XML with javascript

You can get pretty formatted xml with xml-beautify

var prettyXmlText = new XmlBeautify().beautify(xmlText, 
                    {indent: "  ",useSelfClosingElement: true});

indent:indent pattern like white spaces

useSelfClosingElement: true=>use self-closing element when empty element.

JSFiddle

Original(Before)

<?xml version="1.0" encoding="utf-8"?><example version="2.0">
  <head><title>Original aTitle</title></head>
  <body info="none" ></body>
</example>

Beautified(After)

<?xml version="1.0" encoding="utf-8"?>
<example version="2.0">
  <head>
    <title>Original aTitle</title>
  </head>
  <body info="none" />
</example>

Minimum rights required to run a windows service as a domain account

Thanks for the links, Chris. I've often wondered about the specific effects of privileges like "BypassTraverseChecking" but never bothered to look them up.

I was having interesting problems getting a service to run and discovered that it didn't have access to it's files after the initial installation had been done by the administrator. I was thinking it needed something in addition to Logon As A Service until I found the file issue.

  1. Disabled simple file sharing.
  2. Temporarily made my service account an administrator.
  3. Used the service account to take ownership of the files.
  4. Remove service account from the administrators group.
  5. Reboot.

During Take Ownership, it was necessary to disable inheritance of permissions from the parent directories and apply permissions recursively down the tree.

Wasn't able to find a "give ownership" option to avoid making the service account an administrator temporarily, though.

Anyway, thought I'd post this in case anyone else was going down the same road I was looking for security policy issues when it was really just filesystem rights.

How to do a timer in Angular 5

You can simply use setInterval to create such timer in Angular, Use this Code for timer -

timeLeft: number = 60;
  interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left....</p>

Working Example

Another way using Observable timer like below -

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information read here

HashMap get/put complexity

HashMap operation is dependent factor of hashCode implementation. For the ideal scenario lets say the good hash implementation which provide unique hash code for every object (No hash collision) then the best, worst and average case scenario would be O(1). Let's consider a scenario where a bad implementation of hashCode always returns 1 or such hash which has hash collision. In this case the time complexity would be O(n).

Now coming to the second part of the question about memory, then yes memory constraint would be taken care by JVM.

Android OnClickListener - identify a button

Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId() == R.id.button1){
        Toast.makeText(context, "Button 1 Click", Toast.LENGTH_LONG).show();
    }
}

Check this article for more details

Convert object to JSON in Android

Spring for Android do this using RestTemplate easily:

final String url = "http://192.168.1.50:9000/greeting";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Greeting greeting = restTemplate.getForObject(url, Greeting.class);

Oracle copy data to another table

Creating a table and copying the data in a single command:

create table T_NEW as
  select * from T;

* This will not copy PKs, FKs, Triggers, etc.

How can I change the image of an ImageView?

Have a look at the ImageView API. There are several setImage* methods. Which one to use depends on the image you provide. If you have the image as resource (e.g. file res/drawable/my_image.png)

ImageView img = new ImageView(this);  // or (ImageView) findViewById(R.id.myImageView);
img.setImageResource(R.drawable.my_image);

MS SQL Date Only Without Time

FWIW, I've been doing the same thing as you for years

CAST(CONVERT(VARCHAR, [tstamp], 102) AS DATETIME) = @dateParam 

Seems to me like this is one of the better ways to strip off time in terms of flexibility, speed and readabily. (sorry). Some UDF functions as suggested can be useful, but UDFs can be slow with larger result sets.

What's the difference between SHA and AES encryption?

SHA is a hash function and AES is an encryption standard. Given an input you can use SHA to produce an output which is very unlikely to be produced from any other input. Also, some information is lost while applying the function so even if you knew how to produce an input yielding the same output, that input wouldn't likely be the same one used in the first place. On the other hand AES is meant to protect from disclosure to third parties any data sent between two parties sharing the same encryption key. This means that once you know the encryption key and the output (and the IV...) you can seamlessly get back to the original input. Please notice that SHA doesn't require anything but an input to be applied, while AES requires at least 3 thins: what you're encrypting/decrypting, an encryption key and the initialization vector (IV).

Trying to load local JSON file to show data in a html page using JQuery

I have Used Following Methods But non of them worked:

   // 2 Method Failed

        $.get(
            'http://www.corsproxy.com/' +
            'en.github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
            function (response) {
                console.log("> ", response);
                $("#viewer").html(response);
            });
// 3 Method Failed

    var jqxhr = $.getJSON( "./json/movies-coming-soon.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {
  console.log( "second complete" );
});

// 4 Method Failed

$.ajax({
   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
   success: function(jsondata){
    console.log(jsondata)
   }
})

// 5 Method Failed


$.ajax({
   url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
   headers: {  'Access-Control-Allow-Origin': 'htt://site allowed to access' },
   dataType: 'jsonp',
   /* etc */
   success: function(jsondata){

   }
})

What worked For me to simply download chrome extension called "200 OK!" or Web server for chrome and write my code like this:

// Worked After local Web Server

        $(document).ready(function () {
            $.getJSON('./json/movies-coming-soon.json', function (data) {
              var movie_name = '';
              var movie_year = '';
                $.each(data,function(i,item){
                    console.log(item.title,item.year,item.poster)
                    movie_name += item.title + "  " + item.year + "<br> <br>"

                    $('#movie_name').html(movie_name)


                })

            })

        })

Its because you can not access local file without running local web server as per CORS policy so in order to running it you must have some host server.

Make error: missing separator

Just to add yet another reason this can show up:

$(eval VALUE)

is not valid and will produce a "missing separator" error.

$(eval IDENTIFIER=VALUE)

is acceptable. This sort of error showed up for me when I had an macro defined with define and tried to do

define SOME_MACRO
... some expression ...
endef

VAR=$(eval $(call SOME_MACRO,arg))

where the macro did not evaluate to an assignment.

Is there an easy way to add a border to the top and bottom of an Android View?

To add a 1dp white border at the bottom only and to have a transparent background you can use the following which is simpler than most answers here.

For the TextView or other view add:

android:background="@drawable/borderbottom"

And in the drawable directory add the following XML, called borderbottom.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-2dp" android:left="-2dp" android:right="-2dp">
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="#ffffffff" />
            <solid android:color="#00000000" />
        </shape>
    </item>
</layer-list>

If you want a border at the top, change the android:top="-2dp" to android:bottom="-2dp"

The colour does not need to be white and the background does not need to be transparent either.

The solid element may not be required. This will depend on your design (thanks V. Kalyuzhnyu).

Basically, this XML will create a border using the rectangle shape, but then pushes the top, right and left sides beyond the render area for the shape. This leaves just the bottom border visible.

JavaScript/regex: Remove text between parentheses

I found this version most suitable for all cases. It doesn't remove all whitespaces.

For example "a (test) b" -> "a b"

"Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, " ").trim(); "Hello, this is (example) Mike ".replace(/ *\([^)]*\) */g, " ").trim();

How can one pull the (private) data of one's own Android app?

You may use this shell script below. It is able to pull files from app cache as well, not like the adb backup tool:

#!/bin/sh

if [ -z "$1" ]; then 
    echo "Sorry script requires an argument for the file you want to pull."
    exit 1
fi

adb shell "run-as com.corp.appName cat '/data/data/com.corp.appNamepp/$1' > '/sdcard/$1'"
adb pull "/sdcard/$1"
adb shell "rm '/sdcard/$1'"

Then you can use it like this:

./pull.sh files/myFile.txt
./pull.sh cache/someCachedData.txt

Java switch statement: Constant expression required, but it IS constant

You can use an enum like in this example:

public class MainClass {
enum Choice { Choice1, Choice2, Choice3 }
public static void main(String[] args) {
Choice ch = Choice.Choice1;

switch(ch) {
  case Choice1:
    System.out.println("Choice1 selected");
    break;
 case Choice2:
   System.out.println("Choice2 selected");
   break;
 case Choice3:
   System.out.println("Choice3 selected");
   break;
    }
  }
}

Source: Switch statement with enum

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

PermGen elimination in JDK 8

This is one of the new features of Java 8, part of JDK Enhancement Proposals 122:

Remove the permanent generation from the Hotspot JVM and thus the need to tune the size of the permanent generation.

The list of all the JEPs that will be included in Java 8 can be found on the JDK8 milestones page.

SQL WHERE condition is not equal to?

Use <> to negate the where clause.

How to get name of the computer in VBA?

You can do like this:

Sub Get_Environmental_Variable()

Dim sHostName As String
Dim sUserName As String

' Get Host Name / Get Computer Name    
sHostName = Environ$("computername")

' Get Current User Name    
sUserName = Environ$("username")

End Sub

Removing elements from an array in C

What solution you need depends on whether you want your array to retain its order, or not.

Generally, you never only have the array pointer, you also have a variable holding its current logical size, as well as a variable holding its allocated size. I'm also assuming that the removeIndex is within the bounds of the array. With that given, the removal is simple:

Order irrelevant

array[removeIndex] = array[--logicalSize];

That's it. You simply copy the last array element over the element that is to be removed, decrementing the logicalSize of the array in the process.

If removeIndex == logicalSize-1, i.e. the last element is to be removed, this degrades into a self-assignment of that last element, but that is not a problem.

Retaining order

memmove(array + removeIndex, array + removeIndex + 1, (--logicalSize - removeIndex)*sizeof(*array));

A bit more complex, because now we need to call memmove() to perform the shifting of elements, but still a one-liner. Again, this also updates the logicalSize of the array in the process.

Get the records of last month in SQL server

SELECT * 
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, date_created) = DATEPART(yyyy, DATEADD(m, -1, getdate()))

You need to check the month and year.

Using Html.ActionLink to call action on different controller

Note that Details is a "View" page under the "Products" folder.

ProductId is the primary key of the table . Here is the line from Index.cshtml

 @Html.ActionLink("Details", "Details","Products" , new  {  id=item.ProductId  },null)

What's the difference between Visual Studio Community and other, paid versions?

Check the following: https://www.visualstudio.com/vs/compare/ Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!

How can I multiply and divide using only bit shifting and adding?

The answer by Andrew Toulouse can be extended to division.

The division by integer constants is considered in details in the book "Hacker's Delight" by Henry S. Warren (ISBN 9780201914658).

The first idea for implementing division is to write the inverse value of the denominator in base two.

E.g., 1/3 = (base-2) 0.0101 0101 0101 0101 0101 0101 0101 0101 .....

So, a/3 = (a >> 2) + (a >> 4) + (a >> 6) + ... + (a >> 30) for 32-bit arithmetics.

By combining the terms in an obvious manner we can reduce the number of operations:

b = (a >> 2) + (a >> 4)

b += (b >> 4)

b += (b >> 8)

b += (b >> 16)

There are more exciting ways to calculate division and remainders.

EDIT1:

If the OP means multiplication and division of arbitrary numbers, not the division by a constant number, then this thread might be of use: https://stackoverflow.com/a/12699549/1182653

EDIT2:

One of the fastest ways to divide by integer constants is to exploit the modular arithmetics and Montgomery reduction: What's the fastest way to divide an integer by 3?

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html

Specifically:

Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.

I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.

How to cache data in a MVC application

Reference the System.Web dll in your model and use System.Web.Caching.Cache

    public string[] GetNames()
    {
      string[] names = Cache["names"] as string[];
      if(names == null) //not in cache
      {
        names = DB.GetNames();
        Cache["names"] = names;
      }
      return names;
    }

A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.

Capturing image from webcam in java?

Here is a similar question with some - yet unaccepted - answers. One of them mentions FMJ as a java alternative to JMF.

How can I auto hide alert box after it showing it?

impossible with javascript. Just as another alternative to suggestions from other answers: consider using jGrowl: http://archive.plugins.jquery.com/project/jGrowl

Where is Java's Array indexOf?

There are a couple of ways to accomplish this using the Arrays utility class.

If the array is not sorted and is not an array of primitives:

java.util.Arrays.asList(theArray).indexOf(o)

If the array is primitives and not sorted, one should use a solution offered by one of the other answers such as Kerem Baydogan's, Andrew McKinlay's or Mishax's. The above code will compile even if theArray is primitive (possibly emitting a warning) but you'll get totally incorrect results nonetheless.

If the array is sorted, you can make use of a binary search for performance:

java.util.Arrays.binarySearch(theArray, o)

How do I start a program with arguments when debugging?

Go to Project-><Projectname> Properties. Then click on the Debug tab, and fill in your arguments in the textbox called Command line arguments.

Check if user is using IE

I know this is an old question, but in case anyone comes across it again and has issues with detecting IE11, here is a working solution for all current versions of IE.

var isIE = false;
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
    isIE = true;   
}

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

Scp command syntax for copying a folder from local machine to a remote server

In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command

Please check this

java.util.Date to XMLGregorianCalendar

I hope my encoding here is right ;D To make it faster just use the ugly getInstance() call of GregorianCalendar instead of constructor call:

import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class DateTest {

   public static void main(final String[] args) throws Exception {
      // do not forget the type cast :/
      GregorianCalendar gcal = (GregorianCalendar) GregorianCalendar.getInstance();
      XMLGregorianCalendar xgcal = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(gcal);
      System.out.println(xgcal);
   }

}

How to create nested directories using Mkdir in Golang?

If the issue is to create all the necessary parent directories, you could consider using os.MkDirAll()

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.

The path_test.go is a good illustration on how to use it:

func TestMkdirAll(t *testing.T) {
    tmpDir := TempDir()
    path := tmpDir + "/_TestMkdirAll_/dir/./dir2"
    err := MkdirAll(path, 0777)
    if err != nil {
    t.Fatalf("MkdirAll %q: %s", path, err)
    }
    defer RemoveAll(tmpDir + "/_TestMkdirAll_")
...
}

(Make sure to specify a sensible permission value, as mentioned in this answer)

How to reload current page without losing any form data?

You can use various local storage mechanisms to store this data in the browser such as Web Storage, IndexedDB, WebSQL (deprecated) and File API (deprecated and only available in Chrome) (and UserData with IE).

The simplest and most widely supported is WebStorage where you have persistent storage (localStorage) or session based (sessionStorage) which is in memory until you close the browser. Both share the same API.

You can for example (simplified) do something like this when the page is about to reload:

window.onbeforeunload = function() {
    localStorage.setItem("name", $('#inputName').val());
    localStorage.setItem("email", $('#inputEmail').val());
    localStorage.setItem("phone", $('#inputPhone').val());
    localStorage.setItem("subject", $('#inputSubject').val());
    localStorage.setItem("detail", $('#inputDetail').val());
    // ...
}

Web Storage works synchronously so this may work here. Optionally you can store the data for each blur event on the elements where the data is entered.

At page load you can check:

window.onload = function() {

    var name = localStorage.getItem("name");
    if (name !== null) $('#inputName').val("name");

    // ...
}

getItem returns null if the data does not exist.

Use sessionStorage instead of localStorage if you want to store only temporary.

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

I had similar issue, I resolved by changing the requestlimits maxAllowedContentLength ="40000000" section of applicationhost.config file, located in "C:\Windows\System32\inetsrv\config" directory

Look for security Section and add the sectionGroup.

<sectionGroup name="requestfiltering">
    <section name="requestlimits" maxAllowedContentLength ="40000000" />
</sectionGroup>

*NOTE delete;

<section name="requestfiltering" overrideModeDefault="Deny" />

Java maximum memory on Windows XP

Keep in mind that Windows has virtual memory management and the JVM only needs memory that is contiguous in its address space. So, other programs running on the system shouldn't necessarily impact your heap size. What will get in your way are DLL's that get loaded in to your address space. Unfortunately optimizations in Windows that minimize the relocation of DLL's during linking make it more likely you'll have a fragmented address space. Things that are likely to cut in to your address space aside from the usual stuff include security software, CBT software, spyware and other forms of malware. Likely causes of the variances are different security patches, C runtime versions, etc. Device drivers and other kernel bits have their own address space (the other 2GB of the 4GB 32-bit space).

You could try going through your DLL bindings in your JVM process and look at trying to rebase your DLL's in to a more compact address space. Not fun, but if you are desperate...

Alternatively, you can just switch to 64-bit Windows and a 64-bit JVM. Despite what others have suggested, while it will chew up more RAM, you will have much more contiguous virtual address space, and allocating 2GB contiguously would be trivial.

DROP IF EXISTS VS DROP?

You forgot the table in your syntax:

drop table [table_name]

which drops a table.

Using

drop table if exists [table_name]

checks if the table exists before dropping it.
If it exists, it gets dropped.
If not, no error will be thrown and no action be taken.

What is the difference between the float and integer data type when the size is the same?

  • float stores floating-point values, that is, values that have potential decimal places
  • int only stores integral values, that is, whole numbers

So while both are 32 bits wide, their use (and representation) is quite different. You cannot store 3.141 in an integer, but you can in a float.

Dissecting them both a little further:

In an integer, all bits are used to store the number value. This is (in Java and many computers too) done in the so-called two's complement. This basically means that you can represent the values of −231 to 231 − 1.

In a float, those 32 bits are divided between three distinct parts: The sign bit, the exponent and the mantissa. They are laid out as follows:

S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM

There is a single bit that determines whether the number is negative or non-negative (zero is neither positive nor negative, but has the sign bit set to zero). Then there are eight bits of an exponent and 23 bits of mantissa. To get a useful number from that, (roughly) the following calculation is performed:

M × 2E

(There is more to it, but this should suffice for the purpose of this discussion)

The mantissa is in essence not much more than a 24-bit integer number. This gets multiplied by 2 to the power of the exponent part, which, roughly, is a number between −128 and 127.

Therefore you can accurately represent all numbers that would fit in a 24-bit integer but the numeric range is also much greater as larger exponents allow for larger values. For example, the maximum value for a float is around 3.4 × 1038 whereas int only allows values up to 2.1 × 109.

But that also means, since 32 bits only have 4.2 × 109 different states (which are all used to represent the values int can store), that at the larger end of float's numeric range the numbers are spaced wider apart (since there cannot be more unique float numbers than there are unique int numbers). You cannot represent some numbers exactly, then. For example, the number 2 × 1012 has a representation in float of 1,999,999,991,808. That might be close to 2,000,000,000,000 but it's not exact. Likewise, adding 1 to that number does not change it because 1 is too small to make a difference in the larger scales float is using there.

Similarly, you can also represent very small numbers (between 0 and 1) in a float but regardless of whether the numbers are very large or very small, float only has a precision of around 6 or 7 decimal digits. If you have large numbers those digits are at the start of the number (e.g. 4.51534 × 1035, which is nothing more than 451534 follows by 30 zeroes – and float cannot tell anything useful about whether those 30 digits are actually zeroes or something else), for very small numbers (e.g. 3.14159 × 10−27) they are at the far end of the number, way beyond the starting digits of 0.0000...

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

You can use bash. Note for very large files in terms of GB, use awk/wc. However it should still be manageable in performance for files with a few MB.

declare -i count=0
while read
do
    ((count++))
done < file    
echo "line count: $count"

Why use a ReentrantLock if one can use synchronized(this)?

I think the wait/notify/notifyAll methods don't belong on the Object class as it pollutes all objects with methods that are rarely used. They make much more sense on a dedicated Lock class. So from this point of view, perhaps it's better to use a tool that is explicitly designed for the job at hand - ie ReentrantLock.

How to remove the URL from the printing page?

Browser issue but can be solved by these:

<style type="text/css" media="print">
      @media print
      {
         @page {
           margin-top: 0;
           margin-bottom: 0;
         }
         body  {
           padding-top: 72px;
           padding-bottom: 72px ;
         }
      } 
</style>

How to get the start time of a long-running Linux process?

As a follow-up to Adam Matan's answer, the /proc/<pid> directory's time stamp as such is not necessarily directly useful, but you can use

awk -v RS=')' 'END{print $20}' /proc/12345/stat

to get the start time in clock ticks since system boot.1

This is a slightly tricky unit to use; see also convert jiffies to seconds for details.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/12345/stat

This should give you seconds, which you can pass to strftime() to get a (human-readable, or otherwise) timestamp.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/12345/stat

Updated with some fixes from Stephane Chazelas in the comments; thanks as always!

If you only have Mawk, maybe try

awk -v ticks="$(getconf CLK_TCK)" -v epoch="$(date +%s)" '
  NR==1 { now=$1; next }
  END { printf "%9.0f\n", epoch - (now-($20/ticks)) }' /proc/uptime RS=')' /proc/12345/stat |
xargs -i date -d @{}

1 man proc; search for starttime.

How can I force browsers to print background images in CSS?

Browsers, by default, have their option to print background-colors and images turned off. You can add some lines in CSS to bypass this. Just add:

* {
    -webkit-print-color-adjust: exact !important;   /* Chrome, Safari */
    color-adjust: exact !important;                 /*Firefox*/
}

Is it possible to use the instanceof operator in a switch statement?

This is a typical scenario where subtype polymorphism helps. Do the following

interface I {
  void do();
}

class A implements I { void do() { doA() } ... }
class B implements I { void do() { doB() } ... }
class C implements I { void do() { doC() } ... }

Then you can simply call do() on this.

If you are not free to change A, B, and C, you could apply the visitor pattern to achieve the same.

HTML radio buttons allowing multiple selections

All radio buttons must have the same name attribute added.

Have a div cling to top of screen if scrolled down past it

The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.

This is done with something like this, attaching a handler to the window.scroll event

   // Cache selectors outside callback for performance. 
   var $window = $(window),
       $stickyEl = $('#the-sticky-div'),
       elTop = $stickyEl.offset().top;

   $window.scroll(function() {
        $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
    });

This simply adds a sticky CSS class when the page has scrolled past it, and removes the class when it's back up.

And the CSS class looks like this

  #the-sticky-div.sticky {
     position: fixed;
     top: 0;
  }

EDIT- Modified code to cache jQuery objects, faster now.

How can I import data into mysql database via mysql workbench?

  • Under Server Administration on the Home window select the server instance you want to restore database to (Create New Server Instance if doing it first time).
  • Click on Manage Import/Export
  • Click on Data Import/Restore on the left side of the screen.
  • Select Import from Self-Contained File radio button (right side of screen)
  • Select the path of .sql
  • Click Start Import button at the right bottom corner of window.

Hope it helps.

---Edited answer---

Regarding selection of the schema. MySQL Workbench (5.2.47 CE Rev1039) does not yet support exporting to the user defined schema. It will create only the schema for which you exported the .sql... In 5.2.47 we see "New" target schema. But it does not work. I use MySQL Administrator (the old pre-Oracle MySQL Admin beauty) for my work for backup/restore. You can still download it from Googled trustable sources (search MySQL Administrator 1.2.17).

Using PowerShell to remove lines from a text file if it contains a string

Suppose you want to write that in the same file, you can do as follows:

Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)

How to check if object property exists with a variable holding the property name?

Thank you for everyone's assistance and pushing to get rid of the eval statement. Variables needed to be in brackets, not dot notation. This works and is clean, proper code.

Each of these are variables: appChoice, underI, underObstr.

if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
    //enter code here
}

How in node to split string by newline ('\n')?

I made an eol module for working with line endings in node or browsers. It has a split method like

var lines = eol.split(text)

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

git reset does know five "modes": soft, mixed, hard, merge and keep. I will start with the first three, since these are the modes you'll usually encounter. After that you'll find a nice little a bonus, so stay tuned.

soft

When using git reset --soft HEAD~1 you will remove the last commit from the current branch, but the file changes will stay in your working tree. Also the changes will stay on your index, so following with a git commit will create a commit with the exact same changes as the commit you "removed" before.

mixed

This is the default mode and quite similar to soft. When "removing" a commit with git reset HEAD~1 you will still keep the changes in your working tree but not on the index; so if you want to "redo" the commit, you will have to add the changes (git add) before commiting.

hard

When using git reset --hard HEAD~1 you will lose all uncommited changes in addition to the changes introduced in the last commit. The changes won't stay in your working tree so doing a git status command will tell you that you don't have any changes in your repository.

Tread carefully with this one. If you accidentally remove uncommited changes which were never tracked by git (speak: committed or at least added to the index), you have no way of getting them back using git.

Bonus

keep

git reset --keep HEAD~1 is an interesting and useful one. It only resets the files which are different between the current HEAD and the given commit. It aborts the reset if one or more of these files has uncommited changes. It basically acts as a safer version of hard.


You can read more about that in the git reset documentation.

Note
When doing git reset to remove a commit the commit isn't really lost, there just is no reference pointing to it or any of it's children. You can still recover a commit which was "deleted" with git reset by finding it's SHA-1 key, for example with a command such as git reflog.

How to make an embedded video not autoplay

I had the same problem and came across this post. Nothing worked. After randomly playing around, I found that <embed ........ play="false"> stopped it from playing automatically. I now have the problem that I can't get a controller to appear, so can't start the movie! :S

Get first and last date of current month with JavaScript or jQuery

Very simple, no library required:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

or you might prefer:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

EDIT

Some browsers will treat two digit years as being in the 20th century, so that:

new Date(14, 0, 1);

gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:

var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14

how to convert String into Date time format in JAVA?

Using this,

        String s = "03/24/2013 21:54";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
        try
        {
            Date date = simpleDateFormat.parse(s);

            System.out.println("date : "+simpleDateFormat.format(date));
        }
        catch (ParseException ex)
        {
            System.out.println("Exception "+ex);
        }

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

The Concat method will return an object which implements IEnumerable<T> by returning an object (call it Cat) whose enumerator will attempt to use the two passed-in enumerable items (call them A and B) in sequence. If the passed-in enumerables represent sequences which will not change during the lifetime of Cat, and which can be read from without side-effects, then Cat may be used directly. Otherwise, it may be a good idea to call ToList() on Cat and use the resulting List<T> (which will represent a snapshot of the contents of A and B).

Some enumerables take a snapshot when enumeration begins, and will return data from that snapshot if the collection is modified during enumeration. If B is such an enumerable, then any change to B which occurs before Cat has reached the end of A will show up in Cat's enumeration, but changes which occur after that will not. Such semantics may likely be confusing; taking a snapshot of Cat can avoid such issues.

Differences between SP initiated SSO and IDP initiated SSO

https://support.procore.com/faq/what-is-the-difference-between-sp-and-idp-initiated-sso

There is much more to this but this is a high level overview on which is which.

Procore supports both SP- and IdP-initiated SSO:

Identity Provider Initiated (IdP-initiated) SSO. With this option, your end users must log into your Identity Provider's SSO page (e.g., Okta, OneLogin, or Microsoft Azure AD) and then click an icon to log into and open the Procore web application. To configure this solution, see Configure IdP-Initiated SSO for Microsoft Azure AD, Configure Procore for IdP-Initated Okta SSO, or Configure IdP-Initiated SSO for OneLogin. OR Service Provider Initiated (SP-initiated) SSO. Referred to as Procore-initiated SSO, this option gives your end users the ability to sign into the Procore Login page and then sends an authorization request to the Identify Provider (e.g., Okta, OneLogin, or Microsoft Azure AD). Once the IdP authenticates the user's identify, the user is logged into Procore. To configure this solution, see Configure Procore-Initiated SSO for Microsoft Azure Active Directory, Configure Procore-Initiated SSO for Okta, or Configure Procore-Initiated SSO for OneLogin.

Decimal to Hexadecimal Converter in Java

The easiest way to do this is:

String hexadecimalString = String.format("%x", integerValue);

Use curly braces to initialize a Set in Python

Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.

JUnit Testing Exceptions

@Test(expected = Exception.class)  

Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.

For

@Test

Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

6 digits regular expression

You could try

^[0-9]{1,6}$

it should work.

Angular, content type is not being sent with $http

Just to show an example of how to dynamically add the "Content-type" header to every POST request. In may case I'm passing POST params as query string, that is done using the transformRequest. In this case its value is application/x-www-form-urlencoded.

// set Content-Type for POST requests
angular.module('myApp').run(basicAuth);
function basicAuth($http) {
    $http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
}

Then from the interceptor in the request method before return the config object

// if header['Content-type'] is a POST then add data
'request': function (config) {
  if (
    angular.isDefined(config.headers['Content-Type']) 
    && !angular.isDefined(config.data)
  ) {
    config.data = '';
  }
  return config;
}

installing vmware tools: location of GCC binary?

sudo apt-get install build-essential is enough to get it working.

time.sleep -- sleeps thread or process?

The thread will block, but the process is still alive.

In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.

Developing for Android in Eclipse: R.java not regenerating

It is ALWAYS helpful to take a look at the Problems Tab in Eclipse. In my case, I was getting a "android unable to resolve target 'android-8'" error message that kept the R.java from being generated. So, I corrected the imported target to the one I was using in the default.properties file, then I performed a clean via Projects->Clean and voila! R.java is automatically generated! Hope it helps!

Delete ActionLink with confirm dialog

I wanted the same thing; a delete button on my Details view. I eventually realised I needed to post from that view:

@using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(model => model.Id)
            @Html.ActionLink("Edit", "Edit", new { id = Model.Id }, new { @class = "btn btn-primary", @style="margin-right:30px" })

            <input type="submit" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this record?');" />
        }

And, in the Controller:

 // this action deletes record - called from the Delete button on Details view
    [HttpPost]
    public ActionResult Details(MainPlus mainPlus)
    {
        if (mainPlus != null)
        {
            try
            {
                using (IDbConnection db = new SqlConnection(PCALConn))
                {
                    var result = db.Execute("DELETE PCAL.Main WHERE Id = @Id", new { Id = mainPlus.Id });
                }
                return RedirectToAction("Calls");
            } etc

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Add button to navigationbar programmatically

UIImage* image3 = [UIImage imageNamed:@"back_button.png"];
CGRect frameimg = CGRectMake(15,5, 25,25);

UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(Back_btn:)
     forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];

UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem =mailbutton;
[someButton release];

///// called event

-(IBAction)Back_btn:(id)sender
{
    //Your code here
}

SWIFT:

var image3 = UIImage(named: "back_button.png")
var frameimg = CGRect(x: 15, y: 5, width: 25, height: 25)

var someButton = UIButton(frame: frameimg)
someButton.setBackgroundImage(image3, for: .normal)
someButton.addTarget(self, action: Selector("Back_btn:"), for: .touchUpInside)
someButton.showsTouchWhenHighlighted = true

var mailbutton = UIBarButtonItem(customView: someButton)
navigationItem?.leftBarButtonItem = mailbutton

func back_btn(_ sender: Any) {
    //Your code here
}

what is the difference between json and xml

XML uses a tag structures for presenting items, like <tag>item</tag>, so an XML document is a set of tags nested into each other. And JSON syntax looks like a construction from Javascript language, with all stuff like lists and dictionaries:

{
 'attrib' : 'value',
 'array' : [1, 2, 3]
}

So if you use JSON it's really simple to use a JSON strings in many script languages, especially Javascript and Python.

Have bash script answer interactive prompts

If you only have Y to send :

$> yes Y |./your_script

If you only have N to send :

$> yes N |./your_script

Webpack.config how to just copy the index.html to the dist folder

You can add the index directly to your entry config and using a file-loader to load it

module.exports = {

  entry: [
    __dirname + "/index.html",
    .. other js files here
  ],

  module: {
    rules: [
      {
        test: /\.html/, 
        loader: 'file-loader?name=[name].[ext]', 
      },
      .. other loaders
    ]
  }

}

Annotation-specified bean name conflicts with existing, non-compatible bean def

If none of the other answers fix your problem and it started occurring after change any configuration direct or indirectly (via git pull / merge / rebase) and your project is a Maven project:

mvn clean

Hope this fixes your problem. Or someones

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

How can I issue a single command from the command line through sql plus?

For UNIX (AIX):

export ORACLE_HOME=/oracleClient/app/oracle/product/version
export DBUSER=fooUser
export DBPASSWD=fooPW
export DBNAME=fooSchema 

echo "select * from someTable;" | $ORACLE_HOME/bin/sqlplus $DBUSER/$DBPASSWD@$DBNAME

Origin <origin> is not allowed by Access-Control-Allow-Origin

router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header("Access-Control-Allow-Headers", "*");
next();});

add this to your routes which you are calling from front-end. Ex- if you call for http://localhost:3000/users/register you must add this code fragment on your back-end .js file which this route lays.

How to tell if UIViewController's view is visible

Here's @progrmr's solution as a UIViewController category:

// UIViewController+Additions.h

@interface UIViewController (Additions)

- (BOOL)isVisible;

@end


// UIViewController+Additions.m

#import "UIViewController+Additions.h"

@implementation UIViewController (Additions)

- (BOOL)isVisible {
    return [self isViewLoaded] && self.view.window;
}

@end

Measure string size in Bytes in php

Further to PhoneixS answer to get the correct length of string in bytes - Since mb_strlen() is slower than strlen(), for the best performance one can check "mbstring.func_overload" ini setting so that mb_strlen() is used only when it is really required:

$content_length = ini_get('mbstring.func_overload') ? mb_strlen($content , '8bit') : strlen($content);

AngularJS - Attribute directive input value change

Since this must have an input element as a parent, you could just use

<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">

Alternatively, you could use the ngModelController and add a function to $formatters, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

.directive("myDirective", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      ngModel.$formatters.push(function(value) {
        // Do stuff here, and return the formatted value.
      });
  };
};

XAMPP installation on Win 8.1 with UAC Warning

You can solve this problem by installing xampp in different Drive .Instead of C Drive .

Select Last Row in the Table

To get last record details

  1. Model::all()->last(); or
  2. Model::orderBy('id', 'desc')->first();

To get last record id

  1. Model::all()->last()->id; or
  2. Model::orderBy('id', 'desc')->first()->id;

submit the form using ajax

I would suggest to use jquery for this type of requirement . Give this a try

<div id="commentList"></div>
<div id="addCommentContainer">
    <p>Add a Comment</p> <br/> <br/>
    <form id="addCommentForm" method="post" action="">
        <div>
            Your Name <br/>
            <input type="text" name="name" id="name" />


            <br/> <br/>
            Comment Body <br/>
            <textarea name="body" id="body" cols="20" rows="5"></textarea>

            <input type="submit" id="submit" value="Submit" />
        </div>
    </form>
</div>?

$(document).ready(function(){
    /* The following code is executed once the DOM is loaded */

    /* This flag will prevent multiple comment submits: */
    var working = false;
    $("#submit").click(function(){
    $.ajax({
         type: 'POST',
         url: "mysubmitpage.php",
         data: $('#addCommentForm').serialize(), 
         success: function(response) {
            alert("Submitted comment"); 
             $("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
         },
        error: function() {
             //$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
            alert("There was an error submitting comment");
        }
     });
});
});?

Run a single test method with maven

I tried several solutions provided in this thread, however they were not working for module which depends on a different one. In that case I had to run mvn from the root-module with additional parameters: -am (--also-make), which tells maven to built modules which your test module depends on and -DfailIfNoTests=false, otherwise "No tests were executed!" error appears.

mvn test -pl B -Dtest=MyTestClass#myTest -am -DfailIfNoTests=false

pom.xml section in root:

<modules>
    <module>A</module>
    <module>B</module>
<modules>

B depends on A.

Bring a window to the front in WPF

The problem could be that the thread calling your code from the hook hasn't been initialized by the runtime so calling runtime methods don't work.

Perhaps you could try doing an Invoke to marshal your code on to the UI thread to call your code that brings the window to the foreground.

Java difference between FileWriter and BufferedWriter

In unbuffered Input/Output(FileWriter, FileReader) read or write request is handled directly by the underlying OS. https://hajsoftutorial.com/java/wp-content/uploads/2018/04/Unbuffered.gif

This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams. The BufferedReader and BufferedWriter classes provide internal character buffers. Text that’s written to a buffered writer is stored in the internal buffer and only written to the underlying writer when the buffer fills up or is flushed. https://hajsoftutorial.com/java/wp-content/uploads/2018/04/bufferedoutput.gif

More https://hajsoftutorial.com/java-bufferedwriter/

MySQL Cannot drop index needed in a foreign key constraint

I think this is easy way to drop the index.

set FOREIGN_KEY_CHECKS=0; //disable checks

ALTER TABLE mytable DROP INDEX AID;

set FOREIGN_KEY_CHECKS=1; //enable checks

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

What solved it for me was setting Build Active Architecture Only from No to Yes.

Using number as "index" (JSON)

JSON is "JavaScript Object Notation". JavaScript specifies its keys must be strings or symbols.

The following quotation from MDN Docs uses the terms "key/property" to refer to what I more often hear termed as "key/value".

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Objects

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

Batch File; List files in directory, only filenames?

If you need the subdirectories too you need a "dir" command and a "For" command

dir /b /s DIRECTORY\*.* > list1.txt

for /f "tokens=*" %%A in (list1.txt) do echo %%~nxA >> list.txt

del list1.txt

put your root directory in dir command. It will create a list1.txt with full path names and then a list.txt with only the file names.

React PropTypes : Allow different types of PropTypes for one prop

size: PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]),

Learn more: Typechecking With PropTypes

A project with an Output Type of Class Library cannot be started directly

If you got this issue (got it in Visual Studio 2017 RC), and you don't get any of the things listed by Mak post from step 3 onward "4 In the Output Type drop box....", it is because you made a Class Library app when you want to create a cross platform app, so here is the solution :

1 Start a new project

2 select Visual C# and cross-platform app.

3 select cross-platform app (Xamarin and native app)

4 select blank form.

From then , right click, select as startup project and build as mentioned by Mak, and it should work.

If you can afford to start from scratch, it could do the trick as it did for me.

This could do the trick for the main issue as well, but must be adapted to your current version of Visual Studio ("Xamarin.forms portable" for visual studio 2015 for example).

Bye!

Adding an onclick function to go to url in JavaScript?

try

location = url;

_x000D_
_x000D_
function url() {_x000D_
    location = 'https://example.com';_x000D_
}
_x000D_
<input type="button" value="Inline" _x000D_
onclick="location='https://example.com'" />_x000D_
_x000D_
<input type="button" value="URL()" _x000D_
onclick="url()" />
_x000D_
_x000D_
_x000D_

How to set the thumbnail image on HTML5 video?

<?php
$thumbs_dir = 'E:/xampp/htdocs/uploads/thumbs/';
$videos = array();
if (isset($_POST["name"])) {
 if (!preg_match('/data:([^;]*);base64,(.*)/', $_POST['data'], $matches)) {
  die("error");
 }
 $data = $matches[2];
 $data = str_replace(' ', '+', $data);
 $data = base64_decode($data);
 $file = 'text.jpg';
 $dataname = file_put_contents($thumbs_dir . $file, $data);
}
?>
//jscode
<script type="text/javascript">
 var videos = <?= json_encode($videos); ?>;
 var video = document.getElementById('video');
 video.addEventListener('canplay', function () {
     this.currentTime = this.duration / 2;
 }, false);
 var seek = true;
 video.addEventListener('seeked', function () {
    if (seek) {
         getThumb();
    }
 }, false);

 function getThumb() {
     seek = false;
     var filename = video.src;
     var w = video.videoWidth;//video.videoWidth * scaleFactor;
     var h = video.videoHeight;//video.videoHeight * scaleFactor;
     var canvas = document.createElement('canvas');
     canvas.width = w;
     canvas.height = h;
     var ctx = canvas.getContext('2d');
     ctx.drawImage(video, 0, 0, w, h);
     var data = canvas.toDataURL("image/jpg");
     var xmlhttp = new XMLHttpRequest;
     xmlhttp.onreadystatechange = function () {
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
         }
     }
     xmlhttp.open("POST", location.href, true);
     xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xmlhttp.send('name=' + encodeURIComponent(filename) + '&data=' + data);
 }
  function failed(e) {
     // video playback failed - show a message saying why
     switch (e.target.error.code) {
         case e.target.error.MEDIA_ERR_ABORTED:
             console.log('You aborted the video playback.');
             break;
         case e.target.error.MEDIA_ERR_NETWORK:
             console.log('A network error caused the video download to fail part-way.');
             break;
         case e.target.error.MEDIA_ERR_DECODE:
             console.log('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
              break;
          case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
              console.log('The video could not be loaded, either because the server or network failed or because the format is not supported.');
              break;
          default:
              console.log('An unknown error occurred.');
              break;
      }


  }
</script>
//Html
<div>
    <video   id="video" src="1499752288.mp4" autoplay="true"  onerror="failed(event)" controls="controls" preload="none"></video>
</div>

Colorplot of 2D array matplotlib

Here is the simplest example that has the key lines of code:

import numpy as np 
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')
plt.show()

enter image description here

Switch statement equivalent in Windows batch file

I searched switch / case in batch files today and stumbled upon this. I used this solution and extended it with a goto exit.

IF "%1"=="red" echo "one selected" & goto exit
IF "%1"=="two" echo "two selected" & goto exit
...

echo "Options: [one | two | ...]

:exit 

Which brings in the default state (echo line) and no extra if's when the choice is found.

How to convert unsigned long to string

Try using sprintf:

unsigned long x=1000000;
char buffer[21];
sprintf(buffer,"%lu", x);

Edit:

Notice that you have to allocate a buffer in advance, and have no idea how long the numbers will actually be when you do so. I'm assuming 32bit longs, which can produce numbers as big as 10 digits.

See Carl Smotricz's answer for a better explanation of the issues involved.

jQuery: go to URL with target="_blank"

The .ready function is used to insert the attribute once the page has finished loading.

$(document).ready(function() {
     $("class name or id a.your class name").attr({"target" : "_blank"})
})

How do I make background-size work in IE?

you can use this file (https://github.com/louisremi/background-size-polyfill “background-size polyfill”) for IE8 that is really simple to use:

.selector {
background-size: cover;
-ms-behavior: url(/backgroundsize.min.htc);
}

How to remove first and last character of a string?

Another solution for this issue is use commons-lang (since version 2.0) StringUtils.substringBetween(String str, String open, String close) method. Main advantage is that it's null safe operation.

StringUtils.substringBetween("[wdsd34svdf]", "[", "]"); // returns wdsd34svdf

Restore a postgres backup file using the command line?

try this:

psql -U <username> -d <dbname> -f <filename>.sql

Restore DB psql from .sql file

Dockerfile if else condition with external arguments

The accepted answer may solve the question, but if you want multiline if conditions in the dockerfile, you can do that placing \ at the end of each line (similar to how you would do in a shell script) and ending each command with ;. You can even define someting like set -eux as the 1st command.

Example:

RUN set -eux; \
  if [ -f /path/to/file ]; then \
    mv /path/to/file /dest; \
  fi; \
  if [ -d /path/to/dir ]; then \
    mv /path/to/dir /dest; \
  fi

In your case:

FROM centos:7
ARG arg
RUN if [ -z "$arg" ] ; then \
    echo Argument not provided; \
  else \
    echo Argument is $arg; \
  fi

Then build with:

docker build -t my_docker . --build-arg arg=42

Printing PDFs from Windows Command Line

I had two problems with using Acrobat Reader for this task.

  1. The command line API is not officially supported, so it could change or be removed without warning.
  2. Send a print command to Reader loads up the GUI, with seemingly no way to prevent it. I needed the process to be transparent to the user.

I stumbled across this blog, that suggests using Foxit Reader. Foxit Reader is free, the API is almost identical to Acrobat Reader, but crucially is documented and does not load the GUI for print jobs.

A word of warning, don't just click through the install process without paying attention, it tries to install unrelated software as well. Why are software vendors still doing this???

Regular expression field validation in jQuery

My code :

$("input.numeric").keypress(function(e) { /* pour les champs qui ne prennent que du numeric en entrée */          
            var key = e.charCode || e.keyCode || 0;                     
            var keychar = String.fromCharCode(key);
            /*alert("keychar:"+keychar + " \n charCode:" + e.charCode + " \n key:" +key);*/
            if (  ((key == 8 || key == 9 || key == 46 || key == 35 || key == 36 || (key >= 37 && key <= 40)) && e.charCode==0) /* backspace, end, begin, top, bottom, right, left, del, tab */
                    || (key >= 48 && key <= 57) ) { /* 0-9 */
                return;
            } else {
                e.preventDefault();
            }
        });

Go to "next" iteration in JavaScript forEach loop

just return true inside your if statement

var myArr = [1,2,3,4];

myArr.forEach(function(elem){
  if (elem === 3) {

      return true;

    // Go to "next" iteration. Or "continue" to next iteration...
  }

  console.log(elem);
});

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

Update your pom.xml

<dependency>
  <groupId>asm</groupId>
  <artifactId>asm</artifactId>
  <version>3.1</version>
</dependency>

What is the most efficient way to loop through dataframes with pandas?

Just as a small addition, you can also do an apply if you have a complex function that you apply to a single column:

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html

df[b] = df[a].apply(lambda col: do stuff with col here)

How to initailize byte array of 100 bytes in java with all 0's

Actually the default value of byte is 0.

How to parse string into date?

You can use:

SELECT CONVERT(datetime, '24.04.2012', 103) AS Date

Reference: CAST and CONVERT (Transact-SQL)

What is the difference between background and background-color

This is the best answer. Shorthand (background) is for reset and DRY (combine with longhand).

Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup....

manifest.json

{
  "name": "Get pages source",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Get pages source from a popup",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

getPagesSource.js

// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);

function DOMtoString(document_root) {
    var html = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            html += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            html += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            html += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            html += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
            break;
        }
        node = node.nextSibling;
    }
    return html;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

Below solved. I have wrongly given the bin /directory/, so faced the issue:

if you installed apache at C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24
then the modules are at.. C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24/modules

So, the file           C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24/conf/httpd.conf
should have
       Define SRVROOT "C:/httpd-2.4.41-o102s-x64-vc14-r2/Apache24/"

Hope that helps

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

Get content of a cell given the row and column numbers

It took me a while, but here's how I made it dynamic. It doesn't depend on a sorted table.

First I started with a column of state names (Column A) and a column of aircraft in each state (Column B). (Row 1 is a header row).

Finding the cell that contains the number of aircraft was:

=MATCH(MAX($B$2:$B$54),$B$2:$B$54,0)+MIN(ROW($B$2:$B$54))-1

I put that into a cell and then gave that cell a name, "StateRow" Then using the tips from above, I wound up with this:

=INDIRECT(ADDRESS(StateRow,1))

This returns the name of the state from the dynamic value in row "StateRow", column 1

Now, as the values in the count column change over time as more data is entered, I always know which state has the most aircraft.

CASE in WHERE, SQL Server

.. ELSE a.Country ...

I suppose

IE11 meta element Breaks SVG

It sounds as though you're not in a modern document mode. Internet Explorer 11 shows the SVG just fine when you're in Standards Mode. Make sure that if you have an x-ua-compatible meta tag, you have it set to Edge, rather than an earlier mode.

<meta http-equiv="X-UA-Compatible" content="IE=edge">

You can determine your document mode by opening up your F12 Developer Tools and checking either the document mode dropdown (seen at top-right, currently "Edge") or the emulation tab:

enter image description here

If you do not have an x-ua-compatible meta tag (or header), be sure to use a doctype that will put the document into Standards mode, such as <!DOCTYPE html>.

enter image description here

In log4j, does checking isDebugEnabled before logging improve performance?

Using the isDebugEnabled() is reserved for when you're building up log messages by concatenating Strings:

Var myVar = new MyVar();
log.debug("My var is " + myVar + ", value:" + myVar.someCall());

However, in your example there is no speed gain as you're just logging a String and not performing operations such as concatenation. Therefore you're just adding bloat to your code and making it harder to read.

I personally use the Java 1.5 format calls in the String class like this:

Var myVar = new MyVar();
log.debug(String.format("My var is '%s', value: '%s'", myVar, myVar.someCall()));

I doubt there's much optimisation but it's easier to read.

Do note though that most logging APIs offer formatting like this out of the box: slf4j for example provides the following:

logger.debug("My var is {}", myVar);

which is even easier to read.

XSLT - How to select XML Attribute by Attribute?

Try this

xsl:variable name="myVarA" select="//DataSet/Data[@Value1='2']/@Value2" />

The '//' will search for DataSet at any depth

unable to set private key file: './cert.pem' type PEM

I have a similar situation, but I use the key and the certificate in different files.

in my case you can check the matching of the key and the lock by comparing the hashes (see https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/). This helped me to identify inconsistencies.

How to sort an array of objects in Java?

import java.util.Collections;

import java.util.List;

import java.util.ArrayList;


public class Test {

public static void main(String[] args) {

   List<Student> str = new ArrayList<Student>();

   str.add(new Student(101, "aaa"));

   str.add(new Student(104, "bbb"));

   str.add(new Student(103, "ccc"));

   str.add(new Student(105, "ddd"));

   str.add(new Student(104, "eee"));

   str.add(new Student(102, "fff"));




   Collections.sort(str);
    for(Student student : str) {

        System.out.println(student);
    }

}
}

How to get a complete list of object's methods and attributes?

Only to supplement:

  1. dir() is the most powerful/fundamental tool. (Most recommended)
  2. Solutions other than dir() merely provide their way of dealing the output of dir().

    Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __, but sometimes you may well need the __doc__ doc-string.

  3. __dir__() and dir() returns identical content.
  4. __dict__ and dir() are different. __dict__ returns incomplete content.
  5. IMPORTANT: __dir__() can be sometimes overwritten with a function, value or type, by the author for whatever purpose.

    Here is an example:

    \\...\\torchfun.py in traverse(self, mod, search_attributes)
    445             if prefix in traversed_mod_names:
    446                 continue
    447             names = dir(m)
    448             for name in names:
    449                 obj = getattr(m,name)
    

    TypeError: descriptor __dir__ of 'object' object needs an argument

    The author of PyTorch modified the __dir__() method to something that requires an argument. This modification makes dir() fail.

  6. If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.

Index (zero based) must be greater than or equal to zero

Change this line:

The 2 should be 0. Every count starts at 0.

//Aboutme.Text = String.Format("{2}", reader.GetString(0));//wrong

//Aboutme.Text = String.Format("{0}", reader.GetString(0));//correct

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Assuming you want uppercase case letters:

function numberToLetter(num){
        var alf={
            '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G'
        };
        if(num.length== 1) return alf[num] || ' ';
        return num.split('').map(numberToLetter);
    }

Example:

numberToLetter('023') is ["A", "C", "D"]

numberToLetter('5') is "F"

number to letter function

C# static class constructor

Static constructor called only the first instance of the class created.

like this:

static class YourClass
{
    static YourClass()
    {
        //initialization
    }
}

Convert a SQL query result table to an HTML table for email

based on JustinStolle code (thank you), I wanted a solution that could be generic without having to specify the column names.

This sample is using the data of a temp table but of course it can be adjusted as required.

Here is what I got:

DECLARE @htmlTH VARCHAR(MAX) = '',
        @htmlTD VARCHAR(MAX)

--get header, columns name
SELECT @htmlTH = @htmlTH + '<TH>' +  name + '</TH>' FROM tempdb.sys.columns WHERE object_id = OBJECT_ID('tempdb.dbo.#results')

--convert table to XML PATH, ELEMENTS XSINIL is used to include NULL values
SET @htmlTD = (SELECT * FROM #results FOR XML PATH('TR'), ELEMENTS XSINIL)

--convert the way ELEMENTS XSINIL display NULL to display word NULL
SET @htmlTD = REPLACE(@htmlTD, ' xsi:nil="true"/>', '>NULL</TD>')
SET @htmlTD = REPLACE(@htmlTD, '<TR xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">', '<TR>')

--FOR XML PATH will set tags for each column name, <columnName1>abc</columnName1><columnName2>def</columnName2>
--this will replace all the column names with TD (html table data tag)
SELECT @htmlTD = REPLACE(REPLACE(@htmlTD, '<' + name + '>', '<TD>'), '</' + name + '>', '</TD>')
FROM tempdb.sys.columns WHERE object_id = OBJECT_ID('tempdb.dbo.#results')


SELECT '<TABLE cellpadding="2" cellspacing="2" border="1">'
     + '<TR>' + @htmlTH + '</TR>'
     + @htmlTD
     + '</TABLE>'

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

I am using Docker. I am trying to create a docker image that has all of my node dependencies installed, but can use my local app directory at container run time (without polluting it with a node_modules directory or link). This causes problems in this scenario. My workaround is to require from the exact path where the module, e.g. require('/usr/local/lib/node_modules/socket.io')

C# how to convert File.ReadLines into string array?

string[] lines = File.ReadLines("c:\\file.txt").ToArray();

Although one wonders why you'll want to do that when ReadAllLines works just fine.

Or perhaps you just want to enumerate with the return value of File.ReadLines:

var lines = File.ReadAllLines("c:\\file.txt");
foreach (var line in lines)
{
    Console.WriteLine("\t" + line);
}

jQuery/JavaScript: accessing contents of an iframe

You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

Best practice to run Linux service as a different user

I needed to run a Spring .jar application as a service, and found a simple way to run this as a specific user:

I changed the owner and group of my jar file to the user I wanted to run as. Then symlinked this jar in init.d and started the service.

So:

#chown myuser:myuser /var/lib/jenkins/workspace/springApp/target/springApp-1.0.jar

#ln -s /var/lib/jenkins/workspace/springApp/target/springApp-1.0.jar /etc/init.d/springApp

#service springApp start

#ps aux | grep java
myuser    9970  5.0  9.9 4071348 386132 ?      Sl   09:38   0:21 /bin/java -Dsun.misc.URLClassPath.disableJarChecking=true -jar /var/lib/jenkins/workspace/springApp/target/springApp-1.0.jar

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

To trigger an event you basically just call the event handler for that element. Slight change from your code.

var a = document.getElementById("element");
var evnt = a["onclick"];

if (typeof(evnt) == "function") {
    evnt.call(a);
}

How to use a switch case 'or' in PHP

Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

Lambda function in list comprehensions

The other answers are correct, but if you are trying to make a list of functions, each with a different parameter, that can be executed later, the following code will do that:

import functools
a = [functools.partial(lambda x: x*x, x) for x in range(10)]

b = []
for i in a:
    b.append(i())

In [26]: b
Out[26]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

While the example is contrived, I found it useful when I wanted a list of functions that each print something different, i.e.

import functools
a = [functools.partial(lambda x: print(x), x) for x in range(10)]

for i in a:
    i()

Extracting time from POSIXct

I can't find anything that deals with clock times exactly, so I'd just use some functions from package:lubridate and work with seconds-since-midnight:

require(lubridate)
clockS = function(t){hour(t)*3600+minute(t)*60+second(t)}
plot(clockS(times),val)

You might then want to look at some of the axis code to figure out how to label axes nicely.

How to write one new line in Bitbucket markdown?

I was facing the same issue in bitbucket, and this worked for me:

line1
##<2 white spaces><enter>
line2

How to remove duplicate white spaces in string using Java?

You can use the regex

(\s)\1

and

replace it with $1.

Java code:

str = str.replaceAll("(\\s)\\1","$1");

If the input is "foo\t\tbar " you'll get "foo\tbar " as output
But if the input is "foo\t bar" it will remain unchanged because it does not have any consecutive whitespace characters.

If you treat all the whitespace characters(space, vertical tab, horizontal tab, carriage return, form feed, new line) as space then you can use the following regex to replace any number of consecutive white space with a single space:

str = str.replaceAll("\\s+"," ");

But if you want to replace two consecutive white space with a single space you should do:

str = str.replaceAll("\\s{2}"," ");

How to group dataframe rows into list in pandas groupby

It is time to use agg instead of apply .

When

df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6], 'c': [1,2,5,5,4,6]})

If you want multiple columns stack into list , result in pd.DataFrame

df.groupby('a')[['b', 'c']].agg(list)
# or 
df.groupby('a').agg(list)

If you want single column in list, result in ps.Series

df.groupby('a')['b'].agg(list)
#or
df.groupby('a')['b'].apply(list)

Note, result in pd.DataFrame is about 10x slower than result in ps.Series when you only aggregate single column, use it in multicolumns case .

How can I get a list of locally installed Python modules?

Solution

Do not use with pip > 10.0!

My 50 cents for getting a pip freeze-like list from a Python script:

import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages])
print(installed_packages_list)

As a (too long) one liner:

sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])

Giving:

['behave==1.2.4', 'enum34==1.0', 'flask==0.10.1', 'itsdangerous==0.24', 
 'jinja2==2.7.2', 'jsonschema==2.3.0', 'markupsafe==0.23', 'nose==1.3.3', 
 'parse-type==0.3.4', 'parse==1.6.4', 'prettytable==0.7.2', 'requests==2.3.0',
 'six==1.6.1', 'vioozer-metadata==0.1', 'vioozer-users-server==0.1', 
 'werkzeug==0.9.4']

Scope

This solution applies to the system scope or to a virtual environment scope, and covers packages installed by setuptools, pip and (god forbid) easy_install.

My use case

I added the result of this call to my flask server, so when I call it with http://example.com/exampleServer/environment I get the list of packages installed on the server's virtualenv. It makes debugging a whole lot easier.

Caveats

I have noticed a strange behaviour of this technique - when the Python interpreter is invoked in the same directory as a setup.py file, it does not list the package installed by setup.py.

Steps to reproduce:

Create a virtual environment
$ cd /tmp
$ virtualenv test_env
New python executable in test_env/bin/python
Installing setuptools, pip...done.
$ source test_env/bin/activate
(test_env) $ 
Clone a git repo with setup.py
(test_env) $ git clone https://github.com/behave/behave.git
Cloning into 'behave'...
remote: Reusing existing pack: 4350, done.
remote: Total 4350 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (4350/4350), 1.85 MiB | 418.00 KiB/s, done.
Resolving deltas: 100% (2388/2388), done.
Checking connectivity... done.

We have behave's setup.py in /tmp/behave:

(test_env) $ ls /tmp/behave/setup.py
/tmp/behave/setup.py
Install the python package from the git repo
(test_env) $ cd /tmp/behave && pip install . 
running install
...
Installed /private/tmp/test_env/lib/python2.7/site-packages/enum34-1.0-py2.7.egg
Finished processing dependencies for behave==1.2.5a1

If we run the aforementioned solution from /tmp

>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['behave==1.2.5a1', 'enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp'

If we run the aforementioned solution from /tmp/behave

>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp/behave'

behave==1.2.5a1 is missing from the second example, because the working directory contains behave's setup.py file.

I could not find any reference to this issue in the documentation. Perhaps I shall open a bug for it.

CSS/HTML: What is the correct way to make text italic?

HTML italic text displays the text in italic format.

<i>HTML italic text example</i>

The emphasis and strong elements can both be used to increase the importance of certain words or sentences.

<p>This is <em>emphasized </em> text format <em>example</em></p>

The emphasis tag should be used when you want to emphasize a point in your text and not necessarily when you want to italicize that text.

See this guide for more: HTML Text Formatting

Remove xticks in a matplotlib plot?

Modify the following rc parameters by adding the commands to the script:

plt.rcParams['xtick.bottom'] = False
plt.rcParams['xtick.labelbottom'] = False

A sample matplotlibrc file is depicted in this section of the matplotlib documentation, which lists many other parameters like changing figure size, color of figure, animation settings, etc.

How to configure Docker port mapping to use Nginx as an upstream proxy?

@T0xicCode's answer is correct, but I thought I would expand on the details since it actually took me about 20 hours to finally get a working solution implemented.

If you're looking to run Nginx in its own container and use it as a reverse proxy to load balance multiple applications on the same server instance then the steps you need to follow are as such:

Link Your Containers

When you docker run your containers, typically by inputting a shell script into User Data, you can declare links to any other running containers. This means that you need to start your containers up in order and only the latter containers can link to the former ones. Like so:

#!/bin/bash
sudo docker run -p 3000:3000 --name API mydockerhub/api
sudo docker run -p 3001:3001 --link API:API --name App mydockerhub/app
sudo docker run -p 80:80 -p 443:443 --link API:API --link App:App --name Nginx mydockerhub/nginx

So in this example, the API container isn't linked to any others, but the App container is linked to API and Nginx is linked to both API and App.

The result of this is changes to the env vars and the /etc/hosts files that reside within the API and App containers. The results look like so:

/etc/hosts

Running cat /etc/hosts within your Nginx container will produce the following:

172.17.0.5  0fd9a40ab5ec
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3  App
172.17.0.2  API



ENV Vars

Running env within your Nginx container will produce the following:

API_PORT=tcp://172.17.0.2:3000
API_PORT_3000_TCP_PROTO=tcp
API_PORT_3000_TCP_PORT=3000
API_PORT_3000_TCP_ADDR=172.17.0.2

APP_PORT=tcp://172.17.0.3:3001
APP_PORT_3001_TCP_PROTO=tcp
APP_PORT_3001_TCP_PORT=3001
APP_PORT_3001_TCP_ADDR=172.17.0.3

I've truncated many of the actual vars, but the above are the key values you need to proxy traffic to your containers.

To obtain a shell to run the above commands within a running container, use the following:

sudo docker exec -i -t Nginx bash

You can see that you now have both /etc/hosts file entries and env vars that contain the local IP address for any of the containers that were linked. So far as I can tell, this is all that happens when you run containers with link options declared. But you can now use this information to configure nginx within your Nginx container.



Configuring Nginx

This is where it gets a little tricky, and there's a couple of options. You can choose to configure your sites to point to an entry in the /etc/hosts file that docker created, or you can utilize the ENV vars and run a string replacement (I used sed) on your nginx.conf and any other conf files that may be in your /etc/nginx/sites-enabled folder to insert the IP values.



OPTION A: Configure Nginx Using ENV Vars

This is the option that I went with because I couldn't get the /etc/hosts file option to work. I'll be trying Option B soon enough and update this post with any findings.

The key difference between this option and using the /etc/hosts file option is how you write your Dockerfile to use a shell script as the CMD argument, which in turn handles the string replacement to copy the IP values from ENV to your conf file(s).

Here's the set of configuration files I ended up with:

Dockerfile

FROM ubuntu:14.04
MAINTAINER Your Name <[email protected]>

RUN apt-get update && apt-get install -y nano htop git nginx

ADD nginx.conf /etc/nginx/nginx.conf
ADD api.myapp.conf /etc/nginx/sites-enabled/api.myapp.conf
ADD app.myapp.conf /etc/nginx/sites-enabled/app.myapp.conf
ADD Nginx-Startup.sh /etc/nginx/Nginx-Startup.sh

EXPOSE 80 443

CMD ["/bin/bash","/etc/nginx/Nginx-Startup.sh"]

nginx.conf

daemon off;
user www-data;
pid /var/run/nginx.pid;
worker_processes 1;


events {
    worker_connections 1024;
}


http {

    # Basic Settings

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 33;
    types_hash_max_size 2048;

    server_tokens off;
    server_names_hash_bucket_size 64;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;


    # Logging Settings
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;


    # Gzip Settings

gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 3;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/xml text/css application/x-javascript application/json;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    # Virtual Host Configs  
    include /etc/nginx/sites-enabled/*;

    # Error Page Config
    #error_page 403 404 500 502 /srv/Splash;


}

NOTE: It's important to include daemon off; in your nginx.conf file to ensure that your container doesn't exit immediately after launching.

api.myapp.conf

upstream api_upstream{
    server APP_IP:3000;
}

server {
    listen 80;
    server_name api.myapp.com;
    return 301 https://api.myapp.com/$request_uri;
}

server {
    listen 443;
    server_name api.myapp.com;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        proxy_pass http://api_upstream;
    }

}

Nginx-Startup.sh

#!/bin/bash
sed -i 's/APP_IP/'"$API_PORT_3000_TCP_ADDR"'/g' /etc/nginx/sites-enabled/api.myapp.com
sed -i 's/APP_IP/'"$APP_PORT_3001_TCP_ADDR"'/g' /etc/nginx/sites-enabled/app.myapp.com

service nginx start

I'll leave it up to you to do your homework about most of the contents of nginx.conf and api.myapp.conf.

The magic happens in Nginx-Startup.sh where we use sed to do string replacement on the APP_IP placeholder that we've written into the upstream block of our api.myapp.conf and app.myapp.conf files.

This ask.ubuntu.com question explains it very nicely: Find and replace text within a file using commands

GOTCHA On OSX, sed handles options differently, the -i flag specifically. On Ubuntu, the -i flag will handle the replacement 'in place'; it will open the file, change the text, and then 'save over' the same file. On OSX, the -i flag requires the file extension you'd like the resulting file to have. If you're working with a file that has no extension you must input '' as the value for the -i flag.

GOTCHA To use ENV vars within the regex that sed uses to find the string you want to replace you need to wrap the var within double-quotes. So the correct, albeit wonky-looking, syntax is as above.

So docker has launched our container and triggered the Nginx-Startup.sh script to run, which has used sed to change the value APP_IP to the corresponding ENV variable we provided in the sed command. We now have conf files within our /etc/nginx/sites-enabled directory that have the IP addresses from the ENV vars that docker set when starting up the container. Within your api.myapp.conf file you'll see the upstream block has changed to this:

upstream api_upstream{
    server 172.0.0.2:3000;
}

The IP address you see may be different, but I've noticed that it's usually 172.0.0.x.

You should now have everything routing appropriately.

GOTCHA You cannot restart/rerun any containers once you've run the initial instance launch. Docker provides each container with a new IP upon launch and does not seem to re-use any that its used before. So api.myapp.com will get 172.0.0.2 the first time, but then get 172.0.0.4 the next time. But Nginx will have already set the first IP into its conf files, or in its /etc/hosts file, so it won't be able to determine the new IP for api.myapp.com. The solution to this is likely to use CoreOS and its etcd service which, in my limited understanding, acts like a shared ENV for all machines registered into the same CoreOS cluster. This is the next toy I'm going to play with setting up.



OPTION B: Use /etc/hosts File Entries

This should be the quicker, easier way of doing this, but I couldn't get it to work. Ostensibly you just input the value of the /etc/hosts entry into your api.myapp.conf and app.myapp.conf files, but I couldn't get this method to work.

UPDATE: See @Wes Tod's answer for instructions on how to make this method work.

Here's the attempt that I made in api.myapp.conf:

upstream api_upstream{
    server API:3000;
}

Considering that there's an entry in my /etc/hosts file like so: 172.0.0.2 API I figured it would just pull in the value, but it doesn't seem to be.

I also had a couple of ancillary issues with my Elastic Load Balancer sourcing from all AZ's so that may have been the issue when I tried this route. Instead I had to learn how to handle replacing strings in Linux, so that was fun. I'll give this a try in a while and see how it goes.

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

This is a local installation. You downloaded and built OpenSSL taking the default prefix, of you configured with ./config --prefix=/usr/local/ssl or ./config --openssldir=/usr/local/ssl.

You will use this if you use the OpenSSL in /usr/local/ssl/bin. That is, /usr/local/ssl/openssl.cnf will be used when you issue:

/usr/local/ssl/bin/openssl s_client -connect localhost:443 -tls1 -servername localhost

/usr/lib/ssl/openssl.cnf

This is where Ubuntu places openssl.cnf for the OpenSSL they provide.

You will use this if you use the OpenSSL in /usr/bin. That is, /usr/lib/ssl/openssl.cnf will be used when you issue:

openssl s_client -connect localhost:443 -tls1 -servername localhost

/etc/ssl/openssl.cnf

I don't know when this is used. The stuff in /etc/ssl is usually certificates and private keys, and it sometimes contains a copy of openssl.cnf. But I've never seen it used for anything.


Which is the main/correct one that I should use to make changes?

From the sounds of it, you should probably add the engine to /usr/lib/ssl/openssl.cnf. That ensures most "off the shelf" gear will use the new engine.

After you do that, add it to /usr/local/ssl/openssl.cnf also because copy/paste is easy.


Here's how to see which openssl.cnf directory is associated with a OpenSSL installation. The library and programs look for openssl.cnf in OPENSSLDIR. OPENSSLDIR is a configure option, and its set with --openssldir.

I'm on a MacBook with 3 different OpenSSL's (Apple's, MacPort's and the one I build):

# Apple    
$ /usr/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/System/Library/OpenSSL"

# MacPorts
$ /opt/local/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/opt/local/etc/openssl"

# My build of OpenSSL
$ openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/usr/local/ssl/darwin"

I have an Ubuntu system and I have installed openssl.

Just bike shedding, but be careful of Ubuntu's version of OpenSSL. It disables TLSv1.1 and TLSv1.2, so you will only have clients capable of older cipher suites; and you will not be able to use newer ciphers like AES/CTR (to replace RC4) and elliptic curve gear (like ECDHE_ECDSA_* and ECDHE_RSA_*). See Ubuntu 12.04 LTS: OpenSSL downlevel version is 1.0.0, and does not support TLS 1.2 in Launchpad.

EDIT: Ubuntu enabled TLS 1.1 and TLS 1.2 recently. See Comment 17 on the bug report.

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

maybe you forget to add parameter dataType:'json' in your $.ajax

$.ajax({
   type: "POST",
   dataType: "json",
   url: url,
   data: { get_member: id },
   success: function( response ) 
   { 
     //some action here
   },
   error: function( error )
   {
     alert( error );
   }
});

How do I change TextView Value inside Java Code?

First, add a textView in the XML file

<TextView  
    android:id="@+id/rate_id"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/what_U_want_to_display_in_first_time"
    />

then add a button in xml file with id btn_change_textView and write this two line of code in onCreate() method of activity

Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);

then use clickListener() on button object like this

btn.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
      
        textView.setText("write here what u want to display after button click in string");
    }
});

SimpleXML - I/O warning : failed to load external entity

this also works:

$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);

then I just run a forloop to grab the stuff from the nodes.

like this:`

for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;

***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.

How do I add indices to MySQL tables?

ALTER TABLE `table` ADD INDEX `product_id_index` (`product_id`)

Never compare integer to strings in MySQL. If id is int, remove the quotes.

os.walk without digging into directories below

If you have more complex requirements than just the top directory (eg ignore VCS dirs etc), you can also modify the list of directories to prevent os.walk recursing through them.

ie:

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        dirs[:] = [d for d in dirs if is_good(d)]
        for f in files:
            do_stuff()

Note - be careful to mutate the list, rather than just rebind it. Obviously os.walk doesn't know about the external rebinding.

How do I implement __getattribute__ without an infinite recursion error?

Python language reference:

In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

Meaning:

def __getattribute__(self,name):
    ...
        return self.__dict__[name]

You're calling for an attribute called __dict__. Because it's an attribute, __getattribute__ gets called in search for __dict__ which calls __getattribute__ which calls ... yada yada yada

return  object.__getattribute__(self, name)

Using the base classes __getattribute__ helps finding the real attribute.

How to add local .jar file dependency to build.gradle file?

The accepted answer is good, however, I would have needed various library configurations within my multi-project Gradle build to use the same 3rd-party Java library.

Adding '$rootProject.projectDir' to the 'dir' path element within my 'allprojects' closure meant each sub-project referenced the same 'libs' directory, and not a version local to that sub-project:

//gradle.build snippet
allprojects {
    ...

    repositories {
        //All sub-projects will now refer to the same 'libs' directory
        flatDir {
            dirs "$rootProject.projectDir/libs"
        }
        mavenCentral()
    }

    ...
}

EDIT by Quizzie: changed "${rootProject.projectDir}" to "$rootProject.projectDir" (works in the newest Gradle version).

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

If you know the the name of the file and if you always want to download that specific file, then you can easily get the ID and other attributes for your desired file from: https://developers.google.com/drive/v2/reference/files/list (towards the bottom you will find a way to run queries). In the q field enter title = 'your_file_name' and run it. You should see some result show up right below and within it should be an "id" field. That is the id you are looking for.

You can also play around with additional parameters from: https://developers.google.com/drive/search-parameters

Check if datetime instance falls in between other two datetime objects

You can, use:

if (date >= startDate && date<= EndDate) { return true; }

Oracle SqlPlus - saving output in a file but don't show on screen

Right from the SQL*Plus manual
http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch8.htm#sthref1597

SET TERMOUT

SET TERMOUT OFF suppresses the display so that you can spool output from a script without seeing it on the screen.

If both spooling to file and writing to terminal are not required, use SET TERMOUT OFF in >SQL scripts to disable terminal output.

SET TERMOUT is not supported in iSQL*Plus

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

How to decompile a whole Jar file?

Something like:

jar -xf foo.jar && find . -iname "*.class" | xargs /opt/local/bin/jad -r

maybe?

Groovy method with optional parameters

You can use arguments with default values.

def someMethod(def mandatory,def optional=null){}

if argument "optional" not exist, it turns to "null".

Error In PHP5 ..Unable to load dynamic library

Even though several other answers suggest it, installing more unnecessary software is generally not the best solution. Instead, you should fix the underlying problem. The reason these messages appear is because you are trying to load those extensions, but they are not installed. So the easy solution is simply to tell PHP to stop trying to load them:

First, find out which files are trying to load the above extensions:

$ grep -Hrv ";" /etc/php5 | grep -E "extension(\s+)?="

Example output for Ubuntu:

/etc/php5/mods-available/gd.ini:extension=gd.so
/etc/php5/mods-available/pdo_sqlite.ini:extension=pdo_sqlite.so
/etc/php5/mods-available/pdo.ini:extension=pdo.so
/etc/php5/mods-available/pdo_mysql.ini:extension=pdo_mysql.so
/etc/php5/mods-available/mysqli.ini:extension=mysqli.so
/etc/php5/mods-available/mysql.ini:extension=mysql.so
/etc/php5/mods-available/curl.ini:extension=curl.so
/etc/php5/mods-available/sqlite3.ini:extension=sqlite3.so
/etc/php5/conf.d/mcrypt.ini:extension=mcrypt.so
/etc/php5/conf.d/imagick.ini:extension=imagick.so
/etc/php5/apache2/php.ini:extension=http.so

Now just find the files that are loading the extensions that are causing the errors and comment out those lines with a ;. For some reason this happened to me with the default install of Ubuntu, so hopefully this helps someone else.

How to fix Git error: object file is empty?

if you have an OLD backup and is in a hurry:

make a NEW BACKUP of your current, git-broken, project path.

  1. move your .git to trash (never delete)
  2. copy .git from the OLD backup
  3. git pull (will create merge conflicts)
  4. move all your sources (everything you put in git) to trash: ./src (never delete)
  5. .copy all your sources (everything you put in git) from the NEW BACKUP
  6. accept all "merges" at git gui, push and... clap your hands!

R: Select values from data table in range

Lots of options here, but one of the easiest to follow is subset. Consider:

> set.seed(43)
> df <- data.frame(name = sample(letters, 100, TRUE), date = sample(1:500, 100, TRUE))
> 
> subset(df, date > 5 & date < 15)
   name date
11    k   10
67    y   12
86    e    8

You can also insert logic directly into the index for your data.frame. The comma separates the rows from columns. We just have to remember that R indexes rows first, then columns. So here we are saying rows with date > 5 & < 15 and then all columns:

df[df$date > 5 & df$date < 15 ,]

I'd also recommend checking out the help pages for subset, ?subset and the logical operators ?"&"

Add two textbox values and display the sum in a third textbox automatically

This is the correct code

function sum() 
{ 
    var txtFirstNumberValue = document.getElementById('total_fees').value; 
    var txtSecondNumberValue = document.getElementById('advance_payement').value; 
    var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue); 
    if(txtFirstNumberValue=="" ||txtSecondNumberValue=="") 
    { 
        document.getElementById('balance_payement').value = 0; 
    }
    if (!isNaN(result)) 
    { 
        document.getElementById('balance_payement').value = result;
    }
} 

Good examples of python-memcache (memcached) being used in Python?

A good rule of thumb: use the built-in help system in Python. Example below...

jdoe@server:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)

------------------------------------------
NAME
    memcache - client module for memcached (memory cache daemon)

FILE
    /usr/lib/python2.7/dist-packages/memcache.py

MODULE DOCS
    http://docs.python.org/library/memcache

DESCRIPTION
    Overview
    ========

    See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

    Usage summary
    =============
...
------------------------------------------

jQuery checkbox check/uncheck

 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});

Javascript Equivalent to C# LINQ Select

The ES6 way:

let people = [{firstName:'Alice',lastName:'Cooper'},{firstName:'Bob',age:'Dylan'}];
let names = Array.from(people, p => p.firstName);
for (let name of names) {
  console.log(name);
}

also at: https://jsfiddle.net/52dpucey/

Is it possible to use "return" in stored procedure?

It is possible.

When you use Return inside a procedure, the control is transferred to the calling program which calls the procedure. It is like an exit in loops.

It won't return any value.

Can vue-router open a link in a new tab?

For those who are wondering the answer is no. See related issue on github.

Q: Can vue-router open link in new tab progammaticaly

A: No. use a normal link.

What does "pending" mean for request in Chrome Developer Window?

The Network pending state on time, means your request is in progressing state. As soon as it responds the time will be updated with total elapsed time.

This picture shows the network call is in processing state(Pending) This picture shows the network call is in processing state(Pending)

This picture shows the time taken in processing by network call. This picture shows the time taken in processing by network call

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

How can I pad an int with leading zeros when using cout << operator?

With the following,

#include <iomanip>
#include <iostream>

int main()
{
    std::cout << std::setfill('0') << std::setw(5) << 25;
}

the output will be

00025

setfill is set to the space character (' ') by default. setw sets the width of the field to be printed, and that's it.


If you are interested in knowing how the to format output streams in general, I wrote an answer for another question, hope it is useful: Formatting C++ Console Output.

Reset AutoIncrement in SQL Server after Delete

Delete and Reseed all the tables in a database.

    USE [DatabaseName]
    EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"       -- Disable All the constraints
    EXEC sp_MSForEachTable "DELETE FROM ?"    -- Delete All the Table data
    Exec sp_MSforeachtable 'DBCC CHECKIDENT(''?'', RESEED, 0)' -- Reseed All the table to 0
    Exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"  -- Enable All  the constraints back

-- You may ignore the errors that shows the table without Auto increment field.

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Can't load AMD 64-bit .dll on a IA 32-bit platform

If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.

Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)

Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.

If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

As sklearn.cross_validation module was deprecated, you can use:

import numpy as np
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)

X_trn, X_tst, y_trn, y_tst = train_test_split(X, y, test_size=0.2, random_state=42)

OpenCV & Python - Image too big to display

In opencv, cv.namedWindow() just creates a window object as you determine, but not resizing the original image. You can use cv2.resize(img, resolution) to solve the problem.

Here's what it displays, a 740 * 411 resolution image. The original image

image = cv2.imread("740*411.jpg")
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, it displays a 100 * 200 resolution image after resizing. Remember the resolution parameter use column first then is row.

Image after resizing

image = cv2.imread("740*411.jpg")
image = cv2.resize(image, (200, 100))
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

How to include duplicate keys in HashMap?

You can't have duplicate keys in a Map. You can rather create a Map<Key, List<Value>>, or if you can, use Guava's Multimap.

Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "rohit");
multimap.put(1, "jain");

System.out.println(multimap.get(1));  // Prints - [rohit, jain]

And then you can get the java.util.Map using the Multimap#asMap() method.

How to preview a part of a large pandas DataFrame, in iPython notebook?

In Python pandas provide head() and tail() to print head and tail data respectively.

import pandas as pd
train = pd.read_csv('file_name')
train.head() # it will print 5 head row data as default value is 5
train.head(n) # it will print n head row data
train.tail() #it will print 5 tail row data as default value is 5
train.tail(n) #it will print n tail row data

What is sys.maxint in Python 3?

An alternative is

import math

... math.inf ...

Display SQL query results in php

You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.

// Process all rows
while($row = mysql_fetch_array($result)) {
    echo $row['column_name']; // Print a single column data
    echo print_r($row);       // Print the entire row data
}

Change your code to this :

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['fieldname']; 
}

diff to output only the file names

From the diff man page:

-q   Report only whether the files differ, not the details of the differences.
-r   When comparing directories, recursively compare any subdirectories found.

Example command:

diff -qr dir1 dir2

Example output (depends on locale):

$ ls dir1 dir2
dir1:
same-file  different  only-1

dir2:
same-file  different  only-2
$ diff -qr dir1 dir2
Files dir1/different and dir2/different differ
Only in dir1: only-1
Only in dir2: only-2

How do I add an "Add to Favorites" button or link on my website?

I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:

jQuery('.bookmarkMeLink').click(function() {
    if (window.sidebar && window.sidebar.addPanel) { 
        // Mozilla Firefox Bookmark
        window.sidebar.addPanel(document.title,window.location.href,'');
    }
    else if(window.sidebar && jQuery.browser.mozilla){
        //for other version of FF add rel="sidebar" to link like this:
        //<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
        jQuery(this).attr('rel', 'sidebar');
    }
    else if(window.external && ('AddFavorite' in window.external)) { 
        // IE Favorite
        window.external.AddFavorite(location.href,document.title); 
    } else if(window.opera && window.print) { 
        // Opera Hotlist
        this.title=document.title;
        return true;
    } else { 
        // webkit - safari/chrome
        alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');

    }
});

How can I write maven build to add resources to classpath?

If you place anything in src/main/resources directory, then by default it will end up in your final *.jar. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:

  1. *.jar is not correctly loaded (maybe typo in the path?)
  2. you are not addressing the resource correctly, for instance: /src/main/resources/conf/settings.properties is seen on classpath as classpath:conf/settings.properties

CSS: image link, change on hover

It can be better if you set the a element in this way

display:block;

and then by css sprites set your over background

Edit: check this example out http://jsfiddle.net/steweb/dTwtk/

Maintaining Session through Angular.js

You would use a service for that in Angular. A service is a function you register with Angular, and that functions job is to return an object which will live until the browser is closed/refreshed. So it's a good place to store state in, and to synchronize that state with the server asynchronously as that state changes.

How to save user input into a variable in html and js

I mean a prompt script would work if the variable was not needed for the HTML aspect, even then in certain situations, a function could be used.

_x000D_
_x000D_
var save_user_input = prompt('what needs to be saved?');
//^ makes a variable of the prompt's answer
if (save_user_input == null) {
//^ if the answer is null, it is nothing
//however, if it is nothing, it is cancelled (as seen below). If it is "null" it is what the user said, then assigned to the variable(i think), but also null as in nothing in the prompt answer window, but ok pressed. So you cant do an or "null" (which would look like: if (save_user_input == null || "null") {)because (I also don't really know if this is right) the variable is "null". Very confusing
alert("cancelled");
//^ alerts the user the cancel button was pressed. No long explanation this time.
}
//^ is an end for the if (i got stumped as to why it wasn’t working and then realised this. very important to remember.)
else {
alert(save_user_input + " is what you said");
//^ alerts the user the variable and adds the string " is what you said" on the end
}
_x000D_
_x000D_
_x000D_

How to see the values of a table variable at debug time in T-SQL?

In the Stored Procedure create a global temporary table ##temptable and write an insert query within your stored procedure which inserts the data in your table into this temporary table.

Once this is done you can check the content of the temporary table by opening a new query window. Just use "select * from ##temptable"

C# - Substring: index and length must refer to a location within the string

Your mistake is the parameters to Substring. The first parameter should be the start index and the second should be the length or offset from the startindex.

string newString = url.Substring(18, 7);

If the length of the substring can vary you need to calculate the length.

Something in the direction of (url.Length - 18) - 4 (or url.Length - 22)

In the end it will look something like this

string newString = url.Substring(18, url.Length - 22);

Angular 2: Get Values of Multiple Checked Checkboxes

<input type="checkbox" name="options" value="option" (change)="updateChecked(option, $event)" /> 

export class MyComponent {
  checked: boolean[] = [];
  updateChecked(option, event) {
    this.checked[option]=event; // or `event.target.value` not sure what this event looks like
  }
}

Reading RFID with Android phones

You can hijack your Android audio port using an Arduino board like this. Then, you have two options (as far as I'm concerned):

1) Buy another Arduino Shield that supports RFID. I haven't seen one that supports UHF so far.

2) Try to connect your Arduino hijack with a USB RFID reader and build some embedded hardware kit.

Right now, I'm working in the second option but with iPhone.