Programs & Examples On #Stringbuffer

StringBuffer in Java is used as a thread-safe, mutable sequence of characters.

Difference between StringBuilder and StringBuffer

The major difference is StringBuffer is syncronized but StringBuilder is not.If you need to use more than one thread , then StringBuffer is recommended.But, as per the execution speed StringBuilder is faster than StringBuffer , because its not syncronized .

What is the difference between String and StringBuffer in Java?

String is an immutable class. This means that once you instantiate an instance of a string like so:

String str1 = "hello";

The object in memory cannot be altered. Instead you will have to create a new instance, copy the old String and append whatever else as in this example:

String str1 = "hello";
str1 = str1 + " world!";

What is really happening hear is that we are NOT updating the existing str1 object... we are reallocating new memory all together, copying the "hello" data and appending " world!" to the end, then settings the str1 reference to point to this new memory. So it really looks more like this under the hood:

String str1 = "hello";
String str2 = str1 + " world!";
str1 = str2;

So it follows that this "copy + paste and move stuff around in memory" process can be very expensive if done repitively especially recursively.

When you are in that situation of having to do things over and over utilize StringBuilder. It is mutable and can append strings to the end of the current one because it's back by an [growing array] (not 100% if that is the actual data structure, could be a list).

How to add an element at the end of an array?

The OP says, for unknown reasons, "I prefer it without an arraylist or list."

If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int or Integer), then you can use one of the NIO Buffer classes like java.nio.IntBuffer. These act a lot like StringBuffer does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.

Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate() a larger one and use put() to dump the old buffer into the new one.

If it's not a primitive, you should probably just use List, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.

What is difference between mutable and immutable String in java


String in Java is immutable. However what does it mean to be mutable in programming context is the first question. Consider following class,

public class Dimension {
    private int height;

    private int width;

    public Dimenstion() {
    }

    public void setSize(int height, int width) {
        this.height = height;
        this.width = width;
    }

    public getHeight() {
        return height;
    }

    public getWidth() {
        return width;
    }
}

Now after creating the instance of Dimension we can always update it's attributes. Note that if any of the attribute, in other sense state, can be updated for instance of the class then it is said to be mutable. We can always do following,

Dimension d = new Dimension();
d.setSize(10, 20);// Dimension changed
d.setSize(10, 200);// Dimension changed
d.setSize(100, 200);// Dimension changed

Let's see in different ways we can create a String in Java.

String str1 = "Hey!";
String str2 = "Jack";
String str3 = new String("Hey Jack!");
String str4 = new String(new char[] {'H', 'e', 'y', '!'});
String str5 = str1 + str2;
str1 = "Hi !";
// ...

So,

  1. str1 and str2 are String literals which gets created in String constant pool
  2. str3, str4 and str5 are String Objects which are placed in Heap memory
  3. str1 = "Hi!"; creates "Hi!" in String constant pool and it's totally different reference than "Hey!" which str1 referencing earlier.

Here we are creating the String literal or String Object. Both are different, I would suggest you to read following post to understand more about it.

In any String declaration, one thing is common, that it does not modify but it gets created or shifted to other.

String str = "Good"; // Create the String literal in String pool
str = str + " Morning"; // Create String with concatenation of str + "Morning"
|_____________________|
       |- Step 1 : Concatenate "Good"  and " Morning" with StringBuilder
       |- Step 2 : assign reference of created "Good Morning" String Object to str

How String became immutable ?

It's non changing behaviour, means, the value once assigned can not be updated in any other way. String class internally holds data in character array. Moreover, class is created to be immutable. Take a look at this strategy for defining immutable class.

Shifting the reference does not mean you changed it's value. It would be mutable if you can update the character array which is behind the scene in String class. But in reality that array will be initialized once and throughout the program it remains the same.

Why StringBuffer is mutable ?

As you already guessed, StringBuffer class is mutable itself as you can update it's state directly. Similar to String it also holds value in character array and you can manipulate that array by different methods i.e. append, delete, insert etc. which directly changes the character value array.

Create a string with n characters

In most cases you only need Strings upto a certains length, say 100 spaces. You could prepare an array of Strings where the index number is equal to the size of the space-filled string and lookup the string, if the required length is within the limits or create it on demand if it's outside the boundary.

Semaphore vs. Monitors - what's the difference?

When a semaphore is used to guard a critical region, there is no direct relationship between the semaphore and the data being protected. This is part of the reason why semaphores may be dispersed around the code, and why it is easy to forget to call wait or notify, in which case the result will be, respectively, to violate mutual exclusion or to lock the resource permanently.

In contrast, niehter of these bad things can happen with a monitor. A monitor is tired directly to the data (it encapsulates the data) and, because the monitor operations are atomic actions, it is impossible to write code that can access the data without calling the entry protocol. The exit protocol is called automatically when the monitor operation is completed.

A monitor has a built-in mechanism for condition synchronisation in the form of condition variable before proceeding. If the condition is not satisfied, the process has to wait until it is notified of a change in the condition. When a process is waiting for condition synchronisation, the monitor implementation takes care of the mutual exclusion issue, and allows another process to gain access to the monitor.

Taken from The Open University M362 Unit 3 "Interacting process" course material.

Turn off deprecated errors in PHP 5.3

I just faced a similar problem where a SEO plugin issued a big number of warnings making my blog disk use exceed the plan limit.

I found out that you must include the error_reporting command after the wp-settings.php require in the wp-config.php file:

   require_once( ABSPATH .'wp-settings.php' );
   error_reporting( E_ALL ^ ( E_NOTICE | E_WARNING | E_DEPRECATED ) );

by doing this no more warnings, notices nor deprecated lines are appended to your error log file!

Tested on WordPress 3.8 but I guess it works for every installation.

CSS Flex Box Layout: full-width row and columns

You've almost done it. However setting flex: 0 0 <basis> declaration to the columns would prevent them from growing/shrinking; And the <basis> parameter would define the width of columns.

In addition, you could use CSS3 calc() expression to specify the height of columns with the respect to the height of the header.

#productShowcaseTitle {
  flex: 0 0 100%; /* Let it fill the entire space horizontally */
  height: 100px;
}

#productShowcaseDetail,
#productShowcaseThumbnailContainer {
  height: calc(100% - 100px); /* excluding the height of the header */
}

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
  flex: 0 0 100%; /* Let it fill the entire space horizontally */_x000D_
  height: 100px;_x000D_
  background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
  flex: 0 0 66%; /* ~ 2 * 33.33% */_x000D_
  height: calc(100% - 100px); /* excluding the height of the header */_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
  flex: 0 0 34%;  /* ~ 33.33% */_x000D_
  height: calc(100% - 100px); /* excluding the height of the header */_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
  <div id="productShowcaseTitle"></div>_x000D_
  <div id="productShowcaseDetail"></div>_x000D_
  <div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vendor prefixes omitted due to brevity)


Alternatively, if you could change your markup e.g. wrapping the columns by an additional <div> element, it would be achieved without using calc() as follows:

<div class="contentContainer"> <!-- Added wrapper -->
    <div id="productShowcaseDetail"></div>
    <div id="productShowcaseThumbnailContainer"></div>
</div>
#productShowcaseContainer {
  display: flex;
  flex-direction: column;
  height: 600px; width: 580px;
}

.contentContainer { display: flex; flex: 1; }
#productShowcaseDetail { flex: 3; }
#productShowcaseThumbnailContainer { flex: 2; }

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.contentContainer {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
  height: 100px;_x000D_
  background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
  flex: 3;_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
  <div id="productShowcaseTitle"></div>_x000D_
_x000D_
  <div class="contentContainer"> <!-- Added wrapper -->_x000D_
    <div id="productShowcaseDetail"></div>_x000D_
    <div id="productShowcaseThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vendor prefixes omitted due to brevity)

How to show first commit by 'git log'?

I found that:

git log --reverse

shows commits from start.

How can strings be concatenated?

For cases of appending to end of existing string:

string = "Sec_"
string += "C_type"
print(string)

results in

Sec_C_type

Align <div> elements side by side

keep it simple

<div align="center">
<div style="display: inline-block"> <img src="img1.png"> </div>
<div style="display: inline-block"> <img src="img2.png"> </div>
</div>

How do I associate file types with an iPhone application?

In addition to Brad's excellent answer, I have found out that (on iOS 4.2.1 at least) when opening custom files from the Mail app, your app is not fired or notified if the attachment has been opened before. The "open with…" popup appears, but just does nothing.

This seems to be fixed by (re)moving the file from the Inbox directory. A safe approach seems to be to both (re)move the file as it is opened (in -(BOOL)application:openURL:sourceApplication:annotation:) as well as going through the Documents/Inbox directory, removing all items, e.g. in applicationDidBecomeActive:. That last catch-all may be needed to get the app in a clean state again, in case a previous import causes a crash or is interrupted.

Amazon Interview Question: Design an OO parking lot

In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".

Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.

The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)

License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.

How can I get current date in Android?

The simplest way to get the current date in current locale (device locale!) :

String currentDate = DateFormat.getDateInstance().format(Calendar.getInstance().getTime());

If you want to have the date in different styles use getDateInstance(int style):

DateFormat.getDateInstance(DateFormat.FULL).format(Calendar.getInstance().getTime());

Other styles: DateFormat.LONG, DateFormat.DATE_FIELD, DateFormat.DAY_OF_YEAR_FIELD, etc. (use CTRL+Space to see all of them)

If you need the time too:

String currentDateTime = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,DateFormat.LONG).format(Calendar.getInstance().getTime());

Disable LESS-CSS Overwriting calc()

Using an escaped string (a.k.a. escaped value):

width: ~"calc(100% - 200px)";

Also, in case you need to mix Less math with escaped strings:

width: calc(~"100% - 15rem +" (10px+5px) ~"+ 2em");

Compiles to:

width: calc(100% - 15rem + 15px + 2em);

This works as Less concatenates values (the escaped strings and math result) with a space by default.

how to query child objects in mongodb

Assuming your "states" collection is like:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistake to query for nulls as:

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

Spring Boot REST API - request timeout?

A fresh answer for Spring Boot 2.2 is required as server.connection-timeout=5000 is deprecated. Each server behaves differently, so server specific properties are recommended instead.

SpringBoot embeds Tomcat by default, if you haven't reconfigured it with Jetty or something else. Use server specific application properties like server.tomcat.connection-timeout or server.jetty.idle-timeout.

What are the differences between the different saving methods in Hibernate?

Actually the difference between hibernate save() and persist() methods is depends on generator class we are using.

If our generator class is assigned, then there is no difference between save() and persist() methods. Because generator ‘assigned’ means, as a programmer we need to give the primary key value to save in the database right [ Hope you know this generators concept ] In case of other than assigned generator class, suppose if our generator class name is Increment means hibernate it self will assign the primary key id value into the database right [ other than assigned generator, hibernate only used to take care the primary key id value remember ], so in this case if we call save() or persist() method then it will insert the record into the database normally But hear thing is, save() method can return that primary key id value which is generated by hibernate and we can see it by

long s = session.save(k);

In this same case, persist() will never give any value back to the client.

How to upper case every first letter of word in a string?

package com.raj.samplestring;

/**
 * @author gnagara
 */
public class SampleString {

    /**
     * @param args
     */
    public static void main(String[] args) {
       String[] stringArray;
       String givenString = "ramu is Arr Good boy";

       stringArray = givenString.split(" ");


       for(int i=0; i<stringArray.length;i++){
           if(!Character.isUpperCase(stringArray[i].charAt(0))){
               Character c = stringArray[i].charAt(0);
               Character change = Character.toUpperCase(c);

               StringBuffer ss = new StringBuffer(stringArray[i]);
               ss.insert(0, change);
               ss.deleteCharAt(1);
               stringArray[i]= ss.toString();
           }
       }
       for(String e:stringArray){
           System.out.println(e);
      }
    }
}

a = open("file", "r"); a.readline() output without \n

A solution, can be:

with open("file", "r") as fd:
    lines = fd.read().splitlines()

You get the list of lines without "\r\n" or "\n".

Or, use the classic way:

with open("file", "r") as fd:
    for line in fd:
        line = line.strip()

You read the file, line by line and drop the spaces and newlines.

If you only want to drop the newlines:

with open("file", "r") as fd:
    for line in fd:
        line = line.replace("\r", "").replace("\n", "")

Et voilà.

Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open.

See the documentation of io.open.

So, you can use:

with io.open("file", "r", newline=None) as fd:
    for line in fd:
        line = line.replace("\n", "")

When the newline parameter is None: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.

newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

How do I use Ruby for shell scripting?

Here's something important that's missing from the other answers: the command-line parameters are exposed to your Ruby shell script through the ARGV (global) array.

So, if you had a script called my_shell_script:

#!/usr/bin/env ruby
puts "I was passed: "
ARGV.each do |value|
  puts value
end

...make it executable (as others have mentioned):

chmod u+x my_shell_script

And call it like so:

> ./my_shell_script one two three four five

You'd get this:

I was passed: 
one
two
three
four
five

The arguments work nicely with filename expansion:

./my_shell_script *

I was passed: 
a_file_in_the_current_directory
another_file    
my_shell_script
the_last_file

Most of this only works on UNIX (Linux, Mac OS X), but you can do similar (though less convenient) things in Windows.

How to insert logo with the title of a HTML page?

Are you referring to the favicon?

Upload a 16x16px ico to your site, and link it in your head section.

<link rel="shortcut icon" href="/favicon.ico" />

There are a multitude of sites that help you convert images into .ico format too. This is just the first one I saw on Google. http://www.favicon.cc/

Reading serial data in realtime in Python

You can use inWaiting() to get the amount of bytes available at the input queue.

Then you can use read() to read the bytes, something like that:

While True:
    bytesToRead = ser.inWaiting()
    ser.read(bytesToRead)

Why not to use readline() at this case from Docs:

Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.

You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)

Get IFrame's document, from JavaScript in main document

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

How to form a correct MySQL connection string?

try creating connection string this way:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";

using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{    //watch out for this SQL injection vulnerability below
     cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
                                    OSGconv.deciLat, OSGconv.deciLon);
     conn.Open();
     cmd.ExecuteNonQuery();
}

C# DropDownList with a Dictionary as DataSource

When a dictionary is enumerated, it will yield KeyValuePair<TKey,TValue> objects... so you just need to specify "Value" and "Key" for DataTextField and DataValueField respectively, to select the Value/Key properties.

Thanks to Joe's comment, I reread the question to get these the right way round. Normally I'd expect the "key" in the dictionary to be the text that's displayed, and the "value" to be the value fetched. Your sample code uses them the other way round though. Unless you really need them to be this way, you might want to consider writing your code as:

list.Add(cul.DisplayName, cod);

(And then changing the binding to use "Key" for DataTextField and "Value" for DataValueField, of course.)

In fact, I'd suggest that as it seems you really do want a list rather than a dictionary, you might want to reconsider using a dictionary in the first place. You could just use a List<KeyValuePair<string, string>>:

string[] languageCodsList = service.LanguagesAvailable();
var list = new List<KeyValuePair<string, string>>();

foreach (string cod in languageCodsList)
{
    CultureInfo cul = new CultureInfo(cod);
    list.Add(new KeyValuePair<string, string>(cul.DisplayName, cod));
}

Alternatively, use a list of plain CultureInfo values. LINQ makes this really easy:

var cultures = service.LanguagesAvailable()
                      .Select(language => new CultureInfo(language));
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

If you're not using LINQ, you can still use a normal foreach loop:

List<CultureInfo> cultures = new List<CultureInfo>();
foreach (string cod in service.LanguagesAvailable())
{
    cultures.Add(new CultureInfo(cod));
}
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

How to create PDFs in an Android app?

Late, but relevant to request and hopefully helpful. If using an external service (as suggested in the reply by CommonsWare) then Docmosis has a cloud service that might help - offloading processing to a cloud service that does the heavy processing. That approach is ideal in some circumstances but of course relies on being net-connected.

How to call codeigniter controller function from view

class MY_Controller extends CI_Controller {

    public $CI = NULL;

    public function __construct() {
        parent::__construct();
        $this->CI = & get_instance();
    }

    public function yourMethod() {

    }

}

// in view just call
$this->CI->yourMethod();

How to check visibility of software keyboard in Android?

Don't make any hard code. Best way is you have to resize your views while on Get Focus on EditText with KeyBord Show. You can do this adding resize property on activity into Manifest file using below code.

android:windowSoftInputMode="adjustResize"

CSS3 transition doesn't work with display property

I faced the problem with display:none

I have several horizontal bars with transition effects but I wanted to show only part of that container and fold the rest while maintaining the effects. I reproduced a small demo here

The obvious was to wrap those hidden animated bars in a div then toggle that element's height and opacity

.hide{
  opacity: 0;
  height: 0;
}
.bars-wrapper.expanded > .hide{
 opacity: 1;
 height: auto;
}

The animation works well but the issue was that these hidden bars were still consuming space on my page and overlapping other elements

enter image description here

so adding display:none to the hidden wrapper .hide solves the margin issue but not the transition, neither applying display:none or height:0;opacity:0 works on the children elements.

So my final workaround was to give those hidden bars a negative and absolute position and it worked well with CSS transitions.

Jsfiddle

sendKeys() in Selenium web driver

For python selenium,

Importing the library,

from selenium.webdriver.common.keys import Keys

Use this code to press any key you want,

Anyelement.send_keys(Keys.RETURN)

You can find all the key names by searching this selenium.webdriver.common.keys.

How to make a TextBox accept only alphabetic characters?

you can try following code that alert at the time of key press event

private void tbOwnerName_KeyPress(object sender, KeyPressEventArgs e)
    {

        //===================to accept only charactrs & space/backspace=============================================

        if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
        {
            e.Handled = true;
            base.OnKeyPress(e);
            MessageBox.Show("enter characters only");
        }

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

another thing that worked for me after everything didn't - change "localhost" in config.inc.php to 127.0.0.1

Change the selected value of a drop-down list with jQuery

With hidden field you need to use like this:

$("._statusDDL").val(2);
$("._statusDDL").change();

or

$("._statusDDL").val(2).change();

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

Angular 2: How to style host element of the component?

Check out this issue. I think the bug will be resolved when new template precompilation logic will be implemented. For now I think the best you can do is to wrap your template into <div class="root"> and style this div:

@Component({ ... })
@View({
  template: `
    <div class="root">
      <h2>Hello Angular2!</h2>
      <p>here is your template</p>
    </div>
  `,
  styles: [`
    .root {
      background: blue;
    }
  `],
   ...
})
class SomeComponent {}

See this plunker

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

ENOENT means it's not there.

Just update your code to:

File.open(File.dirname(__FILE__) + '/text.txt').each {|line| puts line}

Understanding passport serialize deserialize

  1. Where does user.id go after passport.serializeUser has been called?

The user id (you provide as the second argument of the done function) is saved in the session and is later used to retrieve the whole object via the deserializeUser function.

serializeUser determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}

  1. We are calling passport.deserializeUser right after it where does it fit in the workflow?

The first argument of deserializeUser corresponds to the key of the user object that was given to the done function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc). In deserializeUser that key is matched with the in memory array / database or any data resource.

The fetched object is attached to the request object as req.user

Visual Flow

passport.serializeUser(function(user, done) {
    done(null, user.id);
});              ¦
                 ¦ 
                 ¦
                 +--------------------? saved to session
                                   ¦    req.session.passport.user = {id: '..'}
                                   ¦
                                   ?           
passport.deserializeUser(function(id, done) {
                   +---------------+
                   ¦
                   ? 
    User.findById(id, function(err, user) {
        done(err, user);
    });            +--------------? user object attaches to the request as req.user   
});

Can I limit the length of an array in JavaScript?

var  arrLength = arr.length;
if(arrLength > maxNumber){
    arr.splice( 0, arrLength - maxNumber);
}

This soultion works better in an dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.

The problem with:

arr.slice(0,5)

...is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.

The problem with:

if (arr.length > 4) arr.length = 4;

...is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().

How to import/include a CSS file using PHP code and not HTML code?

The best way to do it is:

Step 1: Rename your main.css to main.php

Step 2: in your main.php add

<style> ... </style>

Step 3: include it as usual

<?php include 'main.php'; ?>

That is how i did it, and it works smoothly..

Why are empty catch blocks a bad idea?

It's probably never the right thing because you're silently passing every possible exception. If there's a specific exception you're expecting, then you should test for it, rethrow if it's not your exception.

try
{
    // Do some processing.
}
catch (FileNotFound fnf)
{
    HandleFileNotFound(fnf);
}
catch (Exception e)
{
    if (!IsGenericButExpected(e))
        throw;
}

public bool IsGenericButExpected(Exception exception)
{
    var expected = false;
    if (exception.Message == "some expected message")
    {
        // Handle gracefully ... ie. log or something.
        expected = true;
    }

    return expected;
}

Repeat String - Javascript

Here's the JSLint safe version

String.prototype.repeat = function (num) {
  var a = [];
  a.length = num << 0 + 1;
  return a.join(this);
};

Best way to disable button in Twitter's Bootstrap

For input and button:

$('button').prop('disabled', true);

For anchor:

$('a').attr('disabled', true);

Checked in firefox, chrome.

See http://jsfiddle.net/czL54/2/

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

How do I rename a Git repository?

  1. Go to the remote host (e.g., https://github.com/<User>/<Project>/ ).
  2. Click tab Settings.
  3. Rename under Repository name (and press button Rename).

How to query GROUP BY Month in a Year

You can use:

    select FK_Items,Sum(PoiQuantity) Quantity  from PurchaseOrderItems POI
    left join PurchaseOrder PO ON po.ID_PurchaseOrder=poi.FK_PurchaseOrder
    group by FK_Items,DATEPART(MONTH, TransDate)

Browser Timeouts

You can see the default value in Chrome in this link

int64_t g_used_idle_socket_timeout_s = 300 // 5 minutes

In Chrome, as far as I know, there isn't an easy way (as Firefox do) to change the timeout value.

How to save and load numpy.array() data properly?

The most reliable way I have found to do this is to use np.savetxt with np.loadtxt and not np.fromfile which is better suited to binary files written with tofile. The np.fromfile and np.tofile methods write and read binary files whereas np.savetxt writes a text file. So, for example:

a = np.array([1, 2, 3, 4])
np.savetxt('test1.txt', a, fmt='%d')
b = np.loadtxt('test1.txt', dtype=int)
a == b
# array([ True,  True,  True,  True], dtype=bool)

Or:

a.tofile('test2.dat')
c = np.fromfile('test2.dat', dtype=int)
c == a
# array([ True,  True,  True,  True], dtype=bool)

I use the former method even if it is slower and creates bigger files (sometimes): the binary format can be platform dependent (for example, the file format depends on the endianness of your system).

There is a platform independent format for NumPy arrays, which can be saved and read with np.save and np.load:

np.save('test3.npy', a)    # .npy extension is added if not given
d = np.load('test3.npy')
a == d
# array([ True,  True,  True,  True], dtype=bool)

Invoking modal window in AngularJS Bootstrap UI using JavaScript

The AngularJS Bootstrap website hasn't been updated with the latest documentation. About 3 months ago pkozlowski-opensource authored a change to separate out $modal from $dialog commit is below:

https://github.com/angular-ui/bootstrap/commit/d7a48523e437b0a94615350a59be1588dbdd86bd

In that commit he added new documentation for $modal, which can be found below:

https://github.com/angular-ui/bootstrap/blob/d7a48523e437b0a94615350a59be1588dbdd86bd/src/modal/docs/readme.md.

Hope this helps!

Disable/Enable Submit Button until all forms have been filled

Put it inside a table and then do on her:

var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);

How to detect IE11?

Get IE Version from the User-Agent

var ie = 0;
try { ie = navigator.userAgent.match( /(MSIE |Trident.*rv[ :])([0-9]+)/ )[ 2 ]; }
catch(e){}

How it works: The user-agent string for all IE versions includes a portion "MSIE space version" or "Trident other-text rv space-or-colon version". Knowing this, we grab the version number from a String.match() regular expression. A try-catch block is used to shorten the code, otherwise we'd need to test the array bounds for non-IE browsers.

Note: The user-agent can be spoofed or omitted, sometimes unintentionally if the user has set their browser to a "compatibility mode". Though this doesn't seem like much of an issue in practice.


Get IE Version without the User-Agent

var d = document, w = window;
var ie = ( !!w.MSInputMethodContext ? 11 : !d.all ? 99 : w.atob ? 10 : 
d.addEventListener ? 9 : d.querySelector ? 8 : w.XMLHttpRequest ? 7 : 
d.compatMode ? 6 : w.attachEvent ? 5 : 1 );

How it works: Each version of IE adds support for additional features not found in previous versions. So we can test for the features in a top-down manner. A ternary sequence is used here for brevity, though if-then and switch statements would work just as well. The variable ie is set to an integer 5-11, or 1 for older, or 99 for newer/non-IE. You can set it to 0 if you just want to test for IE 1-11 exactly.

Note: Object detection may break if your code is run on a page with third-party scripts that add polyfills for things like document.addEventListener. In such situations the user-agent is the best option.


Detect if the Browser is Modern

If you're only interested in whether or not a browser supports most HTML 5 and CSS 3 standards, you can reasonably assume that IE 8 and lower remain the primary problem apps. Testing for window.getComputedStyle will give you a fairly good mix of modern browsers, as well (IE 9, FF 4, Chrome 11, Safari 5, Opera 11.5). IE 9 greatly improves on standards support, but native CSS animation requires IE 10.

var isModernBrowser = ( !document.all || ( document.all && document.addEventListener ) ); 

PyTorch: How to get the shape of a Tensor as a list of int

Previous answers got you list of torch.Size Here is how to get list of ints

listofints = [int(x) for x in tensor.shape]

How to convert binary string value to decimal

int num = Integer.parseInt("binaryString",2);

Why use String.Format?

String.Format adds many options in addition to the concatenation operators, including the ability to specify the specific format of each item added into the string.

For details on what is possible, I'd recommend reading the section on MSDN titled Composite Formatting. It explains the advantage of String.Format (as well as xxx.WriteLine and other methods that support composite formatting) over normal concatenation operators.

Java how to sort a Linked List?

You can use Collections#sort to sort things alphabetically.

How to align texts inside of an input?

Without CSS: Use the STYLE property of text input

STYLE="text-align: right;"

Why do we assign a parent reference to the child object in Java?

When you compile your program the reference variable of the base class gets memory and compiler checks all the methods in that class. So it checks all the base class methods but not the child class methods. Now at runtime when the object is created, only checked methods can run. In case a method is overridden in the child class that function runs. Child class other functions aren't run because the compiler hasn't recognized them at the compile time.

Import text file as single character string

Too bad that Sharon's solution cannot be used anymore. I've added Josh O'Brien's solution with asieira's modification to my .Rprofile file:

read.text = function(pathname)
{
    return (paste(readLines(pathname), collapse="\n"))
}

and use it like this: txt = read.text('path/to/my/file.txt'). I couldn't replicate bumpkin's (28 oct. 14) finding, and writeLines(txt) showed the contents of file.txt. Also, after write(txt, '/tmp/out') the command diff /tmp/out path/to/my/file.txt reported no differences.

Rails formatting date

Use

Model.created_at.strftime("%FT%T")

where,

%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)

Following are some of the frequently used useful list of Date and Time formats that you could specify in strftime method:

Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (round down.  20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..59)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)
          %6N  microsecond (6 digits)
          %9N  nanosecond (9 digits)
          %12N picosecond (12 digits)

For the complete list of formats for strftime method please visit APIDock

Detecting IE11 using CSS Capability/Feature Detection

If you're using Modernizr - then you can easily differntiate between IE10 and IE11.

IE10 doesn't support the pointer-events property. IE11 does. (caniuse)

Now, based on the class which Modernizr inserts you could have the following CSS:

.class
{ 
   /* for IE11 */
}

.no-pointerevents .class
{ 
   /* for IE10 */
}

How to insert a line break before an element using CSS

This works for me:

#restart:before {
    content: ' ';
    clear: right;
    display: block;
}

How to properly compare two Integers in Java?

== checks for reference equality, however when writing code like:

Integer a = 1;
Integer b = 1;

Java is smart enough to reuse the same immutable for a and b, so this is true: a == b. Curious, I wrote a small example to show where java stops optimizing in this way:

public class BoxingLol {
    public static void main(String[] args) {
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            Integer a = i;
            Integer b = i;
            if (a != b) {
                System.out.println("Done: " + i);
                System.exit(0);
            }
        }
        System.out.println("Done, all values equal");
    }
}

When I compile and run this (on my machine), I get:

Done: 128

Detect the Internet connection is offline?

 if(navigator.onLine){
  alert('online');
 } else {
  alert('offline');
 }

How to implement common bash idioms in Python?

  • If you want to use Python as a shell, why not have a look at IPython ? It is also good to learn interactively the language.
  • If you do a lot of text manipulation, and if you use Vim as a text editor, you can also directly write plugins for Vim in python. just type ":help python" in Vim and follow the instructions or have a look at this presentation. It is so easy and powerfull to write functions that you will use directly in your editor!

Why use the params keyword?

Another example

public IEnumerable<string> Tokenize(params string[] words)
{
  ...
}

var items = Tokenize(product.Name, product.FullName, product.Xyz)

How do I modify fields inside the new PostgreSQL JSON datatype?

To build upon @pozs's answers, here are a couple more PostgreSQL functions which may be useful to some. (Requires PostgreSQL 9.3+)

Delete By Key: Deletes a value from JSON structure by key.

CREATE OR REPLACE FUNCTION "json_object_del_key"(
  "json"          json,
  "key_to_del"    TEXT
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_to_del") IS NULL THEN "json"
  ELSE (SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')
          FROM (SELECT *
                  FROM json_each("json")
                 WHERE "key" <> "key_to_del"
               ) AS "fields")::json
END
$function$;

Recursive Delete By Key: Deletes a value from JSON structure by key-path. (requires @pozs's json_object_set_key function)

CREATE OR REPLACE FUNCTION "json_object_del_path"(
  "json"          json,
  "key_path"      TEXT[]
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_path"[l] ) IS NULL THEN "json"
  ELSE
     CASE COALESCE(array_length("key_path", 1), 0)
         WHEN 0 THEN "json"
         WHEN 1 THEN "json_object_del_key"("json", "key_path"[l])
         ELSE "json_object_set_key"(
           "json",
           "key_path"[l],
           "json_object_del_path"(
             COALESCE(NULLIF(("json" -> "key_path"[l])::text, 'null'), '{}')::json,
             "key_path"[l+1:u]
           )
         )
       END
    END
  FROM array_lower("key_path", 1) l,
       array_upper("key_path", 1) u
$function$;

Usage examples:

s1=# SELECT json_object_del_key ('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 'foo'),
            json_object_del_path('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 '{"foo","moe"}');

 json_object_del_key |          json_object_del_path
---------------------+-----------------------------------------
 {"hello":[7,3,1]}   | {"hello":[7,3,1],"foo":{"mofu":"fuwa"}}

SQL Server 2005 Setting a variable to the result of a select query

You can use something like

SET @cnt = (SELECT COUNT(*) FROM User)

or

SELECT @cnt = (COUNT(*) FROM User)

For this to work the SELECT must return a single column and a single result and the SELECT statement must be in parenthesis.

Edit: Have you tried something like this?

DECLARE @OOdate DATETIME

SET @OOdate = Select OO.Date from OLAP.OutageHours as OO where OO.OutageID = 1

Select COUNT(FF.HALID) 
from Outages.FaultsInOutages as OFIO 
inner join Faults.Faults as FF 
    ON FF.HALID = OFIO.HALID 
WHERE @OODate = FF.FaultDate
    AND OFIO.OutageID = 1

What is the difference between syntax and semantics in programming languages?

  • You need correct syntax to compile.
  • You need correct semantics to make it work.

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

About the removal of componentWillReceiveProps: you should be able to handle its uses with a combination of getDerivedStateFromProps and componentDidUpdate, see the React blog post for example migrations. And yes, the object returned by getDerivedStateFromProps updates the state similarly to an object passed to setState.

In case you really need the old value of a prop, you can always cache it in your state with something like this:

state = {
  cachedSomeProp: null
  // ... rest of initial state
};

static getDerivedStateFromProps(nextProps, prevState) {
  // do things with nextProps.someProp and prevState.cachedSomeProp
  return {
    cachedSomeProp: nextProps.someProp,
    // ... other derived state properties
  };
}

Anything that doesn't affect the state can be put in componentDidUpdate, and there's even a getSnapshotBeforeUpdate for very low-level stuff.

UPDATE: To get a feel for the new (and old) lifecycle methods, the react-lifecycle-visualizer package may be helpful.

Access Controller method from another controller in Laravel 5

If you need that method in another controller, that means you need to abstract it and make it reusable. Move that implementation into a service class (ReportingService or something similar) and inject it into your controllers.

Example:

class ReportingService
{
  public function getPrintReport()
  {
    // your implementation here.
  }
}
// don't forget to import ReportingService at the top (use Path\To\Class)
class SubmitPerformanceController extends Controller
{
  protected $reportingService;
  public function __construct(ReportingService $reportingService)
  {
     $this->reportingService = $reportingService;
  }

  public function reports() 
  {
    // call the method 
    $this->reportingService->getPrintReport();
    // rest of the code here
  }
}

Do the same for the other controllers where you need that implementation. Reaching for controller methods from other controllers is a code smell.

How do I set the colour of a label (coloured text) in Java?

Just wanted to add on to what @aioobe mentioned above...

In that approach you use HTML to color code your text. Though this is one of the most frequently used ways to color code the label text, but is not the most efficient way to do it.... considering that fact that each label will lead to HTML being parsed, rendering, etc. If you have large UI forms to be displayed, every millisecond counts to give a good user experience.

You may want to go through the below and give it a try....

Jide OSS (located at https://jide-oss.dev.java.net/) is a professional open source library with a really good amount of Swing components ready to use. They have a much improved version of JLabel named StyledLabel. That component solves your problem perfectly... See if their open source licensing applies to your product or not.

This component is very easy to use. If you want to see a demo of their Swing Components you can run their WebStart demo located at www.jidesoft.com (http://www.jidesoft.com/products/1.4/jide_demo.jnlp). All of their offerings are demo'd... and best part is that the StyledLabel is compared with JLabel (HTML and without) in terms of speed! :-)

A screenshot of the perf test can be seen at (http://img267.imageshack.us/img267/9113/styledlabelperformance.png)

How to sort a list/tuple of lists/tuples by the element at a given index?

@Stephen 's answer is to the point! Here is an example for better visualization,

Shout out for the Ready Player One fans! =)

>>> gunters = [('2044-04-05', 'parzival'), ('2044-04-07', 'aech'), ('2044-04-06', 'art3mis')]
>>> gunters.sort(key=lambda tup: tup[0])
>>> print gunters
[('2044-04-05', 'parzival'), ('2044-04-06', 'art3mis'), ('2044-04-07', 'aech')]

key is a function that will be called to transform the collection's items for comparison.. like compareTo method in Java.

The parameter passed to key must be something that is callable. Here, the use of lambda creates an anonymous function (which is a callable).
The syntax of lambda is the word lambda followed by a iterable name then a single block of code.

Below example, we are sorting a list of tuple that holds the info abt time of certain event and actor name.

We are sorting this list by time of event occurrence - which is the 0th element of a tuple.

Note - s.sort([cmp[, key[, reverse]]]) sorts the items of s in place

Splitting dataframe into multiple dataframes

You can use the groupby command, if you already have some labels for your data.

 out_list = [group[1] for group in in_series.groupby(label_series.values)]

Here's a detailed example:

Let's say we want to partition a pd series using some labels into a list of chunks For example, in_series is:

2019-07-01 08:00:00   -0.10
2019-07-01 08:02:00    1.16
2019-07-01 08:04:00    0.69
2019-07-01 08:06:00   -0.81
2019-07-01 08:08:00   -0.64
Length: 5, dtype: float64

And its corresponding label_series is:

2019-07-01 08:00:00   1
2019-07-01 08:02:00   1
2019-07-01 08:04:00   2
2019-07-01 08:06:00   2
2019-07-01 08:08:00   2
Length: 5, dtype: float64

Run

out_list = [group[1] for group in in_series.groupby(label_series.values)]

which returns out_list a list of two pd.Series:

[2019-07-01 08:00:00   -0.10
2019-07-01 08:02:00   1.16
Length: 2, dtype: float64,
2019-07-01 08:04:00    0.69
2019-07-01 08:06:00   -0.81
2019-07-01 08:08:00   -0.64
Length: 3, dtype: float64]

Note that you can use some parameters from in_series itself to group the series, e.g., in_series.index.day

When does a process get SIGABRT (signal 6)?

You can send any signal to any process using the kill(2) interface:

kill -SIGABRT 30823

30823 was a dash process I started, so I could easily find the process I wanted to kill.

$ /bin/dash
$ Aborted

The Aborted output is apparently how dash reports a SIGABRT.

It can be sent directly to any process using kill(2), or a process can send the signal to itself via assert(3), abort(3), or raise(3).

What represents a double in sql server?

For SQL Sever:

Decimal Type is 128 bit signed number Float is a 64 bit signed number.

The real answer is Float, I was incorrect about decimal.

The reason is if you use a decimal you will never fill 64 bit of the decimal type.

Although decimal won't give you an error if you try to use a int type.

Here is a nice reference chart of the types.

How to encode URL to avoid special characters in Java?

Here is my solution which is pretty easy:

Instead of encoding the url itself i encoded the parameters that I was passing because the parameter was user input and the user could input any unexpected string of special characters so this worked for me fine :)

String review="User input"; /*USER INPUT AS STRING THAT WILL BE PASSED AS PARAMTER TO URL*/
try {
    review = URLEncoder.encode(review,"utf-8");
    review = review.replace(" " , "+");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
String URL = "www.test.com/test.php"+"?user_review="+review;

git diff between two different files

If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"

Working with $scope.$emit and $scope.$on

You must use $rootScope to send and capture events between controllers in same app. Inject $rootScope dependency to your controllers. Here is a working example.

app.controller('firstCtrl', function($scope, $rootScope) {        
        function firstCtrl($scope) {
        {
            $rootScope.$emit('someEvent', [1,2,3]);
        }
}

app.controller('secondCtrl', function($scope, $rootScope) {
        function secondCtrl($scope)
        {
            $rootScope.$on('someEvent', function(event, data) { console.log(data); });
        }
}

Events linked into $scope object just work in the owner controller. Communication between controllers is done via $rootScope or Services.

How to copy text from a div to clipboard

Made a modification to the solutions, so it will work with multiple divs based on class instead of specific IDs. For example, if you have multiple blocks of code. This assumes that the div class is set to "code".

<script>
        $( document ).ready(function() {
            $(".code").click(function(event){
                var range = document.createRange();
                range.selectNode(this);
                window.getSelection().removeAllRanges(); // clear current selection
                window.getSelection().addRange(range); // to select text
                document.execCommand("copy");
                window.getSelection().removeAllRanges();// to deselect
            });
        });
    </script>

How to pass anonymous types as parameters?

Unfortunately, what you're trying to do is impossible. Under the hood, the query variable is typed to be an IEnumerable of an anonymous type. Anonymous type names cannot be represented in user code hence there is no way to make them an input parameter to a function.

Your best bet is to create a type and use that as the return from the query and then pass it into the function. For example,

struct Data {
  public string ColumnName; 
}

var query = (from name in some.Table
            select new Data { ColumnName = name });
MethodOp(query);
...
MethodOp(IEnumerable<Data> enumerable);

In this case though, you are only selecting a single field, so it may be easier to just select the field directly. This will cause the query to be typed as an IEnumerable of the field type. In this case, column name.

var query = (from name in some.Table select name);  // IEnumerable<string>

Detect if PHP session exists

The original code is from Sabry Suleiman.

Made it a bit prettier:

function is_session_started() {

    if ( php_sapi_name() === 'cli' )
        return false;

    return version_compare( phpversion(), '5.4.0', '>=' )
        ? session_status() === PHP_SESSION_ACTIVE
        : session_id() !== '';
}

First condition checks the Server API in use. If Command Line Interface is used, the function returns false.

Then we return the boolean result depending on the PHP version in use.

In ancient history you simply needed to check session_id(). If it's an empty string, then session is not started. Otherwise it is.

Since 5.4 to at least the current 8.0 the norm is to check session_status(). If it's not PHP_SESSION_ACTIVE, then either the session isn't started yet (PHP_SESSION_NONE) or sessions are not available altogether (PHP_SESSION_DISABLED).

How to convert number to words in java

You probably don't need this any more, but I recently wrote a java class to do this. Apparently Yanick Rochon did something similar. It will convert numbers up to 999 Novemdecillion (999*10^60). It could do more if I knew what came after Novemdecillion, but I would be willing to bet it's unnecessary. Just feed the number as a string in cents. The output is also grammatically correct.

Here is a link to the Bitbucket Repo

When to use the JavaScript MIME type application/javascript instead of text/javascript?

The problem with Javascript's MIME type is that there hasn't been a standard for years. Now we've got application/javascript as an official MIME type.

But actually, the MIME type doesn't matter at all, as the browser can determine the type itself. That's why the HTML5 specs state that the type="text/javascript" is no longer required.

In Java, remove empty elements from a list of Strings

  • This code compiles and runs smoothly.
  • It uses no iterator so more readable.
  • list is your collection.
  • result is filtered form (no null no empty).

public static void listRemove() {
    List<String> list = Arrays.asList("", "Hi", "", "How", "are", "you");
    List<String> result = new ArrayList<String>();

    for (String str : list) {
        if (str != null && !str.isEmpty()) {
            result.add(str);
        }
    }

    System.out.println(result);
}

CSS list-style-image size

You can see how layout engines determine list-image sizes here: http://www.w3.org/wiki/CSS/Properties/list-style-image

There are three ways to do get around this while maintaining the benefits of CSS:

  1. Resize the image.
  2. Use a background-image and padding instead (easiest method).
  3. Use an SVG without a defined size using viewBox that will then resize to 1em when used as a list-style-image (Kudos to Jeremy).

How to edit an Android app?

You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.

You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.

If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.

In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.

PHPExcel Make first row bold

This iterates through a variable number of columns of a particular row, which in this case is the 1st row:

$rownumber = 1;
$row = $this->objPHPExcel->getActiveSheet()->getRowIterator($rownumber)->current();

$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);

foreach ($cellIterator as $cell) {
    $cell->getStyle()->getFont()->setBold(true);
}

Regular vs Context Free Grammars

a regular grammer is never ambiguous because it is either left linear or right linear so we cant make two decision tree for regular grammer so it is always unambiguous.but othert than regular grammar all are may or may not be regular

How to iterate over each string in a list of strings and operate on it's elements

The suggestion that using range(len()) is the equivalent of using enumerate() is incorrect. They return the same results, but they are not the same.

Using enumerate() actually gives you key/value pairs. Using range(len()) does not.

Let's check range(len()) first (working from the example from the original poster):

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
    print range(len(words))

This gives us a simple list:

[0, 1, 2, 3, 4]

... and the elements in this list serve as the "indexes" in our results.

So let's do the same thing with our enumerate() version:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']    
   print enumerate(words)

This certainly doesn't give us a list:

<enumerate object at 0x7f6be7f32c30>

...so let's turn it into a list, and see what happens:

print list(enumerate(words))

It gives us:

[(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')]

These are actual key/value pairs.

So this ...

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']

for i in range(len(words)):
    print "words[{}] = ".format(i), words[i]

... actually takes the first list (Words), and creates a second, simple list of the range indicated by the length of the first list.

So we have two simple lists, and we are merely printing one element from each list in order to get our so-called "key/value" pairs.

But they aren't really key/value pairs; they are merely two single elements printed at the same time, from different lists.

Whereas the enumerate () code:

for i, word in enumerate(words):
    print "words[{}] = {}".format(i, word)

... also creates a second list. But that list actually is a list of key/value pairs, and we are asking for each key and value from a single source -- rather than from two lists (like we did above).

So we print the same results, but the sources are completely different -- and handled completely differently.

String Padding in C

The function itself looks fine to me. The problem could be that you aren't allocating enough space for your string to pad that many characters onto it. You could avoid this problem in the future by passing a size_of_string argument to the function and make sure you don't pad the string when the length is about to be greater than the size.

Django: Model Form "object has no attribute 'cleaned_data'"

At times, if we forget the

return self.cleaned_data 

in the clean function of django forms, we will not have any data though the form.is_valid() will return True.

The Network Adapter could not establish the connection when connecting with Oracle DB

I had similar problem before. But this was resolved when I started using hostname instead of IP address in my connection string.

Select multiple columns by labels in pandas

Just pick the columns you want directly....

df[['A','E','I','C']]

generate days from date range

Accepted answer didn't work for PostgreSQL (syntax error at or near "a").

The way you do this in PostgreSQL is by using generate_series function, i.e.:

SELECT day::date
FROM generate_series('2010-01-20', '2010-01-24', INTERVAL '1 day') day;

    day
------------
 2010-01-20
 2010-01-21
 2010-01-22
 2010-01-23
 2010-01-24
(5 rows)

Show MySQL host via SQL Command

I think you try to get the remote host of the conneting user...

You can get a String like 'myuser@localhost' from the command:

SELECT USER()

You can split this result on the '@' sign, to get the parts:

-- delivers the "remote_host" e.g. "localhost" 
SELECT SUBSTRING_INDEX(USER(), '@', -1) 

-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)

if you are conneting via ip address you will get the ipadress instead of the hostname.

How to change port for jenkins window service when 8080 is being used

Check in Jenkins.xml and update like below

<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8090</arguments>

How to create a custom scrollbar on a div (Facebook style)

I solved this problem by adding another div as a sibling to the scrolling content div. It's height is set to the radius of the curved borders. There will be design issues if you have content that you want nudged to the very bottom, or text you want to flow into this new div, etc,. but for my UI this thin div is no problem.

The real trick is to have the following structure:

<div class="window">
 <div class="title">Some title text</div>
 <div class="content">Main content area</div>
 <div class="footer"></div>
</div>

Important CSS highlights:

  • Your CSS would define the content region with a height and overflow to allow the scrollbar(s) to appear.
  • The window class gets the same diameter corners as the title and footer
  • The drop shadow, if desired, is only given to the window class
  • The height of the footer div is the same as the radius of the bottom corners

Here's what that looks like:

Bottom right corner

Get time of specific timezone

You can use getUTCDate() and the related getUTC...() methods to access a time based off UTC time, and then convert.

If you wish, you can use valueOf(), which returns the number of seconds, in UTC, since the Unix epoch, and work with that, but it's likely going to be much more involved.

How to generate classes from wsdl using Maven and wsimport?

The key here is keep option of wsimport. And it is configured using element in About keep from the wsimport documentation :

-keep                     keep generated files

Checking for a null object in C++

C++ references naturally can't be null, you don't need the check. The function can only be called by passing a reference to an existing object.

Reset AutoIncrement in SQL Server after Delete

DBCC CHECKIDENT('databasename.dbo.tablename', RESEED, number)

if number=0 then in the next insert the auto increment field will contain value 1

if number=101 then in the next insert the auto increment field will contain value 102


Some additional info... May be useful to you

Before giving auto increment number in above query, you have to make sure your existing table's auto increment column contain values less that number.

To get the maximum value of a column(column_name) from a table(table1), you can use following query

 SELECT MAX(column_name) FROM table1

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

Xml tag arrangement in Web.config is important

First

<configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>

After

<connectionStrings>
  <add name="SqlConnectionString" connectionString="Data Source=.; Initial Catalog=TestDB; Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

What is the most useful script you've written for everyday life?

Mass file renaming via drag&drop.

Ages ago I've made a small VBScript that accepts a RegEx and replaces file names accordingly. You would simply drop a bunch of files or folders on it. I found that to be very useful throughout the years.

gist.github.com/15824 (Beware, the comments are in German)

javascript filter array of objects

_x000D_
_x000D_
var nameList = [_x000D_
{name:'x', age:20, email:'[email protected]'},_x000D_
{name:'y', age:60, email:'[email protected]'},_x000D_
{name:'Joe', age:22, email:'[email protected]'},_x000D_
{name:'Abc', age:40, email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var filteredValue = nameList.filter(function (item) {_x000D_
      return item.name == "Joe" && item.age < 30;_x000D_
});_x000D_
_x000D_
//To See Output Result as Array_x000D_
console.log(JSON.stringify(filteredValue));
_x000D_
_x000D_
_x000D_

You can simply use javascript :)

Best practice multi language website

I had the same probem a while ago, before starting using Symfony framework.

  1. Just use a function __() which has arameters pageId (or objectId, objectTable described in #2), target language and an optional parameter of fallback (default) language. The default language could be set in some global config in order to have an easier way to change it later.

  2. For storing the content in database i used following structure: (pageId, language, content, variables).

    • pageId would be a FK to your page you want to translate. if you have other objects, like news, galleries or whatever, just split it into 2 fields objectId, objectTable.

    • language - obviously it would store the ISO language string EN_en, LT_lt, EN_us etc.

    • content - the text you want to translate together with the wildcards for variable replacing. Example "Hello mr. %%name%%. Your account balance is %%balance%%."

    • variables - the json encoded variables. PHP provides functions to quickly parse these. Example "name: Laurynas, balance: 15.23".

    • you mentioned also slug field. you could freely add it to this table just to have a quick way to search for it.

  3. Your database calls must be reduced to minimum with caching the translations. It must be stored in PHP array, because it is the fastest structure in PHP language. How you will make this caching is up to you. From my experience you should have a folder for each language supported and an array for each pageId. The cache should be rebuilt after you update the translation. ONLY the changed array should be regenerated.

  4. i think i answered that in #2

  5. your idea is perfectly logical. this one is pretty simple and i think will not make you any problems.

URLs should be translated using the stored slugs in the translation table.

Final words

it is always good to research the best practices, but do not reinvent the wheel. just take and use the components from well known frameworks and use them.

take a look at Symfony translation component. It could be a good code base for you.

Kill process by name?

You can use pkill <process_name> in a unix system to kill process by name.

Then the python code will be:

>>> import os
>>> process_name=iChat
>>> os.system('pkill '+process_name)

move div with CSS transition

I added the vendor prefixes, and changed the animation to all, so you have both opacity and width that are animated.

Is this what you're looking for ? http://jsfiddle.net/u2FKM/3/

Does List<T> guarantee insertion order?

If you will change the order of operations, you will avoid the strange behavior: First insert the value to the right place in the list, and then delete it from his first position. Make sure you delete it by his index, because if you will delete it by reference, you might delete them both...

Make a dictionary in Python from input values

n = int(input("enter a n value:"))
d = {}

for i in range(n):
    keys = input() # here i have taken keys as strings
    values = int(input()) # here i have taken values as integers
    d[keys] = values
print(d)

How to use sys.exit() in Python

Using 2.7:

from functools import partial
from random import randint

for roll in iter(partial(randint, 1, 8), 1):
    print 'you rolled: {}'.format(roll)
print 'oops you rolled a 1!'

you rolled: 7
you rolled: 7
you rolled: 8
you rolled: 6
you rolled: 8
you rolled: 5
oops you rolled a 1!

Then change the "oops" print to a raise SystemExit

How do I bind the enter key to a function in tkinter?

I found one good thing about using bind is that you get to know the trigger event: something like: "You clicked with event = [ButtonPress event state=Mod1 num=1 x=43 y=20]" due to the code below:

self.submit.bind('<Button-1>', self.parse)
def parse(self, trigger_event):
        print("You clicked with event = {}".format(trigger_event))

Comparing the following two ways of coding a button click:

btn = Button(root, text="Click me to submit", command=(lambda: reply(ent.get())))
btn = Button(root, text="Click me to submit")
btn.bind('<Button-1>', (lambda event: reply(ent.get(), e=event)))
def reply(name, e = None):
    messagebox.showinfo(title="Reply", message = "Hello {0}!\nevent = {1}".format(name, e))

The first one is using the command function which doesn't take an argument, so no event pass-in is possible. The second one is a bind function which can take an event pass-in and print something like "Hello Charles! event = [ButtonPress event state=Mod1 num=1 x=68 y=12]"

We can left click, middle click or right click a mouse which corresponds to the event number of 1, 2 and 3, respectively. Code:

btn = Button(root, text="Click me to submit")
buttonClicks = ["<Button-1>", "<Button-2>", "<Button-3>"]
for bc in buttonClicks:
    btn.bind(bc, lambda e : print("Button clicked with event = {}".format(e.num)))

Output:

Button clicked with event = 1
Button clicked with event = 2
Button clicked with event = 3

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

Disabling user-scalable (namely, the ability to double tap to zoom) allows the browser to reduce the click delay. In touch-enable browsers, when the user expects the double tap to zoom, the browser generally waits 300ms before firing the click event, waiting to see if the user will double tap. Disabling user-scalable allows for the Chrome browser to fire the click event immediately, allowing for a better user experience.

From Google IO 2013 session https://www.youtube.com/watch?feature=player_embedded&v=DujfpXOKUp8#t=1435s

Update: its not true anymore, <meta name="viewport" content="width=device-width"> is enough to remove 300ms delay

Unrecognized SSL message, plaintext connection? Exception

Another reason is maybe "access denided", maybe you can't access to the URI and received blocking response page for internal network access. If you are not sure your application zone need firewall rule, you try to connect from terminal,command line. For GNU/Linux or Unix, you can try run like this command and see result is coming from blocking rule or really remote address: echo | nc -v yazilimcity.net 443

How do you uninstall the package manager "pip", if installed from source?

I was using above command but it was not working. This command worked for me:

python -m pip uninstall pip setuptools

C program to check little vs. big endian

In short, yes.

Suppose we are on a 32-bit machine.

If it is little endian, the x in the memory will be something like:

       higher memory
          ----->
    +----+----+----+----+
    |0x01|0x00|0x00|0x00|
    +----+----+----+----+
    A
    |
   &x

so (char*)(&x) == 1, and *y+48 == '1'.

If it is big endian, it will be:

    +----+----+----+----+
    |0x00|0x00|0x00|0x01|
    +----+----+----+----+
    A
    |
   &x

so this one will be '0'.

"Least Astonishment" and the Mutable Default Argument

There is a simple way to understand why this happens.

Python executes code, from top to bottom, in a namespace.

The 'internals' just embody of this rule.

The reason for this choice is to "let the language fit in your head". All the odd corner cases tend to simplify to executing code in a namespace: default immutables, nested functions, classes (with a little patch-up when done compiling), the self argument, etc. Similarly, complex syntax could be written in simple syntax: a.foo(...) is just a.lookup('foo').__call__(a,...). This works with list comprehensions; decorators; metaclasses; and more. This gives you a near perfect view of the strange corners. The language fits in your head.

You should keep at it. Learning Python has a period of railing at the language, but it gets comfortable. It's the only language I've worked in that gets simpler the more you look at corner cases.

Keep Hacking! Keep notes.

For your specific code, in too much detail:

def foo(a=[]):
    a.append(5)
    return a

foo()

is one statement, equivalent to:

  1. Start making a code object.
  2. Interpreting (a=[]) right now, as we go. The [] is the default value of argument a. It is of type list, as [] always is.
  3. Compile all the code after the : into Python bytecode and stick it in another list.
  4. Create the callable dictionary, with the arguments and code in the 'code' field
  5. Add the callable to the current namespace in the 'foo' field.

Then, it goes to the next line, foo().

  1. It's not a reserved word, so look it up in the namespace.
  2. Call the function, which will use the list as the default argument. Start executing its bytecode in its namespace.
  3. append does not create a new list, so the old one is modified.

Java List.contains(Object with field value equal to x)

Streams

If you are using Java 8, perhaps you could try something like this:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().filter(o -> o.getName().equals(name)).findFirst().isPresent();
}

Or alternatively, you could try something like this:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().map(MyObject::getName).filter(name::equals).findFirst().isPresent();
}

This method will return true if the List<MyObject> contains a MyObject with the name name. If you want to perform an operation on each of the MyObjects that getName().equals(name), then you could try something like this:

public void perform(final List<MyObject> list, final String name){
    list.stream().filter(o -> o.getName().equals(name)).forEach(
            o -> {
                //...
            }
    );
}

Where o represents a MyObject instance.

Alternatively, as the comments suggest (Thanks MK10), you could use the Stream#anyMatch method:

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().anyMatch(o -> o.getName().equals(name));
}

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How to see the changes in a Git commit?

In case of checking the source change in a graphical view,

$gitk (Mention your commit id here)

for example:

$gitk HEAD~1 

Git Pull While Ignoring Local Changes?

If you are on Linux:

git fetch
for file in `git diff origin/master..HEAD --name-only`; do rm -f "$file"; done
git pull

The for loop will delete all tracked files which are changed in the local repo, so git pull will work without any problems.
The nicest thing about this is that only the tracked files will be overwritten by the files in the repo, all other files will be left untouched.

Enable/disable buttons with Angular

    <div class="col-md-12">
      <p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
      <button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
        Ver Pedido
      </button>
     </p>
    </div>

How do I get the function name inside a function in PHP?

If you are using PHP 5 you can try this:

function a() {
    $trace = debug_backtrace();
    echo $trace[0]["function"];
}

What's the best visual merge tool for Git?

Diffuse is my favourite but of course I am biased. :-) It is very easy to use:

$ diffuse "mine" "output" "theirs"

Diffuse is a small and simple text merge tool written in Python. With Diffuse, you can easily merge, edit, and review changes to your code. Diffuse is free software.

How to use new PasswordEncoder from Spring Security

If you haven't actually registered any users with your existing format then you would be best to switch to using the BCrypt password encoder instead.

It's a lot less hassle, as you don't have to worry about salt at all - the details are completely encapsulated within the encoder. Using BCrypt is stronger than using a plain hash algorithm and it's also a standard which is compatible with applications using other languages.

There's really no reason to choose any of the other options for a new application.

How can I connect to Android with ADB over TCP?

adb can communicate with adb server over tcp socket. you can verify this by telnet.

$ telnet 127.0.0.1 5037
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
000chost:version
OKAY00040020

generally, command has the format %04x%s with <message.length><msg> the following is the ruby command witch sends adb command cmd against tcp socket socket

def send_to_adb(socket, cmd)
  socket.printf("%04x%s", cmd.length, cmd)
end

the first example sends the command host:version which length is 12(000c in hex). you can enjoy more exciting command like framebuffer: which takes screenshot from framebuffer as you can guess from its name.

How to round the minute of a datetime object

Here is a simpler generalized solution without floating point precision issues and external library dependencies:

import datetime

def time_mod(time, delta, epoch=None):
    if epoch is None:
        epoch = datetime.datetime(1970, 1, 1, tzinfo=time.tzinfo)
    return (time - epoch) % delta

def time_round(time, delta, epoch=None):
    mod = time_mod(time, delta, epoch)
    if mod < (delta / 2):
       return time - mod
    return time + (delta - mod)

In your case:

>>> tm = datetime.datetime(2010, 6, 10, 3, 56, 23)
>>> time_round(tm, datetime.timedelta(minutes=10))
datetime.datetime(2010, 6, 10, 4, 0)

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

How to use Lambda in LINQ select statement

using LINQ query expression

 IEnumerable<SelectListItem> stores =
        from store in database.Stores
        where store.CompanyID == curCompany.ID
        select new SelectListItem { Value = store.Name, Text = store.ID };

 ViewBag.storeSelector = stores;

or using LINQ extension methods with lambda expressions

 IEnumerable<SelectListItem> stores = database.Stores
        .Where(store => store.CompanyID == curCompany.ID)
        .Select(store => new SelectListItem { Value = store.Name, Text = store.ID });

 ViewBag.storeSelector = stores;

Force overwrite of local file with what's in origin repo?

This worked for me:

git reset HEAD <filename>

Converting String to "Character" array in Java

Use this:

String str = "testString";
char[] charArray = str.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);

Linux/Unix command to determine if process is running?

You SHOULD know the PID !

Finding a process by trying to do some kind of pattern recognition on the process arguments (like pgrep "mysqld") is a strategy that is doomed to fail sooner or later. What if you have two mysqld running? Forget that approach. You MAY get it right temporarily and it MAY work for a year or two but then something happens that you haven't thought about.

Only the process id (pid) is truly unique.

Always store the pid when you launch something in the background. In Bash this can be done with the $! Bash variable. You will save yourself SO much trouble by doing so.

How to determine if process is running (by pid)

So now the question becomes how to know if a pid is running.

Simply do:

ps -o pid= -p <pid>

This is POSIX and hence portable. It will return the pid itself if the process is running or return nothing if the process is not running. Strictly speaking the command will return a single column, the pid, but since we've given that an empty title header (the stuff immediately preceding the equals sign) and this is the only column requested then the ps command will not use header at all. Which is what we want because it makes parsing easier.

This will work on Linux, BSD, Solaris, etc.

Another strategy would be to test on the exit value from the above ps command. It should be zero if the process is running and non-zero if it isn't. The POSIX spec says that ps must exit >0 if an error has occurred but it is unclear to me what constitutes 'an error'. Therefore I'm not personally using that strategy although I'm pretty sure it will work as well on all Unix/Linux platforms.

git: patch does not apply

Johannes Sixt from the [email protected] mailing list suggested using following command line arguments:

git apply --ignore-space-change --ignore-whitespace mychanges.patch

This solved my problem.

Check if number is decimal

function is_decimal_value( $a ) {
    $d=0; $i=0;
    $b= str_split(trim($a.""));
    foreach ( $b as $c ) {
        if ( $i==0 && strpos($c,"-") ) continue;
        $i++;
        if ( is_numeric($c) ) continue;
        if ( stripos($c,".") === 0 ) {
            $d++;
            if ( $d > 1 ) return FALSE;
            else continue;
        } else
        return FALSE;
    }
    return TRUE;
}

Known Issues with the above function:

1) Does not support "scientific notation" (1.23E-123), fiscal (leading $ or other) or "Trailing f" (C++ style floats) or "trailing currency" (USD, GBP etc)

2) False positive on string filenames that match a decimal: Please note that for example "10.0" as a filename cannot be distinguished from the decimal, so if you are attempting to detect a type from a string alone, and a filename matches a decimal name and has no path included, it will be impossible to discern.

PHP - Check if the page run on Mobile or Desktop browser

There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net

Using that it's quite easy to only display content for a mobile:

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

// Check for any mobile device.
if ($detect->isMobile()){
   // mobile content
}
else {
   // other content for desktops
}

"Gradle Version 2.10 is required." Error

First Check your Project-level settings at

File > Settings > Build, Executions, Deployment > Build Tools > Gradle

and Select the Option :

  • Use default gradle wrapper (recommended)

then go to Project's

Gradle > wrapper > gradle-wrapper.properties

and edit version of the distributionUrl

distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip

And you are done :)

What is the difference between \r and \n?

\r is used to point to the start of a line and can replace the text from there, e.g.

main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}

Produces this output:

hai

\n is for new line.

How to initialize var?

C# is a strictly/strongly typed language. var was introduced for compile-time type-binding for anonymous types yet you can use var for primitive and custom types that are already known at design time. At runtime there's nothing like var, it is replaced by an actual type that is either a reference type or value type.

When you say,

var x = null; 

the compiler cannot resolve this because there's no type bound to null. You can make it like this.

string y = null;
var x = y;

This will work because now x can know its type at compile time that is string in this case.

How to disable Google Chrome auto update?

For Ubuntu:

  1. go to 'Software & Updates'.
  2. click 'Other Software' tab.
  3. Uncheck the next checkbox 'http://dl.google.com/linux/chrome/deb/ stable main'

enter image description here

"Unable to launch the IIS Express Web server" error

At the start, Try to disable your firewall. It helped me. The Eset Smart Security 5 blocked it.

Editable 'Select' element

_x000D_
_x000D_
A bit more universal <select name="env" style="width: 200px; position:absolute;" onchange="this.nextElementSibling.value=this.value">_x000D_
    <option></option>_x000D_
    <option>1</option>_x000D_
    <option>2</option>_x000D_
    <option>3</option> _x000D_
</select>_x000D_
<input style="width: 178px; margin-top: 1px; border: none; position:relative; left:1px; margin-right: 25px;" value="123456789012345678901234"/>layout ...
_x000D_
_x000D_
_x000D_

Set colspan dynamically with jquery

Setting colspan="0" is support only in firefox.

In other browsers we can get around it with:

// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
    colCount = 0;
    $(this).parents("table").find('tr').eq(0).children().each(function(){
        if ($(this).attr('colspan')){
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
$(this).attr("colspan", colCount);
});

http://tinker.io/3d642/4

Is there an opposite of include? for Ruby Arrays?

Looking at Ruby only:

TL;DR

Use none? passing it a block with == for the comparison:

[1, 2].include?(1)
  #=> true
[1, 2].none? { |n| 1 == n  }
  #=> false

Array#include? accepts one argument and uses == to check against each element in the array:

player = [1, 2, 3]
player.include?(1)
 #=> true

Enumerable#none? can also accept one argument in which case it uses === for the comparison. To get the opposing behaviour to include? we omit the parameter and pass it a block using == for the comparison.

player.none? { |n| 7 == n }
 #=> true 
!player.include?(7)    #notice the '!'
 #=> true

In the above example we can actually use:

player.none?(7)
 #=> true

That's because Integer#== and Integer#=== are equivalent. But consider:

player.include?(Integer)
 #=> false
player.none?(Integer)
 #=> false

none? returns false because Integer === 1 #=> true. But really a legit notinclude? method should return true. So as we did before:

player.none? { |e| Integer == e  }
 #=> true

Apply CSS to jQuery Dialog Buttons

You can use the open event handler to apply additional styling:

 open: function(event) {
     $('.ui-dialog-buttonpane').find('button:contains("Cancel")').addClass('cancelButton');
 }

Make the size of a heatmap bigger with seaborn

add plt.figure(figsize=(16,5)) before the sns.heatmap and play around with the figsize numbers till you get the desired size

...

plt.figure(figsize = (16,5))

ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

How to set background color of a button in Java GUI?

You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.

Commands out of sync; you can't run this command now

Create two connections, use both separately

$mysqli = new mysqli("localhost", "Admin", "dilhdk", "SMS");

$conn = new mysqli("localhost", "Admin", "dilhdk", "SMS"); 

Waiting on a list of Future

I've got a utility class that contains these:

@FunctionalInterface
public interface CheckedSupplier<X> {
  X get() throws Throwable;
}

public static <X> Supplier<X> uncheckedSupplier(final CheckedSupplier<X> supplier) {
    return () -> {
        try {
            return supplier.get();
        } catch (final Throwable checkedException) {
            throw new IllegalStateException(checkedException);
        }
    };
}

Once you have that, using a static import, you can simple wait for all futures like this:

futures.stream().forEach(future -> uncheckedSupplier(future::get).get());

you can also collect all their results like this:

List<MyResultType> results = futures.stream()
    .map(future -> uncheckedSupplier(future::get).get())
    .collect(Collectors.toList());

Just revisiting my old post and noticing that you had another grief:

But the problem here is if, for example, the 4th future throws an exception, then I will wait unnecessarily for the first 3 futures to be available.

In this case, the simple solution is to do this in parallel:

futures.stream().parallel()
 .forEach(future -> uncheckedSupplier(future::get).get());

This way the first exception, although it will not stop the future, will break the forEach-statement, like in the serial example, but since all wait in parallel, you won't have to wait for the first 3 to complete.

/usr/bin/codesign failed with exit code 1

One thing that you'll want to watch out for (it's a stupid mistake on my part, but it happens), is that the email address attached to the CSR needs to be the same as the email connected to your Apple Dev account. Once I used a new CSR and rebuilt all the certs and provisioning profiles, all was well in applesville.

Convert month name to month number in SQL Server

select  Convert(datetime, '01 ' +  Replace('OCT-12', '-', ' '),6)

Access Control Origin Header error using Axios in React Web throwing error in Chrome

First of all, CORS is definitely a server-side problem and not client-side but I was more than sure that server code was correct in my case since other apps were working using the same server on different domains. The solution for this described in more details in other answers.

My problem started when I started using axios with my custom instance. In my case, it was a very specific problem when we use a baseURL in axios instance and then try to make GET or POST calls from anywhere, axios adds a slash / between baseURL and request URL. This makes sense too, but it was the hidden problem. My Laravel server was redirecting to remove the trailing slash which was causing this problem.

In general, the pre-flight OPTIONS request doesn't like redirects. If your server is redirecting with 301 status code, it might be cached at different levels. So, definitely check for that and avoid it.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

How to use underscore.js as a template engine?

I wanted to share one more important finding.

use of <%= variable => would result in cross-site scripting vulnerability. So its more safe to use <%- variable -> instead.

We had to replace <%= with <%- to prevent cross-site scripting attacks. Not sure, whether this will it have any impact on the performance

Convert RGB values to Integer

int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);

If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff

Additionaly

int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb)    &0x0ff;

No need for multipling.

Is there any advantage of using map over unordered_map in case of trivial keys?

I've made a test recently which makes 50000 merge&sort. That means if the string keys are the same, merge the byte string. And the final output should be sorted. So this includes a look up for every insertion.

For the map implementation, it takes 200 ms to finish the job. For the unordered_map + map, it takes 70 ms for unordered_map insertion and 80 ms for map insertion. So the hybrid implementation is 50 ms faster.

We should think twice before we use the map. If you only need the data to be sorted in the final result of your program, a hybrid solution may be better.

Select Last Row in the Table

You never mentioned whether you are using Eloquent, Laravel's default ORM or not. In case you are, let's say you want to get the latest entry of a User table, by created_at, you probably could do as follow:

User::orderBy('created_at', 'desc')->first();

First it orders users by created_at field, descendingly, and then it takes the first record of the result.

That will return you an instance of the User object, not a collection. Of course, to make use of this alternative, you got to have an User model, extending Eloquent class. This may sound a bit confusing, but it's really easy to get started and ORM can be really helpful.

For more information, check out the official documentation which is pretty rich and well detailed.

How can I view a git log of just one user's commits?

Although, there are many useful answers. Whereas, just to add another way to it. You can also use

git shortlog --author="<author name>" --format="%h %s"

It will show the output in the grouped manner:

<Author Name> (5):
  4da3975f dependencies upgraded
  49172445 runtime dependencies resolved
  bff3e127 user-service, kratos, and guava dependencies upgraded
  414b6f1e dropwizard :- service, rmq and db-sharding depedencies upgraded
  a96af8d3 older dependecies removed

Here, total of 5 commits are done by <Author Name> under the current branch. Whereas, you can also use --all to enforce the search everywhere (all the branches) in the git repository.

One catch: git internally tries to match an input <author name> with the name and email of the author in the git database. It is case-sensitive.

wget: unable to resolve host address `http'

The DNS server seems out of order. You can use another DNS server such as 8.8.8.8. Put nameserver 8.8.8.8 to the first line of /etc/resolv.conf.

How to execute an .SQL script file using c#

This works for me:

public void updatedatabase()
{

    SqlConnection conn = new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + txtdatabase.Text.Trim() + ";User ID=" + txtuserid.Text.Trim() + ";Password=" + txtpwd.Text.Trim() + "");
    try
    {

        conn.Open();

        string script = File.ReadAllText(Server.MapPath("~/Script/DatingDemo.sql"));

        // split script on GO command
        IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        foreach (string commandString in commandStrings)
        {
            if (commandString.Trim() != "")
            {
                new SqlCommand(commandString, conn).ExecuteNonQuery();
            }
        }
        lblmsg.Text = "Database updated successfully.";

    }
    catch (SqlException er)
    {
        lblmsg.Text = er.Message;
        lblmsg.ForeColor = Color.Red;
    }
    finally
    {
        conn.Close();
    }
}

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

Search All Fields In All Tables For A Specific Value (Oracle)

I modified Flood's script to execute once for each table rather than for every column of each table for faster execution. It requires Oracle 11g or greater.

    set serveroutput on size 100000

declare
    v_match_count integer;
    v_counter integer;

    -- The owner of the tables to search through (case-sensitive)
    v_owner varchar2(255) := 'OWNER_NAME';
    -- A string that is part of the data type(s) of the columns to search through (case-insensitive)
    v_data_type varchar2(255) := 'CHAR';
    -- The string to be searched for (case-insensitive)
    v_search_string varchar2(4000) := 'FIND_ME';

    -- Store the SQL to execute for each table in a CLOB to get around the 32767 byte max size for a VARCHAR2 in PL/SQL
    v_sql clob := '';
begin
    for cur_tables in (select owner, table_name from all_tables where owner = v_owner and table_name in 
                       (select table_name from all_tab_columns where owner = all_tables.owner and data_type like '%' ||  upper(v_data_type) || '%')
                       order by table_name) loop
        v_counter := 0;
        v_sql := '';

        for cur_columns in (select column_name from all_tab_columns where 
                            owner = v_owner and table_name = cur_tables.table_name and data_type like '%' || upper(v_data_type) || '%') loop
            if v_counter > 0 then
                v_sql := v_sql || ' or ';
            end if;
            v_sql := v_sql || 'upper(' || cur_columns.column_name || ') like ''%' || upper(v_search_string) || '%''';
            v_counter := v_counter + 1;
        end loop;

        v_sql := 'select count(*) from ' || cur_tables.table_name || ' where ' || v_sql;

        execute immediate v_sql
        into v_match_count;

        if v_match_count > 0 then
            dbms_output.put_line('Match in ' || cur_tables.owner || ': ' || cur_tables.table_name || ' - ' || v_match_count || ' records');
        end if;
    end loop;

    exception
        when others then
            dbms_output.put_line('Error when executing the following: ' || dbms_lob.substr(v_sql, 32600));
end;
/

How to install both Python 2.x and Python 3.x in Windows

Install the one you use most (3.3 in my case) over the top of the other. That'll force IDLE to use the one you want.

Alternatively (from the python3.3 README):

Installing multiple versions

On Unix and Mac systems if you intend to install multiple versions of Python using the same installation prefix (--prefix argument to the configure script) you must take care that your primary python executable is not overwritten by the installation of a different version. All files and directories installed using "make altinstall" contain the major and minor version and can thus live side-by-side. "make install" also creates ${prefix}/bin/python3 which refers to ${prefix}/bin/pythonX.Y. If you intend to install multiple versions using the same prefix you must decide which version (if any) is your "primary" version. Install that version using "make install". Install all other versions using "make altinstall".

For example, if you want to install Python 2.6, 2.7 and 3.3 with 2.7 being the primary version, you would execute "make install" in your 2.7 build directory and "make altinstall" in the others.

How to generate service reference with only physical wsdl file

This may be the easiest method

  • Right click on the project and select "Add Service Reference..."
  • In the Address: box, enter the physical path (C:\test\project....) of the downloaded/Modified wsdl.
  • Hit Go

Adding days to a date in Python

The previous answers are correct but it's generally a better practice to do:

import datetime

Then you'll have, using datetime.timedelta:

date_1 = datetime.datetime.strptime(start_date, "%m/%d/%y")

end_date = date_1 + datetime.timedelta(days=10)

'module' object is not callable - calling method in another file

The problem is in the import line. You are importing a module, not a class. Assuming your file is named other_file.py (unlike java, again, there is no such rule as "one class, one file"):

from other_file import findTheRange

if your file is named findTheRange too, following java's convenions, then you should write

from findTheRange import findTheRange

you can also import it just like you did with random:

import findTheRange
operator = findTheRange.findTheRange()

Some other comments:

a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)

b) You can build the list directly:

  randomList = [random.randint(0, 100) for i in range(5)]

c) You can call methods in the same way you do in java:

largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)

d) You can use built in function, and the huge python library:

largestInList = max(randomList)
smallestInList = min(randomList)

e) If you still want to use a class, and you don't need self, you can use @staticmethod:

class findTheRange():
    @staticmethod
    def findLargest(_list):
        #stuff...

C# DateTime to "YYYYMMDDHHMMSS" format

An easy Method, Full control over 'from type' and 'to type', and only need to remember this code for future castings

DateTime.ParseExact(InputDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd"));

JS search in object values

You can use the _filter method of lodash:

return _filter((item) => item.name.includes("fo"),tempObjectHolder);

Check if PHP session has already started

PHP 5.4 introduced session_status(), which is more reliable than relying on session_id().

Consider the following snippet:

session_id('test');
var_export(session_id() != ''); // true, but session is still not started!
var_export(session_status() == PHP_SESSION_ACTIVE); // false

So, to check whether a session is started, the recommended way in PHP 5.4 is now:

session_status() == PHP_SESSION_ACTIVE

How to export non-exportable private key from store

i wanted to mention Jailbreak specifically (GitHub):

Jailbreak

Jailbreak is a tool for exporting certificates marked as non-exportable from the Windows certificate store. This can help when you need to extract certificates for backup or testing. You must have full access to the private key on the filesystem in order for jailbreak to work.

Prerequisites: Win32

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

If you are extending from an AppCompatActivity and are trying to get the ActionBar from the Fragment, you can do this:

ActionBar mActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();

Javascript to stop HTML5 video playback on modal window close

The right answer is : $("#videoContainer")[0].pause();

ASP.NET MVC ActionLink and post method

I have done the same issue using following code:

@using (Html.BeginForm("Delete", "Admin"))
{
       @Html.Hidden("ProductID", item.ProductID)
       <input type="submit" value="Delete" />
}

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

Lea's converter is no longer available. I just used this converter

Steps:

  1. Enter the Unicode decimal version such as 8226 in the tool's green input field.
  2. Press Dec code points
  3. See the result in the box Unicode U+hex notation (eg U+2022)
  4. Use it in your CSS. Eg content: '\2022'

ps. I have no connection with the web site.

How to fix Invalid AES key length?

Things to know in general:

  1. Key != Password
    • SecretKeySpec expects a key, not a password. See below
  2. It might be due to a policy restriction that prevents using 32 byte keys. See other answer on that

In your case

The problem is number 1: you are passing the password instead of the key.

AES only supports key sizes of 16, 24 or 32 bytes. You either need to provide exactly that amount or you derive the key from what you type in.

There are different ways to derive the key from a passphrase. Java provides a PBKDF2 implementation for such a purpose.

I used erickson's answer to paint a complete picture (only encryption, since the decryption is similar, but includes splitting the ciphertext):

SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);

KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 256); // AES-256
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] key = f.generateSecret(spec).getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

byte[] ivBytes = new byte[16];
random.nextBytes(ivBytes);
IvParameterSpec iv = new IvParameterSpec(ivBytes);

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encValue = c.doFinal(valueToEnc.getBytes());

byte[] finalCiphertext = new byte[encValue.length+2*16];
System.arraycopy(ivBytes, 0, finalCiphertext, 0, 16);
System.arraycopy(salt, 0, finalCiphertext, 16, 16);
System.arraycopy(encValue, 0, finalCiphertext, 32, encValue.length);

return finalCiphertext;

Other things to keep in mind:

  • Always use a fully qualified Cipher name. AES is not appropriate in such a case, because different JVMs/JCE providers may use different defaults for mode of operation and padding. Use AES/CBC/PKCS5Padding. Don't use ECB mode, because it is not semantically secure.
  • If you don't use ECB mode then you need to send the IV along with the ciphertext. This is usually done by prefixing the IV to the ciphertext byte array. The IV is automatically created for you and you can get it through cipherInstance.getIV().
  • Whenever you send something, you need to be sure that it wasn't altered along the way. It is hard to implement a encryption with MAC correctly. I recommend you to use an authenticated mode like CCM or GCM.

How can I set the initial value of Select2 when using AJAX?

One scenario that I haven't seen people really answer, is how to have a preselection when the options are AJAX sourced, and you can select multiple. Since this is the go-to page for AJAX preselection, I'll add my solution here.

$('#mySelect').select2({
    ajax: {
        url: endpoint,
        dataType: 'json',
        data: [
            { // Each of these gets processed by fnRenderResults.
                id: usersId,
                text: usersFullName,
                full_name: usersFullName,
                email: usersEmail,
                image_url: usersImageUrl,
                selected: true // Causes the selection to actually get selected.
            }
        ],
        processResults: function(data) {

            return {
                results: data.users,
                pagination: {
                    more: data.next !== null
                }
            };

        }
    },
    templateResult: fnRenderResults,
    templateSelection: fnRenderSelection, // Renders the result with my own style
    selectOnClose: true
}); 

"relocation R_X86_64_32S against " linking Error

Relocation R_X86_64_PC32 against undefined symbol , usually happens when LDFLAGS are set with hardening and CFLAGS not .
Maybe just user error:
If you are using -specs=/usr/lib/rpm/redhat/redhat-hardened-ld at link time, you also need to use -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 at compile time, and as you are compiling and linking at the same time, you need either both, or drop the -specs=/usr/lib/rpm/redhat/redhat-hardened-ld . Common fixes :
https://bugzilla.redhat.com/show_bug.cgi?id=1304277#c3
https://github.com/rpmfusion/lxdream/blob/master/lxdream-0.9.1-implicit.patch

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
    ]
  }

}

Can't bind to 'routerLink' since it isn't a known property

In my case I just need to import my newly created component to RouterModule

{path: 'newPath', component: newComponent}

Then in your app.module import the router and configure the routes:

import { RouterModule } from '@angular/router';

imports: [
        RouterModule.forRoot([
            {path: '', component: DashboardComponent},
            {path: 'dashboard', component: DashboardComponent},
            {path: 'newPath', component: newComponent}
        ])
    ],

Hope this helps to some one !!!

What does from __future__ import absolute_import actually do?

The changelog is sloppily worded. from __future__ import absolute_import does not care about whether something is part of the standard library, and import string will not always give you the standard-library module with absolute imports on.

from __future__ import absolute_import means that if you import string, Python will always look for a top-level string module, rather than current_package.string. However, it does not affect the logic Python uses to decide what file is the string module. When you do

python pkg/script.py

pkg/script.py doesn't look like part of a package to Python. Following the normal procedures, the pkg directory is added to the path, and all .py files in the pkg directory look like top-level modules. import string finds pkg/string.py not because it's doing a relative import, but because pkg/string.py appears to be the top-level module string. The fact that this isn't the standard-library string module doesn't come up.

To run the file as part of the pkg package, you could do

python -m pkg.script

In this case, the pkg directory will not be added to the path. However, the current directory will be added to the path.

You can also add some boilerplate to pkg/script.py to make Python treat it as part of the pkg package even when run as a file:

if __name__ == '__main__' and __package__ is None:
    __package__ = 'pkg'

However, this won't affect sys.path. You'll need some additional handling to remove the pkg directory from the path, and if pkg's parent directory isn't on the path, you'll need to stick that on the path too.

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

How to grep and replace

Be very careful when using find and sed in a git repo! If you don't exclude the binary files you can end up with this error:

error: bad index file sha1 signature 
fatal: index file corrupt

To solve this error you need to revert the sed by replacing your new_string with your old_string. This will revert your replaced strings, so you will be back to the beginning of the problem.

The correct way to search for a string and replace it is to skip find and use grep instead in order to ignore the binary files:

sed -ri -e "s/old_string/new_string/g" $(grep -Elr --binary-files=without-match "old_string" "/files_dir")

Credits for @hobs

Create text file and fill it using bash

Assuming you mean UNIX shell commands, just run

echo >> file.txt

echo prints a newline, and the >> tells the shell to append that newline to the file, creating if it doesn't already exist.

In order to properly answer the question, though, I'd need to know what you would want to happen if the file already does exist. If you wanted to replace its current contents with the newline, for example, you would use

echo > file.txt

EDIT: and in response to Justin's comment, if you want to add the newline only if the file didn't already exist, you can do

test -e file.txt || echo > file.txt

At least that works in Bash, I'm not sure if it also does in other shells.

How to escape the % (percent) sign in C's printf?

As others have said, %% will escape the %.

Note, however, that you should never do this:

char c[100];
char *c2;
...
printf(c); /* OR */
printf(c2);

Whenever you have to print a string, always, always, always print it using

printf("%s", c)

to prevent an embedded % from causing problems [memory violations, segfault, etc]

How to get time difference in minutes in PHP

function date_getFullTimeDifference( $start, $end )
{
$uts['start']      =    strtotime( $start );
        $uts['end']        =    strtotime( $end );
        if( $uts['start']!==-1 && $uts['end']!==-1 )
        {
            if( $uts['end'] >= $uts['start'] )
            {
                $diff    =    $uts['end'] - $uts['start'];
                if( $years=intval((floor($diff/31104000))) )
                    $diff = $diff % 31104000;
                if( $months=intval((floor($diff/2592000))) )
                    $diff = $diff % 2592000;
                if( $days=intval((floor($diff/86400))) )
                    $diff = $diff % 86400;
                if( $hours=intval((floor($diff/3600))) )
                    $diff = $diff % 3600;
                if( $minutes=intval((floor($diff/60))) )
                    $diff = $diff % 60;
                $diff    =    intval( $diff );
                return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
            }
            else
            {
                echo "Ending date/time is earlier than the start date/time";
            }
        }
        else
        {
            echo "Invalid date/time data detected";
        }
}

How to improve performance of ngRepeat over a huge dataset (angular.js)?

You can use "track by" to increase the performance:

<div ng-repeat="a in arr track by a.trackingKey">

Faster than:

<div ng-repeat="a in arr">

ref:https://www.airpair.com/angularjs/posts/angularjs-performance-large-applications

sql server Get the FULL month name from a date

Most answers are a bit more complicated than necessary, or don't provide the exact format requested.

select Format(getdate(), 'MMMM dd yyyy') --returns 'October 01 2020', note the leading zero
select Format(getdate(), 'MMMM d yyyy') --returns the desired format with out the leading zero: 'October 1 2020'

If you want a comma, as you normally would, use:

select Format(getdate(), 'MMMM d, yyyy') --returns 'October 1, 2020'

Note: even though there is only one 'd' for the day, it will become a 2 digit day when needed.

How to find out if an installed Eclipse is 32 or 64 bit version?

Help -> About Eclipse -> Installation Details -> tab Configuration

Look for -arch, and below it you'll see either x86_64 (meaning 64bit) or x86 (meaning 32bit).

Smooth scroll to specific div on click

You can use basic css to achieve smooth scroll

html {
  scroll-behavior: smooth;
}

Change directory command in Docker?

I was wondering if two times WORKDIR will work or not, but it worked :)

FROM ubuntu:18.04

RUN apt-get update && \
    apt-get install -y python3.6

WORKDIR /usr/src

COPY ./ ./

WORKDIR /usr/src/src

CMD ["python3", "app.py"]

case statement in where clause - SQL Server

simply do the select:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

How to add row in JTable?

For the sake of completeness, first make sure you have the correct import so you can use the addRow function:

import javax.swing.table.*;

Assuming your jTable is already created, you can proceed and create your own add row method which will accept the parameters that you need:

public void yourAddRow(String str1, String str2, String str3){
  DefaultTableModel yourModel = (DefaultTableModel) yourJTable.getModel();
  yourModel.addRow(new Object[]{str1, str2, str3});
}

How to write macro for Notepad++?

This post can help you as a little bit related :

Using RegEX To Prefix And Append In Notepad++

Assuming alphanumeric words, you can use:

Search = ^([A-Za-z0-9]+)$ Replace = able:"\1"

Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):

Search = ^(.+)$

^ points to the start of the line. $ points to the end of the line.

\1 will be the source match within the parentheses.

array.select() in javascript

Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.

The source code for Array.prototype is posted in MDN

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */)
  {
    "use strict";

    if (this == null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details

How do I wrap text in a span?

Try putting your text in another div inside your span:

i.e.

<span><div>some text</div></span>

Select distinct values from a table field

In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by() on distinct("field_name") queries. This is, however, a Postgres only feature!

If you are using Postgres and if you define a field name that the query should be distinct for, then order_by() needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).

Note

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.

For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.

If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:

# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')  

Recommended date format for REST GET API

Every datetime field in input/output needs to be in UNIX/epoch format. This avoids the confusion between developers across different sides of the API.

Pros:

  • Epoch format does not have a timezone.
  • Epoch has a single format (Unix time is a single signed number).
  • Epoch time is not effected by daylight saving.
  • Most of the Backend frameworks and all native ios/android APIs support epoch conversion.
  • Local time conversion part can be done entirely in application side depends on the timezone setting of user's device/browser.

Cons:

  • Extra processing for converting to UTC for storing in UTC format in the database.
  • Readability of input/output.
  • Readability of GET URLs.

Notes:

  • Timezones are a presentation-layer problem! Most of your code shouldn't be dealing with timezones or local time, it should be passing Unix time around.
  • If you want to store a humanly-readable time (e.g. logs), consider storing it along with Unix time, not instead of Unix time.

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

How to elegantly check if a number is within a range?

If it's to validate method parameters, none of the solutions throw ArgumentOutOfRangeException and allow easy/proper configuration of inclusive/exclusive min/max values.

Use like this

public void Start(int pos)
{
    pos.CheckRange(nameof(pos), min: 0);

    if (pos.IsInRange(max: 100, maxInclusive: false))
    {
        // ...
    }
}

I just wrote these beautiful functions. It also has the advantage of having no branching (a single if) for valid values. The hardest part is to craft the proper exception messages.

/// <summary>
/// Returns whether specified value is in valid range.
/// </summary>
/// <typeparam name="T">The type of data to validate.</typeparam>
/// <param name="value">The value to validate.</param>
/// <param name="min">The minimum valid value.</param>
/// <param name="minInclusive">Whether the minimum value is valid.</param>
/// <param name="max">The maximum valid value.</param>
/// <param name="maxInclusive">Whether the maximum value is valid.</param>
/// <returns>Whether the value is within range.</returns>
public static bool IsInRange<T>(this T value, T? min = null, bool minInclusive = true, T? max = null, bool maxInclusive = true)
    where T : struct, IComparable<T>
{
    var minValid = min == null || (minInclusive && value.CompareTo(min.Value) >= 0) || (!minInclusive && value.CompareTo(min.Value) > 0);
    var maxValid = max == null || (maxInclusive && value.CompareTo(max.Value) <= 0) || (!maxInclusive && value.CompareTo(max.Value) < 0);
    return minValid && maxValid;
}

/// <summary>
/// Validates whether specified value is in valid range, and throws an exception if out of range.
/// </summary>
/// <typeparam name="T">The type of data to validate.</typeparam>
/// <param name="value">The value to validate.</param>
/// <param name="name">The name of the parameter.</param>
/// <param name="min">The minimum valid value.</param>
/// <param name="minInclusive">Whether the minimum value is valid.</param>
/// <param name="max">The maximum valid value.</param>
/// <param name="maxInclusive">Whether the maximum value is valid.</param>
/// <returns>The value if valid.</returns>
public static T CheckRange<T>(this T value, string name, T? min = null, bool minInclusive = true, T? max = null, bool maxInclusive = true)
where T : struct, IComparable<T>
{
    if (!value.IsInRange(min, minInclusive, max, maxInclusive))
    {
        if (min.HasValue && minInclusive && max.HasValue && maxInclusive)
        {
            var message = "{0} must be between {1} and {2}.";
            throw new ArgumentOutOfRangeException(name, value, message.FormatInvariant(name, min, max));
        }
        else
        {
            var messageMin = min.HasValue ? GetOpText(true, minInclusive).FormatInvariant(min) : null;
            var messageMax = max.HasValue ? GetOpText(false, maxInclusive).FormatInvariant(max) : null;
            var message = (messageMin != null && messageMax != null) ?
                "{0} must be {1} and {2}." :
                "{0} must be {1}.";
            throw new ArgumentOutOfRangeException(name, value, message.FormatInvariant(name, messageMin ?? messageMax, messageMax));
        }
    }
    return value;
}

private static string GetOpText(bool greaterThan, bool inclusive)
{
    return (greaterThan && inclusive) ? "greater than or equal to {0}" :
        greaterThan ? "greater than {0}" :
        inclusive ? "less than or equal to {0}" :
        "less than {0}";
}

public static string FormatInvariant(this string format, params object?[] args) => string.Format(CultureInfo.InvariantCulture, format, args);

How do I delete from multiple tables using INNER JOIN in SQL server

Basically, no you have to make three delete statements in a transaction, children first and then parents. Setting up cascading deletes is a good idea if this is not a one-off thing and its existence won't conflict with any existing trigger setup.