Programs & Examples On #Docx

`.docx` is the file extension for files created using the default format of Microsoft Word 2007 or higher.

Is there a Java API that can create rich Word documents?

In 2007 my project successfully used OpenOffice.org's Universal Network Objects (UNO) interface to programmatically generate MS-Word compatible documents (*.doc), as well as corresponding PDF documents, from a Java Web application (a Struts/JSP framework).

OpenOffice UNO also lets you build MS-Office-compatible charts, spreadsheets, presentations, etc. We were able to dynamically build sophisticated Word documents, including charts and tables.

We simplified the process by using template MS-Word documents with bookmark inserts into which the software inserted content, however, you can build documents completely from scratch. The goal was to have the software generate report documents that could be shared and further tweaked by end-users before converting them to PDF for final delivery and archival.

You can optionally produce documents in OpenOffice formats if you want users to use OpenOffice instead of MS-Office. In our case the users want to use MS-Office tools.

UNO is included within the OpenOffice suite. We simply linked our Java app to UNO-related libraries within the suite. An OpenOffice Software Development Kit (SDK) is available containing example applications and the UNO Developer's Guide.

I have not investigated whether the latest OpenOffice UNO can generate MS-Office 2007 Open XML document formats.

The important things about OpenOffice UNO are:

  1. It is freeware
  2. It supports multiple languages (e.g. Visual Basic, Java, C++, and others).
  3. It is platform-independent (Windows, Linux, Unix, etc.).

Here are some useful web sites:

How do I get milliseconds from epoch (1970-01-01) in Java?

How about System.currentTimeMillis()?

From the JavaDoc:

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

Java 8 introduces the java.time framework, particularly the Instant class which "...models a ... point on the time-line...":

long now = Instant.now().toEpochMilli();

Returns: the number of milliseconds since the epoch of 1970-01-01T00:00:00Z -- i.e. pretty much the same as above :-)

Cheers,

Get the last element of a std::string

In C++11 and beyond, you can use the back member function:

char ch = myStr.back();

In C++03, std::string::back is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator you get back from rbegin:

char ch = *myStr.rbegin();

In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.

Hope this helps!

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

ToolBar's name can easily be changed using

android:label="My Activity"

in your Manifest File. I just going through Manifest & found

android:label 

Helps to change according to the specific activity, Hope you'll give it a try

eloquent laravel: How to get a row count from a ->get()

Answer has been updated

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$wordCount = count($wordlist);

If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();

There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478

However as of now, the query builder always returns an array.

Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->get();
$wordCount = $wordlist->count();

However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:

// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->count();

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();

How do I write a bash script to restart a process if it dies?

if ! test -f $PIDFILE || ! psgrep `cat $PIDFILE`; then
    restart_process
    # Write PIDFILE
    echo $! >$PIDFILE
fi

R not finding package even after package installation

When you run

install.packages("whatever")

you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:

.libPaths()

If libPaths shows 2 locations, then paste into second one. Load library:

library(whatever)

Fixed.

Enabling refreshing for specific html elements only

Try this:

_x000D_
_x000D_
function reload(){_x000D_
    var container = document.getElementById("yourDiv");_x000D_
    var content = container.innerHTML;_x000D_
    container.innerHTML= content; _x000D_
    _x000D_
   //this line is to watch the result in console , you can remove it later _x000D_
    console.log("Refreshed"); _x000D_
}
_x000D_
<a href="javascript: reload()">Click to Reload</a>_x000D_
    <div id="yourDiv">The content that you want to refresh/reload</div>
_x000D_
_x000D_
_x000D_

Hope it works. Let me know

Regex: matching up to the first occurrence of a character

Would;

/^(.*?);/

work?

The ? is a lazy operator, so the regex grabs as little as possible before matching the ;.

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

The Three20 library has a way to do this:

  UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle: @"Title" style:UIBarButtonItemStylePlain 
                                                                target:self action:@selector(foo)];

  UIColor* darkBlue = RGBCOLOR(109, 132, 162);

  TTShapeStyle* style = [TTShapeStyle styleWithShape:[TTRoundedLeftArrowShape shapeWithRadius:4.5] next:
    [TTShadowStyle styleWithColor:RGBCOLOR(255,255,255) blur:1 offset:CGSizeMake(0, 1) next:
    [TTReflectiveFillStyle styleWithColor:darkBlue next:
    [TTBevelBorderStyle styleWithHighlight:[darkBlue shadow]
                                     shadow:[darkBlue multiplyHue:1 saturation:0.5 value:0.5]
                                      width:1 lightSource:270 next:
    [TTInsetStyle styleWithInset:UIEdgeInsetsMake(0, -1, 0, -1) next:
    [TTBevelBorderStyle styleWithHighlight:nil shadow:RGBACOLOR(0,0,0,0.15)
                                        width:1 lightSource:270 next:nil]]]]]];

  TTView* view = [[[TTView alloc] initWithFrame:CGRectMake(0, 0, 80, 35)] autorelease];
  view.backgroundColor = [UIColor clearColor];
  view.style = style;
  backButton.customView = view;


  self.navigationItem.leftBarButtonItem = backButton;

Date format in the json output using spring boot

If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd format you need to specify @JsonFormat above your field on which you want to apply this format.

For Example :

public class Subject {

     private String uid;
     private String number;
     private String initials;

     @JsonFormat(pattern="yyyy-MM-dd")
     private Date dateOfBirth;  

     //Other Code  

}  

From Docs :

annotation used for configuring details of how values of properties are to be serialized.

More Reference Doc

Hope this helps.

How to check if field is null or empty in MySQL?

Either use

SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 
from tablename

or

SELECT case when field1 IS NULL or field1 = ''
            then 'empty'
            else field1
       end as field1 
from tablename

If you only want to check for null and not for empty strings then you can also use ifnull() or coalesce(field1, 'empty'). But that is not suitable for empty strings.

How to get the current date and time

Just construct a new Date object without any arguments; this will assign the current date and time to the new object.

import java.util.Date;

Date d = new Date();

In the words of the Javadocs for the zero-argument constructor:

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

Make sure you're using java.util.Date and not java.sql.Date -- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)

Represent space and tab in XML tag

Illegal XML Tag Name Characters can be encoded using Unicode UCS-2. This works very nicely. I am using it to create XML that gets turned into json (JPath is weak compared to XPath). Notice the handling of spaces, (, ) characters. Unicode UCS-2 Code Chart: http://www.columbia.edu/kermit/ucs2.html

        tag.Name = tag.Name.Replace(" ", "_x005F_x0020_");
        tag.Name = tag.Name.Replace("(", "_x005F_x0028_");
        tag.Name = tag.Name.Replace(")", "_x005F_x0029_");

XML:

  <Internal_x005F_x0020_Chargeback_x005F_x0020_ID>{CHARGEBACKCODE}</Internal_x005F_x0020_Chargeback_x005F_x0020_ID>
  <Bill_x005F_x0020_To>{CHARGEBACKCODE}</Bill_x005F_x0020_To>
  <Operator_x005F_x0020_or_x005F_x0020_Directly_x005F_x0020_Responsible_x005F_x0020_Individual_x005F_x0020__x005F_x0028_DRI_x005F_x0029_>[email protected]</Operator_x005F_x0020_or_x005F_x0020_Directly_x005F_x0020_Responsible_x005F_x0020_Individual_x005F_x0020__x005F_x0028_DRI_x005F_x0029_>

transformed to json via json.net:

    "Internal Chargeback ID": "{CHARGEBACKCODE}",
    "Bill To": "{CHARGEBACKCODE}",
    "Operator or Directly Responsible Individual (DRI)": "[email protected]",

Clearing coverage highlighting in Eclipse

For those using Cobertura and only have the Coverage Session View like I do,just try closing Eclipse and starting it up again. This got rid of the highlighting for me.

Is there a W3C valid way to disable autocomplete in a HTML form?

HTML 4: No

HTML 5: Yes

The autocomplete attribute is an enumerated attribute. The attribute has two states. The on keyword maps to the on state, and the off keyword maps to the off state. The attribute may also be omitted. The missing value default is the on state. The off state indicates that by default, form controls in the form will have their autofill field name set to off; the on state indicates that by default, form controls in the form will have their autofill field name set to "on".

Reference: W3

AddRange to a Collection

Here is a bit more advanced/production-ready version:

    public static class CollectionExtensions
    {
        public static TCol AddRange<TCol, TItem>(this TCol destination, IEnumerable<TItem> source)
            where TCol : ICollection<TItem>
        {
            if(destination == null) throw new ArgumentNullException(nameof(destination));
            if(source == null) throw new ArgumentNullException(nameof(source));

            // don't cast to IList to prevent recursion
            if (destination is List<TItem> list)
            {
                list.AddRange(source);
                return destination;
            }

            foreach (var item in source)
            {
                destination.Add(item);
            }

            return destination;
        }
    }

How to create custom view programmatically in swift having controls text field, button etc

view = MyCustomView(frame: CGRectZero)

In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.

What is object serialization?

|*| Serializing a class : Converting an object to bytes and bytes back to object (Deserialization).

class NamCls implements Serializable
{
    int NumVar;
    String NamVar;
}

|=> Object-Serialization is process of converting the state of an object into steam of bytes.

  • |-> Implement when you want the object to exist beyond the lifetime of the JVM.
  • |-> Serialized Object can be stored in Database.
  • |-> Serializable-objects cannot be read and understood by humans so we can acheive security.

|=> Object-Deserialization is the process of getting the state of an object and store it into an object(java.lang.Object).

  • |-> Before storing its state it checks whether serialVersionUID form input-file/network and .class file serialVersionUID are same.
    &nbsp&nbspIf not throw java.io.InvalidClassException.

|=> A Java object is only serializable, if its class or any of its superclasses

  • implements either the java.io.Serializable interface or
  • its subinterface, java.io.Externalizable.

|=> Static fields in a class cannot be serialized.

class NamCls implements Serializable
{
    int NumVar;
    static String NamVar = "I won't be serializable";;
}

|=> If you do not want to serialise a variable of a class use transient keyword

class NamCls implements Serializable
{
    int NumVar;
    transient String NamVar;
}

|=> If a class implements serializable then all its sub classes will also be serializable.

|=> If a class has a reference of another class, all the references must be Serializable otherwise serialization process will not be performed. In such case,
NotSerializableException is thrown at runtime.

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.

The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.

If this issue is causing serious problems, here are a few things I would suggest:

  • Revert back to JDK 1.7.0_25 until a fix is added to the JDK.

  • Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.

  • Try the JDK early releases as they come out. One of them might fix your problem.

Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.

Get spinner selected items text?

spinner_button.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?>arg0, View view, int arg2, long arg3) {

            String selected_val=spinner_button.getSelectedItem().toString();

            Toast.makeText(getApplicationContext(), selected_val ,
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

}

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

How do I get the current date in JavaScript?

The shortest possible.

To get format like "2018-08-03":

_x000D_
_x000D_
let today = new Date().toISOString().slice(0, 10)_x000D_
_x000D_
console.log(today)
_x000D_
_x000D_
_x000D_

To get format like "8/3/2018":

_x000D_
_x000D_
let today = new Date().toLocaleDateString()_x000D_
_x000D_
console.log(today)
_x000D_
_x000D_
_x000D_

Also, you can pass locale as argument, for example toLocaleDateString("sr"), etc.

No Android SDK found - Android Studio

Right now, the last version of Android Studio bundled (Windows IDE bundle with SDK (64-bit)) with Android SDK is version 2.3.3:

https://developer.android.com/studio/archive.html#android-studio-2-3-3

which size is about 2GB.

You can use it and then upgrade to the latest version of Android Studio.

Best way to store data locally in .NET (C#)

My first inclination is an access database. The .mdb files are stored locally, and can be encrypted if that is deemed necessary. Though XML or JSON would also work for many scenarios. Flat files I would only use for read only, non-search (forward read only) information. I tend to prefer csv format to set width.

MongoDB SELECT COUNT GROUP BY

Mongo shell command that worked for me:

db.getCollection(<collection_name>).aggregate([{"$match": {'<key>': '<value to match>'}}, {"$group": {'_id': {'<group_by_attribute>': "$group_by_attribute"}}}])

Change key pair for ec2 instance

Thanks for the tips guys. Will definitely keep them in mind when I need to rest the key pairs. However, in the interest of efficiency and laziness I've come up with something else:

  1. Create your new key pair and download the credentials
  2. Right-click your instance > Create AMI Once it is done
  3. terminate your instance (or just stop it until you are sure you can create another one from your new shiny AMI)
  4. Start a new EC2 instance from the AMI you just created and specify your new key pair created in step (1) above.

Hope this can be of use to you and save you some time as well as minimize the amount of white hair you get from stuff like this :)

Can't update data-attribute value

If we wanted to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

JavaScript

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>

Through jQuery

// Fetching data
var fruitCount = $(this).data('fruit');

// Above does not work in firefox. So use below to get attribute value.
var fruitCount = $(this).attr('data-fruit');

// Assigning data
$(this).data('fruit','7');

// But when you get the value again, it will return old value. 
// You have to set it as below to update value. Then you will get updated value.
$(this).attr('data-fruit','7'); 

Read this documentation for vanilla js or this documentation for jquery

Nested or Inner Class in PHP

Real nested classes with public/protected/private accessibility were proposed in 2013 for PHP 5.6 as an RFC but did not make it (No voting yet, no update since 2013 - as of 2021/02/03):

https://wiki.php.net/rfc/nested_classes

class foo {
    public class bar {
 
    }
}

At least, anonymous classes made it into PHP 7

https://wiki.php.net/rfc/anonymous_classes

From this RFC page:

Future Scope

The changes made by this patch mean named nested classes are easier to implement (by a tiny bit).

So, we might get nested classes in some future version, but it's not decided yet.

How do I return multiple values from a function in C?

Option 1: Declare a struct with an int and string and return a struct variable.

struct foo {    
 int bar1;
 char bar2[MAX];
};

struct foo fun() {
 struct foo fooObj;
 ...
 return fooObj;
}

Option 2: You can pass one of the two via pointer and make changes to the actual parameter through the pointer and return the other as usual:

int fun(char **param) {
 int bar;
 ...
 strcpy(*param,"....");
 return bar;
}

or

 char* fun(int *param) {
 char *str = /* malloc suitably.*/
 ...
 strcpy(str,"....");
 *param = /* some value */
 return str;
}

Option 3: Similar to the option 2. You can pass both via pointer and return nothing from the function:

void fun(char **param1,int *param2) {
 strcpy(*param1,"....");
 *param2 = /* some calculated value */
}

Spring MVC Missing URI template variable

@PathVariable is used to tell Spring that part of the URI path is a value you want passed to your method. Is this what you want, or are the variables supposed to be form data posted to the URI?

If you want form data, use @RequestParam instead of @PathVariable.

If you want @PathVariable, you need to specify placeholders in the @RequestMapping entry to tell Spring where the path variables fit in the URI. For example, if you want to extract a path variable called contentId, you would use:

@RequestMapping(value = "/whatever/{contentId}", method = RequestMethod.POST)

Edit: Additionally, if your path variable could contain a '.' and you want that part of the data, then you will need to tell Spring to grab everything, not just the stuff before the '.':

@RequestMapping(value = "/whatever/{contentId:.*}", method = RequestMethod.POST)

This is because the default behaviour of Spring is to treat that part of the URL as if it is a file extension, and excludes it from variable extraction.

HTML5 input type range show range value

version with editable input:

<form>
    <input type="range" name="amountRange" min="0" max="20" value="0" oninput="this.form.amountInput.value=this.value" />
    <input type="number" name="amountInput" min="0" max="20" value="0" oninput="this.form.amountRange.value=this.value" />
</form>

http://jsfiddle.net/Xjxe6/

how to check for special characters php

<?php

$string = 'foo';

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
    // one or more of the 'special characters' found in $string
}

Get changes from master into branch in Git

Scenario :

  • I created a branch from master say branch-1 and pulled it to my local.
  • My Friend created a branch from master say branch-2.
  • He committed some code changes to master.
  • Now I want to take those changes from master branch to my local branch.

Solution

git stash // to save all existing changes in local branch
git checkout master // Switch to master branch from branch-1
git pull // take changes from the master
git checkout branch-1 // switchback to your own branch
git rebase master // merge all the changes and move you git head  forward
git stash apply // reapply all you saved changes 

You can find conflicts on your file after executing "git stash apply". You need to fix it manually and now you are ready to push.

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

A simple inline JavaScript confirm would suffice:

<form onsubmit="return confirm('Do you really want to submit the form?');">

No need for an external function unless you are doing validation, which you can do something like this:

<script>
function validate(form) {

    // validation code here ...


    if(!valid) {
        alert('Please correct the errors in the form!');
        return false;
    }
    else {
        return confirm('Do you really want to submit the form?');
    }
}
</script>
<form onsubmit="return validate(this);">

Establish a VPN connection in cmd

Have you looked into rasdial?

Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network

ie rasdial "VPN NETWORK NAME" "Username" *

it will then prompt for a password, else you can use "username" "password", this is however less secure

http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

How to grep for multiple strings in file on different lines (Use the pipe symbol):

for file in *;do 
   test $(grep -E 'Dansk|Norsk|Svenska' $file | wc -l) -ge 3 && echo $file
done

Notes:

  1. If you use double quotes "" with your grep, you will have to escape the pipe like this: \| to search for Dansk, Norsk and Svenska.

  2. Assumes that one line has only one language.

Walkthrough: http://www.cyberciti.biz/faq/howto-use-grep-command-in-linux-unix/

How to enable scrolling of content inside a modal?

.modal-body {
    max-height: 80vh;
    overflow-y: scroll;
}

it's works for me

MS Access DB Engine (32-bit) with Office 64-bit

If both versions of Microsoft Access Database Engine 2010 can't coexists, then your only solution is to complain to Microsoft, regarding loading 64 bits versions of this in your 32 bits app is impossible directly, what you can do is a service that runs in 64 bits that comunicates with another 32 bits service or your application via pipes or networks sockets, but it may require a significant effort.

Variable might not have been initialized error

It's a good practice to initialize the local variables inside the method block before using it. Here is a mistake that a beginner may commit.

  public static void main(String[] args){
    int a;
    int[] arr = {1,2,3,4,5};
    for(int i=0; i<arr.length; i++){
        a = arr[i];
    }
    System.out.println(a);
  }

You may expect the console will show '5' but instead the compiler will throw 'variable a might not be initialized' error. Though one may think variable a is 'initialized' inside the for loop, the compiler does not think in that way. What if arr.length is 0? The for loop will not be run at all. Hence, the compiler will give variable a might not have been initialized to point out the potential danger and require you to initialize the variable.

To prevent this kind of error, just initialize the variable when you declare it.

int a = 0;

addEventListener for keydown on Canvas

encapsulate all of your js code within a window.onload function. I had a similar issue. Everything is loaded asynchronously in javascript so some parts load quicker than others, including your browser. Putting all of your code inside the onload function will ensure everything your code will need from the browser will be ready to use before attempting to execute.

Passing arguments to C# generic new() of templated type

Object initializer

If your constructor with the parameter isn't doing anything besides setting a property, you can do this in C# 3 or better using an object initializer rather than calling a constructor (which is impossible, as has been mentioned):

public static string GetAllItems<T>(...) where T : new()
{
   ...
   List<T> tabListItems = new List<T>();
   foreach (ListItem listItem in listCollection) 
   {
       tabListItems.Add(new T() { YourPropertyName = listItem } ); // Now using object initializer
   } 
   ...
}

Using this, you can always put any constructor logic in the default (empty) constructor, too.

Activator.CreateInstance()

Alternatively, you could call Activator.CreateInstance() like so:

public static string GetAllItems<T>(...) where T : new()
{
   ...
   List<T> tabListItems = new List<T>();
   foreach (ListItem listItem in listCollection) 
   {
        object[] args = new object[] { listItem };
        tabListItems.Add((T)Activator.CreateInstance(typeof(T), args)); // Now using Activator.CreateInstance
   } 
   ...
}

Note that Activator.CreateInstance can have some performance overhead that you may want to avoid if execution speed is a top priority and another option is maintainable to you.

PHP Warning: PHP Startup: Unable to load dynamic library

After Windows 10 XAMPP now I installed LAMPP (XAMPP) on Ubuntu. Windows XAMPP had a lot less to configure compare to MAC (iOS) but now with Linux Ubuntu I had a few more since there are more going in Linux (a good thing).

I confused and activated mysqli.dll (and mysql.dll: erase "#" in /etc/php/7.2/cli/php.ini

I started to get the PHP Warning: PHP Startup: Unable to load dynamic library message related to dll. I commented out mysql(and i).dll in the same file but the message didn't go away up until I commented out " " in /opt/lampp/etc/php.ini.

Looks like XAMPP reads php.ini file from /etc/php/7.2/cli and makes modification in php.ini of /opt/lampp/etc. (;extension=php_pdo_mysql.dll after ";" restarted Apache and no more any message.

Sending commands and strings to Terminal.app with Applescript

set up passwordless ssh (ssh-keygen, then add the key to ~/.ssh/authorized_keys on the server). Make an entry in ~/.ssh/config (on your desktop), so that when you run ssh mysqlserver, it goes to user@hostname... Or make a shell alias, like gotosql, that expands to ssh user@host -t 'mysql_client ...' to start the mysql client interactively on the server.

Then you probably do need someone else's answer to script the process after that, since I don't know how to set startup commands for mysql.

At least that keeps your ssh password out of the script!

How to calculate the inverse of the normal cumulative distribution function in python?

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

It can be used to get the inverse cumulative distribution function (inv_cdf - inverse of the cdf), also known as the quantile function or the percent-point function for a given mean (mu) and standard deviation (sigma):

from statistics import NormalDist

NormalDist(mu=10, sigma=2).inv_cdf(0.95)
# 13.289707253902943

Which can be simplified for the standard normal distribution (mu = 0 and sigma = 1):

NormalDist().inv_cdf(0.95)
# 1.6448536269514715

how to setup ssh keys for jenkins to publish via ssh

You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.

Step 1, generate public and private key on build server as user jenkins

build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): 
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...] 
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw-------  1 jenkins  jenkins  1679 Feb 28 11:55 id_rsa
-rw-r--r--  1 jenkins  jenkins   411 Feb 28 11:55 id_rsa.pub 
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]

Step 2, paste the pub file contents onto the target server.

target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)

Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644

Step 3, configure Jenkins

  1. In the jenkins web control panel, nagivate to "Manage Jenkins" -> "Configure System" -> "Publish over SSH"
  2. Either enter the path of the file e.g. "var/lib/jenkins/.ssh/id_rsa", or paste in the same content as on the target server.
  3. Enter your passphrase, server and user details, and you are good to go!

update query with join on two tables

Try this one

UPDATE employee 
set EMPLOYEE.MAIDEN_NAME = 
  (SELECT ADD1 
   FROM EMPS 
   WHERE EMP_CODE=EMPLOYEE.EMP_CODE);
WHERE EMPLOYEE.EMP_CODE >='00' 
AND EMPLOYEE.EMP_CODE <='ZZ';

"Data too long for column" - why?

Turns out, as is often the case, it was a stupid error on my part. The way I was testing this, I wasn't rebuilding the Department table after changing the data type from varchar(50) to varchar(200); I was just re-running the insert command, still with the column as varchar(50).

Java: notify() vs. notifyAll() all over again

All the above answers are correct, as far as I can tell, so I'm going to tell you something else. For production code you really should use the classes in java.util.concurrent. There is very little they cannot do for you, in the area of concurrency in java.

error 1265. Data truncated for column when trying to load data from txt file

You're missing FIELDS TERMINATED BY ',' and it's assuming you're delimiting by tabs by default.

disable editing default value of text input

You can either use the readonly or the disabled attribute. Note that when disabled, the input's value will not be submitted when submitting the form.

<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">

MySQL DROP all tables, ignoring foreign keys

This is a pretty old post, but none of the answers here really answered the question in my opinion, so I hope my post will help people!

I found this solution on another question that works really well for me:

mysql -Nse 'show tables' DB_NAME | while read table; do mysql -e "SET FOREIGN_KEY_CHECKS=0; truncate table \`$table\`" DB_NAME; done

That will actually empty all your tables in the database DB_NAME, and not only display the TRUNCATE command line.

Hope this helps!

How long will my session last?

You're searching for gc_maxlifetime, see http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime for a description.

Your session will last 1440 seconds which is 24 minutes (default).

Give all permissions to a user on a PostgreSQL database

GRANT ALL PRIVILEGES ON DATABASE "my_db" to my_user;

c#: getter/setter

Those are Auto-Implemented Properties (Auto Properties for short).

The compiler will auto-generate the equivalent of the following simple implementation:

private string _type;

public string Type
{
    get { return _type; }
    set { _type = value; }
}

How to perform an SQLite query within an Android application?

Alternatively, db.rawQuery(sql, selectionArgs) exists.

Cursor c = db.rawQuery(select, null);

How can I make the browser wait to display the page until it's fully loaded?

I know this is an old thread, but still. Another simple option is this library: http://gayadesign.com/scripts/queryLoader2/

jQuery - Follow the cursor with a DIV

You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

$(document).on('mousemove', function(e){
    $('#your_div_id').css({
       left:  e.pageX,
       top:   e.pageY
    });
});

That div must be off the float, so position: absolute should be set.

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

****Following solution is working for me**** Manually deleted all files from C:\Users\Admin.gradle\wrapper\dists\

where Admin is my user name

Determining whether an object is a member of a collection in VBA

For the case when key is unused for collection:

Public Function Contains(col As Collection, thisItem As Variant) As   Boolean

  Dim item As Variant

  Contains = False
  For Each item In col
    If item = thisItem Then
      Contains = True
      Exit Function
    End If
  Next
End Function

pandas: How do I split text in a column into multiple rows?

Another approach would be like this:

temp = df['Seatblocks'].str.split(' ')
data = data.reindex(data.index.repeat(temp.apply(len)))
data['new_Seatblocks'] = np.hstack(temp)

More than 1 row in <Input type="textarea" />

Although <input> ignores the rows attribute, you can take advantage of the fact that <textarea> doesn't have to be inside <form> tags, but can still be a part of a form by referencing the form's id:

<form method="get" id="testformid">
    <input type="submit" />
</form> 
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>

Of course, <textarea> now appears below "submit" button, but maybe you'll find a way to reposition it.

Get record counts for all tables in MySQL database

I just run:

show table status;

This will give you the row count for EVERY table plus a bunch of other info. I used to use the selected answer above, but this is much easier.

I'm not sure if this works with all versions, but I'm using 5.5 with InnoDB engine.

Xcode Debugger: view value of variable

You can print values onto console window at run-time. Below are steps :

  1. Place a break-point for which you want to get values
  2. Now perform step-by-step debug.
  3. Place a cursor on variable/delegate whose value is to be checked at run-time.
  4. Now this will show description of variable/delegate
  5. Clicking on "i" will show detailed description
  6. This will also print details onto console window.

Screenshot for printing details on console window

Column count doesn't match value count at row 1

You can resolve the error by providing the column names you are affecting.

> INSERT INTO table_name (column1,column2,column3)
 `VALUES(50,'Jon Snow','Eye');`

please note that the semi colon should be added only after the statement providing values

How to set up Android emulator proxy settings

Sometime even after setting all it may not work. I have tried all the methods like

  1. Setting the proxy in Emulator APN
  2. Setting it thru eclipse preferences --> Android --> Launch

Nothing worked. Then I did the following which worked instantly.

Goto eclipse Run --> run configurations. Under Android Applications you can see you application. Now, on the right hand side click on the Target tab. Under the 'Additional Emulator Command line options' add the following.

-dns-server <DNS servers from your local machine upto three> -http-proxy http://<your proxy>:<your proxy port>

The catch here is that the DNS Server setting should be from your local system. Goto cmd prompt and run ipconfig to check your DNS servers. Same with the proxy server and port. Whatever works for your browser should be put in here.

Converting Integers to Roman Numerals - Java

I think if you study the theory of roman numerals carefully you don't require mappings for numbers 4,9,40 etc because the theory tells us if the roman numeral is IV = 5-1 = 4, hence when the prefix is smaller than the succeeding number in that case you have to subtract the former number from the succeeding number to get the actual value and this is what I have incorporated into my code for the problem, take a look and point out any mistakes if necessary, I followed this table to devise my logic - http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm

import java.util.Set;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;

public class RomanStringToIntegerConversion {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)));
        String[] romanString = br.readLine().split("");

        HashMap<String, Integer> romanToIntegerMap = new HashMap<String, Integer>();
        romanToIntegerMap.put("I", 1);
        romanToIntegerMap.put("V", 5);
        romanToIntegerMap.put("X", 10);
        romanToIntegerMap.put("L", 50);
        romanToIntegerMap.put("C", 100);
        romanToIntegerMap.put("D", 500);
        romanToIntegerMap.put("M", 1000);

        int numLength = romanString.length;
        Set<Integer> lessIndices = new HashSet<Integer>();

        for(int i = 0; i < numLength; ++i){
            if(i+1 < numLength){
                if(romanToIntegerMap.get(romanString[i]) < romanToIntegerMap.get(romanString[i+1]))
                    lessIndices.add(i);
            }
        }

        int num = 0;
        for(int i = 0; i < numLength;){
            if(!lessIndices.contains(i)){
                num = num + romanToIntegerMap.get(romanString[i]);
                ++i;
            }
            else{
                num = num + romanToIntegerMap.get(romanString[i+1]) - romanToIntegerMap.get(romanString[i]);
                i+=2;
            }
        }
        System.out.println("The integer representation of the roman numeral is : " + num);
    }
}

What do the makefile symbols $@ and $< mean?

The Makefile builds the hello executable if any one of main.cpp, hello.cpp, factorial.cpp changed. The smallest possible Makefile to achieve that specification could have been:

hello: main.cpp hello.cpp factorial.cpp
    g++ -o hello main.cpp hello.cpp factorial.cpp
  • pro: very easy to read
  • con: maintenance nightmare, duplication of the C++ dependencies
  • con: efficiency problem, we recompile all C++ even if only one was changed

To improve on the above, we only compile those C++ files that were edited. Then, we just link the resultant object files together.

OBJECTS=main.o hello.o factorial.o

hello: $(OBJECTS)
    g++ -o hello $(OBJECTS)

main.o: main.cpp
    g++ -c main.cpp

hello.o: hello.cpp
    g++ -c hello.cpp

factorial.o: factorial.cpp
    g++ -c factorial.cpp
  • pro: fixes efficiency issue
  • con: new maintenance nightmare, potential typo on object files rules

To improve on this, we can replace all object file rules with a single .cpp.o rule:

OBJECTS=main.o hello.o factorial.o

hello: $(OBJECTS)
    g++ -o hello $(OBJECTS)

.cpp.o:
    g++ -c $< -o $@
  • pro: back to having a short makefile, somewhat easy to read

Here the .cpp.o rule defines how to build anyfile.o from anyfile.cpp.

  • $< matches to first dependency, in this case, anyfile.cpp
  • $@ matches the target, in this case, anyfile.o.

The other changes present in the Makefile are:

  • Making it easier to changes compilers from g++ to any C++ compiler.
  • Making it easier to change the compiler options.
  • Making it easier to change the linker options.
  • Making it easier to change the C++ source files and output.
  • Added a default rule 'all' which acts as a quick check to ensure all your source files are present before an attempt to build your application is made.

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

In my case, I had to create a new app, reinstall my node packages, and copy my src document over. That worked.

"CSV file does not exist" for a filename with embedded quotes

Had an issue with the path, it turns out that you need to specify the first '/' to get it to work! I am using VSCode/Python on macOS

Rename multiple files in a folder, add a prefix (Windows)

Free Software 'Bulk Rename Utility' also works well (and is powerful for advanced tasks also). Download and installation takes a minute.

See screenshots and tutorial on original website.

--

I cannot provide step-by-step screenshots as the images will have to be released under Creative Commons License, and I do not own the screenshots of the software.

Disclaimer: I am not associated with the said software/company in any way. I liked the product for my own task, it serves OP's and similar requirements, thus recommending.

How should you diagnose the error SEHException - External component has thrown an exception

I got this error while running unit tests on inmemory caching I was setting up. It flooded the cache. After invalidating the cache and restarting the VM, it worked fine.

python setup.py uninstall

For me, the following mostly works:

have pip installed, e.g.:

$ easy_install pip

Check, how is your installed package named from pip point of view:

$ pip freeze

This shall list names of all packages, you have installed (and which were detected by pip). The name can be sometime long, then use just the name of the package being shown at the and after #egg=. You can also in most cases ignore the version part (whatever follows == or -).

Then uninstall the package:

$ pip uninstall package.name.you.have.found

If it asks for confirmation about removing the package, then you are lucky guy and it will be removed.

pip shall detect all packages, which were installed by pip. It shall also detect most of the packages installed via easy_install or setup.py, but this may in some rare cases fail.

Here is real sample from my local test with package named ttr.rdstmc on MS Windows.

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev

$ python setup.py develop
.....
.....
Finished processing dependencies for ttr.rdstmc==0.0.1dev

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
-e hg+https://[email protected]/vlcinsky/ttr.rdstmc@d61a9922920c508862602f7f39e496f7b99315f0#egg=ttr.rdstmc-dev
ttr.utcutils==0.1.1dev

$ pip uninstall ttr.rdstmc
Uninstalling ttr.rdstmc:
  c:\python27\lib\site-packages\ttr.rdstmc.egg-link
Proceed (y/n)? y
  Successfully uninstalled ttr.rdstmc

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev

Edit 2015-05-20

All what is written above still applies, anyway, there are small modifications available now.

Install pip in python 2.7.9 and python 3.4

Recent python versions come with a package ensurepip allowing to install pip even when being offline:

$ python -m ensurepip --upgrade

On some systems (like Debian Jessie) this is not available (to prevent breaking system python installation).

Using grep or find

Examples above assume, you have grep installed. I had (at the time I had MS Windows on my machine) installed set of linux utilities (incl. grep). Alternatively, use native MS Windows find or simply ignore that filtering and find the name in a bit longer list of detected python packages.

git push rejected

First use

git pull https://github.com/username/repository master

and then try

git push -u origin master

How to split a large text file into smaller files with equal number of lines?

split the file "file.txt" into 10000 lines files:

split -l 10000 file.txt

How can I increment a char?

For me i made the fallowing as a test.

string_1="abcd"

def test(string_1):
   i = 0
   p = ""
   x = len(string_1)
   while i < x:
    y = (string_1)[i]
    i=i+1
    s = chr(ord(y) + 1)
    p=p+s

   print(p)

test(string_1)

CSS Inset Borders

I know this is three years old, but thought it might be helpful to someone.

The concept is to use the :after (or :before) selector to position a border within the parent element.

    .container{
        position:relative; /*Position must be set to something*/
    }

    .container:after{
        position:relative;
        top: 0;
        content:"";
        left:0;
        height: 100%; /*Set pixel height and width if not defined in parent element*/
        width: 100%; 

        -webkit-box-sizing:border-box;
        -moz-box-sizing:border-box;
        -ms-box-sizing:border-box;
        box-sizing:border-box;

        border:1px solid #000; /*set your border style*/

    }

Python - OpenCV - imread - Displaying Image

This can help you

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image );                   // Show our image inside it.

Failed to install Python Cryptography package with PIP and setup.py

Those two commands fixed it for me:

brew install openssl
brew link openssl --force

Source: https://github.com/phusion/passenger/issues/1630#issuecomment-147527656

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

Yes. As many have previously pointed out, I have added the src path to all the controller files in the index.html.

_x000D_
_x000D_
<script src="controllers/home.js"></script>_x000D_
<script src="controllers/detail.js"></script>_x000D_
<script src="controllers/login.js"></script>_x000D_
<script src="controllers/navbar.js"></script>_x000D_
<script src="controllers/signup.js"></script>
_x000D_
_x000D_
_x000D_

This fixed that error.

Print Currency Number Format in PHP

I built this little function to automatically format anything into a nice currency format.

function formatDollars($dollars)
{
    return "$".number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)),2);
}

Edit

It was pointed out that this does not show negative values. I broke it into two lines so it's easier to edit the formatting. Wrap it in parenthesis if it's a negative value:

function formatDollars($dollars)
{
    $formatted = "$" . number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)), 2);
    return $dollars < 0 ? "({$formatted})" : "{$formatted}";
}

.toLowerCase not working, replacement function?

Numbers inherit from the Number constructor which doesn't have the .toLowerCase method. You can look it up as a matter of fact:

"toLowerCase" in Number.prototype; // false

How to dismiss the dialog with click on outside of the dialog?

Or, if you're customizing the dialog using a theme defined in your style xml, put this line in your theme:

<item name="android:windowCloseOnTouchOutside">true</item>

python: get directory two levels up

You can use pathlib. Unfortunately this is only available in the stdlib for Python 3.4. If you have an older version you'll have to install a copy from PyPI here. This should be easy to do using pip.

from pathlib import Path

p = Path(__file__).parents[1]

print(p)
# /absolute/path/to/two/levels/up

This uses the parents sequence which provides access to the parent directories and chooses the 2nd one up.

Note that p in this case will be some form of Path object, with their own methods. If you need the paths as string then you can call str on them.

How to remove newlines from beginning and end of a string?

tl;dr

String cleanString = dirtyString.strip() ; // Call new `String::string` method.

String::strip…

The old String::trim method has a strange definition of whitespace.

As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.

Example code.

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");

Or you can strip just the leading or just the trailing whitespace.

You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
  • It is '\t', U+0009 HORIZONTAL TABULATION.
  • It is '\n', U+000A LINE FEED.
  • It is '\u000B', U+000B VERTICAL TABULATION.
  • It is '\f', U+000C FORM FEED.
  • It is '\r', U+000D CARRIAGE RETURN.
  • It is '\u001C', U+001C FILE SEPARATOR.
  • It is '\u001D', U+001D GROUP SEPARATOR.
  • It is '\u001E', U+001E RECORD SEPARATOR.
  • It is '\u001F', U+0

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

I was getting this error today. And above answers didn't help me. I was getting this error when I try to start the SQL Server(SQLEXPRESS) service in Services(services.msc).

When I checked the error log at the location C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\Log, there was an entry related TCP/IP port.

2018-06-19 20:41:52.20 spid12s TDSSNIClient initialization failed with error 0x271d, status code 0xa. Reason: Unable to initialize the TCP/IP listener. An attempt was made to access a socket in a way forbidden by its access permissions.

Recently I was running a MSSQLEXPRESS image in my docker container, which was using the same TCP/IP port, that caused this issue.

enter image description here

So, what I did is, I just reset my TCP/IP by doing the below command.

netsh int ip reset resetlog.txt

enter image description here

Once the resetting is done, I had to restart the machine and when I try to start the SQLEXPRESS service again, it started successfully. Hope it helps.

Installing TensorFlow on Windows (Python 3.6.x)

For someone w/ TF 1.3:

Current TensorFlow 1.3 support Python 3.6, and then you need cuDNN 6 (cudnn64_6.dll)

Based on Tensorflow on windows - ImportError: DLL load failed: The specified module could not be found and this: https://github.com/tensorflow/tensorflow/issues/7705

Remove an entire column from a data.frame in R

You can set it to NULL.

> Data$genome <- NULL
> head(Data)
   chr region
1 chr1    CDS
2 chr1   exon
3 chr1    CDS
4 chr1   exon
5 chr1    CDS
6 chr1   exon

As pointed out in the comments, here are some other possibilities:

Data[2] <- NULL    # Wojciech Sobala
Data[[2]] <- NULL  # same as above
Data <- Data[,-2]  # Ian Fellows
Data <- Data[-2]   # same as above

You can remove multiple columns via:

Data[1:2] <- list(NULL)  # Marek
Data[1:2] <- NULL        # does not work!

Be careful with matrix-subsetting though, as you can end up with a vector:

Data <- Data[,-(2:3)]             # vector
Data <- Data[,-(2:3),drop=FALSE]  # still a data.frame

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I had the same issue for my angular project, then I make it work in Chrome by changing the setting. Go to Chrome setting -->site setting -->Insecure content --> click add button of allow, then add your domain name [*.]XXXX.biz

Now problem will be solved.

How to add border around linear layout except at the bottom?

Kenny is right, just want to clear some things out.

  1. Create the file border.xml and put it in the folder res/drawable/
  2. add the code

    <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
       <stroke android:width="4dp" android:color="#FF00FF00" /> 
       <solid android:color="#ffffff" /> 
       <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
       <corners android:radius="4dp" /> 
    </shape>
    
  3. set back ground like android:background="@drawable/border" wherever you want the border

Mine first didn't work cause i put the border.xml in the wrong folder!

How to read a PEM RSA private key from .NET

With respect to easily importing the RSA private key, without using 3rd party code such as BouncyCastle, I think the answer is "No, not with a PEM of the private key alone."

However, as alluded to above by Simone, you can simply combine the PEM of the private key (*.key) and the certificate file using that key (*.crt) into a *.pfx file which can then be easily imported.

To generate the PFX file from the command line:

openssl pkcs12 -in a.crt -inkey a.key -export -out a.pfx

Then use normally with the .NET certificate class such as:

using System.Security.Cryptography.X509Certificates;

X509Certificate2 combinedCertificate = new X509Certificate2(@"C:\path\to\file.pfx");

Now you can follow the example from MSDN for encrypting and decrypting via RSACryptoServiceProvider:

I left out that for decrypting you would need to import using the PFX password and the Exportable flag. (see: BouncyCastle RSAPrivateKey to .NET RSAPrivateKey)

X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;
X509Certificate2 cert = new X509Certificate2("my.pfx", "somepass", flags);

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
RSAParameters rsaParam = rsa.ExportParameters(true); 

How to iterate over a TreeMap?

Assuming type TreeMap<String,Integer> :

for(Map.Entry<String,Integer> entry : treeMap.entrySet()) {
  String key = entry.getKey();
  Integer value = entry.getValue();

  System.out.println(key + " => " + value);
}

(key and Value types can be any class of course)

Eclipse can't find / load main class

Standard troubleshooting steps for Eclipse should include deleting and re-importing the project at some point, which when I have dealt with this error has worked.

Static linking vs dynamic linking

One reason to do a statically linked build is to verify that you have full closure for the executable, i.e. that all symbol references are resolved correctly.

As a part of a large system that was being built and tested using continuous integration, the nightly regression tests were run using a statically linked version of the executables. Occasionally, we would see that a symbol would not resolve and the static link would fail even though the dynamically linked executable would link successfully.

This was usually occurring when symbols that were deep seated within the shared libs had a misspelt name and so would not statically link. The dynamic linker does not completely resolve all symbols, irrespective of using depth-first or breadth-first evaluation, so you can finish up with a dynamically linked executable that does not have full closure.

Explanation of the UML arrows

The accepted answer being said, It is missing some explanations. For example, what is the difference between a uni-directional and a bi-directional association? In the provided example, both do exist. ( Both '5's in the arrows)

If looking for a more complete answer and have more time, here is a thorough explanation.

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

HTTP Basic Authentication credentials passed in URL and encryption

Yes, it will be encrypted.

You'll understand it if you simply check what happens behind the scenes.

  1. The browser or application will first break down the URL and try to get the IP of the host using a DNS Query. ie: A DNS request will be made to find the IP address of the domain (www.example.com). Please note that no other information will be sent via this request.
  2. The browser or application will initiate a SSL connection with the IP address received from the DNS request. Certificates will be exchanged and this happens at the transport level. No application level information will be transferred at this point. Remember that the Basic authentication is part of HTTP and HTTP is an application level protocol. Not a transport layer task.
  3. After establishing the SSL connection, now the necessary data will be passed to the server. ie: The path or the URL, the parameters and basic authentication username and password.

Detect if the app was launched/opened from a push notification

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
    print("Push notification received: \(data)")

    if let info = data["aps"] as? Dictionary<String, AnyObject> {
        let alertMsg = info["alert"] as! String
        print(alertMsg)
        switch application.applicationState {
        case .active:
            print("do stuff in case App is active")
        case .background:
            print("do stuff in case App is in background")
           // navigateToChatDetailViewControler(pushdata: data)
        case .inactive:
            print("do stuff in case App is inactive")
            // navigateToChatDetailViewControler(pushdata: data)
        }
    }
}

Remove space above and below <p> tag HTML

In case anyone wishes to do this with bootstrap, version 4 offers the following:

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Where property is one of:

m - for classes that set margin
p - for classes that set padding

Where sides is one of:

t - for classes that set margin-top or padding-top
b - for classes that set margin-bottom or padding-bottom
l - for classes that set margin-left or padding-left
r - for classes that set margin-right or padding-right
x - for classes that set both *-left and *-right
y - for classes that set both *-top and *-bottom
blank - for classes that set a margin or padding on all 4 sides of the element

Where size is one of:

0 - for classes that eliminate the margin or padding by setting it to 0
1 - (by default) for classes that set the margin or padding to $spacer * .25
2 - (by default) for classes that set the margin or padding to $spacer * .5
3 - (by default) for classes that set the margin or padding to $spacer
4 - (by default) for classes that set the margin or padding to $spacer * 1.5
5 - (by default) for classes that set the margin or padding to $spacer * 3
auto - for classes that set the margin to auto

For example:

.mt-0 {
  margin-top: 0 !important;
}

.ml-1 {
  margin-left: ($spacer * .25) !important;
}

.px-2 {
  padding-left: ($spacer * .5) !important;
  padding-right: ($spacer * .5) !important;
}

.p-3 {
  padding: $spacer !important;
}

Reference: https://getbootstrap.com/docs/4.0/utilities/spacing/

how to filter out a null value from spark dataframe

Another easy way to filter out null values from multiple columns in spark dataframe. Please pay attention there is AND between columns.

df.filter(" COALESCE(col1, col2, col3, col4, col5, col6) IS NOT NULL")

If you need to filter out rows that contain any null (OR connected) please use

df.na.drop()

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

jQuery checkbox checked state changed event

This is the solution to find is the checkbox is checked or not. Use the #prop() function//

$("#c_checkbox").on('change', function () {
                    if ($(this).prop('checked')) {
                        // do stuff//
                    }
                });

Get height and width of a layout programmatically

As CapDroid say, you are trying to get the size before the view drawn, another possible solution could be to do a Post with a runnable on the View:

mView.post(new Runnable() {
        @Override
        public void run() {
            int width = mView.getWidth();
            int height = mView.getHeight();
        }
}

Cross browser JavaScript (not jQuery...) scroll to top animation

Linear scrolling animation to bottom. Pure JS, no JQuery. Maybe my solution will be helpful for someone.

let action_count = 8;
let speed_ms = 15;
let objDiv = document.getElementsByClassName('js_y5_area3').item(0);

let scroll_height = objDiv.scrollHeight;
let window_height = objDiv.offsetHeight;

let scroll_top = objDiv.scrollTop;
let need_scroll_top = scroll_height - window_height;

if (scroll_top < need_scroll_top)
{
    let step = Math.ceil((need_scroll_top - scroll_top) / action_count);

    let scrollInterval = setInterval(function()
    {
        scroll_top += step;
        objDiv.scrollTop = scroll_top;

        if (scroll_top >= need_scroll_top)
        {
            clearInterval(scrollInterval);
        }

    }, speed_ms);
}

You can change variables action_count, speed_ms to configure scrolling animation on your taste.

Swift apply .uppercaseString to only the first letter of a string

extension String {
    func firstCharacterUpperCase() -> String? {
        let lowercaseString = self.lowercaseString

        return lowercaseString.stringByReplacingCharactersInRange(lowercaseString.startIndex...lowercaseString.startIndex, withString: String(lowercaseString[lowercaseString.startIndex]).uppercaseString)
    }
}

let x = "heLLo"
let m = x.firstCharacterUpperCase()

For Swift 5:

extension String {
    func firstCharacterUpperCase() -> String? {
        guard !isEmpty else { return nil }
        let lowerCasedString = self.lowercased()
        return lowerCasedString.replacingCharacters(in: lowerCasedString.startIndex...lowerCasedString.startIndex, with: String(lowerCasedString[lowerCasedString.startIndex]).uppercased())
    }
}

sed with literal string--not input file

Works like you want:

echo "A,B,C" | sed s/,/\',\'/g

Switching users inside Docker image to a non-root user

In case you need to perform privileged tasks like changing permissions of folders you can perform those tasks as a root user and then create a non-privileged user and switch to it:

From <some-base-image:tag>

# Switch to root user
USER root # <--- Usually you won't be needed it - Depends on base image

# Run privileged command
RUN apt install <packages>
RUN apt <privileged command>

# Set user and group
ARG user=appuser
ARG group=appuser
ARG uid=1000
ARG gid=1000
RUN groupadd -g ${gid} ${group}
RUN useradd -u ${uid} -g ${group} -s /bin/sh -m ${user} # <--- the '-m' create a user home directory

# Switch to user
USER ${uid}:${gid}

# Run non-privileged command
RUN apt <non-privileged command>

store return value of a Python script in a bash script

In addition to what Tichodroma said, you might end up using this syntax:

outputString=$(python myPythonScript arg1 arg2 arg3)

How to start debug mode from command prompt for apache tomcat server?

On windows
$ catalina.bat jpda start
On Linux/Unix
$ catalina.sh jpda start

More info ----> https://cwiki.apache.org/confluence/display/TOMCAT/Developing

How to add jQuery code into HTML Page

I would recommend to call the script like this

...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</body>

The js and css files must be treat differently

Put jquery as the first before other JS scripts at the bottom of <BODY> tag

  • The problem caused is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname.
  • So select 2 (two) most important scripts on your page like analytic and pixel script on the <head> tags and let the rest including the jquery to be called on the bottom <body> tag.

Put CSS style on top of <HEAD> tag after the other more priority tags

  • Moving style sheets to the document HEAD makes pages appear to be loading faster. This is because putting style sheets in the HEAD allows the page to render progressively.
  • So for css sheets, it is better to put them all on the <head> tag but let the style that shall be immediately rendered to be put in <style> tags inside <HEAD> and the rest in <body>.

You may also find other suggestion when you test your page like on Google PageSpeed Insight

Where in an Eclipse workspace is the list of projects stored?

In Eclipse 3.3:

It's installed under your Eclipse workspace. Something like:

.metadata\.plugins\org.eclipse.core.resources\.projects\

within your workspace folder.

Under that folder is one folder per project. There's a file in there called .location, but it's binary.

So it looks like you can't do what you want, without interacting w/ Eclipse programmatically.

Setting equal heights for div's with jQuery

You need this:

$('.container').each(function(){  
     var $columns = $('.column',this);
     var maxHeight = Math.max.apply(Math, $columns.map(function(){
         return $(this).height();
     }).get());
     $columns.height(maxHeight);
});

Explanation

  • The following snippet constructs an array of the heights:

    $columns.map(function(){
        return $(this).height();
    }).get()
    
  • Math.max.apply( Math, array ) finds the maximum of array items

  • $columns.height(maxHeight); sets all columns' height to maximum height.

Live demo

How to import JsonConvert in C# application?

Or if you're using dotnet Core,

add to your .csproj file

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
  </ItemGroup>

And

dotnet restore

Get a list of dates between two dates using a function

This query works on Microsoft SQL Server.

select distinct format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) as aDate
       from (
             SELECT ones.n + 10 * tens.n + 100 * hundreds.n + 1000 * thousands.n as v
             FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
                    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
                    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
                  (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
       ) a
       where format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) < cast('2010-01-13' as datetime)
       order by aDate asc;

Now let's look at how it works.

The inner query merely returns a list of integers from 0 to 9999. It will give us a range of 10,000 values for calculating dates. You can get more dates by adding rows for ten_thousands and hundred_thousands and so forth.

SELECT ones.n + 10 * tens.n + 100 * hundreds.n + 1000 * thousands.n as v
         FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
                (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
                (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
              (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
   ) a;

This part converts the string to a date and adds a number to it from the inner query.

cast('2010-01-01' as datetime) + ( a.v / 10 )

Then we convert the result into the format you want. This is also the column name!

format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' )

Next we extract only the distinct values and give the column name an alias of aDate.

distinct format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) as aDate

We use the where clause to filter in only dates within the range you want. Notice that we use the column name here since SQL Server does not accept the column alias, aDate, within the where clause.

where format( cast('2010-01-01' as datetime) + ( a.v / 10 ), 'yyyy-MM-dd' ) < cast('2010-01-13' as datetime)

Lastly, we sort the results.

   order by aDate asc;

Promise Error: Objects are not valid as a React child

You can't do this: {this.state.arrayFromJson} As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map to do that.

I am pasting a link from where you can learn how to render elements from an array with React.

http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/

Hope it helps!

Dependent DLL is not getting copied to the build output folder in Visual Studio

NO NEED FOR DUMMY IN CODE
Just :

add a Reference to the Executeable Project

or/and ensure that the reference in the executeable project has "Copy Local" set to TRUE (which was my "fault") is seems that this "overwrote" the setting in the base referenced library-project...

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

How to check that an element is in a std::set?

I use

if(!my_set.count(that_element)) //Element is present...
;

But it is not as efficient as

if(my_set.find(that_element)!=my_set.end()) ....;

My version only saves my time in writing the code. I prefer it this way for competitive coding.

How to convert timestamps to dates in Bash?

I use this cross-platform one-liner:

date -d @1267619929 2>/dev/null || date -r 1267619929

It should work in both macOS and later versions of popular Linux distributions.

Connecting to Microsoft SQL server using Python

I tried to connect sql server in following ways and those worked for me.

To connect using windows authentication

import pyodbc

conn = pyodbc.connect('Driver={SQL Server};Server='+servername+';Trusted_Connection=yes;Database='+databasename+';')
cursor = conn.cursor()
cursor.execute("Select 1 as Data")

To use sql server authentication I used following code.

import pyodbc

conn = pyodbc.connect('Driver={SQL Server};Server='+servername+  ';UID='+userid+';PWD='+password+';Database='+databasename) 
cursor1 = conn.cursor()
cursor1.execute("SELECT 1 AS DATA")

How to send push notification to web browser?

You can push data from the server to the browser via Server Side Events. This is essentially a unidirectional stream that a client can "subscribe" to from a browser. From here, you could just create new Notification objects as SSEs stream into the browser:

var source = new EventSource('/events');

source.on('message', message => {
  var notification = new Notification(message.title, {
    body: message.body
  });
}); 

A bit old, but this article by Eric Bidelman explains the basics of SSE and provides some server code examples as well.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I was having the same problem.Turns out my Node.js was outdated. After upgrading it's working.

Importing a CSV file into a sqlite3 database table using Python

You're right that .import is the way to go, but that's a command from the SQLite3.exe shell. A lot of the top answers to this question involve native python loops, but if your files are large (mine are 10^6 to 10^7 records), you want to avoid reading everything into pandas or using a native python list comprehension/loop (though I did not time them for comparison).

For large files, I believe the best option is to create the empty table in advance using sqlite3.execute("CREATE TABLE..."), strip the headers from your CSV files, and then use subprocess.run() to execute sqlite's import statement. Since the last part is I believe the most pertinent, I will start with that.

subprocess.run()

from pathlib import Path
db_name = Path('my.db').resolve()
csv_file = Path('file.csv').resolve()
result = subprocess.run(['sqlite3',
                         str(db_name),
                         '-cmd',
                         '.mode csv',
                         '.import '+str(csv_file).replace('\\','\\\\')
                                 +' <table_name>'],
                        capture_output=True)

Explanation
From the command line, the command you're looking for is sqlite3 my.db -cmd ".mode csv" ".import file.csv table". subprocess.run() runs a command line process. The argument to subprocess.run() is a sequence of strings which are interpreted as a command followed by all of it's arguments.

  • sqlite3 my.db opens the database
  • -cmd flag after the database allows you to pass multiple follow on commands to the sqlite program. In the shell, each command has to be in quotes, but here, they just need to be their own element of the sequence
  • '.mode csv' does what you'd expect
  • '.import '+str(csv_file).replace('\\','\\\\')+' <table_name>' is the import command.
    Unfortunately, since subprocess passes all follow-ons to -cmd as quoted strings, you need to double up your backslashes if you have a windows directory path.

Stripping Headers

Not really the main point of the question, but here's what I used. Again, I didn't want to read the whole files into memory at any point:

with open(csv, "r") as source:
    source.readline()
    with open(str(csv)+"_nohead", "w") as target:
        shutil.copyfileobj(source, target)

Single line sftp from terminal

Or echo 'put {path to file}' | sftp {user}@{host}:{dir}, which would work in both unix and powershell.

Undo a merge by pull request?

If the pull was the last thing he did then

git reset --hard HEAD~1

Delete with "Join" in Oracle sql Query

Use a subquery in the where clause. For a delete query requirig a join, this example will delete rows that are unmatched in the joined table "docx_document" and that have a create date > 120 days in the "docs_documents" table.

delete from docs_documents d
where d.id in (
    select a.id from docs_documents a
    left join docx_document b on b.id = a.document_id
    where b.id is null
        and floor(sysdate - a.create_date) > 120
 );

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

brew switch openssl 1.0.2s

worked for me on "macOS Mojave", "version 10.14.6".

How comment a JSP expression?

Pure JSP comments look like this:

<%-- Comment --%>

So if you want to retain the "=".you could do something like:

<%--= map.size() --%>

The key thing is that <%= defines the beginning of an expression, in which you can't leave the body empty, but you could do something like this instead if the pure JSP comment doesn't appeal to you:

<% /*= map.size()*/ %>

Code Conventions for the JavaServer Pages Technology Version 1.x Language has details about the different commenting options available to you (but has a complete lack of link targets, so I can't link you directly to the relevant section - boo!)

How open PowerShell as administrator from the run window

Yes, it is possible to run PowerShell through the run window. However, it would be burdensome and you will need to enter in the password for computer. This is similar to how you will need to set up when you run cmd:

runas /user:(ComputerName)\(local admin) powershell.exe

So a basic example would be:

runas /user:MyLaptop\[email protected]  powershell.exe

You can find more information on this subject in Runas.

However, you could also do one more thing :

  • 1: `Windows+R`
  • 2: type: `powershell`
  • 3: type: `Start-Process powershell -verb runAs`

then your system will execute the elevated powershell.

How to get the scroll bar with CSS overflow on iOS

::-webkit-scrollbar {
    width: 15px;
    height: 15px;
}

::-webkit-scrollbar-thumb {
    border-radius: 8px;
    background-color: #C3C3C3;
    border: 2px solid #eee;
}

Use this code, it work in ios/android APP webview; It delete some not portable css code;

How to find the length of a string in R

You could also use the stringr package:

library(stringr)
str_length("foo")
[1] 3

AngularJS resource promise

If you're looking to get promise in resource call, you should use

Regions.query().$q.then(function(){ .... })

Update : the promise syntax is changed in current versions which reads

Regions.query().$promise.then(function(){ ..... })

Those who have downvoted don't know what it was and who first added this promise to resource object. I used this feature in late 2012 - yes 2012.

Setting environment variables for accessing in PHP when using Apache

Unbelievable, but on httpd 2.2 on centos 6.4 this works.

Export env vars in /etc/sysconfig/httpd

export mydocroot=/var/www/html

Then simply do this...

<VirtualHost *:80>
  DocumentRoot ${mydocroot}
</VirtualHost>

Then finally....

service httpd restart;

Eclipse and Windows newlines

You could give it a try. The problem is that Windows inserts a carriage return as well as a line feed when given a new line. Unix-systems just insert a line feed. So the extra carriage return character could be the reason why your eclipse messes up with the newlines.

Grab one or two files from your project and convert them. You could use Notepad++ to do so. Just open the file, go to Format->Convert to Unix (when you are using windows).

In Linux just try this on a command line:

sed 's/$'"/`echo \\\r`/" yourfile.java > output.java

Char array declaration and initialization in C

That's because your first code snippet is not performing initialization, but assignment:

char myarray[4] = "abc";  // Initialization.

myarray = "abc";          // Assignment.

And arrays are not directly assignable in C.

The name myarray actually resolves to the address of its first element (&myarray[0]), which is not an lvalue, and as such cannot be the target of an assignment.

Converting NSString to NSDictionary / JSON

Use this code where str is your JSON string:

NSError *err = nil;
NSArray *arr = 
 [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:NSJSONReadingMutableContainers 
                                   error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
  // do something using dictionary
}

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

For Me adding few below line in WebApi.config works as after updating the new nuget package did not works out

var setting = config.Formatters.JsonFormatter.SerializerSettings;
setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
setting.Formatting = Formatting.Indented;

Don't forget to add namespace:

using Newtonsoft.Json.Serialization; 
using Newtonsoft.Json;

git ahead/behind info between master and branch?

First of all to see how many revisions you are behind locally, you should do a git fetch to make sure you have the latest info from your remote.

The default output of git status tells you how many revisions you are ahead or behind, but usually I find this too verbose:

$ git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 1 different commit each, respectively.
#
nothing to commit (working directory clean)

I prefer git status -sb:

$ git status -sb
## master...origin/master [ahead 2, behind 1]

In fact I alias this to simply git s, and this is the main command I use for checking status.

To see the diff in the "ahead revisions" of master, I can exclude the "behind revisions" from origin/master:

git diff master..origin/master^

To see the diff in the "behind revisions" of origin/master, I can exclude the "ahead revisions" from master:

git diff origin/master..master^^

If there are 5 revisions ahead or behind it might be easier to write like this:

git diff master..origin/master~5
git diff origin/master..master~5

UPDATE

To see the ahead/behind revisions, the branch must be configured to track another branch. For me this is the default behavior when I clone a remote repository, and after I push a branch with git push -u remotename branchname. My version is 1.8.4.3, but it's been working like this as long as I remember.

As of version 1.8, you can set the tracking branch like this:

git branch --track test-branch

As of version 1.7, the syntax was different:

git branch --set-upstream test-branch

Can comments be used in JSON?

If your text file, which is a JSON string, is going to be read by some program, how difficult would it be to strip out either C or C++ style comments before using it?

Answer: It would be a one liner. If you do that then JSON files could be used as configuration files.

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

String whole = "something";
String first = whole.substring(0, 1);
System.out.println(first);

HTML5 Canvas Resize (Downscale) Image High Quality?

I found a solution that doesn't need to access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.

The drawImage() function is using a linear-interpolation, nearest-neighbor resampling method. That works well when you are not resizing down more than half the original size.

If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.

This function downsample to half at a time until reaching the desired size:

  function resize_image( src, dst, type, quality ) {
     var tmp = new Image(),
         canvas, context, cW, cH;

     type = type || 'image/jpeg';
     quality = quality || 0.92;

     cW = src.naturalWidth;
     cH = src.naturalHeight;

     tmp.src = src.src;
     tmp.onload = function() {

        canvas = document.createElement( 'canvas' );

        cW /= 2;
        cH /= 2;

        if ( cW < src.width ) cW = src.width;
        if ( cH < src.height ) cH = src.height;

        canvas.width = cW;
        canvas.height = cH;
        context = canvas.getContext( '2d' );
        context.drawImage( tmp, 0, 0, cW, cH );

        dst.src = canvas.toDataURL( type, quality );

        if ( cW <= src.width || cH <= src.height )
           return;

        tmp.src = dst.src;
     }

  }
  // The images sent as parameters can be in the DOM or be image objects
  resize_image( $( '#original' )[0], $( '#smaller' )[0] );

How can I disable editing cells in a WPF Datagrid?

The DataGrid has an XAML property IsReadOnly that you can set to true:

<my:DataGrid
    IsReadOnly="True"
/>

How to efficiently count the number of keys/properties of an object in JavaScript?

Here are some performance tests for three methods;

https://jsperf.com/get-the-number-of-keys-in-an-object

Object.keys().length

20,735 operations per second

Very simple and compatible. Runs fast but expensive because it creates a new array of keys, which that then gets thrown away.

return Object.keys(objectToRead).length;

loop through the keys

15,734 operations per second

let size=0;
for(let k in objectToRead) {
  size++
}
return size;

Slightly slower, but nowhere near the memory usage, so probably better if you're interested in optimising for mobile or other small machines

Using Map instead of Object

953,839,338 operations per second

return mapToRead.size;

Basically, Map tracks its own size so we're just returning a number field. Far, far faster than any other method. If you have control of the object, convert them to maps instead.

max(length(field)) in mysql

SELECT  name, LENGTH(name) AS mlen
FROM    mytable
ORDER BY
        mlen DESC
LIMIT 1

Mapping composite keys using EF code first

For Mapping Composite primary key using Entity framework we can use two approaches.

1) By Overriding the OnModelCreating() Method

For ex: I have the model class named VehicleFeature as shown below.

public class VehicleFeature
{
    public int VehicleId { get; set; }
    public int FeatureId{get;set;}
    public Vehicle Vehicle{get;set;}
    public Feature Feature{get;set;}
}

The Code in my DBContext would be like ,

public class VegaDbContext : DbContext
{
    public DbSet<Make> Makes{get;set;}

    public DbSet<Feature> Features{get;set;}
    public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)        
    {           

    }
    // we override the OnModelCreating method here.
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
    }
}

2) By Data Annotations.

public class VehicleFeature
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    [Key]
    public int VehicleId { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]   
    [Key]
    public int FeatureId{get;set;}
    public Vehicle Vehicle{get;set;}
    public Feature Feature{get;set;}
}

Please refer the below links for the more information.

1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx

2) How to add a composite unique key using EF 6 Fluent Api?

How to check if variable's type matches Type stored in a variable

GetType() exists on every single framework type, because it is defined on the base object type. So, regardless of the type itself, you can use it to return the underlying Type

So, all you need to do is:

u.GetType() == t

JavaScript Loading Screen while page loads

You can wait until the body is ready:

_x000D_
_x000D_
function onReady(callback) {_x000D_
  var intervalId = window.setInterval(function() {_x000D_
    if (document.getElementsByTagName('body')[0] !== undefined) {_x000D_
      window.clearInterval(intervalId);_x000D_
      callback.call(this);_x000D_
    }_x000D_
  }, 1000);_x000D_
}_x000D_
_x000D_
function setVisible(selector, visible) {_x000D_
  document.querySelector(selector).style.display = visible ? 'block' : 'none';_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
  setVisible('.page', true);_x000D_
  setVisible('#loading', false);_x000D_
});
_x000D_
body {_x000D_
  background: #FFF url("https://i.imgur.com/KheAuef.png") top left repeat-x;_x000D_
  font-family: 'Alex Brush', cursive !important;_x000D_
}_x000D_
_x000D_
.page    { display: none; padding: 0 0.5em; }_x000D_
.page h1 { font-size: 2em; line-height: 1em; margin-top: 1.1em; font-weight: bold; }_x000D_
.page p  { font-size: 1.5em; line-height: 1.275em; margin-top: 0.15em; }_x000D_
_x000D_
#loading {_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  z-index: 100;_x000D_
  width: 100vw;_x000D_
  height: 100vh;_x000D_
  background-color: rgba(192, 192, 192, 0.5);_x000D_
  background-image: url("https://i.stack.imgur.com/MnyxU.gif");_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>_x000D_
<link href="https://fonts.googleapis.com/css?family=Alex+Brush" rel="stylesheet">_x000D_
<div class="page">_x000D_
  <h1>The standard Lorem Ipsum passage</h1>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
<div id="loading"></div>
_x000D_
_x000D_
_x000D_

Here is a JSFiddle that demonstrates this technique.

Convert String to double in Java

You only need to parse String values using Double

String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);

How to enumerate a range of numbers starting at 1

As you already mentioned, this is straightforward to do in Python 2.6 or newer:

enumerate(range(2000, 2005), 1)

Python 2.5 and older do not support the start parameter so instead you could create two range objects and zip them:

r = xrange(2000, 2005)
r2 = xrange(1, len(r) + 1)
h = zip(r2, r)
print h

Result:

[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

If you want to create a generator instead of a list then you can use izip instead.

Border around specific rows in a table?

Here's an approach using tbody elements that could be the way to do it. You can't set the border on a tbody (same as you can't on a tr) but you can set the background colour. If the effect you're wanting to acheive can be obtained with a background colour on the groups of rows instead of a border this will work.

<table cellspacing="0">  
    <tbody>
        <tr>    
            <td>no border</td>    
            <td>no border here either</td>  
        </tr>  
    <tbody bgcolor="gray">
        <tr>    
            <td>one</td>    
            <td>two</td>  
        </tr>  
        <tr>    
            <td>three</td>    
            <td>four</td>  
        </tr>  
    <tbody>
        <tr>    
             <td colspan="2">once again no borders</td>  
        </tr>  
    <tbody bgcolor="gray">
        <tr>    
             <td colspan="2">hello</td>  
        </tr>
    <tbody>
    <tr>    
         <td colspan="2">world</td>  
    </tr>
</table>

How do you automatically set text box to Uppercase?

As nobody suggested it:

If you want to use the CSS solution with lowercase placeholders, you just have to style the placeholders separately. Split the 2 placeholder styles for IE compatibility.

_x000D_
_x000D_
input {_x000D_
    text-transform: uppercase;_x000D_
}_x000D_
input:-ms-input-placeholder {_x000D_
    text-transform: none;_x000D_
}_x000D_
input::placeholder {_x000D_
    text-transform: none;_x000D_
}
_x000D_
The below input has lowercase characters, but all typed characters are CSS-uppercased :<br/>_x000D_
<input type="text" placeholder="ex : ABC" />
_x000D_
_x000D_
_x000D_

Python Flask, how to set content type

from flask import Flask, render_template, make_response
app = Flask(__name__)

@app.route('/user/xml')
def user_xml():
    resp = make_response(render_template('xml/user.html', username='Ryan'))
    resp.headers['Content-type'] = 'text/xml; charset=utf-8'
    return resp

How to use subList()

You could use streams in Java 8. To always get 10 entries at the most, you could do:

dataList.stream().skip(5).limit(10).collect(Collectors.toList());
dataList.stream().skip(30).limit(10).collect(Collectors.toList());

The APK file does not exist on disk

Click this option to solve the error:

Run: View > Tool Windows > Gradle > [project] > Tasks > build > build

Regex Match all characters between two strings

This worked for me (I'm using VS Code):

for: This is just\na simple sentence

Use: This .+ sentence

How to build and run Maven projects after importing into Eclipse IDE

answer 1

  1. Right click on your project in eclipse
  2. go to maven -> Update Project

answer 2

simply press Alt+F5 after updating your pom.xml. This will build your project again and download all jar files

How to open link in new tab on html?

If you would like to make the command once for your entire site, instead of having to do it after every link. Try this place within the Head of your web site and bingo.

<head>
<title>your text</title>
<base target="_blank" rel="noopener noreferrer">
</head>

hope this helps

scale Image in an UIButton to AspectFit?

1 - clear Button default text (important)

2 - set alignment like image

3 - set content mode like image

enter image description here

Exception from HRESULT: 0x800A03EC Error

Go to Excel Options > Save > Save Files in this format > Select "Excel Workbook(*.xlsx)". This problem occurs if you are using an older version of excel file (.xls) instead of .xlsx. The older version does not allow more than 65k rows in the excel sheet.

Once you have saved as .xslx, try executing your code again.

edit ----

Looking more into your problem, it seems that the problem might be locale specific. Does the code work on another machine? What value does the cell have? Is it datetime format? Have a look here:

http://support.microsoft.com/kb/320369

http://blogs.msdn.com/b/eric_carter/archive/2005/06/15/429515.aspx

SQL grouping by month and year

SELECT CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4)) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada 
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4))

Or as @40-Love mentioned you can cast with leading zeroes:

GROUP BY 
  CAST(YEAR(date) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH(date) AS VARCHAR(2)), 2) 

How to make modal dialog in WPF?

Window.Show will show the window, and continue execution -- it's a non-blocking call.

Window.ShowDialog will block the calling thread (kinda [1]), and show the dialog. It will also block interaction with the parent/owning window. When the dialog is dismissed (for whatever reason), ShowDialog will return to the caller, and will allow you to access DialogResult (if you want it).

[1] It will keep the dispatcher pumping by pushing a dispatcher frame onto the WPF dispatcher. This will cause the message pump to keep pumping.

key_load_public: invalid format

The error is misleading - it says "pubkey" while pointing to a private key file ~/.ssh/id_rsa.

In my case, it was simply a missing public key (as I haven't restored it from a vault).


DETAILS

I used to skip deploying ~/.ssh/id_rsa.pub by automated scripts.

All ssh usages worked, but the error made me think of a possible mess.

Not at all - strace helped to notice that the trigger was actually the *.pub file:

strace ssh example.com
...
openat(AT_FDCWD, "/home/uvsmtid/.ssh/id_rsa.pub", O_RDONLY) = -1 ENOENT (No such file or directory)
...
write(2, "load pubkey \"/home/uvsmtid/.ssh/"..., 57) = 57
load pubkey "/home/uvsmtid/.ssh/id_rsa": invalid format

Stick button to right side of div

Another solution: change margins. Depending on the siblings of the button, display should be modified.

button {
    display:      block;
    margin-left:  auto;
    margin-right: 0;
}

Pan & Zoom Image

To zoom relative to the mouse position, all you need is:

var position = e.GetPosition(image1);
image1.RenderTransformOrigin = new Point(position.X / image1.ActualWidth, position.Y / image1.ActualHeight);

How to perform a for loop on each character in a string in Bash?

I've only tested this with ascii strings, but you could do something like:

while test -n "$words"; do
   c=${words:0:1}     # Get the first character
   echo character is "'$c'"
   words=${words:1}   # trim the first character
done

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

appending array to FormData and send via AJAX

I've fixed the typescript version. For javascript, just remove type definitions.

  _getFormDataKey(key0: any, key1: any): string {
    return !key0 ? key1 : `${key0}[${key1}]`;
  }
  _convertModelToFormData(model: any, key: string, frmData?: FormData): FormData {
    let formData = frmData || new FormData();

    if (!model) return formData;

    if (model instanceof Date) {
      formData.append(key, model.toISOString());
    } else if (model instanceof Array) {
      model.forEach((element: any, i: number) => {
        this._convertModelToFormData(element, this._getFormDataKey(key, i), formData);
      });
    } else if (typeof model === 'object' && !(model instanceof File)) {
      for (let propertyName in model) {
        if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
        this._convertModelToFormData(model[propertyName], this._getFormDataKey(key, propertyName), formData);
      }
    } else {
      formData.append(key, model);
    }

    return formData;
  }

How do you access the matched groups in a JavaScript regular expression?

_x000D_
_x000D_
var myString = "something format_abc";_x000D_
var arr = myString.match(/\bformat_(.*?)\b/);_x000D_
console.log(arr[0] + " " + arr[1]);
_x000D_
_x000D_
_x000D_

The \b isn't exactly the same thing. (It works on --format_foo/, but doesn't work on format_a_b) But I wanted to show an alternative to your expression, which is fine. Of course, the match call is the important thing.

Wireshark vs Firebug vs Fiddler - pros and cons?

Wireshark, Firebug, Fiddler all do similar things - capture network traffic.

  • Wireshark captures any kind of network packet. It can capture packet details below TCP/IP (HTTP is at the top). It does have filters to reduce the noise it captures.

  • Firebug tracks each request the browser page makes and captures the associated headers and the time taken for each stage of the request (DNS, receiving, sending, ...).

  • Fiddler works as an HTTP/HTTPS proxy. It captures every HTTP request the computer makes and records everything associated with it. It does allow things like converting post variables to a table form and editing/replaying requests. It doesn't, by default, capture localhost traffic in IE, see the FAQ for the workaround.

Where does PHP's error log reside in XAMPP?

Look in your configuration file and search for the error_log setting. Or use phpinfo() to find this setting.

Error pushing to GitHub - insufficient permission for adding an object to repository database

OK - turns out it was a permissions problem on GitHub that happened during the fork of emi/bixo to bixo/bixo. Once Tekkub fixed these, it started working again.

Deep cloning objects

The best is to implement an extension method like

public static T DeepClone<T>(this T originalObject)
{ /* the cloning code */ }

and then use it anywhere in the solution by

var copy = anyObject.DeepClone();

We can have the following three implementations:

  1. By Serialization (the shortest code)
  2. By Reflection - 5x faster
  3. By Expression Trees - 20x faster

All linked methods are well working and were deeply tested.

setTimeout / clearTimeout problems

Practical example Using Jquery for a dropdown menu ! On mouse over on #IconLoggedinUxExternal shows div#ExternalMenuLogin and set time out to hide the div#ExternalMenuLogin

On mouse over on div#ExternalMenuLogin it cancels the timeout. On mouse out on div#ExternalMenuLogin it sets the timeout.

The point here is always to invoke clearTimeout before set the timeout, as so, avoiding double calls

var ExternalMenuLoginTO;
$('#IconLoggedinUxExternal').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
    $("#ExternalMenuLogin").show()
});

$('#IconLoggedinUxExternal').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )    
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,1000
    );
    $("#ExternalMenuLogin").show()
});

$('#ExternalMenuLogin').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
});
$('#ExternalMenuLogin').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,500
    );
});

How do I select child elements of any depth using XPath?

Also, you can do it with css selectors:

form#myform input[type='submit']

space beween elements in css elector means searching input[type='submit'] that elements at any depth of parent form#myform element

PHP Warning: Invalid argument supplied for foreach()

You should check that what you are passing to foreach is an array by using the is_array function

If you are not sure it's going to be an array you can always check using the following PHP example code:

if (is_array($variable)) {

  foreach ($variable as $item) {
   //do something
  }
}

Get UTC time in seconds

I believe +%s is seconds since epoch. It's timezone invariant.

error: command 'gcc' failed with exit status 1 while installing eventlet

Your install is failing because you don't have the python development headers installed. You can do this through apt on ubuntu/debian with:

sudo apt-get install python-dev 

for python3 use:

sudo apt-get install python3-dev

For eventlet you might also need the libevent libraries installed so if you get an error talking about that you can install libevent with:

sudo apt-get install libevent-dev

What is "pom" packaging in maven?

I suggest to see the classic example at: http://maven.apache.org/guides/getting-started/index.html#How_do_I_build_more_than_one_project_at_once

Here my-webapp is web project, which depends on the code at my-app project. So to bundle two projects in one, we have top level pom.xml which mentions which are the projects (modules as per maven terminology) to be bundled finally. Such top level pom.xml can use pom packaging.

my-webapp can have war packaging and can have dependency on my-app. my-app can have jar packaging.

Can you have multiline HTML5 placeholder text in a <textarea>?

If you're using AngularJS, you can simply use braces to place whatever you'd like in it: Here's a fiddle.

<textarea rows="6" cols="45" placeholder="{{'Address Line1\nAddress Line2\nCity State, Zip\nCountry'}}"></textarea>

limit text length in php and provide 'Read more' link

I Guess this will help you fix your problem please check under given Function : trims text to a space then adds ellipses if desired

  • @param string $input text to trim

    • @param int $length in characters to trim to
    • @param bool $ellipses if ellipses (...) are to be added
    • @param bool $strip_html if html tags are to be stripped
    • @return string

      function trim_text($input, $length, $ellipses = true, $strip_html = true) {
      //strip tags, if desired
      if ($strip_html) {
          $input = strip_tags($input);
      }//no need to trim, already shorter than trim length
      if (strlen($input) <= $length) {
          return $input;
      }
      
      //find last space within length
      $last_space = strrpos(substr($input, 0, $length), ' ');
      $trimmed_text = substr($input, 0, $last_space);
      
      //add ellipses (...)
      if ($ellipses) {
          $trimmed_text .= '...';
      }
      
      return $trimmed_text;}
      

how to set start value as "0" in chartjs?

If you need use it as a default configuration, just place min: 0 inside the node defaults.scale.ticks, as follows:

defaults: {
  global: {...},
  scale: {
    ...
    ticks: { min: 0 },
  }
},

Reference: https://www.chartjs.org/docs/latest/axes/

Angular 2.0 router not working on reloading the browser

For those of us struggling through life in IIS: use the following PowerShell code to fix this issue based on the official Angular 2 docs (that someone posted in this thread? http://blog.angular-university.io/angular2-router/)

Import-WebAdministration
# Grab the 404 handler and update it to redirect to index.html.
$redirect = Get-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS 
$redirect.path = "/index.html"
$redirect.responseMode = 1
# shove the updated config back into IIS
Set-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS -value $redirect

This redirects the 404 to the /index.html file as per the suggestion in the Angular 2 docs (link above).

Setting size for icon in CSS

None of those work for me.

.fa-volume-down {
    color: white;
    width: 50% !important;
    height: 50% !important;
    margin-top: 8%;
    margin-left: 7.5%;
    font-size: 1em;
    background-size: 120%;
}

Can I call a constructor from another constructor (do constructor chaining) in C++?

No, in C++ you cannot call a constructor from a constructor. What you can do, as warren pointed out, is:

  • Overload the constructor, using different signatures
  • Use default values on arguments, to make a "simpler" version available

Note that in the first case, you cannot reduce code duplication by calling one constructor from another. You can of course have a separate, private/protected, method that does all the initialization, and let the constructor mainly deal with argument handling.

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

use this code

 public List<Blog> removeDuplicates(List<Blog> list) {
    // Set set1 = new LinkedHashSet(list);
    Set set = new TreeSet(new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            if (((Blog) o1).get().equalsIgnoreCase(((Blog) o2).getId()) /*&&
                    ((Blog)o1).getName().equalsIgnoreCase(((Blog)o2).getName())*/) {
                return 0;
            }
            return 1;
        }
    });
    set.addAll(list);

    final List newList = new ArrayList(set);
    return newList;
}

What is a software framework?

A simple explanation is: A framework is a scaffold that you can you build applications around.

A framework generally provides some base functionality which you can use and extend to make more complex applications from, there are frameworks for all sorts of things. Microsofts MVC framework is a good example of this. It provides everything you need to get off the ground building website using the MVC pattern, it handles web requests, routes and the like. All you have to do is implement "Controllers" and provide "Views" which are two constructs defined by the MVC framework. The MVC framework then handles calling your controllers and rendering your views.

Perhaps not the best wording but I hope it helps

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

If you're generating your javascript with a php file, add this as the beginning of your file:

<?php Header("Content-Type: application/x-javascript; charset=UTF-8"); ?>

Get value of Span Text

Judging by your other post: How to Get the inner text of a span in PHP. You're quite new to web programming, and need to learn about the differences between code on the client (JavaScript) and code on the server (PHP).

As for the correct approach to grabbing the span text from the client I recommend Johns answer.

These are a good place to get started.

JavaScript: https://stackoverflow.com/questions/11246/best-resources-to-learn-javascript

PHP: https://stackoverflow.com/questions/772349/what-is-a-good-online-tutorial-for-php

Also I recommend using jQuery (Once you've got some JavaScript practice) it will eliminate most of the cross-browser compatability issues that you're going to have. But don't use it as a crutch to learn on, it's good to understand JavaScript too. http://jquery.com/

How to convert an array of strings to an array of floats in numpy?

Well, if you're reading the data in as a list, just do np.array(map(float, list_of_strings)) (or equivalently, use a list comprehension). (In Python 3, you'll need to call list on the map return value if you use map, since map returns an iterator now.)

However, if it's already a numpy array of strings, there's a better way. Use astype().

import numpy as np
x = np.array(['1.1', '2.2', '3.3'])
y = x.astype(np.float)

What's the quickest way to multiply multiple cells by another number?

As one of the answers above says: " then drag the formula fill handle." This KEY feature is not mentioned in MS's explanation, nor in others here. I spent over an hour trying to follow the various instructions, to no avail. This is because you have to click and hold near the bottom of the cell just right (and at least on my computer that is not at all easy) so that a sort of "handle" appears. Once you're luck enough to get that, then carefully slide ["drag"] your cursor down to the lowermost of the cells you want to be multiplied by the constant. The products should show up in each cell as you move down. Just dragging down will give you only the answer in the first cell and a lot of white space.

Assignment inside lambda expression in Python

There's no need to use a lambda, when you can remove all the null ones, and put one back if the input size changes:

input = [Object(name=""), Object(name="fake_name"), Object(name="")] 
output = [x for x in input if x.name]
if(len(input) != len(output)):
    output.append(Object(name=""))

SQL to search objects, including stored procedures, in Oracle

In Oracle 11g, if you want to search any text in whole database or procedure below mentioned query can be used:

select * from user_source WHERE UPPER(text) LIKE '%YOUR SAGE%'

How to get the primary IP address of the local machine on Linux and OS X?

Assuming you need your primary public IP as it seen from the rest of the world, try any of those:

wget http://ipecho.net/plain -O - -q
curl http://icanhazip.com
curl http://ifconfig.me/ip

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

Why don't you just make it easy and simple. If I need to know the number of days between today and say, March 10th, 2015, I can just enter the simple formula.

Lets say the static date is March 10th, 2015, and is in cell O5.

The formula to determine the number of days between today and O5 would be, =O5-Today()

Nothing fancy or DATEDIF stuff. Obviously, the cell where you type this formula in must have a data type of 'number'. Just type your date in normally in the reference cell, in this case O5.

Visual Studio Error: (407: Proxy Authentication Required)

The situation is essentially that VS is not set up to go through a proxy to get to the resources it's trying to get to (when using FTP). This is the cause of the 407 error you're getting. I did some research on this and there are a few things that you can try to get this debugged. Fundamentally this is a bit of a flawed area in the product that is supposed to be reviewed in a later release.

Here are some solutions, in order of less complex to more complex:

  • If possible don't use the proxy for the specified domains that you're trying to get to.
  • Set up your proxy settings correctly Internet Explorer (even if you don't use it) as that affects system wide settings. Even go so far as to connect to the internet with internet explorer and leave it connected then go back and try again from VS.
  • In the devenv.exe.config add <servicePointManager expect100Continue="false" /> as laid out below:
  • <configuration>
      <system.net>
        <settings>
          <servicePointManager expect100Continue="false" />
        </settings>
      </system.net>
    </configuration>
    

  • Add defaultProxy settings as follows:
  • <system.net>
      <defaultProxy useDefaultCredentials="true" enabled="true">
          <proxy proxyaddress="http://your.proxyserver.ip:port"/>
      </defaultProxy>
      <settings>
      ...
    

  • Alternately you could try telling it to use system default (which should pull from internet explorer) like so:

    <defaultProxy useDefaultCredentials="true" enabled="true">
        <proxy usesystemdefault="True" />
    </defaultProxy>
    

  • There is an older solution involving creating a plugin here
  • Hope this solves it for you.

    Browser detection in JavaScript?

    Below code snippet will show how how you can show UI elemnts depends on IE version and browser

    $(document).ready(function () {
    
    var msiVersion = GetMSIieversion();
    if ((msiVersion <= 8) && (msiVersion != false)) {
    
        //Show UI elements specific to IE version 8 or low
    
        } else {
        //Show UI elements specific to IE version greater than 8 and for other browser other than IE,,ie..Chrome,Mozila..etc
        }
    }
    );
    

    Below code will give how we can get IE version

    function GetMSIieversion() {
    
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }
    
    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }
    
    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
        // Edge (IE 12+) => return version number
        return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }
    
    // other browser like Chrome,Mozila..etc
    return false;
    
    }
    

    Android-java- How to sort a list of objects by a certain value within the object

    It's very easy for Kotlin!

    listToBeSorted.sortBy { it.distance }