Programs & Examples On #Preforking

How to create a scrollable Div Tag Vertically?

This code creates a nice vertical scrollbar for me in Firefox and Chrome:

_x000D_
_x000D_
#answerform {
  position: absolute;
  border: 5px solid gray;
  padding: 5px;
  background: white;
  width: 300px;
  height: 400px;
  overflow-y: scroll;
}
_x000D_
<div id='answerform'>
  badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
  <br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
_x000D_
_x000D_

Here is a JS fiddle demo proving the above works.

Eclipse error "ADB server didn't ACK, failed to start daemon"

The best and the most efficient way without restarting any device or software is:

Run the following:

adt-bundle-windows-x86_64\sdk\platform-tools\adb.exe

And one more thing.. ADB is a self-dependent thing. You cannot do anything until unless it wants itself to work. There is one more way which I found out: Leave the device connected for 5-6 minutes and wait. Soon the device gets connected and tries to launch.

How to find NSDocumentDirectory in Swift?

For everyone who looks example that works with Swift 2.2, Abizern code with modern do try catch handle of error

func databaseURL() -> NSURL? {

    let fileManager = NSFileManager.defaultManager()

    let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

    if let documentDirectory:NSURL = urls.first { // No use of as? NSURL because let urls returns array of NSURL
        // This is where the database should be in the documents directory
        let finalDatabaseURL = documentDirectory.URLByAppendingPathComponent("OurFile.plist")

        if finalDatabaseURL.checkResourceIsReachableAndReturnError(nil) {
            // The file already exists, so just return the URL
            return finalDatabaseURL
        } else {
            // Copy the initial file from the application bundle to the documents directory
            if let bundleURL = NSBundle.mainBundle().URLForResource("OurFile", withExtension: "plist") {

                do {
                    try fileManager.copyItemAtURL(bundleURL, toURL: finalDatabaseURL)
                } catch let error as NSError  {// Handle the error
                    print("Couldn't copy file to final location! Error:\(error.localisedDescription)")
                }

            } else {
                print("Couldn't find initial database in the bundle!")
            }
        }
    } else {
        print("Couldn't get documents directory!")
    }

    return nil
}

Update I've missed that new swift 2.0 have guard(Ruby unless analog), so with guard it is much shorter and more readable

func databaseURL() -> NSURL? {

let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

// If array of path is empty the document folder not found
guard urls.count != 0 else {
    return nil
}

let finalDatabaseURL = urls.first!.URLByAppendingPathComponent("OurFile.plist")
// Check if file reachable, and if reacheble just return path
guard finalDatabaseURL.checkResourceIsReachableAndReturnError(nil) else {
    // Check if file is exists in bundle folder
    if let bundleURL = NSBundle.mainBundle().URLForResource("OurFile", withExtension: "plist") {
        // if exist we will copy it
        do {
            try fileManager.copyItemAtURL(bundleURL, toURL: finalDatabaseURL)
        } catch let error as NSError { // Handle the error
            print("File copy failed! Error:\(error.localizedDescription)")
        }
    } else {
        print("Our file not exist in bundle folder")
        return nil
    }
    return finalDatabaseURL
}
return finalDatabaseURL 
}

How to use CURL via a proxy?

root@APPLICATIOSERVER:/var/www/html# php connectiontest.php
61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#

Post declaring the proxy settings in the php script file issue has been fixed.

$proxy = '10.172.123.1:80';
curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port

Switching to landscape mode in Android Emulator

Just use 9 in numeric keyboard with num-lock off.

Image showing the numpad with 9 highlighted

7 rotates in the opposite direction.

Disabling Chrome Autofill

I've just found that if you have a remembered username and password for a site, the current version of Chrome will autofill your username/email address into the field before any type=password field. It does not care what the field is called - just assumes the field before password is going to be your username.

Old Solution

Just use <form autocomplete="off"> and it prevents the password prefilling as well as any kind of heuristic filling of fields based on assumptions a browser may make (which are often wrong). As opposed to using <input autocomplete="off"> which seems to be pretty much ignored by the password autofill (in Chrome that is, Firefox does obey it).

Updated Solution

Chrome now ignores <form autocomplete="off">. Therefore my original workaround (which I had deleted) is now all the rage.

Simply create a couple of fields and make them hidden with "display:none". Example:

<!-- fake fields are a workaround for chrome autofill getting the wrong fields -->
<input style="display: none" type="text" name="fakeusernameremembered" />
<input style="display: none" type="password" name="fakepasswordremembered" />

Then put your real fields underneath.

Remember to add the comment or other people on your team will wonder what you are doing!

Update March 2016

Just tested with latest Chrome - all good. This is a fairly old answer now but I want to just mention that our team has been using it for years now on dozens of projects. It still works great despite a few comments below. There are no problems with accessibility because the fields are display:none meaning they don't get focus. As I mentioned you need to put them before your real fields.

If you are using javascript to modify your form, there is an extra trick you will need. Show the fake fields while you are manipulating the form and then hide them again a millisecond later.

Example code using jQuery (assuming you give your fake fields a class):

$(".fake-autofill-fields").show();
// some DOM manipulation/ajax here
window.setTimeout(function () {
  $(".fake-autofill-fields").hide();
}, 1);

Update July 2018

My solution no longer works so well since Chrome's anti-usability experts have been hard at work. But they've thrown us a bone in the form of:

<input type="password" name="whatever" autocomplete="new-password" />

This works and mostly solves the problem.

However, it does not work when you don't have a password field but only an email address. That can also be difficult to get it to stop going yellow and prefilling. The fake fields solution can be used to fix this.

In fact you sometimes need to drop in two lots of fake fields, and try them in different places. For example, I already had fake fields at the beginning of my form, but Chrome recently started prefilling my 'Email' field again - so then I doubled down and put in more fake fields just before the 'Email' field, and that fixed it. Removing either the first or second lot of the fields reverts to incorrect overzealous autofill.

Update Mar 2020

It is not clear if and when this solution still works. It appears to still work sometimes but not all the time.

In the comments below you will find a few hints. One just added by @anilyeni may be worth some more investigation:

As I noticed, autocomplete="off" works on Chrome 80, IF there is less than 3 elements in <form>. I don't know what is the logic or where the related documentation about it.

Also this one from @dubrox may be relevant, although I have not tested it:

thanks a lot for the trick, but please update the answer, as display:none; doesn't work anymore, but position: fixed;top:-100px;left:-100px; width:5px; does :)

Update APRIL 2020

Special value for chrome for this attribute is doing the job: (tested on input - but not by me) autocomplete="chrome-off"

Difference between static memory allocation and dynamic memory allocation

Difference between STATIC MEMORY ALLOCATION & DYNAMIC MEMORY ALLOCATION

Memory is allocated before the execution of the program begins (During Compilation).
Memory is allocated during the execution of the program.

No memory allocation or deallocation actions are performed during Execution.
Memory Bindings are established and destroyed during the Execution.

Variables remain permanently allocated.
Allocated only when program unit is active.

Implemented using stacks and heaps.
Implemented using data segments.

Pointer is needed to accessing variables.
No need of Dynamically allocated pointers.

Faster execution than Dynamic.
Slower execution than static.

More memory Space required.
Less Memory space required.

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

"The system cannot find the file specified"

The most common reason could be the database connection string. You have to change the connection string attachDBFile=|DataDirectory|file_name.mdf. there might be problem in host name which would be (local),localhost or .\sqlexpress.

Use space as a delimiter with cut command

I have an answer (I admit somewhat confusing answer) that involvessed, regular expressions and capture groups:

  • \S* - first word
  • \s* - delimiter
  • (\S*) - second word - captured
  • .* - rest of the line

As a sed expression, the capture group needs to be escaped, i.e. \( and \).

The \1 returns a copy of the captured group, i.e. the second word.

$ echo "alpha beta gamma delta" | sed 's/\S*\s*\(\S*\).*/\1/'
beta

When you look at this answer, its somewhat confusing, and, you may think, why bother? Well, I'm hoping that some, may go "Aha!" and will use this pattern to solve some complex text extraction problems with a single sed expression.

Deep cloning objects

As nearly all of the answers to this question have been unsatisfactory or plainly don't work in my situation, I have authored AnyClone which is entirely implemented with reflection and solved all of the needs here. I was unable to get serialization to work in a complicated scenario with complex structure, and IClonable is less than ideal - in fact it shouldn't even be necessary.

Standard ignore attributes are supported using [IgnoreDataMember], [NonSerialized]. Supports complex collections, properties without setters, readonly fields etc.

I hope it helps someone else out there who ran into the same problems I did.

what is the difference between XSD and WSDL

XSD is schema for WSDL file. XSD contain datatypes for WSDL. Element declared in XSD is valid to use in WSDL file. We can Check WSDL against XSD to check out web service WSDL is valid or not.

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

First override equals() method:

@Override
public boolean equals(Object obj)
{
    if(obj == null) return false;
    else if(obj instanceof MyObject && getTitle() == obj.getTitle() && getAuthor() == obj.getAuthor() && getURL() == obj.getURL() && getDescription() == obj.getDescription()) return true;
    else return false;
}

and then use:

List<MyObject> list = new ArrayList<MyObject>;
for(MyObject obj1 : list)
{
    for(MyObject obj2 : list)
    {
        if(obj1.equals(obj2)) list.remove(obj1); // or list.remove(obj2);
    }
}

How do I find the value of $CATALINA_HOME?

Just as a addition. You can find the Catalina Paths in

->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS

In the VM Arguments the Paths are listed and changeable

How to tell PowerShell to wait for each command to end before starting the next?

Just use "Wait-process" :

"notepad","calc","wmplayer" | ForEach-Object {Start-Process $_} | Wait-Process ;dir

job is done

How can I use JQuery to post JSON data?

Base on lonesomeday's answer, I create a jpost that wraps certain parameters.

$.extend({
    jpost: function(url, body) {
        return $.ajax({
            type: 'POST',
            url: url,
            data: JSON.stringify(body),
            contentType: "application/json",
            dataType: 'json'
        });
    }
});

Usage:

$.jpost('/form/', { name: 'Jonh' }).then(res => {
    console.log(res);
});

Insert Data Into Tables Linked by Foreign Key

Use stored procedures.

And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".

Error in Process.Start() -- The system cannot find the file specified

Try to replace your initialization code with:

ProcessStartInfo info 
    = new ProcessStartInfo(@"C:\Program Files\Internet Explorer\iexplore.exe");

Using non full filepath on Process.Start only works if the file is found in System32 folder.

How to convert binary string value to decimal

public static Long binToDec(String bin) {
long dec = 0L;
    long pow = 1L;
    for (int i = (bin.length() - 1); i >= 0; i--) {
        char c = bin.charAt(i);
        dec = dec + (Long.parseLong(c + "") * pow);
        pow = pow * 2;
    }
    return dec;
}

or

long num = Long.parseLong("101110111",2);

How to display my application's errors in JSF?

Simple answer, if you don't need to bind it to a specific component...

Java:

            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Authentication failed", null);
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, message);      

XHTML:

            <h:messages></h:messages>

How to open/run .jar file (double-click not working)?

Use cmd prompt and type

java -jar exapmple.jar

To run your jar file.

for more information refer to this link it describes how to properly open the jar file. https://superuser.com/questions/745112/how-do-i-run-a-jar-file-without-installing-java

"Auth Failed" error with EGit and GitHub

After spending hours looking for the solution to this problem, I finally struck gold by making the changes mentioned on an Eclipse Forum.

Steps:

Prerequisites: mysysgit is installed with default configuration.

1.Create the file C:/Users/Username/.ssh/config (Replace "Username" with your Windows 7 user name. (e.g. C:/Users/John/.ssh/config)) and put this in it:

Host github.com
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa

2.Try setting up the remote repository now in Eclipse.

Cheers. It should work perfectly.

Ubuntu says "bash: ./program Permission denied"

Sounds like you don't have the execute flag set on the file permissions, try:

chmod u+x program_name

To switch from vertical split to horizontal split fast in Vim

When you have two or more windows open horizontally or vertically and want to switch them all to the other orientation, you can use the following:

(switch to horizontal)

:windo wincmd K

(switch to vertical)

:windo wincmd H

It's effectively going to each window individually and using ^WK or ^WH.

Is HTML considered a programming language?

List it under technologies or something. I'd just leave it off if I were you as it's pretty much expected that you know HTML and XML at this point.

Calling one Bash script from another Script passing it arguments with quotes and spaces

I found following program works for me

test1.sh 
a=xxx
test2.sh $a

in test2.sh you use $1 to refer variable a in test1.sh

echo $1

The output would be xxx

Android charting libraries

  • Achartengine: I have used this. Although for real time graph this might not give good performance if you do not tweak properly.

Draw text in OpenGL ES

I've written a tutorial that expands on the answer posted by JVitela. Basically, it uses the same idea, but instead of rendering each string to a texture, it renders all characters from a font file to a texture and uses that to allow for full dynamic text rendering with no further slowdowns (once the initialization is complete).

The main advantage of my method, compared to the various font atlas generators, is that you can ship small font files (.ttf .otf) with your project instead of having to ship large bitmaps for every font variation and size. It can generate perfect quality fonts at any resolution using only a font file :)

The tutorial includes full code that can be used in any project :)

How to add a local repo and treat it as a remote repo

It appears that your format is incorrect:

If you want to share a locally created repository, or you want to take contributions from someone elses repository - if you want to interact in any way with a new repository, it's generally easiest to add it as a remote. You do that by running git remote add [alias] [url]. That adds [url] under a local remote named [alias].

#example
$ git remote
$ git remote add github [email protected]:schacon/hw.git
$ git remote -v

http://gitref.org/remotes/#remote

Copy array by value

When we want to copy an array using the assignment operator ( = ) it doesn't create a copy it merely copies the pointer/reference to the array. For example:

_x000D_
_x000D_
const oldArr = [1,2,3];_x000D_
_x000D_
const newArr = oldArr;  // now oldArr points to the same place in memory _x000D_
_x000D_
console.log(oldArr === newArr);  // Points to the same place in memory thus is true_x000D_
_x000D_
const copy = [1,2,3];_x000D_
_x000D_
console.log(copy === newArr);  // Doesn't point to the same place in memory and thus is false
_x000D_
_x000D_
_x000D_

Often when we transform data we want to keep our initial datastructure (e.g. Array) intact. We do this by making a exact copy of our array so this one can be transformed while the initial one stays intact.

Ways of copying an array:

_x000D_
_x000D_
const oldArr = [1,2,3];_x000D_
_x000D_
// Uses the spread operator to spread out old values into the new array literal_x000D_
const newArr1 = [...oldArr];_x000D_
_x000D_
// Slice with no arguments returns the newly copied Array_x000D_
const newArr2 = oldArr.slice();_x000D_
_x000D_
// Map applies the callback to every element in the array and returns a new array_x000D_
const newArr3 = oldArr.map((el) => el);_x000D_
_x000D_
// Concat is used to merge arrays and returns a new array. Concat with no args copies an array_x000D_
const newArr4 = oldArr.concat();_x000D_
_x000D_
// Object.assign can be used to transfer all the properties into a new array literal_x000D_
const newArr5 = Object.assign([], oldArr);_x000D_
_x000D_
// Creating via the Array constructor using the new keyword_x000D_
const newArr6 = new Array(...oldArr);_x000D_
_x000D_
// For loop_x000D_
function clone(base) {_x000D_
 const newArray = [];_x000D_
    for(let i= 0; i < base.length; i++) {_x000D_
     newArray[i] = base[i];_x000D_
 }_x000D_
 return newArray;_x000D_
}_x000D_
_x000D_
const newArr7 = clone(oldArr);_x000D_
_x000D_
console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);
_x000D_
_x000D_
_x000D_

Be careful when arrays or objects are nested!:

When arrays are nested the values are copied by reference. Here is an example of how this could lead to issues:

_x000D_
_x000D_
let arr1 = [1,2,[1,2,3]]_x000D_
_x000D_
let arr2 = [...arr1];_x000D_
_x000D_
arr2[2][0] = 5;  // we change arr2_x000D_
_x000D_
console.log(arr1);  // arr1 is also changed because the array inside arr1 was copied by reference
_x000D_
_x000D_
_x000D_

So don't use these methods when there are objects or arrays inside your array you want to copy. i.e. Use these methods on arrays of primitives only.

If you do want to deepclone a javascript array use JSON.parse in conjunction with JSON.stringify, like this:

_x000D_
_x000D_
let arr1 = [1,2,[1,2,3]]_x000D_
_x000D_
let arr2 = JSON.parse(JSON.stringify(arr1)) ;_x000D_
_x000D_
arr2[2][0] = 5;_x000D_
_x000D_
console.log(arr1);  // now I'm not modified because I'm a deep clone
_x000D_
_x000D_
_x000D_

Performance of copying:

So which one do we choose for optimal performance. It turns out that the most verbose method, the for loop has the highest performance. Use the for loop for really CPU intensive copying (large/many arrays).

After that the .slice() method also has decent performance and is also less verbose and easier for the programmer to implement. I suggest to use .slice() for your everyday copying of arrays which aren't very CPU intensive. Also avoid using the JSON.parse(JSON.stringify(arr)) (lots of overhead) if no deep clone is required and performance is an issue.

Source performance test

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

This provides an alternative solution if the issue relates to you. If your disk drive is full than the MYSQL server (and most other programmes) is unable to start. Delete files and folders to allow Mysql-server to start up.

JSON encode MySQL results

Code:

$rows = array();

while($r = mysqli_fetch_array($result,MYSQL_ASSOC)) {

 $row_array['result'] = $r;

  array_push($rows,$row_array); // here we push every iteration to an array otherwise you will get only last iteration value
}

echo json_encode($rows);

SQL Data Reader - handling Null column values

Here is helper class which others can use if they need based on @marc_s answer:

public static class SQLDataReaderExtensions
    {
        public static int SafeGetInt(this SqlDataReader dataReader, string fieldName)
        {
            int fieldIndex = dataReader.GetOrdinal(fieldName);
            return dataReader.IsDBNull(fieldIndex) ? 0 : dataReader.GetInt32(fieldIndex);
        }

        public static int? SafeGetNullableInt(this SqlDataReader dataReader, string fieldName)
        {
            int fieldIndex = dataReader.GetOrdinal(fieldName);
            return dataReader.GetValue(fieldIndex) as int?;
        }

        public static string SafeGetString(this SqlDataReader dataReader, string fieldName)
        {
            int fieldIndex = dataReader.GetOrdinal(fieldName);
            return dataReader.IsDBNull(fieldIndex) ? string.Empty : dataReader.GetString(fieldIndex);
        }

        public static DateTime? SafeGetNullableDateTime(this SqlDataReader dataReader, string fieldName)
        {
            int fieldIndex = dataReader.GetOrdinal(fieldName);
            return dataReader.GetValue(fieldIndex) as DateTime?;
        }

        public static bool SafeGetBoolean(this SqlDataReader dataReader, string fieldName)
        {
            return SafeGetBoolean(dataReader, fieldName, false);
        }

        public static bool SafeGetBoolean(this SqlDataReader dataReader, string fieldName, bool defaultValue)
        {
            int fieldIndex = dataReader.GetOrdinal(fieldName);
            return dataReader.IsDBNull(fieldIndex) ? defaultValue : dataReader.GetBoolean(fieldIndex);
        }
    }

Regular Expression Match to test for a valid year

I use this regex in Java ^(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|[2-9][0-9])[0-9]{2}$

Works from 1900 to 9999

create unique id with javascript

function generateId() {
       
return Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36);
       
    
}

console.log(generateId())

How can I open a URL in Android's web browser from my application?

Within in your try block,paste the following code,Android Intent uses directly the link within the URI(Uniform Resource Identifier) braces in order to identify the location of your link.

You can try this:

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

Might be a slightly different cause, but that second issue occurs for me in scala 2.9.0.1 on Win7 (x64), though scala-2.9.1.final has already resolved this issue mentioned here:

\Java\jdk1.6.0_25\bin\java.exe was unexpected at this time.

My %JAVA_HOME% set to a path like this: c:\program files(x86)\Java\jdk...

Note the space and the parentheses.

If you change line 24 in %SCALA_HOME%\bin\scala.bat from:

if exist "%JAVA_HOME%\bin\java.exe" set _JAVACMD=%JAVA_HOME%\bin\java.exe

to

if exist "%JAVA_HOME%\bin\java.exe" set "_JAVACMD=%JAVA_HOME%\bin\java.exe"

It works fine. Note the quotes around the set command parameters, this will properly enclose any spaces and 'special' characters (eg: spaces and parentheses) in the variable's value.

Hope this helps someone else searching for an answer.

How to make an empty div take space

  works but that is not right way I think the w min-height: 1px;

How do you check for permissions to write to a directory or file?

None of these worked for me.. they return as true, even when they aren't. The problem is, you have to test the available permission against the current process user rights, this tests for file creation rights, just change the FileSystemRights clause to 'Write' to test write access..

/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full directory path</param>
/// <returns>State [bool]</returns>
public static bool DirectoryCanCreate(string DirectoryPath)
{
    if (string.IsNullOrEmpty(DirectoryPath)) return false;

    try
    {
        AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
        WindowsIdentity identity = WindowsIdentity.GetCurrent();

        foreach (FileSystemAccessRule rule in rules)
        {
            if (identity.Groups.Contains(rule.IdentityReference))
            {
                if ((FileSystemRights.CreateFiles & rule.FileSystemRights) == FileSystemRights.CreateFiles)
                {
                    if (rule.AccessControlType == AccessControlType.Allow)
                        return true;
                }
            }
        }
    }
    catch {}
    return false;
}

Is it possible to change the content HTML5 alert messages?

Thank you guys for the help,

When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:

http://blog.thomaslebrun.net/2011/11/html-5-how-to-customize-the-error-message-for-a-required-field/#.UsNN1BYrh2M

TypeError: object of type 'int' has no len() error assistance needed

May be it is the problem of using len() for an integer value. does not posses the len attribute in Python.

Error as:I will give u an example:

number= 1
print(len(num))

Instead of use ths,

data = [1,2,3,4]
print(len(data))

How to get the last N rows of a pandas DataFrame?

How to get the last N rows of a pandas DataFrame?

If you are slicing by position, __getitem__ (i.e., slicing with[]) works well, and is the most succinct solution I've found for this problem.

pd.__version__
# '0.24.2'

df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df

   A  B
0  a  1
1  a  2
2  a  3
3  b  4
4  b  5
5  b  6
6  b  7
7  c  8

df[-3:]

   A  B
5  b  6
6  b  7
7  c  8

This is the same as calling df.iloc[-3:], for instance (iloc internally delegates to __getitem__).


As an aside, if you want to find the last N rows for each group, use groupby and GroupBy.tail:

df.groupby('A').tail(2)

   A  B
1  a  2
2  a  3
5  b  6
6  b  7
7  c  8

Allow access permission to write in Program Files of Windows 7

Options I can think of:

  • Run entire app as full admin priv. using UAC
  • Run a sub-process as full admin for only those things needing access
  • Write temporary files elsewhere

How to set null value to int in c#?

int does not allow null, use-

int? value = 0  

or use

Nullable<int> value

How to run multiple DOS commands in parallel?

if you have multiple parameters use the syntax as below. I have a bat file with script as below:

start "dummyTitle" [/options] D:\path\ProgramName.exe Param1 Param2 Param3 
start "dummyTitle" [/options] D:\path\ProgramName.exe Param4 Param5 Param6 

This will open multiple consoles.

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

I assume the question is already answered. If above solution doesn't help in solving the issue then can use below to solve the issue.

The issue occurs if sometimes your maven user settings is not reflecting correct settings.xml file.

To update the settings file go to Windows > Preferences > Maven > User Settings and update the settings.xml to it correct location.

Once this is doen re-build the project, these should solve the issue. Thanks.

SQL Combine Two Columns in Select Statement

If you don't want to change your database schema (and I would not for this simple query) you can just combine them in the filter like this: WHERE (Address1 + Address2) LIKE '%searchstring%'

MVC 4 - how do I pass model data to a partial view?

You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>(). Try this:

@model LetLord.Models.Tenant
<div class="row-fluid">
    <div class="span4 well-border">
         @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
    </div>
</div>

Datatable select method ORDER BY clause

You can use the below simple method of sorting:

datatable.DefaultView.Sort = "Col2 ASC,Col3 ASC,Col4 ASC";

By the above method, you will be able to sort N number of columns.

Missing Authentication Token while accessing API Gateway?

I had the same problem which I solved the following way:

GET Method test

https://54wtstq8d2.execute-api.ap-southeast-2.amazonaws.com/dev/echo/hello
Authorization tab -> 
•   select type(AWS signature)
•   Add AccessKey and SecretKey

Allowed memory size of 536870912 bytes exhausted in Laravel

Sometime limiting your data is also helpful, for example checkout the followings:

//This caused error:
print_r($request);

//This resolved issue:
print_r($request->all());




    

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

I hate the ApplicationPoolIdentity. I always set a Windows User Account as the account on AppPools.

As adrift says, it does sound like a database security issue. So create an NT user account, assign it to the ASP.NET v4.0 AppPool and then grant it permission on the website folder and to the relevant table(s) in SQL.

How to set UICollectionViewCell Width and Height programmatically

Swift 5 Programmatically

lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal

        //Provide Width and Height According to your need
        let cellWidth = UIScreen.main.bounds.width / 10
        let cellHeight = UIScreen.main.bounds.height / 10
        layout.itemSize = CGSize(width: cellWidth, height: cellHeight)

        //You can also provide estimated Height and Width
        layout.estimatedItemSize = CGSize(width: cellWidth, height: cellHeight)

        //For Setting the Spacing between cells
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0

        return UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    }()

How to mkdir only if a directory does not already exist?

This should work:

$ mkdir -p dir

or:

if [[ ! -e $dir ]]; then
    mkdir $dir
elif [[ ! -d $dir ]]; then
    echo "$dir already exists but is not a directory" 1>&2
fi

which will create the directory if it doesn't exist, but warn you if the name of the directory you're trying to create is already in use by something other than a directory.

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

It seems like You haven't set the Mysql server path, Set Environment Variable For MySql Server. Then restart the command prompt and enter mysql -u root-p then it asks for a password enter it. Thank you. Happy learning!

How to convert php array to utf8?

In case of a PDO connection, the following might help, but the database should be in UTF-8:

//Connect
$db = new PDO(
    'mysql:host=localhost;dbname=database_name;', 'dbuser', 'dbpassword',
    array('charset'=>'utf8')
);
$db->query("SET CHARACTER SET utf8");

Inserting code in this LaTeX document with indentation

Specialized packages such as minted, which relies on Pygments to do the formatting, offer various advantages over the listings package. To quote from the minted manual,

Pygments provides far superior syntax highlighting compared to conventional packages. For example, listings basically only highlights strings, comments and keywords. Pygments, on the other hand, can be completely customized to highlight any token kind the source language might support. This might include special formatting sequences inside strings, numbers, different kinds of identifiers and exotic constructs such as HTML tags.

Cannot drop database because it is currently in use

To delete a database even if it's running, you can use this batch file

@echo off

set /p dbName= "Enter your database name to drop: " 

echo Setting to single-user mode
sqlcmd -Q "ALTER DATABASE [%dbName%] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE"

echo Dropping...
sqlcmd -Q "drop database %dbName%"

echo Completed.

pause

Screen

How do I increase modal width in Angular UI Bootstrap?

I solved the problem using Dmitry Komin solution, but with different CSS syntax to make it works directly in browser.

CSS

@media(min-width: 1400px){
    .my-modal > .modal-lg {
        width: 1308px;
    }
}

JS is the same:

var modal = $modal.open({
    animation: true,
    templateUrl: 'modalTemplate.html',
    controller: 'modalController',
    size: 'lg',
    windowClass: 'my-modal'
});

How to unstage large number of files without deleting the content

Warning: do not use the following command unless you want to lose uncommitted work!

Using git reset has been explained, but you asked for an explanation of the piped commands as well, so here goes:

git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached

The command git ls-files lists all files git knows about. The option -z imposes a specific format on them, the format expected by xargs -0, which then invokes rm -f on them, which means to remove them without checking for your approval.

In other words, "list all files git knows about and remove your local copy".

Then we get to git diff, which shows changes between different versions of items git knows about. Those can be changes between different trees, differences between local copies and remote copies, and so on.
As used here, it shows the unstaged changes; the files you have changed but haven't committed yet. The option --name-only means you want the (full) file names only and --diff-filter=D means you're interested in deleted files only. (Hey, didn't we just delete a bunch of stuff?) This then gets piped into the xargs -0 we saw before, which invokes git rm --cached on them, meaning that they get removed from the cache, while the working tree should be left alone — except that you've just removed all files from your working tree. Now they're removed from your index as well.

In other words, all changes, staged or unstaged, are gone, and your working tree is empty. Have a cry, checkout your files fresh from origin or remote, and redo your work. Curse the sadist who wrote these infernal lines; I have no clue whatsoever why anybody would want to do this.


TL;DR: you just hosed everything; start over and use git reset from now on.

How to get input from user at runtime

its very simple

just write:

//first create table named test....

create table test (name varchar2(10),age number(5));

//when you run the above code a table will be created....

//now we have to insert a name & an age..

Make sure age will be inserted via opening a form that seeks our help to enter the value in it

insert into test values('Deepak', :age);

//now run the above code and you'll get "1 row inserted" output...

/now run the select query to see the output

select * from test;

//that's all ..Now i think no one has any queries left over accepting a user data...

Bootstrap 3 Navbar with Logo

If using LESS, this works:

@navbar-height: 150px;
@navbar-brand-vpadding: 10px;

.navbar-brand img {
  height: @navbar-height - @navbar-brand-vpadding * 2;
  position: absolute;
  top: @navbar-brand-vpadding;
}

How can I debug git/git-shell related problems?

If its over SSH, you can use the following:

For a higher debug level for type -vv or -vvv for debug level 2 and 3 respectively:

# Debug level 1
GIT_SSH_COMMAND="ssh -v" git clone <repositoryurl>

# Debug level 2
GIT_SSH_COMMAND="ssh -vv" git clone <repositoryurl>

# Debug level 3
GIT_SSH_COMMAND="ssh -vvv" git clone <repositoryurl>

This is mainly useful to handle public and private key problems with the server. You can use this command for any git command, not only 'git clone'.

Using subprocess to run Python script on Windows

How about this:

import sys
import subprocess

theproc = subprocess.Popen("myscript.py", shell = True)
theproc.communicate()                   # ^^^^^^^^^^^^

This tells subprocess to use the OS shell to open your script, and works on anything that you can just run in cmd.exe.

Additionally, this will search the PATH for "myscript.py" - which could be desirable.

Adding custom HTTP headers using JavaScript

The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method.

Using this with "GET" request will download the resource. The trick then is to access the resource in the intended way. Ostensibly you should be able to allow the GET response to be cacheable for a short period, hence navigation to a new URL or the creation of an IMG tag with a src url should use the cached response from the previous "GET". However that is quite likely to fail especially in IE which can be a bit of a law unto itself where the cache is concerned.

Ultimately I agree with Mehrdad, use of query string is easiest and most reliable method.

Another quirky alternative is use an XHR to make a request to a URL that indicates your intent to access a resource. It could respond with a session cookie which will be carried by the subsequent request for the image or link.

how to add background image to activity?

use the android:background attribute in your xml. Easiest way if you want to apply it to a whole activity is to put it in the root of your layout. So if you have a RelativeLayout as the start of your xml, put it in here:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootRL"
    android:orientation="vertical" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:background="@drawable/background">
</RelativeLayout>

how to hide the content of the div in css

Here is the simplest way to do it with CSS3:

#mybox:hover {
  color: transparent;
}

regardless of the container color you can make the text color transparent on hover.

http://caniuse.com/#feat=css3-colors

Cheers! :)

Favicon: .ico or .png / correct tags?

See here: Cross Browser favicon

Thats the way to go:

<link rel="icon" type="image/png" href="http://www.example.com/image.png"><!-- Major Browsers -->
<!--[if IE]><link rel="SHORTCUT ICON" href="http://www.example.com/alternateimage.ico"/><![endif]--><!-- Internet Explorer-->

What does a bitwise shift (left or right) do and what is it used for?

The bit shift operators are more efficient as compared to the / or * operators.

In computer architecture, divide(/) or multiply(*) take more than one time unit and register to compute result, while, bit shift operator, is just one one register and one time unit computation.

Programmatically generate video or animated GIF in Python?

Here's how you do it using only PIL (install with: pip install Pillow):

import glob
from PIL import Image

# filepaths
fp_in = "/path/to/image_*.png"
fp_out = "/path/to/image.gif"

# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
         save_all=True, duration=200, loop=0)

See docs: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif

Can I run Keras model on gpu?

Yes you can run keras models on GPU. Few things you will have to check first.

  1. your system has GPU (Nvidia. As AMD doesn't work yet)
  2. You have installed the GPU version of tensorflow
  3. You have installed CUDA installation instructions
  4. Verify that tensorflow is running with GPU check if GPU is working

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

for TF > v2.0

sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))

(Thanks @nbro and @Ferro for pointing this out in the comments)

OR

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

output will be something like this:

[
  name: "/cpu:0"device_type: "CPU",
  name: "/gpu:0"device_type: "GPU"
]

Once all this is done your model will run on GPU:

To Check if keras(>=2.1.1) is using GPU:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

All the best.

How to create EditText with rounded corners?

With the Material Components Library you can use the MaterialShapeDrawable to draw custom shapes.

With a EditText you can do:

    <EditText
        android:id="@+id/edittext"
        ../>

Then create a MaterialShapeDrawable:

float radius = getResources().getDimension(R.dimen.default_corner_radius);

EditText editText = findViewById(R.id.edittext);
//Apply the rounded corners 
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
                .toBuilder()
                .setAllCorners(CornerFamily.ROUNDED,radius)
                .build();

MaterialShapeDrawable shapeDrawable = 
            new MaterialShapeDrawable(shapeAppearanceModel);
//Apply a background color
shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,R.color.white));
//Apply a stroke
shapeDrawable.setStroke(2.0f, ContextCompat.getColor(this,R.color.colorAccent));

ViewCompat.setBackground(editText,shapeDrawable);

enter image description here

It requires the version 1.1.0 of the library.

Align an element to bottom with flexbox

Try This

_x000D_
_x000D_
.content {_x000D_
      display: flex;_x000D_
      flex-direction: column;_x000D_
      height: 250px;_x000D_
      width: 200px;_x000D_
      border: solid;_x000D_
      word-wrap: break-word;_x000D_
    }_x000D_
_x000D_
   .content h1 , .content h2 {_x000D_
     margin-bottom: 0px;_x000D_
    }_x000D_
_x000D_
   .content p {_x000D_
     flex: 1;_x000D_
    }
_x000D_
   <div class="content">_x000D_
  <h1>heading 1</h1>_x000D_
  <h2>heading 2</h2>_x000D_
  <p>Some more or less text</p>_x000D_
  <a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery datepicker to prevent past date

Make sure you put multiple properties in the same line (since you only showed 1 line of code, you may have had the same problem I did).

Mine would set the default date, but didn't gray out old dates. This doesn't work:

$('#date_end').datepicker({ defaultDate: +31 })
$('#date_end').datepicker({ minDate: 1 })

This does both:

$('#date_end').datepicker({ defaultDate: +31, minDate: 1 })

1 and +1 work the same (or 0 and +0 in your case).

Me: Windows 7 x64, Rails 3.2.3, Ruby 1.9.3

How to implement a queue using two stacks?

**Easy JS solution **

  • Note: I took ideas from other people comment

_x000D_
_x000D_
/*_x000D_
_x000D_
enQueue(q,  x)_x000D_
 1) Push x to stack1 (assuming size of stacks is unlimited)._x000D_
_x000D_
deQueue(q)_x000D_
 1) If both stacks are empty then error._x000D_
 2) If stack2 is empty_x000D_
   While stack1 is not empty, push everything from stack1 to stack2._x000D_
 3) Pop the element from stack2 and return it._x000D_
_x000D_
*/_x000D_
class myQueue {_x000D_
    constructor() {_x000D_
        this.stack1 = [];_x000D_
        this.stack2 = [];_x000D_
    }_x000D_
_x000D_
    push(item) {_x000D_
        this.stack1.push(item)_x000D_
    }_x000D_
_x000D_
    remove() {_x000D_
        if (this.stack1.length == 0 && this.stack2.length == 0) {_x000D_
            return "Stack are empty"_x000D_
        }_x000D_
_x000D_
        if (this.stack2.length == 0) {_x000D_
_x000D_
            while (this.stack1.length != 0) {_x000D_
                this.stack2.push(this.stack1.pop())_x000D_
            }_x000D_
        }_x000D_
        return this.stack2.pop()_x000D_
    }_x000D_
_x000D_
_x000D_
    peek() {_x000D_
        if (this.stack2.length == 0 && this.stack1.length == 0) {_x000D_
            return 'Empty list'_x000D_
        }_x000D_
_x000D_
        if (this.stack2.length == 0) {_x000D_
            while (this.stack1.length != 0) {_x000D_
                this.stack2.push(this.stack1.pop())_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return this.stack2[0]_x000D_
    }_x000D_
_x000D_
    isEmpty() {_x000D_
        return this.stack2.length === 0 && this.stack1.length === 0;_x000D_
    }_x000D_
_x000D_
}_x000D_
_x000D_
const q = new myQueue();_x000D_
q.push(1);_x000D_
q.push(2);_x000D_
q.push(3);_x000D_
q.remove()_x000D_
_x000D_
console.log(q)
_x000D_
_x000D_
_x000D_

How can I check whether a numpy array is empty or not?

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

How to print without newline or space?

Use the python3-style print function for python2.6+ (will also break any existing keyworded print statements in the same file.)

# for python2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
    print('.', end='')

To not ruin all your python2 print keywords, create a separate printf.py file

# printf.py

from __future__ import print_function

def printf(str, *args):
    print(str % args, end='')

Then, use it in your file

from printf import printf
for x in xrange(10):
    printf('.')
print 'done'
#..........done

More examples showing printf style

printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000

Wildcards in a Windows hosts file

@petah and Acrylic DNS Proxy is the best answer, and at the end he references the ability to do multi-site using an Apache which @jeremyasnyder describes a little further down...

... however, in our case we're testing a multi-tenant hosting system and so most domains we want to test go to the same virtualhost, while a couple others are directed elsewhere.

So in our case, you simply use regex wildcards in the ServerAlias directive, like so...

ServerAlias *.foo.local

Facebook share button and custom text

you could combine AllisonC's idea with window.open function: http://www.w3schools.com/jsref/met_win_open.asp

function openWin(url) {
    myWindow = window.open(url, '', 'width=800,height=400');
    myWindow.focus();
}

And then on each link you call the openWin function with the right social net url.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

You can use date function to format it by using the code below:

echo date("g:i a", strtotime("13:30:30 UTC"));

output: 1:30 pm

Access denied for user 'test'@'localhost' (using password: YES) except root user

First I created the user using :

CREATE user user@localhost IDENTIFIED BY 'password_txt';

After Googling and seeing this, I updated user's password using :

SET PASSWORD FOR 'user'@'localhost' = PASSWORD('password_txt');

and I could connect afterward.

What is the "realm" in basic authentication

From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)

The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.

In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.

Where to put Gradle configuration (i.e. credentials) that should not be committed?

If you have user specific credentials ( i.e each developer might have different username/password ) then I would recommend using the gradle-properties-plugin.

  1. Put defaults in gradle.properties
  2. Each developer overrides with gradle-local.properties ( this should be git ignored ).

This is better than overriding using $USER_HOME/.gradle/gradle.properties because different projects might have same property names.

Create a hidden field in JavaScript

I've found this to work:

var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);

Showing empty view when ListView is empty

Just to add that you don't really need to create new IDs, something like the following will work.

In the layout:

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/list"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@android:id/empty"
    android:text="Empty"/>

Then in the activity:

    ListView listView = (ListView) findViewById(android.R.id.list);
    listView.setEmptyView(findViewById(android.R.id.empty));

How can one display images side by side in a GitHub README.md?

Similar to the other examples, but using html sizing, I use:

<img src="image1.png" width="425"/> <img src="image2.png" width="425"/> 

Here is an example

<img src="https://openclipart.org/image/2400px/svg_to_png/28580/kablam-Number-Animals-1.png" width="200"/> <img src="https://openclipart.org/download/71101/two.svg" width="300"/>

I tested this using Remarkable.

how to convert String into Date time format in JAVA?

Using this,

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

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

Background position, margin-top?

If you mean you want the background image itself to be offset by 50 pixels from the top, like a background margin, then just switch out the top for 50px and you're set.

#thedivstatus {
    background-image: url("imagestatus.gif");
    background-position: right 50px;
    background-repeat: no-repeat;
}

Return JSON for ResponseEntity<String>

@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String so() {
    return "This is a String";
}

What is the reason for having '//' in Python?

// is unconditionally "flooring division", e.g:

>>> 4.0//1.5
2.0

As you see, even though both operands are floats, // still floors -- so you always know securely what it's going to do.

Single / may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:

$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667

As you see, single / may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want flooring, always use //, which guarantees it. If and when you know you don't want flooring, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)

SQL server stored procedure return a table

create procedure PSaleCForms
as
begin
declare 
@b varchar(9),
@c nvarchar(500),
@q nvarchar(max)
declare @T table(FY nvarchar(9),Qtr int,title nvarchar    (max),invoicenumber     nvarchar(max),invoicedate datetime,sp decimal    18,2),grandtotal decimal(18,2))
declare @data cursor
set @data= Cursor
forward_only static
for 
select x.DBTitle,y.CurrentFinancialYear from [Accounts     Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on        y.DBID=x.DBID where x.cfy=1
open @data
fetch next from @data
into @c,@b
while @@FETCH_STATUS=0
begin
set @q=N'Select '''+@b+''' [fy], case cast(month(i.invoicedate)/3.1 as int)     when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr],     l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from     ['+@c+'].dbo.invoicemain i inner join  ['+@c+'].dbo.ledgermain l on     l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''

insert into @T exec [master].dbo.sp_executesql @q fetch next from @data into @c,@b end close @data deallocate @data select * from @T return end

Are vectors passed to functions by value or by reference in C++

when we pass vector by value in a function as an argument,it simply creates the copy of vector and no any effect happens on the vector which is defined in main function when we call that particular function. while when we pass vector by reference whatever is written in that particular function, every action will going to perform on the vector which is defined in main or other function when we call that particular function.

Linux command-line call not returning what it should from os.system?

For your requirement, Popen function of subprocess python module is the answer. For example,

import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout

Get the short Git version hash

A really simple way is to:

git describe --always

Find all stored procedures that reference a specific column in some table

i had the same problem and i found that Microsoft has a systable that shows dependencies.

SELECT 
    referenced_id
    , referenced_entity_name AS table_name
    , referenced_minor_name as column_name
    , is_all_columns_found
FROM sys.dm_sql_referenced_entities ('dbo.Proc1', 'OBJECT'); 

And this works with both Views and Triggers.

How to generate different random numbers in a loop in C++?

You need to extract the initilization of time() out of the for loop.

Here is an example that will output in the windows console expected (ahah) random number.

#include <iostream>
#include <windows.h>
#include "time.h"
int main(int argc, char*argv[])
{
    srand ( time(NULL) );
    for (int t = 0; t < 10; t++)
    {
        int random_x;

        random_x = rand() % 100;
        std::cout << "\nRandom X = " << random_x << std::endl;
    }
    Sleep(50000);
    return 0;
}

How to add border radius on table row

I think collapsing your borders is the wrong thing to do in this case. Collapsing them basically means that the border between two neighboring cells becomes shared. This means it's unclear as to which direction it should curve given a radius.

Instead, you can give a border radius to the two lefthand corners of the first TD and the two righthand corners of the last one. You can use first-child and last-child selectors as suggested by theazureshadow, but these may be poorly supported by older versions of IE. It might be easier to just define classes, such as .first-column and .last-column to serve this purpose.

Add floating point value to android resources/values

Although I've used the accepted answer in the past, it seems with the current Build Tools it is possible to do:

   <dimen name="listAvatarWidthPercent">0.19</dimen>

I'm using Build Tools major version 29.

How can I get log4j to delete old rotating log files?

There is no default value to control deleting old log files created by DailyRollingFileAppender. But you can write your own custom Appender that deletes old log files in much the same way as setting maxBackupIndex does for RollingFileAppender.

Simple instructions found here

From 1:

If you are trying to use the Apache Log4J DailyRollingFileAppender for a daily log file, you may need to want to specify the maximum number of files which should be kept. Just like rolling RollingFileAppender supports maxBackupIndex. But the current version of Log4j (Apache log4j 1.2.16) does not provide any mechanism to delete old log files if you are using DailyRollingFileAppender. I tried to make small modifications in the original version of DailyRollingFileAppender to add maxBackupIndex property. So, it would be possible to clean up old log files which may not be required for future usage.

Syntax for if/else condition in SCSS mixin

You could default the parameter to null or false.
This way, it would be shorter to test if a value has been passed as parameter.

@mixin clearfix($width: null) {

  @if not ($width) {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

How to change sa password in SQL Server 2008 express?

You need to follow the steps described in Troubleshooting: Connecting to SQL Server When System Administrators Are Locked Out and add your own Windows user as a member of sysadmin:

  • shutdown MSSQL$EXPRESS service (or whatever the name of your SQL Express service is)
  • start add the -m and -f startup parameters (or you can start sqlservr.exe -c -sEXPRESS -m -f from console)
  • connect to DAC: sqlcmd -E -A -S .\EXPRESS or from SSMS use admin:.\EXPRESS
  • run create login [machinename\username] from windows to create your Windows login in SQL
  • run sp_addsrvrolemember 'machinename\username', 'sysadmin'; to make urself sysadmin member
  • restart service w/o the -m -f

Creating a script for a Telnet session?

Check for the SendCommand tool.

You can use it as follows:

perl sendcommand.pl -i login.txt -t cisco -c "show ip route"

How to use if-else option in JSTL

There is no if-else, just if.

<c:if test="${user.age ge 40}">
 You are over the hill.
</c:if>

Optionally you can use choose-when:

<c:choose>
  <c:when test="${a boolean expr}">
    do something
  </c:when>
  <c:when test="${another boolean expr}">
    do something else
  </c:when>
  <c:otherwise>
    do this when nothing else is true
  </c:otherwise>
</c:choose>

Configure apache to listen on port other than 80

For FC22 server

cd /etc/httpd/conf edit httpd.conf [enter]

Change: Listen 80 to: Listen whatevernumber

Save the file

systemctl restart httpd.service [enter] if required, open whatevernumber in your router / firewall

How to load a resource from WEB-INF directory of a web archive

Use the getResourceAsStream() method on the ServletContext object, e.g.

servletContext.getResourceAsStream("/WEB-INF/myfile");

How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?

EDITED: If you're inside a Servlet object, then call getServletContext(). If you're in JSP, use the predefined variable application.

Import MySQL database into a MS SQL Server

If you do an export with PhpMyAdmin, you can switch sql compatibility mode to 'MSSQL'. That way you just run the exported script against your MS SQL database and you're done.

If you cannot or don't want to use PhpMyAdmin, there's also a compatibility option in mysqldump, but personally I'd rather have PhpMyAdmin do it for me.

How to get a random value from dictionary?

If you don't want to use the random module, you can also try popitem():

>> d = {'a': 1, 'b': 5, 'c': 7}
>>> d.popitem()
('a', 1)
>>> d
{'c': 7, 'b': 5}
>>> d.popitem()
('c', 7)

Since the dict doesn't preserve order, by using popitem you get items in an arbitrary (but not strictly random) order from it.

Also keep in mind that popitem removes the key-value pair from dictionary, as stated in the docs.

popitem() is useful to destructively iterate over a dictionary

When is "java.io.IOException:Connection reset by peer" thrown?

There are lot of factors , first see whether server returns the result, then check between server and client.

rectify them from server side first,then check the writing condition between server and client !

server side rectify the time outs between the datalayer and server from client side rectify the time out and number of available connections !

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

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

In case that you define your route like the one asked in the question (path: '/link/to/page'):

import Vue from 'vue'
import Router from 'vue-router'
import MyComponent from '@/components/MyComponent.vue';

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/link/to/page',
      component: MyComponent
    }
  ]
})

You can resolve the URL in your summary page and open your sub page as below:

<script>
export default {
  methods: {
    popup() {
      let route = this.$router.resolve({path: '/link/to/page'});
      // let route = this.$router.resolve('/link/to/page'); // This also works.
      window.open(route.href, '_blank');
    }
  }
};
</script>

Of course if you've given your route a name, you can resolve the URL by name:

routes: [
  {
    path: '/link/to/page',
    component: MyComponent,
    name: 'subPage'
  }
]

...

let route = this.$router.resolve({name: 'subPage'});

References:

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

On WebStorm 2020.1

WebStorm -> Preferences -> Languages & Frameworks -> Node.js and NPM -> Check Coding assistance for Node.js -> Apply

WebStorm 2020.1 -> Preferences -> Languages & Frameworks -> Node.js and NPM -> Check Coding assistance for Node.js

Android: How do I get string from resources using its name?

getResources().getString(getResources().getIdentifier("propertyName", "string", getPackageName()))

Use a loop to plot n charts Python

Use a dictionary!!

You can also use dictionaries that allows you to have more control over the plots:

import matplotlib.pyplot as plt
#   plot 0     plot 1    plot 2   plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]

plots = zip(x,y)
def loop_plot(plots):
    figs={}
    axs={}
    for idx,plot in enumerate(plots):
        figs[idx]=plt.figure()
        axs[idx]=figs[idx].add_subplot(111)
        axs[idx].plot(plot[0],plot[1])
return figs, axs

figs, axs = loop_plot(plots)

Now you can select the plot that you want to modify easily:

axs[0].set_title("Now I can control it!")

Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx) or show them plt.show(). Use the argument block=False only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot function or in a separate loop using the dictionaries that the function provided.

What does CultureInfo.InvariantCulture mean?

For things like numbers (decimal points, commas in amounts), they are usually preferred in the specific culture.

A appropriate way to do this would be set it at the culture level (for German) like this:

Thread.CurrentThread.CurrentCulture.NumberFormat = new CultureInfo("de").NumberFormat;

Is the Javascript date object always one day off?

There are several crazy things that happen with a JS DATE object that convert strings, for example consider the following date you provided

Note: The following examples may or may not be ONE DAY OFF depending on YOUR timezone and current time.

new Date("2011-09-24"); // Year-Month-Day
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.

However, if we rearrange the string format to Month-Day-Year...

new Date("09-24-2011");
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

Another strange one

new Date("2011-09-24");
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF AS BEFORE.

new Date("2011/09/24"); // change from "-" to "/".
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

We could easily change hyphens in your date "2011-09-24" when making a new date

new Date("2011-09-24".replace(/-/g, '\/')); // => "2011/09/24".
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

What if we had a date string like "2011-09-24T00:00:00"

new Date("2011-09-24T00:00:00");
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.

Now change hyphen to forward slash as before; what happens?

new Date("2011/09/24T00:00:00");
// => Invalid Date.

I typically have to manage the date format 2011-09-24T00:00:00 so this is what I do.

new Date("2011-09-24T00:00:00".replace(/-/g, '\/').replace(/T.+/, ''));
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

UPDATE

If you provide separate arguments to the Date constructor you can get other useful outputs as described below

Note: arguments can be of type Number or String. I'll show examples with mixed values.

Get the first month and day of a given year

new Date(2011, 0); // Normal behavior as months in this case are zero based.
// => Sat Jan 01 2011 00:00:00 GMT-0700 (MST)

Get the last month and day of a year

new Date((2011 + 1), 0, 0); // The second zero roles back one day into the previous month's last day.
// => Sat Dec 31 2011 00:00:00 GMT-0700 (MST)

Example of Number, String arguments. Note the month is March because zero based months again.

new Date(2011, "02"); 
// => Tue Mar 01 2011 00:00:00 GMT-0700 (MST)

If we do the same thing but with a day of zero, we get something different.

new Date(2011, "02", 0); // Again the zero roles back from March to the last day of February.
// => Mon Feb 28 2011 00:00:00 GMT-0700 (MST)

Adding a day of zero to any year and month argument will get the last day of the previous month. If you continue with negative numbers you can continue rolling back another day

new Date(2011, "02", -1);
// => Sun Feb 27 2011 00:00:00 GMT-0700 (MST)

No Activity found to handle Intent : android.intent.action.VIEW

I have two ideas:

First: if you want to play 3gp file you should use mime types "audio/3gpp" or "audio/mpeg"

And second: you can try use method setData(data) for intent without any mime type.

TypeError: Cannot read property "0" from undefined

Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.

Ammend your while statement to this...

for(var iIndex = 1; iIndex <= data.length; iIndex++){
    if (data[iIndex][0] === name){
         break;
    };
    Logger.log(data[i][0]);
 };

Determine when a ViewPager changes pages

Kotlin Users,

viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {

            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
            }
        })

Update 2020 for ViewPager2

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
        override fun onPageScrollStateChanged(state: Int) {
            println(state)
        }

        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int
        ) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            println(position)
        }


        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            println(position)
        }
    })

Using number as "index" (JSON)

When a Javascript object property's name doesn't begin with either an underscore or a letter, you cant use the dot notation (like Game.status[0].0), and you must use the alternative notation, which is Game.status[0][0].

One different note, do you really need it to be an object inside the status array? If you're using the object like an array, why not use a real array instead?

Call to undefined function mysql_connect

Hi I got this error because I left out the ampersand (&) in

; php.ini
error_reporting = E_ALL & ~E_DEPRECATED

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

If you want to learn, REALLY want to learn, then time is not of consequence. Just move forward everyday. Let your passion for this stuff drive you forward. And one day you'll see that you are good at C#/.NET.

missing private key in the distribution certificate on keychain

I lost hours and hours to resolve this issue, but it's fixed by just restarting MAC...

Redirect to an external URL from controller action in Spring MVC

In short "redirect://yahoo.com" will lend you to yahoo.com.

where as "redirect:yahoo.com" will lend you your-context/yahoo.com ie for ex- localhost:8080/yahoo.com

What's the difference between git clone --mirror and git clone --bare

$ git clone --bare https://github.com/example

This command will make the new "example" directory itself the $GIT_DIR (instead of example/.git). Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping. When this option is used, neither remote-tracking branches nor the related configuration variables are created.

$ git clone --mirror https://github.com/example

As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references (including remote-tracking branches, notes etc.) will be overwritten each time you fetch, so it will always be the same as the original repository.

Aren't Python strings immutable? Then why does a + " " + b work?

Consider this addition to your example

 a = "Dog"
 b = "eats"
 c = "treats"
 print (a,b,c)
 #Dog eats treats
 d = a + " " + b + " " + c
 print (a)
 #Dog
 print (d)
 #Dog eats treats

One of the more precise explanations I found in a blog is:

In Python, (almost) everything is an object. What we commonly refer to as "variables" in Python are more properly called names. Likewise, "assignment" is really the binding of a name to an object. Each binding has a scope that defines its visibility, usually the block in which the name originates.

Eg:

some_guy = 'Fred'
# ...
some_guy = 'George'

When we later say some_guy = 'George', the string object containing 'Fred' is unaffected. We've just changed the binding of the name some_guy. We haven't, however, changed either the 'Fred' or 'George' string objects. As far as we're concerned, they may live on indefinitely.

Link to blog: https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/

PHP Fatal error: Cannot redeclare class

Sometimes that happens due to some bugs in PHP's FastCGI.

Try to restart it. At Ubuntu it's:

service php-fastcgi restart

YouTube API to fetch all videos on a channel

As the documentation states (link), you can use the channel resource type and operation List to get all the videos in an channel. This operation must be performed using argument 'channel id'.

How to convert Django Model object to dict with its fields and values?

The answer from @zags is comprehensive and should suffice but the #5 method (which is the best one IMO) throws an error so I improved the helper function.

As the OP requested for converting many_to_many fields into a list of primary keys rather than a list of objects, I enhanced the function so the return value is now JSON serializable - by converting datetime objects into str and many_to_many objects to a list of id's.

import datetime

def ModelToDict(instance):
    '''
    Returns a dictionary object containing complete field-value pairs of the given instance

    Convertion rules:

        datetime.date --> str
        many_to_many --> list of id's

    '''

    concrete_fields = instance._meta.concrete_fields
    m2m_fields = instance._meta.many_to_many
    data = {}

    for field in concrete_fields:
        key = field.name
        value = field.value_from_object(instance)
        if type(value) == datetime.datetime:
            value = str(field.value_from_object(instance))
        data[key] = value

    for field in m2m_fields:
        key = field.name
        value = field.value_from_object(instance)
        data[key] = [rel.id for rel in value]

    return data

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

How do I configure Apache 2 to run Perl CGI scripts?

You'll need to take a look at your Apache error log to see what the "internal server error" is. The four most likely cases, in my experience would be:

  1. The CGI program is in a directory which does not have CGI execution enabled. Solution: Add the ExecCGI option to that directory via either httpd.conf or a .htaccess file.

  2. Apache is only configured to run CGIs from a dedicated cgi-bin directory. Solution: Move the CGI program there or add an AddHandler cgi-script .cgi statement to httpd.conf.

  3. The CGI program is not set as executable. Solution (assuming a *nix-type operating system): chmod +x my_prog.cgi

  4. The CGI program is exiting without sending headers. Solution: Run the program from the command line and verify that a) it actually runs rather than dying with a compile-time error and b) it generates the correct output, which should include, at the very minimum, a Content-Type header and a blank line following the last of its headers.

Html.RenderPartial() syntax with Razor

  • RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by { }.

  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

How to debug Spring Boot application with Eclipse?

Right click on the spring boot project -> debug as -> spring boot App. Put a debugger point and invoke the app from a client like postman

C++11 reverse range-based for-loop

You could simply use BOOST_REVERSE_FOREACH which iterates backwards. For example, the code

#include <iostream>
#include <boost\foreach.hpp>

int main()
{
    int integers[] = { 0, 1, 2, 3, 4 };
    BOOST_REVERSE_FOREACH(auto i, integers)
    {
        std::cout << i << std::endl;
    }
    return 0;
}

generates the following output:

4

3

2

1

0

Rename Pandas DataFrame Index

The currently selected answer does not mention the rename_axis method which can be used to rename the index and column levels.


Pandas has some quirkiness when it comes to renaming the levels of the index. There is also a new DataFrame method rename_axis available to change the index level names.

Let's take a look at a DataFrame

df = pd.DataFrame({'age':[30, 2, 12],
                       'color':['blue', 'green', 'red'],
                       'food':['Steak', 'Lamb', 'Mango'],
                       'height':[165, 70, 120],
                       'score':[4.6, 8.3, 9.0],
                       'state':['NY', 'TX', 'FL']},
                       index = ['Jane', 'Nick', 'Aaron'])

enter image description here

This DataFrame has one level for each of the row and column indexes. Both the row and column index have no name. Let's change the row index level name to 'names'.

df.rename_axis('names')

enter image description here

The rename_axis method also has the ability to change the column level names by changing the axis parameter:

df.rename_axis('names').rename_axis('attributes', axis='columns')

enter image description here

If you set the index with some of the columns, then the column name will become the new index level name. Let's append to index levels to our original DataFrame:

df1 = df.set_index(['state', 'color'], append=True)
df1

enter image description here

Notice how the original index has no name. We can still use rename_axis but need to pass it a list the same length as the number of index levels.

df1.rename_axis(['names', None, 'Colors'])

enter image description here

You can use None to effectively delete the index level names.


Series work similarly but with some differences

Let's create a Series with three index levels

s = df.set_index(['state', 'color'], append=True)['food']
s

       state  color
Jane   NY     blue     Steak
Nick   TX     green     Lamb
Aaron  FL     red      Mango
Name: food, dtype: object

We can use rename_axis similarly to how we did with DataFrames

s.rename_axis(['Names','States','Colors'])

Names  States  Colors
Jane   NY      blue      Steak
Nick   TX      green      Lamb
Aaron  FL      red       Mango
Name: food, dtype: object

Notice that the there is an extra piece of metadata below the Series called Name. When creating a Series from a DataFrame, this attribute is set to the column name.

We can pass a string name to the rename method to change it

s.rename('FOOOOOD')

       state  color
Jane   NY     blue     Steak
Nick   TX     green     Lamb
Aaron  FL     red      Mango
Name: FOOOOOD, dtype: object

DataFrames do not have this attribute and infact will raise an exception if used like this

df.rename('my dataframe')
TypeError: 'str' object is not callable

Prior to pandas 0.21, you could have used rename_axis to rename the values in the index and columns. It has been deprecated so don't do this

First char to upper case

Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.

Try this.

betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())

How to generate a random number between a and b in Ruby?

def random_int(min, max)
    rand(max - min) + min
end

fs: how do I locate a parent folder?

i'm running electron app and i can get the parent folder by path.resolve()

parent 1 level:path.resolve(__dirname, '..') + '/'

parent 2 levels:path.resolve(__dirname, '..', '..') + '/'

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

It is working after adding to pom.xml following dependencies:

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

Getting started with Hibernate Validator:

Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages. When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container. In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance you can add the following two dependencies to use the JSR 341 reference implementation:

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

Programmatically check Play Store for app updates

Apart from using JSoup, we can alternatively do pattern matching for getting the app version from playStore.

To match the latest pattern from google playstore ie <div class="BgcNfc">Current Version</div><span class="htlgb"><div><span class="htlgb">X.X.X</span></div> we first have to match the above node sequence and then from above sequence get the version value. Below is the code snippet for same:

    private String getAppVersion(String patternString, String inputString) {
        try{
            //Create a pattern
            Pattern pattern = Pattern.compile(patternString);
            if (null == pattern) {
                return null;
            }

            //Match the pattern string in provided string
            Matcher matcher = pattern.matcher(inputString);
            if (null != matcher && matcher.find()) {
                return matcher.group(1);
            }

        }catch (PatternSyntaxException ex) {

            ex.printStackTrace();
        }

        return null;
    }


    private String getPlayStoreAppVersion(String appUrlString) {
        final String currentVersion_PatternSeq = "<div[^>]*?>Current\\sVersion</div><span[^>]*?>(.*?)><div[^>]*?>(.*?)><span[^>]*?>(.*?)</span>";
        final String appVersion_PatternSeq = "htlgb\">([^<]*)</s";
        String playStoreAppVersion = null;

        BufferedReader inReader = null;
        URLConnection uc = null;
        StringBuilder urlData = new StringBuilder();

        final URL url = new URL(appUrlString);
        uc = url.openConnection();
        if(uc == null) {
           return null;
        }
        uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
        inReader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        if (null != inReader) {
            String str = "";
            while ((str = inReader.readLine()) != null) {
                           urlData.append(str);
            }
        }

        // Get the current version pattern sequence 
        String versionString = getAppVersion (currentVersion_PatternSeq, urlData.toString());
        if(null == versionString){ 
            return null;
        }else{
            // get version from "htlgb">X.X.X</span>
            playStoreAppVersion = getAppVersion (appVersion_PatternSeq, versionString);
        }

        return playStoreAppVersion;
    }

I got it solved through this, as this works for latest Google playstore changes also. Hope that helps.

python error: no module named pylab

What you've done by following those directions is created an entirely new Python installation, separate from the system Python that is managed by Ubuntu packages.

Modules you had installed in the system Python (e.g. installed via packages, or by manual installation using the system Python to run the setup process) will not be available, since your /usr/local-based python is configured to look in its own module directories, not the system Python's.

You can re-add missing modules now by building them and installing them using your new /usr/local-based Python.

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

Difference between BYTE and CHAR in column datatypes

Depending on the system configuration, size of CHAR mesured in BYTES can vary. In your examples:

  1. Limits field to 11 BYTE
  2. Limits field to 11 CHARacters


Conclusion: 1 CHAR is not equal to 1 BYTE.

Iterate through the fields of a struct in Go

If you want to Iterate through the Fields and Values of a struct then you can use the below Go code as a reference.

package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Fname  string
    Lname  string
    City   string
    Mobile int64
}

func main() {
    s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
    v := reflect.ValueOf(s)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
    }
}

Run in playground

Note: If the Fields in your struct are not exported then the v.Field(i).Interface() will give panic panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.

Turn off display errors using file "php.ini"

I always use something like this in a configuration file:

// Toggle this to change the setting
define('DEBUG', true);

// You want all errors to be triggered
error_reporting(E_ALL);

if(DEBUG == true)
{
    // You're developing, so you want all errors to be shown
    display_errors(true);

    // Logging is usually overkill during development
    log_errors(false);
}
else
{
    // You don't want to display errors on a production environment
    display_errors(false);

    // You definitely want to log any occurring
    log_errors(true);
}

This allows easy toggling between debug settings. You can improve this further by checking on which server the code is running (development, test, acceptance, and production) and change your settings accordingly.

Note that no errors will be logged if error_reporting is set to 0, as cleverly remarked by Korri.

Parsing CSV files in C#, with header

Single source file solution for straightforward parsing needs, useful. Deals with all the nasty edge cases. Such as new line normalization and handling new lines in quoted string literals. Your welcome!

If you CSV file has a header you just read out the column names (and compute column indexes) from the first row. Simple as that.

Note that Dump is a LINQPad method, you might want to remove that if you are not using LINQPad.

void Main()
{
    var file1 = "a,b,c\r\nx,y,z";
    CSV.ParseText(file1).Dump();

    var file2 = "a,\"b\",c\r\nx,\"y,z\"";
    CSV.ParseText(file2).Dump();

    var file3 = "a,\"b\",c\r\nx,\"y\r\nz\"";
    CSV.ParseText(file3).Dump();

    var file4 = "\"\"\"\"";
    CSV.ParseText(file4).Dump();
}

static class CSV
{
    public struct Record
    {
        public readonly string[] Row;

        public string this[int index] => Row[index];

        public Record(string[] row)
        {
            Row = row;
        }
    }

    public static List<Record> ParseText(string text)
    {
        return Parse(new StringReader(text));
    }

    public static List<Record> ParseFile(string fn)
    {
        using (var reader = File.OpenText(fn))
        {
            return Parse(reader);
        }
    }

    public static List<Record> Parse(TextReader reader)
    {
        var data = new List<Record>();

        var col = new StringBuilder();
        var row = new List<string>();
        for (; ; )
        {
            var ln = reader.ReadLine();
            if (ln == null) break;
            if (Tokenize(ln, col, row))
            {
                data.Add(new Record(row.ToArray()));
                row.Clear();
            }
        }

        return data;
    }

    public static bool Tokenize(string s, StringBuilder col, List<string> row)
    {
        int i = 0;

        if (col.Length > 0)
        {
            col.AppendLine(); // continuation

            if (!TokenizeQuote(s, ref i, col, row))
            {
                return false;
            }
        }

        while (i < s.Length)
        {
            var ch = s[i];
            if (ch == ',')
            {
                row.Add(col.ToString().Trim());
                col.Length = 0;
                i++;
            }
            else if (ch == '"')
            {
                i++;
                if (!TokenizeQuote(s, ref i, col, row))
                {
                    return false;
                }
            }
            else
            {
                col.Append(ch);
                i++;
            }
        }

        if (col.Length > 0)
        {
            row.Add(col.ToString().Trim());
            col.Length = 0;
        }

        return true;
    }

    public static bool TokenizeQuote(string s, ref int i, StringBuilder col, List<string> row)
    {
        while (i < s.Length)
        {
            var ch = s[i];
            if (ch == '"')
            {
                // escape sequence
                if (i + 1 < s.Length && s[i + 1] == '"')
                {
                    col.Append('"');
                    i++;
                    i++;
                    continue;
                }
                i++;
                return true;
            }
            else
            {
                col.Append(ch);
                i++;
            }
        }
        return false;
    }
}

Check if SQL Connection is Open or Closed

This code is a little more defensive, before opening a connection, check state. If connection state is Broken then we should try to close it. Broken means that the connection was previously opened and not functioning correctly. The second condition determines that connection state must be closed before attempting to open it again so the code can be called repeatedly.

// Defensive database opening logic.

if (_databaseConnection.State == ConnectionState.Broken) {
    _databaseConnection.Close();
}

if (_databaseConnection.State == ConnectionState.Closed) {
    _databaseConnection.Open();
}

Read input stream twice

How about:

if (stream.markSupported() == false) {

        // lets replace the stream object
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(stream, baos);
        stream.close();
        stream = new ByteArrayInputStream(baos.toByteArray());
        // now the stream should support 'mark' and 'reset'

    }

Removing duplicate values from a PowerShell array

Whether you're using SORT -UNIQUE, SELECT -UNIQUE or GET-UNIQUE from Powershell 2.0 to 5.1, all the examples given are on single Column arrays. I have yet to get this to function across Arrays with multiple Columns to REMOVE Duplicate Rows to leave single occurrences of a Row across said Columns, or develop an alternative script solution. Instead these cmdlets have only returned Rows in an Array that occurred ONCE with singular occurrence and dumped everything that had a duplicate. Typically I have to Remove Duplicates manually from the final CSV output in Excel to finish the report, but sometimes I would like to continue working with said data within Powershell after removing the duplicates.

How to horizontally center an element

I just use the simplest solution, but it works in all browsers:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>center a div within a div?</title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }

            #outer{
                width: 80%;
                height: 500px;
                background-color: #003;
                margin: 0 auto;
            }

            #outer p{
                color: #FFF;
                text-align: center;
            }

            #inner{
                background-color: #901;
                width: 50%;
                height: 100px;
                margin: 0 auto;

            }

            #inner p{
                color: #FFF;
                text-align: center;
            }
        </style>
    </head>

    <body>
        <div id="outer"><p>this is the outer div</p>
            <div id="inner">
                <p>this is the inner div</p>
            </div>
        </div>
    </body>
</html>

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

Download file using libcurl in C/C++

Just for those interested you can avoid writing custom function by passing NULL as last parameter (if you do not intend to do extra processing of returned data).
In this case default internal function is used.

Details
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTWRITEDATA

Example

#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://stackoverflow.com";
    char outfilename[FILENAME_MAX] = "page.html";
    curl = curl_easy_init();                                                                                                                                                                                                                                                           
    if (curl)
    {   
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }   
    return 0;
}

Properly Handling Errors in VBA (Excel)

You've got one truly marvelous answer from ray023, but your comment that it's probably overkill is apt. For a "lighter" version....

Block 1 is, IMHO, bad practice. As already pointed out by osknows, mixing error-handling with normal-path code is Not Good. For one thing, if a new error is thrown while there's an Error condition in effect you will not get an opportunity to handle it (unless you're calling from a routine that also has an error handler, where the execution will "bubble up").

Block 2 looks like an imitation of a Try/Catch block. It should be okay, but it's not The VBA Way. Block 3 is a variation on Block 2.

Block 4 is a bare-bones version of The VBA Way. I would strongly advise using it, or something like it, because it's what any other VBA programmer inherting the code will expect. Let me present a small expansion, though:

Private Sub DoSomething()
On Error GoTo ErrHandler

'Dim as required

'functional code that might throw errors

ExitSub:
    'any always-execute (cleanup?) code goes here -- analagous to a Finally block.
    'don't forget to do this -- you don't want to fall into error handling when there's no error
    Exit Sub

ErrHandler:
    'can Select Case on Err.Number if there are any you want to handle specially

    'display to user
    MsgBox "Something's wrong: " & vbCrLf & Err.Description

    'or use a central DisplayErr routine, written Public in a Module
    DisplayErr Err.Number, Err.Description

    Resume ExitSub
    Resume
End Sub

Note that second Resume. This is a trick I learned recently: It will never execute in normal processing, since the Resume <label> statement will send the execution elsewhere. It can be a godsend for debugging, though. When you get an error notification, choose Debug (or press Ctl-Break, then choose Debug when you get the "Execution was interrupted" message). The next (highlighted) statement will be either the MsgBox or the following statement. Use "Set Next Statement" (Ctl-F9) to highlight the bare Resume, then press F8. This will show you exactly where the error was thrown.

As to your objection to this format "jumping around", A) it's what VBA programmers expect, as stated previously, & B) your routines should be short enough that it's not far to jump.

Parsing a comma-delimited std::string

bool GetList (const std::string& src, std::vector<int>& res)
  {
    using boost::lexical_cast;
    using boost::bad_lexical_cast;
    bool success = true;
    typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
    boost::char_separator<char> sepa(",");
    tokenizer tokens(src, sepa);
    for (tokenizer::iterator tok_iter = tokens.begin(); 
         tok_iter != tokens.end(); ++tok_iter) {
      try {
        res.push_back(lexical_cast<int>(*tok_iter));
      }
      catch (bad_lexical_cast &) {
        success = false;
      }
    }
    return success;
  }

How to check if activity is in foreground or in visible background?

One possible solution might be setting a flag while showing the system-dialog and then in the onStop method of the activity life-cycle, check for the flag, if true, finish the activity.

For example, if the system dialog is triggered by some buttonclick, then the onclick listener might be like

private OnClickListener btnClickListener = new OnClickListener() {

    @Override
    public void onClick(View v) {           
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        CheckActivity.this.startActivity(Intent.createChooser(intent, "Complete action using"));
        checkFlag = true;  //flag used to check

    }
};

and in onstop of activity:

@Override
protected void onStop() {
    if(checkFlag){
        finish();
    }
    super.onStop();
}

What is FCM token in Firebase?

FirebaseInstanceIdService is now deprecated. you should get the Token in the onNewToken method in the FirebaseMessagingService.

Check out the docs

mysql server port number

For windows, If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.

How can I split a string into segments of n characters?

If you didn't want to use a regular expression...

var chunks = [];

for (var i = 0, charsLength = str.length; i < charsLength; i += 3) {
    chunks.push(str.substring(i, i + 3));
}

jsFiddle.

...otherwise the regex solution is pretty good :)

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

If you want to use only text while making swipe actions then you can use iOS default swipe actions but if you want image and text, then you have to customize it. I have found a great tutorial and sample that can resolve this problem.

Try out this repository to get the custom swipe cell. You can add multiple option here.

http://iosbucket.blogspot.in/2016/04/custom-swipe-table-view-cell_16.html

https://github.com/pradeep7may/PKSwipeTableViewCell

enter image description here

Git/GitHub can't push to master

The below cmnds will fix the issue.

 git pull --rebase
 git push

Matplotlib scatterplot; colour as a function of a third variable

Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,

  • Plot points corresponding to Physical variable 'A' in RED.
  • Plot points corresponding to Physical variable 'B' in BLUE.
  • Plot points corresponding to Physical variable 'C' in GREEN.

In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.

x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]

# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
    cols=[]
    for l in lst:
        if l=='A':
            cols.append('red')
        elif l=='B':
            cols.append('blue')
        else:
            cols.append('green')
    return cols
# Create the colors list using the function above
cols=pltcolor(x)

plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()

Coloring scatter plot as a function of x variable

How to create an empty matrix in R?

The default for matrix is to have 1 column. To explicitly have 0 columns, you need to write

matrix(, nrow = 15, ncol = 0)

A better way would be to preallocate the entire matrix and then fill it in

mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- vector
}

How to count number of files in each directory?

This can also be done with looping over ls instead of find

for f in */; do echo "$f -> $(ls $f | wc -l)"; done

Explanation:

for f in */; - loop over all directories

do echo "$f -> - print out each directory name

$(ls $f | wc -l) - call ls for this directory and count lines

How to install JQ on Mac by command-line?

The simplest way to install jq and test that it works is through brew and then using the simplest filter that merely formats the JSON

Install

brew is the easiest way to manage packages on a mac:

brew install jq

Need brew? Run the following command:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Failing that: instructions to install and use are on https://brew.sh/

Test

The . filter takes its input and produces it unchanged as output. This is the identity operator. (quote the docs)

echo '{ "name":"John", "age":31, "city":"New York" }' | jq .

The result should appear like so in your terminal:

{
  "name": "John",
  "age": 31,
  "city": "New York"
}

jQuery Datepicker onchange event issue

Try :

$('#idPicker').on('changeDate', function() {
    var date = $('#idPicker').datepicker('getFormattedDate');
});

How to extract filename.tar.gz file

It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.

How can I determine whether a specific file is open in Windows?

Use Process Explorer from the Sysinternals Suite, the Find Handle or DLL function will let you search for the process with that file open.

Can't find/install libXtst.so.6?

Had that issue on Ubuntu 14.04, In my case I had also libXtst.so missing:

Could not open library 'libXtst.so': libXtst.so: cannot open shared object 
file: No such file or directory

Make sure your symbolic link is pointing to proper file, cd /usr/lib/x86_64-linux-gnu and list libXtst with:

 ll |grep libXtst                                                                                                                                                           
 lrwxrwxrwx   1 root root        16 Oct  7  2016 libXtst.so.6 -> libXtst.so.6.1.0
 -rw-r--r--   1 root root     22880 Aug 16  2013 libXtst.so.6.1.0

Then just create proper symbolic link using:

sudo ln -s libXtst.so.6 libXtst.so

List again:

ll | grep libXtst
lrwxrwxrwx   1 root root        12 Sep 20 10:23 libXtst -> libXtst.so.6
lrwxrwxrwx   1 root root        12 Sep 20 10:23 libXtst.so -> libXtst.so.6
lrwxrwxrwx   1 root root        16 Oct  7  2016 libXtst.so.6 -> libXtst.so.6.1.0
-rw-r--r--   1 root root     22880 Aug 16  2013 libXtst.so.6.1.0

all set!

Get current category ID of the active page

The oldest but fastest way you can use is:

$cat_id = get_query_var('cat');

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

Get last 3 characters of string

The easiest way would be using Substring

string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);

Using the overload with one int as I put would get the substring of a string, starting from the index int. In your case being str.Length - 3, since you want to get the last three chars.

Can't escape the backslash with regex?

If you're putting this in a string within a program, you may actually need to use four backslashes (because the string parser will remove two of them when "de-escaping" it for the string, and then the regex needs two for an escaped regex backslash).

For instance:

regex("\\\\")

is interpreted as...

regex("\\" [escaped backslash] followed by "\\" [escaped backslash])

is interpreted as...

regex(\\)

is interpreted as a regex that matches a single backslash.


Depending on the language, you might be able to use a different form of quoting that doesn't parse escape sequences to avoid having to use as many - for instance, in Python:

re.compile(r'\\')

The r in front of the quotes makes it a raw string which doesn't parse backslash escapes.

How to view unallocated free space on a hard disk through terminal

This is an old question, but I wanted to give my answer as well.

Since we're talking about free available space, we should talk about sectors, since no partitioning or sizing of sectors is done.

For us human beings this doesn't make much sense. To have human-readable information we must translate this number into bytes. So, we have a disk already partitioned and we want to know how much space we may use. I personally don't like the parted solution because my brain-memory for commands is already taken. There is also cfdisk, which gives you free space. But I think fdisk is the quickest solution: it's plain and simple, with nothing to install: execute fdisk /dev/sdx and then enter v into the interactive shell. It will gives you the number of sectors still free.

2004-54-0 [17:03:33][root@minimac:~]$> fdisk /dev/sda
Welcome to fdisk (util-linux 2.23.2).
..
Command (m for help): v
Remaining 1713 unallocated 512-byte sectors

We still have 1713 sectors at 512 bytes each. So, because you love terminal (in 2012, who knows now?) we do echo $(((1713*512)/1024))k, which is 1713 sectors multiplied for 512 bytes (divided by 1024 to have KB), which gives 856k.. not even 900 KB.. and I need another disk..

Converting SVG to PNG using C#

When I had to rasterize svgs on the server, I ended up using P/Invoke to call librsvg functions (you can get the dlls from a windows version of the GIMP image editing program).

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetDllDirectory(string pathname);

[DllImport("libgobject-2.0-0.dll", SetLastError = true)]
static extern void g_type_init(); 

[DllImport("librsvg-2-2.dll", SetLastError = true)]
static extern IntPtr rsvg_pixbuf_from_file_at_size(string file_name, int width, int height, out IntPtr error);

[DllImport("libgdk_pixbuf-2.0-0.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
static extern bool gdk_pixbuf_save(IntPtr pixbuf, string filename, string type, out IntPtr error, __arglist);

public static void RasterizeSvg(string inputFileName, string outputFileName)
{
    bool callSuccessful = SetDllDirectory("C:\\Program Files\\GIMP-2.0\\bin");
    if (!callSuccessful)
    {
        throw new Exception("Could not set DLL directory");
    }
    g_type_init();
    IntPtr error;
    IntPtr result = rsvg_pixbuf_from_file_at_size(inputFileName, -1, -1, out error);
    if (error != IntPtr.Zero)
    {
        throw new Exception(Marshal.ReadInt32(error).ToString());
    }
    callSuccessful = gdk_pixbuf_save(result, outputFileName, "png", out error, __arglist(null));
    if (!callSuccessful)
    {
        throw new Exception(error.ToInt32().ToString());
    }
}

Angular 1.6.0: "Possibly unhandled rejection" error

I have observed the same behavior during test execution. It is strange that on production code works fine and fails only on tests.

Easy solution to make your tests happy is to add catch(angular.noop) to your promise mock. In case of example above it should looks like this:

_x000D_
_x000D_
resourceMock.get = function () {_x000D_
    var deferred = $q.defer();_x000D_
    deferred.reject(error);_x000D_
    return { $promise: deferred.promise.catch(angular.noop) };_x000D_
};
_x000D_
_x000D_
_x000D_

jQuery function to get all unique elements from an array?

Walk the array and push items into a hash as you come across them. Cross-reference the hash for each new element.

Note that this will ONLY work properly for primitives (strings, numbers, null, undefined, NaN) and a few objects that serialize to the same thing (functions, strings, dates, possibly arrays depending on content). Hashes in this will collide as they all serialize to the same thing, e.g. "[object Object]"

Array.prototype.distinct = function(){
   var map = {}, out = [];

   for(var i=0, l=this.length; i<l; i++){
      if(map[this[i]]){ continue; }

      out.push(this[i]);
      map[this[i]] = 1;
   }

   return out;
}

There's also no reason you can't use jQuery.unique. The only thing I don't like about it is that it destroys the ordering of your array. Here's the exact code for it if you're interested:

Sizzle.uniqueSort = function(results){
    if ( sortOrder ) {
        hasDuplicate = baseHasDuplicate;
        results.sort(sortOrder);

        if ( hasDuplicate ) {
            for ( var i = 1; i < results.length; i++ ) {
                if ( results[i] === results[i-1] ) {
                    results.splice(i--, 1);
                }
            }
        }
    }

    return results;
};

Formatting floats without trailing zeros

Handling %f and you should put

%.2f

, where: .2f == .00 floats.

Example:

print "Price: %.2f" % prices[product]

output:

Price: 1.50

Spring Data JPA find by embedded object property

If you are using BookId as an combined primary key, then remember to change your interface from:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {

to:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {

And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:

public class QueuedBook implements Serializable {

@EmbeddedId
@NotNull
private BookId bookId;

...

Can't concat bytes to str

subprocess.check_output() returns a bytestring.

In Python 3, there's no implicit conversion between unicode (str) objects and bytes objects. If you know the encoding of the output, you can .decode() it to get a string, or you can turn the \n you want to add to bytes with "\n".encode('ascii')

SQL Server: Attach incorrect version 661

To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.

Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:

SELECT @@VERSION

Number format in excel: Showing % value without multiplying with 100

You just have to change to a Custom format - right click and select format and at the bottom of the list is custom.

 0.00##\%;[Red](0.00##\%)

The first part of custom format is your defined format you posted. Everything after the semicolon is for negative numbers. [RED] tells Excel to make the negative numbers red and the () make sure that negative number is in parentheses.

How to open an existing project in Eclipse?

In case you closed multiple projects and trying to re-open all of them then in Project Explorer, select all projects. Go to Project -> Open Project.

C error: Expected expression before int

By C89, variable can only be defined at the top of a block.

if (a == 1)
    int b = 10;   // it's just a statement, syntacitially error 

if (a == 1)
{                  // refer to the beginning of a local block 
    int b = 10;    // at the top of the local block, syntacitially correct
}                  // refer to the end of a local block

if (a == 1)
{
    func();
    int b = 10;    // not at the top of the local block, syntacitially error, I guess
}

utf-8 special characters not displaying

If all the other answers didn't work for you, try disabling HTTP input encoding translation.

This is a setting related to PHP extension mbstring. This was the problem in my case. This setting was enabled by default in my server.

Not Equal to This OR That in Lua

Your problem stems from a misunderstanding of the or operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1, but I'll go into a little more detail about why your attempted solution doesn't work.

When you read x ~=(0 or 1) or x ~= 0 or 1 it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.

However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or has a lower precedence than ~=, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.

As a result, when evaluating x ~=(0 or 1), the interpreter will first compute 0 or 1 (because of the parentheses) and then x ~= the result of the first computation, and in the second example, it will compute x ~= 0 and then apply the result of that computation to or 1.

The logical operator or "returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~= is the inverse of the equality operator ==; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.

Using these rules, x ~=(0 or 1) will decompose to x ~= 0 (after applying the or operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1 will first evaluate x ~= 0 (which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1 or true or 1. In the first case, the statement will return 1, and in the second case, the statement will return true. Because control structures in Lua only consider nil and false to be false, and anything else to be true, this will always enter the if statement, which is not what you want either.

There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:

if x ~= 1 and x ~= 0 then
    print( "X must be equal to 1 or 0" )
    return
end

Alternatively, you can use a loop to check these values:

local x_is_ok = false
for i = 0,1 do 
    if x == i then
        x_is_ok = true
    end
end
if not x_is_ok then
    print( "X must be equal to 1 or 0" )
    return
end

Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)

if not (x >= 0 and x <= 1 and math.floor(x) == x) then
    print( "X must be equal to 1 or 0" )
    return
end

Note that I wrote x >= 0 and x <= 1. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1, and what this erroneous expression would return!

Removing pip's cache?

On Mac OS (Mavericks), I had to delete /tmp/pip-build/

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Creating a URL in the controller .NET MVC

I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:

var urlHelper = new UrlHelper(this.ControllerContext);

Or, you could just use the Controller.Url property if you inherit from Controller.

Identify duplicate values in a list in Python

You can print duplicate and Unqiue using below logic using list.

def dup(x):
    duplicate = []
    unique = []
    for i in x:
        if i in unique:
            duplicate.append(i)
        else:
            unique.append(i)
    print("Duplicate values: ",duplicate)
    print("Unique Values: ",unique)

list1 = [1, 2, 1, 3, 2, 5]
dup(list1)

How to SELECT by MAX(date)?

Workaround but working solution

Only if ID is autoincrement, you can search for the maximum id instead of the max date. So, by the ID you can find all others fields.

select *
from table
where id IN ( 
              select max(id)
              from table
              group by #MY_FIELD#
              )

Fork() function in C

int a = fork(); 

Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.

The child getting 0 returned, and the parent getting the new pid.

Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.

At each fork, only one value is modified - the return value from fork.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

I have the same exact error message while I was doing my unit test and throwing observable exception after mocking my services.

I resolved it by passing exact function and format inside Observable.throw.

Actual code which calls the service and subscribe to get data. notice that catch to handle the 400 error.

     this.search(event).catch((e: Response) => {
        if (e.status === 400) {
          console.log(e.json().message);
        } else if (e.url) {
          console.log('HTTP Error: ' + e.status + ' ' + e.statusText,
            'URL: ' + e.url, 'Info: ' + e.json().message));
        }
      }).finally(() => {
        this.loading = false;
      }).subscribe((bData) => {
        this.data = bData;
      });

The code inside the service

  search() {
    return this.someService.getData(request)
       .do((r) => {
          this.someService.defaultHeaders.delete('skipAlert');
          return r;
        })
      .map((r) => {
          return r.businessObjectDataElements.length && r.businessObjectDataElements || null;
        });
  }

Unit Testing

I have mocked the SomeService and returning observable data and its fine as it have all the required methods inside it.

 someServiceApi = fixture.debugElement.injector.get(SomeService);
 spyOn(someServiceApi, 'getData').and.returnValue(Observable.of({}));

The above code is okey but when when I was trying to test the catch/error condition by passing Observable.throw({}) it was showing me the error as it was expecting Response type return from the service.

So below service mocking return was giving me that error.

someServiceApi.getData
  .and.returnValue(Observable.throw(new Response({status: 400, body: [], message: 'not found error'})));

So I Corrected it by replicating the exact expected function in my return object rather passing a Response type value.

someServiceApi.getData
  .and.returnValue(Observable.throw({status: 400, json: () => { return {message: 'not found error'}}, body: []}));
// see `json: () => { return {message: 'not found error'}}` inside return value

What is the best way to declare global variable in Vue.js?

I strongly recommend taking a look at Vuex, it is made for globally accessible data in Vue.

If you only need a few base variables that will never be modified, I would use ES6 imports:

// config.js
export default {
   hostname: 'myhostname'
}

// .vue file
import config from 'config.js'

console.log(config.hostname)

You could also import a json file in the same way, which can be edited by people without code knowledge or imported into SASS.

Linux: copy and create destination dir if it does not exist

Simply add the following in your .bashrc, tweak if you need. Works in Ubuntu.

mkcp() {
    test -d "$2" || mkdir -p "$2"
    cp -r "$1" "$2"
}

E.g If you want to copy 'test' file to destination directory 'd' Use,

mkcp test a/b/c/d

mkcp will first check if destination directory exists or not, if not then make it and copy source file/directory.

Convert char array to single int?

There are mulitple ways of converting a string to an int.

Solution 1: Using Legacy C functionality

int main()
{
    //char hello[5];     
    //hello = "12345";   --->This wont compile

    char hello[] = "12345";

    Printf("My number is: %d", atoi(hello)); 

    return 0;
}

Solution 2: Using lexical_cast(Most Appropriate & simplest)

int x = boost::lexical_cast<int>("12345"); 

Solution 3: Using C++ Streams

std::string hello("123"); 
std::stringstream str(hello); 
int x;  
str >> x;  
if (!str) 
{      
   // The conversion failed.      
} 

CSS – why doesn’t percentage height work?

Without content, the height has no value to calculate the percentage of. The width, however, will take the percentage from the DOM, if no parent is specified. (Using your example) Placing the second div inside the first div, would have rendered a result...example below...

<div id="working">
  <div id="not-working"></div>
</div>

The second div would be 30% of the first div's height.

How to show a dialog to confirm that the user wishes to exit an Android Activity?

Using Lambda:

    new AlertDialog.Builder(this).setMessage(getString(R.string.exit_msg))
        .setTitle(getString(R.string.info))
        .setPositiveButton(getString(R.string.yes), (arg0, arg1) -> {
            moveTaskToBack(true);
            finish();
        })
        .setNegativeButton(getString(R.string.no), (arg0, arg1) -> {
        })
        .show();

You also need to set level language to support java 8 in your gradle.build:

compileOptions {
       targetCompatibility 1.8
       sourceCompatibility 1.8
}

How to exit in Node.js

Open the command line terminal where node application is running and press Ctrl + C

if you want to exit a node js application from code,

process.exit(); // graceful termination 
process.exit(1); // non graceful termination