Programs & Examples On #Immediacy

validate natural input number with ngpattern

This is working

<form name="myform" ng-submit="create()">
    <input type="number"
           name="price_field"
           ng-model="price"
           require
           ng-pattern="/^\d{0,9}(\.\d{1,9})?$/">
    <span  ng-show="myform.price_field.$error.pattern">Not valid number!</span>
    <input type="submit" class="btn">
 </form>

Disable a Button

Disable a button on Swift 3:

yourButton.isEnabled = false

Correct way to integrate jQuery plugins in AngularJS

Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link function of the directive.

There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls

Using controllers correctly

Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.

EDIT: Rather than using $(element), you can make use of angular.element(element) when using AngularJS with jQuery

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

If you know that you'll want to see all Comments every time you retrieve a Topic then change your field mapping for comments to:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "topic", cascade = CascadeType.ALL)
private Collection<Comment> comments = new LinkedHashSet<Comment>();

Collections are lazy-loaded by default, take a look at this if you want to know more.

Center image in div horizontally

Every solution posted here assumes that you know the dimensions of your img, which is not a common scenario. Also, planting the dimensions into the solution is painful.

Simply set:

/* for the img inside your div */
display: block;
margin-left: auto;
margin-right: auto;

or

/* for the img inside your div */
display: block;
margin: 0 auto;

That's all.

Note, that you'll also have to set an initial min-width for your outer div.

Logo image and H1 heading on the same line

Try this:

  1. Put both elements in a container DIV.
  2. Give that container the property overflow:auto
  3. Float both elements to the left using float:left
  4. Give the H1 a width so that it doesn't take up the full width of it's parent container.

How can I use Async with ForEach?

I would like to add that there is a Parallel class with ForEach function built in that can be used for this purpose.

How to make for loops in Java increase by increments other than 1

for (let i = 0; i <= value; i+=n) { // increments by n
/*code statement*/
}

this format works for me incrementing index by n

for (let i = 0; i <= value; i+=4) { // increments by 4
/*code statement*/
}

if n = 4 this it will increment by 4

Run Stored Procedure in SQL Developer?

--for setting buffer size needed most of time to avoid `anonymous block completed` message
set serveroutput on size 30000;

-- declaration block in case output need to catch
DECLARE
--declaration for in and out parameter
  V_OUT_1 NUMBER;
  V_OUT_2 VARCHAR2(200);
BEGIN

--your stored procedure name
   schema.package.procedure(
  --declaration for in and out parameter
    V_OUT_1 => V_OUT_1,
    V_OUT_2 => V_OUT_2
  );
  V_OUT_1 := V_OUT_1;
  V_OUT_2 := V_OUT_2;
  -- console output, no need to open DBMS OUTPUT seperatly
  -- also no need to print each output on seperat line 
  DBMS_OUTPUT.PUT_LINE('Ouput => ' || V_OUT_1 || ': ' || V_OUT_2);
END;

get all keys set in memcached

Found a way, thanks to the link here (with the original google group discussion here)

First, Telnet to your server:

telnet 127.0.0.1 11211

Next, list the items to get the slab ids:

stats items
STAT items:3:number 1
STAT items:3:age 498
STAT items:22:number 1
STAT items:22:age 498
END

The first number after ‘items’ is the slab id. Request a cache dump for each slab id, with a limit for the max number of keys to dump:

stats cachedump 3 100
ITEM views.decorators.cache.cache_header..cc7d9 [6 b; 1256056128 s]
END

stats cachedump 22 100
ITEM views.decorators.cache.cache_page..8427e [7736 b; 1256056128 s]
END

Remove empty strings from array while keeping record Without Loop?

var arr = ["I", "am", "", "still", "here", "", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(Boolean)
// arr = ["I", "am", "still", "here", "man"]

filter documentation


// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(v=>v!='');
// arr = ["I", "am", "still", "here", "man"]

Arrow functions documentation

How can I disable editing cells in a WPF Datagrid?

If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"

<DataGrid IsReadOnly="True" CanUserAddRows="False" />

Further more you can set IsReadOnly on individual columns to disable editing.

String Pattern Matching In Java

You can do it using string.indexOf("{item}"). If the result is greater than -1 {item} is in the string

Incorrect syntax near ''

The error for me was that I read the SQL statement from a text file, and the text file was saved in the UTF-8 with BOM (byte order mark) format.

To solve this, I opened the file in Notepad++ and under Encoding, chose UTF-8. Alternatively you can remove the first three bytes of the file with a hex editor.

android - How to get view from context?

first use this:

LayoutInflater inflater = (LayoutInflater) Read_file.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Read file is current activity in which you want your context.

View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));

then you can use this to find any element in layout.

ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);

Check if an apt-get package is installed and then install it if it's not on Linux

This feature already exists in Ubuntu and Debian, in the command-not-found package.

Return an empty Observable

Yes, there is am Empty operator

Rx.Observable.empty();

For typescript, you can use from:

Rx.Observable<Response>.from([])

Best tool for inspecting PDF files?

I've used PDFBox with good success. Here's a sample of what the code looks like (back from version 0.7.2), that likely came from one of the provided examples:

// load the document
System.out.println("Reading document: " + filename);
PDDocument doc = null;                                                                                                                                                                                                          
doc = PDDocument.load(filename);

// look at all the document information
PDDocumentInformation info = doc.getDocumentInformation();
COSDictionary dict = info.getDictionary();
List l = dict.keyList();
for (Object o : l) {
    //System.out.println(o.toString() + " " + dict.getString(o));
    System.out.println(o.toString());
}

// look at the document catalog
PDDocumentCatalog cat = doc.getDocumentCatalog();
System.out.println("Catalog:" + cat);

List<PDPage> lp = cat.getAllPages();
System.out.println("# Pages: " + lp.size());
PDPage page = lp.get(4);
System.out.println("Page: " + page);
System.out.println("\tCropBox: " + page.getCropBox());
System.out.println("\tMediaBox: " + page.getMediaBox());
System.out.println("\tResources: " + page.getResources());
System.out.println("\tRotation: " + page.getRotation());
System.out.println("\tArtBox: " + page.getArtBox());
System.out.println("\tBleedBox: " + page.getBleedBox());
System.out.println("\tContents: " + page.getContents());
System.out.println("\tTrimBox: " + page.getTrimBox());
List<PDAnnotation> la = page.getAnnotations();
System.out.println("\t# Annotations: " + la.size());

SSL: CERTIFICATE_VERIFY_FAILED with Python3

When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert

To fix remove urllib3-1.25.3 and install urllib3-1.24.3

pip3 uninstall urllib3

pip3 install urllib3==1.24.3

Tested on Linux MacOS and Window$

Determine when a ViewPager changes pages

Use the ViewPager.onPageChangeListener:

viewPager.addOnPageChangeListener(new OnPageChangeListener() {
    public void onPageScrollStateChanged(int state) {}
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

    public void onPageSelected(int position) {
        // Check if this is the page you want.
    }
});

get client time zone from browser

Often when people are looking for "timezones", what will suffice is just "UTC offset". e.g., their server is in UTC+5 and they want to know that their client is running in UTC-8.


In plain old javascript (new Date()).getTimezoneOffset()/60 will return the current number of hours offset from UTC.

It's worth noting a possible "gotcha" in the sign of the getTimezoneOffset() return value (from MDN docs):

The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, for time zone UTC+10:00 (Australian Eastern Standard Time, Vladivostok Time, Chamorro Standard Time), -600 will be returned.


However, I recommend you use the day.js for time/date related Javascript code. In which case you can get an ISO 8601 formatted UTC offset by running:

> dayjs().format("Z")
"-08:00"

It probably bears mentioning that the client can easily falsify this information.

(Note: this answer originally recommended https://momentjs.com/, but dayjs is a more modern, smaller alternative.)

How do I write a backslash (\) in a string?

There is a special function made for this Path.Combine()

var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");

Add common prefix to all cells in Excel

Go to Format Cells - Custom. Type the required format into the list first. To prefix "0" before the text characters in an Excel column, use the Format 0####. Remember, use the character "#" equal to the maximum number of digits in a cell of that column. For e.g., if there are 4 cells in a column with the entries - 123, 333, 5665, 7 - use the formula 0####. Reason - A single # refers to reference of just one digit.

Find maximum value of a column and return the corresponding row values using Pandas

You can use:

print(df[df['Value']==df['Value'].max()])

Margin between items in recycler view Android

I made a class to manage this issue. This class set different margins for the items inside the recyclerView: only the first row will have a top margin and only the first column will have left margin.

public class RecyclerViewMargin extends RecyclerView.ItemDecoration {
private final int columns;
private int margin;

/**
 * constructor
 * @param margin desirable margin size in px between the views in the recyclerView
 * @param columns number of columns of the RecyclerView
 */
public RecyclerViewMargin(@IntRange(from=0)int margin ,@IntRange(from=0) int columns ) {
    this.margin = margin;
    this.columns=columns;

}

/**
 * Set different margins for the items inside the recyclerView: no top margin for the first row
 * and no left margin for the first column.
 */
@Override
public void getItemOffsets(Rect outRect, View view,
                           RecyclerView parent, RecyclerView.State state) {

    int position = parent.getChildLayoutPosition(view);
    //set right margin to all
    outRect.right = margin;
    //set bottom margin to all
    outRect.bottom = margin;
    //we only add top margin to the first row
    if (position <columns) {
        outRect.top = margin;
    }
    //add left margin only to the first column
    if(position%columns==0){
        outRect.left = margin;
        }
    }
}

you can set it in your recyclerview this way

 RecyclerViewMargin decoration = new RecyclerViewMargin(itemMargin, numColumns);
 recyclerView.addItemDecoration(decoration);

Create two blank lines in Markdown

Backtick quotes with a space inside and two spaces to follow. Repeat as needed for more lines:

text1 text1
`(space)`(space)(space)
`(space)`(space)(space)
text2 text2

It looks decent in Markdown source:

text1 text1
` `  
` `  
text2 text2

Getting a link to go to a specific section on another page

I believe the example you've posted is using HTML5, which allows you to jump to any DOM element with the matching ID attribute. To support older browsers, you'll need to change:

<div id="timeline" name="timeline" ...>

To the old format:

<a name="timeline" />

You'll then be able to navigate to /academics/page.html#timeline and jump right to that section.

Also, check out this similar question.

How to open CSV file in R when R says "no such file or directory"?

I had the same problem and when I checked the properties of the file on file explorer, it shows me the next message:

"Security: This file came from another computer and might be blocked to help protect this computer"

You click on the "Unblock" button and... you can access to the file from R without any problem, just using read.csv() function and from the directory specified as your working directory, even if is not the same as the file’s directory you are accessing to.

Check that a variable is a number in UNIX shell

In either ksh93 or bash with the extglob option enabled:

if [[ $var == +([0-9]) ]]; then ...

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

Okay adding to @null's awesome post about using the Asset Catalog.

You may need to do the following to get the App's Icon linked and working for Ad-Hoc distributions / production to be seen in Organiser, Test flight and possibly unknown AppStore locations.


After creating the Asset Catalog, take note of the name of the Launch Images and App Icon names listed in the .xassets in Xcode.

By Default this should be

  • AppIcon
  • LaunchImage

[To see this click on your .xassets folder/icon in Xcode.] (this can be changed, so just take note of this variable for later)


What is created now each build is the following data structures in your .app:

For App Icons:

iPhone

  • AppIcon57x57.png (iPhone non retina) [Notice the Icon name prefix]
  • [email protected] (iPhone retina)

And the same format for each of the other icon resolutions.

iPad

  • AppIcon72x72~ipad.png (iPad non retina)
  • AppIcon72x72@2x~ipad.png (iPad retina)

(For iPad it is slightly different postfix)


Main Problem

Now I noticed that in my Info.plist in Xcode 5.0.1 it automatically attempted and failed to create a key for "Icon files (iOS 5)" after completing the creation of the Asset Catalog.

If it did create a reference successfully / this may have been patched by Apple or just worked, then all you have to do is review the image names to validate the format listed above.

Final Solution:

Add the following key to you main .plist

I suggest you open your main .plist with a external text editor such as TextWrangler rather than in Xcode to copy and paste the following key in.

<key>CFBundleIcons</key>
<dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>AppIcon57x57.png</string>
            <string>[email protected]</string>
            <string>AppIcon72x72~ipad.png</string>
            <string>AppIcon72x72@2x~ipad.png</string>
        </array>
    </dict>
</dict>

Please Note I have only included my example resolutions, you will need to add them all.


If you want to add this Key in Xcode without an external editor, Use the following:

  • Icon files (iOS 5) - Dictionary
  • Primary Icon - Dictionary
  • Icon files - Array
  • Item 0 - String = AppIcon57x57.png And for each other item / app icon.

Now when you finally archive your project the final .xcarchive payload .plist will now include the above stated icon locations to build and use.

Do not add the following to any .plist: Just an example of what Xcode will now generate for your final payload

<key>IconPaths</key>
<array>
    <string>Applications/Example.app/AppIcon57x57.png</string>
    <string>Applications/Example.app/[email protected]</string>
    <string>Applications/Example.app/AppIcon72x72~ipad.png</string>
    <string>Applications/Example.app/AppIcon72x72@2x~ipad.png</string>
</array>

Implicit type conversion rules in C++ operators

This answer is directed in large part at a comment made by @RafalDowgird:

"The minimum size of operations is int." - This would be very strange (what about architectures that efficiently support char/short operations?) Is this really in the C++ spec?

Keep in mind that the C++ standard has the all-important "as-if" rule. See section 1.8: Program Execution:

3) This provision is sometimes called the "as-if" rule, because an implementation is free to disregard any requirement of the Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program.

The compiler cannot set an int to be 8 bits in size, even if it were the fastest, since the standard mandates a 16-bit minimum int.

Therefore, in the case of a theoretical computer with super-fast 8-bit operations, the implicit promotion to int for arithmetic could matter. However, for many operations, you cannot tell if the compiler actually did the operations in the precision of an int and then converted to a char to store in your variable, or if the operations were done in char all along.

For example, consider unsigned char = unsigned char + unsigned char + unsigned char, where addition would overflow (let's assume a value of 200 for each). If you promoted to int, you would get 600, which would then be implicitly down cast into an unsigned char, which would wrap modulo 256, thus giving a final result of 88. If you did no such promotions,you'd have to wrap between the first two additions, which would reduce the problem from 200 + 200 + 200 to 144 + 200, which is 344, which reduces to 88. In other words, the program does not know the difference, so the compiler is free to ignore the mandate to perform intermediate operations in int if the operands have a lower ranking than int.

This is true in general of addition, subtraction, and multiplication. It is not true in general for division or modulus.

Apk location in New Android Studio

The Android build system is the toolkit you use to build, test, run and package your apps. The build system can run as an integrated tool from the Android Studio menu and independently from the command line. You can use the features of the build system to:

  1. Customize, configure, and extend the build process.
  2. Create multiple APKs for your app with different features using the same project and modules.

The build process involves many tools and processes that generate intermediate files on the way to producing an .apk. If you are developing in Android Studio, the complete build process is done every time you run the Gradle build task for your project or modules.

The build process is very flexible so it's useful, however, to understand what is happening under the hood since much of the build process is configurable and extensible. The following diagram depicts the different tools and processes that are involved in a build:

Build a release version

You can now use the Build menu options to build the release version of your application for distribution.

The build generates an APK for each build variant: the app/build/apk/ (or app/build/outputs/apk) directory contains packages named app--.apk; for example, app-full-release.apk and app-demo-debug.apk.

enter image description here

Build output

The build generates an APK for each build variant in the app/build folder: the app/build/outputs/apk/ directory contains packages named app--.apk; for example, app-full-release.apk and app-demo-debug.apk.

Courtesy goes to Build System Overview

Turn off textarea resizing

this will do your job

  textarea{
        resize:none;
    }

enter image description here

How do I fix a Git detached head?

Detached head means you have not checked out your branch properly or you have just checked out a single commit.

If you encounter such an issue then first stash your local changes so that you won't lose your changes.

After that... checkout your desired branch using the command:

Let's say you want branch MyOriginalBranch:

git checkout -b someName origin/MyOriginalBranch

Javascript onload not working

You are missing the ()

<body onload="imageRefreshBig();">

EC2 Instance Cloning

You can do it very easily with a Cloud Management software -like enStratus, RightScale or Scalr (disclaimer: I work there). With the cloned farm you can:

  1. Create a snapshot or a pre-made image to launch another day
  2. Duplicate your configuration to test it before production

How do I create a branch?

If you even plan on merging your branch, I highly suggest you look at this:

Svnmerge.py

I hear Subversion 1.5 builds more of the merge tracking in, I have no experience with that. My project is on 1.4.x and svnmerge.py is a life saver!

cannot download, $GOPATH not set

Using brew

I installed it using brew.

$ brew install go

When it was done if you run this brew command it'll show the following info:

$ brew info go
go: stable 1.4.2 (bottled), HEAD
Go programming environment
https://golang.org
/usr/local/Cellar/go/1.4.2 (4676 files, 158M) *
  Poured from bottle
From: https://github.com/Homebrew/homebrew/blob/master/Library/Formula/go.rb
==> Options
--with-cc-all
    Build with cross-compilers and runtime support for all supported platforms
--with-cc-common
    Build with cross-compilers and runtime support for darwin, linux and windows
--without-cgo
    Build without cgo
--without-godoc
    godoc will not be installed for you
--without-vet
    vet will not be installed for you
--HEAD
    Install HEAD version
==> Caveats
As of go 1.2, a valid GOPATH is required to use the `go get` command:
  https://golang.org/doc/code.html#GOPATH

You may wish to add the GOROOT-based install location to your PATH:
  export PATH=$PATH:/usr/local/opt/go/libexec/bin

The important pieces there are these lines:

/usr/local/Cellar/go/1.4.2 (4676 files, 158M) *

export PATH=$PATH:/usr/local/opt/go/libexec/bin

Setting up GO's environment

That shows where GO was installed. We need to do the following to setup GO's environment:

$ export PATH=$PATH:/usr/local/opt/go/libexec/bin
$ export GOPATH=/usr/local/opt/go/bin

You can then check using GO to see if it's configured properly:

$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/usr/local/opt/go/bin"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.4.2/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.4.2/libexec/pkg/tool/darwin_amd64"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1"

Setting up json2csv

Looks good, so lets install json2csv:

$ go get github.com/jehiah/json2csv
$

What just happened? It installed it. You can check like this:

$ $ ls -l $GOPATH/bin
total 5248
-rwxr-xr-x  1 sammingolelli  staff  2686320 Jun  9 12:28 json2csv

OK, so why can't I type json2csv in my shell? That's because the /bin directory under $GOPATH isn't on your $PATH.

$ type -f json2csv
-bash: type: json2csv: not found

So let's temporarily add it:

$ export PATH=$GOPATH/bin:$PATH

And re-check:

$ type -f json2csv
json2csv is hashed (/usr/local/opt/go/bin/bin/json2csv)

Now it's there:

$ json2csv --help
Usage of json2csv:
  -d=",": delimiter used for output values
  -i="": /path/to/input.json (optional; default is stdin)
  -k=[]: fields to output
  -o="": /path/to/output.json (optional; default is stdout)
  -p=false: prints header to output
  -v=false: verbose output (to stderr)
  -version=false: print version string

Add the modifications we've made to $PATH and $GOPATH to your $HOME/.bash_profile to make them persist between reboots.

HTTP redirect: 301 (permanent) vs. 302 (temporary)

301 is that the requested resource has been assigned a new permanent URI and any future references to this resource should be done using one of the returned URIs.

302 is that the requested resource resides temporarily under a different URI.

Since the redirection may be altered on occasion, the client should continue to use the Request-URI for future requests.

This response is only cachable if indicated by a Cache-Control or Expires header field.

How to convert String to DOM Document object in java?

     public static void main(String[] args) {
    final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
                            "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
                            "<role>Developer</role><gen>Male</gen></Emp>";
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder;  
        try 
        {  
            builder = factory.newDocumentBuilder();  
            Document doc = builder.parse( new InputSource( new StringReader( xmlStr )) ); 

        } catch (Exception e) {  
            e.printStackTrace();  
        } 
  }

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".


That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.


JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

PostgreSQL Error: Relation already exists

Sometimes this kind of error happens when you create tables with different database users and try to SELECT with a different user. You can grant all privileges using below query.

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA schema_name TO username;

And also you can grant access for DML statements

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA schema_name TO username;

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

Along the same lines as previous answers, but a very short addition that Allows to use all Control properties without having cross thread invokation exception.

Helper Method

    /// <summary>
    /// Helper method to determin if invoke required, if so will rerun method on correct thread.
    /// if not do nothing.
    /// </summary>
    /// <param name="c">Control that might require invoking</param>
    /// <param name="a">action to preform on control thread if so.</param>
    /// <returns>true if invoke required</returns>
    public bool ControlInvokeRequired(Control c,Action a)
    {
        if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate { a(); }));
        else return false;

        return true;
    }

Sample Usage

    // usage on textbox
    public void UpdateTextBox1(String text)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;
        textBox1.Text = ellapsed;
    }

    //Or any control
    public void UpdateControl(Color c,String s)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(myControl, () => UpdateControl(c,s))) return;
        myControl.Text = s;
        myControl.BackColor = c;
    }

What is the difference between Set and List?

The biggest different is the basic concept.

From the Set and List interface. Set is mathematics concept. Set method extends collection.however not add new method. size() means cardinality(more is BitSet.cardinality, Linear counter,Log Log,HyperLogLog). addAll() means union. retainAll() means intersection. removeAll() means difference.

However List lack of these concepts. List add a lot of method to support sequence concept which Collection interface not supply. core concept is INDEX. like add(index,element),get(index),search(indexOf()),remove(index) element. List also provide "Collection View" subList. Set do not have view. do not have positional access. List also provide a lot of algorithms in Collections class. sort(List),binarySearch(List),reverse(List),shuffle(List),fill(List). the method params is List interface. duplicate elements are just the result of concepts. not the essential difference.

So the essential difference is concept. Set is mathematics set concept.List is sequence concept.

Differences between utf8 and latin1

In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).

rails 3 validation on uniqueness on multiple attributes

Dont work for me, need to put scope in plural

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

new Date() is working in Chrome but not Firefox

This is what worked for me on Firefox and Chrome:

// The format is 'year-month-date hr:mins:seconds.milliseconds'
const d = new Date('2020-1-4 12:00:00.999') 
// we use the `.` separator between seconds and milliseconds.

Good Luck...

Printing a java map Map<String, Object> - How?

There is a get method in HashMap:

for (String keys : objectSet.keySet())  
{
   System.out.println(keys + ":"+ objectSet.get(keys));
}

Count number of 1's in binary representation

By utilizing string operations of JS one can do as follows;

0b1111011.toString(2).split(/0|(?=.)/).length // returns 6

or

0b1111011.toString(2).replace("0","").length  // returns 6

Promise.all().then() resolve?

Your return data approach is correct, that's an example of promise chaining. If you return a promise from your .then() callback, JavaScript will resolve that promise and pass the data to the next then() callback.

Just be careful and make sure you handle errors with .catch(). Promise.all() rejects as soon as one of the promises in the array rejects.

How to target the href to div

You can put all your #m1...#m9 divs into .target and display them based on fragment identifier (hash) using :target pseudo-class. It doesn't move the contents between divs, but I think the effect is close to what you wanted to achieve.

Fiddle

HTML

<div class="target">
    <div id="m1">
        dasdasdasd m1
    </div>
    <!-- etc... -->
    <div id="m9">
        dasdasdsgaswa m9
    </div>   
</div>

CSS

.target {
    width:50%;
    height:200px;
    border:solid black 1px; 
}
.target > div {
    display:none;
}

.target > div:target{
    display:block;
}

How do I position an image at the bottom of div?

Add relative positioning to the wrapping div tag, then absolutely position the image within it like this:

CSS:

.div-wrapper {
    position: relative;
    height: 300px;
    width: 300px;
}

.div-wrapper img {
    position: absolute;
    left: 0;
    bottom: 0;
}

HTML:

<div class="div-wrapper">
    <img src="blah.png"/>
</div>

Now the image sits at the bottom of the div.

How eliminate the tab space in the column in SQL Server 2008

UPDATE Table SET Column = REPLACE(Column, char(9), '')

How to set cursor to input box in Javascript?

Sometimes you do get focus but no cursor in a text field. In this case you would do this:

document.getElementById(frmObj.id).select();

Converting ArrayList to Array in java

What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29

Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:

for(String str : dsf){
   System.out.println(str);
}

What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.

Cannot install Aptana Studio 3.6 on Windows

Installing Aptana Studio in passive mode bypasses the installation of Git for Windows and Node.js.

Aptana_Studio_3_Setup_3.6.1 /passive /norestart

(I am unsure whether Aptana Studio will work properly without those "prerequisites", but it appears to.)

If you want a global installation in a specific directory, the command line is

Aptana_Studio_3_Setup_3.6.1.exe /passive /norestart ALLUSERS=1 APPDIR=c:\apps\AptanaStudio

Trying to make bootstrap modal wider

If you need this solution for only few types of modals just use style="width:90%" attribute.

example:

div class="modal-dialog modal-lg" style="width:90%"

note: this will change only this particular modal

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?

I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.

For the second case (event handler never fires even though request made), you may want to try the following suggestions:

  1. Query the Request.Params[ddlCountries.UniqueID] and see if it has value. If it has, manually fire the event handler.
  2. As long as view state is on, only bind the list data when it is not a post back.
  3. If view state has to be off, then put the list data bind in OnInit instead of OnLoad.

Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.

In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.

Thanks for your time reading this, and welcome everyone to correct if I am wrong.

Stopping Excel Macro executution when pressing Esc won't work

My laptop did not have Break nor Scr Lock, so I somehow managed to make it work by pressing Ctrl + Function + Right Shift (to activate 'pause').

How to use \n new line in VB msgbox() ...?

msgbox "This is the first line" & vbcrlf & "and this is the second line"

or in .NET msgbox "This is the first line" & Environment.NewLine & "and this is the second line"

Resize image in the wiki of GitHub using Markdown

Almost 5 years after only the direct HTML formatting works for images on GitHub and other markdown options still prevent images from loading when specifying some custom sizes even with the wrong dimensions. I prefer to specify the desired width and get the height calculated automatically, for example,

_x000D_
_x000D_
<img src="https://github.com/your_image.png" alt="Your image title" width="250"/>
_x000D_
_x000D_
_x000D_

Show and hide divs at a specific time interval using jQuery

Loop through divs every 10 seconds.

$(function () {

    var counter = 0,
        divs = $('#div1, #div2, #div3');

    function showDiv () {
        divs.hide() // hide all divs
            .filter(function (index) { return index == counter % 3; }) // figure out correct div to show
            .show('fast'); // and show it

        counter++;
    }; // function to loop through divs and show correct div

    showDiv(); // show first div    

    setInterval(function () {
        showDiv(); // show next div
    }, 10 * 1000); // do this every 10 seconds    

});

How do I decode a base64 encoded string?

Simple:

byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);

Error: Unfortunately you can't have non-Gradle Java modules and > Android-Gradle modules in one project

You can simply downgrade your gradle dependency to fit your current android studio version.

dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        ....
}

Worked for me.

What's the Use of '\r' escape sequence?

The program is printing "Hey this is my first hello world ", then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.

get DATEDIFF excluding weekends using sql server

BEGIN 
DECLARE @totaldays INT; 
DECLARE @weekenddays INT;

SET @totaldays = DATEDIFF(DAY, @startDate, @endDate) 
SET @weekenddays = ((DATEDIFF(WEEK, @startDate, @endDate) * 2) + -- get the number of weekend days in between
                       CASE WHEN DATEPART(WEEKDAY, @startDate) = 1 THEN 1 ELSE 0 END + -- if selection was Sunday, won't add to weekends
                       CASE WHEN DATEPART(WEEKDAY, @endDate) = 6 THEN 1 ELSE 0 END)  -- if selection was Saturday, won't add to weekends

Return (@totaldays - @weekenddays)

END

This is on SQL Server 2014

How can I tell jaxb / Maven to generate multiple schema packages?

You can use also JAXB bindings to specify different package for each schema, e.g.

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0" schemaLocation="book.xsd">

    <jaxb:globalBindings>
        <xjc:serializable uid="1" />
    </jaxb:globalBindings>

    <jaxb:schemaBindings>
        <jaxb:package name="com.stackoverflow.book" />
    </jaxb:schemaBindings>

</jaxb:bindings>

Then just use the new maven-jaxb2-plugin 0.8.0 <schemas> and <bindings> elements in the pom.xml. Or specify the top most directory in <schemaDirectory> and <bindingDirectory> and by <include> your schemas and bindings:

<schemaDirectory>src/main/resources/xsd</schemaDirectory>
<schemaIncludes>
    <include>book/*.xsd</include>
    <include>person/*.xsd</include>
</schemaIncludes>
<bindingDirectory>src/main/resources</bindingDirectory>
<bindingIncludes>
    <include>book/*.xjb</include>
    <include>person/*.xjb</include>
</bindingIncludes>

I think this is more convenient solution, because when you add a new XSD you do not need to change Maven pom.xml, just add a new XJB binding file to the same directory.

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

In Netbeans please delete current you create the jar file and on the project explore of Netbeans please clean and build 2 or 3 times and right the project folder in project explore and build the jar file.

'any' vs 'Object'

Contrary to .NET where all types derive from an "object", in TypeScript, all types derive from "any". I just wanted to add this comparison as I think it will be a common one made as more .NET developers give TypeScript a try.

Mounting multiple volumes on a docker container?

You can use -v option multiple times in docker run command to mount multiple directory in container:

docker run -t -i \
  -v '/on/my/host/test1:/on/the/container/test1' \
  -v '/on/my/host/test2:/on/the/container/test2' \
  ubuntu /bin/bash

Conditional WHERE clause in SQL Server

To answer the underlying question of how to use a CASE expression in the WHERE clause:

First remember that the value of a CASE expression has to have a normal data type value, not a boolean value. It has to be a varchar, or an int, or something. It's the same reason you can't say SELECT Name, 76 = Age FROM [...] and expect to get 'Frank', FALSE in the result set.

Additionally, all expressions in a WHERE clause need to have a boolean value. They can't have a value of a varchar or an int. You can't say WHERE Name; or WHERE 'Frank';. You have to use a comparison operator to make it a boolean expression, so WHERE Name = 'Frank';

That means that the CASE expression must be on one side of a boolean expression. You have to compare the CASE expression to something. It can't stand by itself!

Here:

WHERE 
    DateDropped = 0
    AND CASE
            WHEN @JobsOnHold  = 1 AND DateAppr >= 0 THEN 'True'
            WHEN DateAppr != 0 THEN 'True'
            ELSE 'False'
        END = 'True'

Notice how in the end the CASE expression on the left will turn the boolean expression into either 'True' = 'True' or 'False' = 'True'.

Note that there's nothing special about 'False' and 'True'. You can use 0 and 1 if you'd rather, too.

You can typically rewrite the CASE expression into boolean expressions we're more familiar with, and that's generally better for performance. However, sometimes is easier or more maintainable to use an existing expression than it is to convert the logic.

Python debugging tips

the obvious way to debug a script

python -m pdb script.py
  • useful when that script raises an exception
  • useful when using virtualenv and pdb command is not running with the venvs python version.

if you don't know exactly where that script is

python -m pdb ``which <python-script-name>``

What is the best/simplest way to read in an XML file in Java application?

Depending on your application and the scope of the cfg file, a properties file might be the easiest. Sure it isn't as elegant as xml but it certainly easier.

Swift - iOS - Dates and times in different format

new Date(year,month,day,0,0,0,0) is local time (as input) new Date(year,month,day) is UTC

I was using a function to attain YYYY-MM-DD format to be compatible on iOS web, but that is also UTC when used in comparisons (not chained by getFullYear or similar) I've found it is best to use only the above with strong (hours,minutes,seconds,milliseconds) building a calendar, calculating with a Date objects and local references

export const zeroPad = (num) => {
  var res = "0";
  if (String(num).length === 1) {
    res = `0${num}`;
  } else {
    res = num;
  }
  return res;
};

Show an image preview before upload

_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
    var files = evt.target.files;_x000D_
_x000D_
    // Loop through the FileList and render image files as thumbnails._x000D_
    for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
      // Only process image files._x000D_
      if (!f.type.match('image.*')) {_x000D_
        continue;_x000D_
      }_x000D_
_x000D_
      var reader = new FileReader();_x000D_
_x000D_
      // Closure to capture the file information._x000D_
      reader.onload = (function(theFile) {_x000D_
        return function(e) {_x000D_
          // Render thumbnail._x000D_
          var span = document.createElement('span');_x000D_
          span.innerHTML = _x000D_
          [_x000D_
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
            e.target.result,_x000D_
            '" title="', escape(theFile.name), _x000D_
            '"/>'_x000D_
          ].join('');_x000D_
          _x000D_
          document.getElementById('list').insertBefore(span, null);_x000D_
        };_x000D_
      })(f);_x000D_
_x000D_
      // Read in the image file as a data URL._x000D_
      reader.readAsDataURL(f);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
_x000D_
_x000D_

Named parameters in JDBC

You can't use named parameters in JDBC itself. You could try using Spring framework, as it has some extensions that allow the use of named parameters in queries.

Increase permgen space

You can also increase it via the VM arguments in your IDE. In my case, I am using Tomcat v7.0 which is running on Eclipse. To do this, double click on your server (Tomcat v7.0). Click the 'Open launch configuration' link. Go to the 'Arguments' tab. Add -XX:MaxPermSize=512m to the VM arguments list. Click 'Apply' and then 'OK'. Restart your server.

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

NSLog(@"%@", CGRectCreateDictionaryRepresentation(rect));

What's the actual use of 'fail' in JUnit test case?

I think the usual use case is to call it when no exception was thrown in a negative test.

Something like the following pseudo-code:

test_addNilThrowsNullPointerException()
{
    try {
        foo.add(NIL);                      // we expect a NullPointerException here
        fail("No NullPointerException");   // cause the test to fail if we reach this            
     } catch (NullNullPointerException e) {
        // OK got the expected exception
    }
}

Rails: How to list database tables/objects using the Rails console?

Run this:

Rails.application.eager_load! 

Then

ActiveRecord::Base.descendants

To return a list of models/tables

Oracle - How to create a materialized view with FAST REFRESH and JOINS

The key checks for FAST REFRESH includes the following:

1) An Oracle materialized view log must be present for each base table.
2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition.
3) If there are outer joins, unique constraints must be placed on the join columns of the inner table.

No 3 is easy to miss and worth highlighting here

Is there a numpy builtin to reject outliers from a list

This method is almost identical to yours, just more numpyst (also working on numpy arrays only):

def reject_outliers(data, m=2):
    return data[abs(data - np.mean(data)) < m * np.std(data)]

How can I exclude a directory from Visual Studio Code "Explore" tab?

In newer versions of VSCode this moved to a folder-specific configuration block.

  • Go to File -> Preferences -> Settings (or on Mac Code -> Preferences -> Settings)
  • Pick the Folder Settings tab

Then add a "files.exclude" block, listing the directory globs you would like to exclude:

{
    "files.exclude": {
        "**/bin": true,
        "**/obj": true
    },
}

enter image description here

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

You can also use a pretty simple for loop:

for f in `find . -not -name "*Music*"`
do
    cp $f /target/dir
done

Bundle ID Suffix? What is it?

The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.

It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.

An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:

com.awesomeapps.thebestapp

In this case the suffix is thebestapp.

connecting to MySQL from the command line

After you run MySQL Shell and you have seen following:

mysql-js>

Firstly, you should:

mysql-js>\sql

Secondly:

 mysql-sql>\connect username@servername (root@localhost)

And finally:

Enter password:*********

Count number of rows within each group

dplyr package does this with count/tally commands, or the n() function:

First, some data:

df <- data.frame(x = rep(1:6, rep(c(1, 2, 3), 2)), year = 1993:2004, month = c(1, 1:11))

Now the count:

library(dplyr)
count(df, year, month)
#piping
df %>% count(year, month)

We can also use a slightly longer version with piping and the n() function:

df %>% 
  group_by(year, month) %>%
  summarise(number = n())

or the tally function:

df %>% 
  group_by(year, month) %>%
  tally()

What are the differences between a pointer variable and a reference variable in C++?

I use references unless I need either of these:

  • Null pointers can be used as a sentinel value, often a cheap way to avoid function overloading or use of a bool.

  • You can do arithmetic on a pointer. For example, p += offset;

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Try this:

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8,iso,utfBytes);
string msg = iso.GetString(isoBytes);

Difference in months between two dates

This simple static function calculates the fraction of months between two Datetimes, e.g.

  • 1.1. to 31.1. = 1.0
  • 1.4. to 15.4. = 0.5
  • 16.4. to 30.4. = 0.5
  • 1.3. to 1.4. = 1 + 1/30

The function assumes that the first date is smaller than the second date. To deal with negative time intervals one can modify the function easily by introducing a sign and a variable swap at the beginning.

public static double GetDeltaMonths(DateTime t0, DateTime t1)
{
     DateTime t = t0;
     double months = 0;
     while(t<=t1)
     {
         int daysInMonth = DateTime.DaysInMonth(t.Year, t.Month);
         DateTime endOfMonth = new DateTime(t.Year, t.Month, daysInMonth);
         int cutDay = endOfMonth <= t1 ? daysInMonth : t1.Day;
         months += (cutDay - t.Day + 1) / (double) daysInMonth;
         t = new DateTime(t.Year, t.Month, 1).AddMonths(1);
     }
     return Math.Round(months,2);
 }

Python Timezone conversion

Time conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

so, below code is to convert the local time to other time zone.

  • datetime.datetime.today() - return current the local time
  • datetime.astimezone() - convert the time zone, but we have to pass the time zone.
  • pytz.timezone('Asia/Kolkata') -passing the time zone to pytz module
  • Strftime - Convert Datetime to string
# Time conversion from local time
import datetime
import pytz
dt_today = datetime.datetime.today()   # Local time
dt_India = dt_today.astimezone(pytz.timezone('Asia/Kolkata')) 
dt_London = dt_today.astimezone(pytz.timezone('Europe/London'))
India = (dt_India.strftime('%m/%d/%Y %H:%M'))
London = (dt_London.strftime('%m/%d/%Y %H:%M'))
print("Indian standard time: "+India+" IST")
print("British Summer Time: "+London+" BST")

list all the time zone

import pytz
for tz in pytz.all_timezones:
    print(tz)

how to pass command line arguments to main method dynamically

If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.

Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3

The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.

Consider a program ArgsTest.java:

package test;

import java.io.IOException;

    public class ArgsTest {

        public static void main(String[] args) throws IOException {

            System.out.println("Program Arguments:");
            for (String arg : args) {
                System.out.println("\t" + arg);
            }

            System.out.println("System Properties from VM Arguments");
            String sysProp1 = "sysProp1";
            System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
            String sysProp2 = "sysProp2";
            System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));

        }
    }

If given input as,

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3 

in the commandline, in project bin folder would give the following result:

Program Arguments:
  pro1
  pro2
  pro3
System Properties from VM Arguments
  Name:sysProp1, Value:sp1
  Name:sysProp2, Value:sp2

How to center horizontally div inside parent div

<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>

How to move an element into another element?

For the sake of completeness, there is another approach wrap() or wrapAll() mentioned in this article. So the OP's question could possibly be solved by this (that is, assuming the <div id="destination" /> does not yet exist, the following approach will create such a wrapper from scratch - the OP was not clear about whether the wrapper already exists or not):

$("#source").wrap('<div id="destination" />')
// or
$(".source").wrapAll('<div id="destination" />')

It sounds promising. However, when I was trying to do $("[id^=row]").wrapAll("<fieldset></fieldset>") on multiple nested structure like this:

<div id="row1">
    <label>Name</label>
    <input ...>
</div>

It correctly wraps those <div>...</div> and <input>...</input> BUT SOMEHOW LEAVES OUT the <label>...</label>. So I ended up use the explicit $("row1").append("#a_predefined_fieldset") instead. So, YMMV.

HTML5 - mp4 video does not play in IE9

Whithout JavaScript, the only way I could play without errors:

<!--[if lte IE 9]>
<!-- PUT HERE A FLASH PLAYER WITH video.flv -->
<![endif]-->

<!--[if gt IE 9]><!-->
<video controls class="video">
    <source src="video.mp4" type="video/mp4">
    <!-- REPEAT FLASH PLAYER CODE HERE -->
</video>
<!--<![endif]-->

How do I check if a string contains a specific word?

While most of these answers will tell you if a substring appears in your string, that's usually not what you want if you're looking for a particular word, and not a substring.

What's the difference? Substrings can appear within other words:

  • The "are" at the beginning of "area"
  • The "are" at the end of "hare"
  • The "are" in the middle of "fares"

One way to mitigate this would be to use a regular expression coupled with word boundaries (\b):

function containsWord($str, $word)
{
    return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str);
}

This method doesn't have the same false positives noted above, but it does have some edge cases of its own. Word boundaries match on non-word characters (\W), which are going to be anything that isn't a-z, A-Z, 0-9, or _. That means digits and underscores are going to be counted as word characters and scenarios like this will fail:

  • The "are" in "What _are_ you thinking?"
  • The "are" in "lol u dunno wut those are4?"

If you want anything more accurate than this, you'll have to start doing English language syntax parsing, and that's a pretty big can of worms (and assumes proper use of syntax, anyway, which isn't always a given).

curl posting with header application/x-www-form-urlencoded

Try something like:

$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));   
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$result = curl_exec($ch);

echo $result;

How to use SQL LIKE condition with multiple values in PostgreSQL?

Use LIKE ANY(ARRAY['AAA%', 'BBB%', 'CCC%']) as per this cool trick @maniek showed earlier today.

Cloning an array in Javascript/Typescript

Using map or other similar solution do not help to clone deeply an array of object. An easier way to do this without adding a new library is using JSON.stringfy and then JSON.parse.

In your case this should work :

this.backupData = JSON.parse(JSON.stringify(genericItems));

"A referral was returned from the server" exception when accessing AD from C#

Probably the path you supplied was not correct. Check that.

I would recomment the article Howto: (Almost) Everything In Active Directory via C# which really helped me in the past in dealing with AD.

Bubble Sort Homework

def bubble_sort(li):
    l = len(li)
    tmp = None
    sorted_l = sorted(li)
    while (li != sorted_l):
        for ele in range(0,l-1):
            if li[ele] > li[ele+1]:
                tmp = li[ele+1]
                li[ele+1] = li [ele]
                li[ele] = tmp
    return li

Run a string as a command within a Bash script

Here is my gradle build script that executes strings stored in heredocs:

current_directory=$( realpath "." )
GENERATED=${current_directory}/"GENERATED"
build_gradle=$( realpath build.gradle )

## touch because .gitignore ignores this folder:
touch $GENERATED

COPY_BUILD_FILE=$( cat <<COPY_BUILD_FILE_HEREDOC

    cp 
        $build_gradle 
        $GENERATED/build.gradle

COPY_BUILD_FILE_HEREDOC
)
$COPY_BUILD_FILE

GRADLE_COMMAND=$( cat <<GRADLE_COMMAND_HEREDOC

    gradle run

        --build-file       
            $GENERATED/build.gradle

        --gradle-user-home 
            $GENERATED  

        --no-daemon

GRADLE_COMMAND_HEREDOC
)
$GRADLE_COMMAND

The lone ")" are kind of ugly. But I have no clue how to fix that asthetic aspect.

How do I create a new branch?

Right click and open SVN Repo-browser:

Enter image description here

Right click on Trunk (working copy) and choose Copy to...:

Enter image description here

Input the respective branch's name/path:

Enter image description here

Click OK, type the respective log message, and click OK.

How to find out when an Oracle table was updated the last time

You would need to add a trigger on insert, update, delete that sets a value in another table to sysdate.

When you run application, it would read the value and save it somewhere so that the next time it is run it has a reference to compare.

Would you consider that "Special Admin Stuff"?

It would be better to describe what you're actually doing so you get clearer answers.

How to set margin of ImageView using code, not xml

If you use kotlin, this can be simplified by creating an extension function

fun View.setMarginExtensionFunction(left: Int, top: Int, right: Int, bottom: Int) {
  val params = layoutParams as ViewGroup.MarginLayoutParams
  params.setMargins(left, top, right, bottom)
  layoutParams = params
}

Now all you need is a view, and this extension function can be used anywhere.

val imageView = findViewById(R.id.imageView)
imageView.setMarginExtensionFunction(0, 0, 0, 0)

Is there any way to configure multiple registries in a single npmrc file

You can use multiple repositories syntax for the registry entry in your .npmrc file:

registry=http://serverA.url/repository-uri/
//serverB.url/repository-uri/
//serverC.url/repository-uri/:_authToken=00000000-0000-0000-0000-0000000000000
//registry.npmjs.org/

That would make your npm look for packages in different servers.

XPath to fetch SQL XML value

I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.

For basic XPath know-how, I'd recommend the W3Schools tutorial.

How to export a CSV to Excel using Powershell

I am using excelcnv.exe to convert csv into xlsx and that seemed to work properly. You will have to change the directory to where your excelcnv is. If 32 bit, it goes to Program Files (x86)

Start-Process -FilePath 'C:\Program Files\Microsoft Office\root\Office16\excelcnv.exe' -ArgumentList "-nme -oice ""$xlsFilePath"" ""$xlsToxlsxPath"""

How to call a function from another controller in angularjs?

If the two controller is nested in One controller.
Then you can simply call:

$scope.parentmethod();  

Angular will search for parentmethod function starting with current scope and up until it will reach the rootScope.

Directory.GetFiles: how to get only filename, not full path?

Use this to obtain only the filename.

Path.GetFileName(files[0]);

Run PowerShell scripts on remote PC

After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:

PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2

Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.

Vue.js—Difference between v-model and v-bind

There are cases where you don't want to use v-model. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.

In these cases, it's not a good idea to use either watchers or computed properties.

Instead, take your v-model and split it as above answer indicates

<input
   :value="something"
   @input="something = $event.target.value"
>

In practice, if you are decoupling your logic this way, you'll probably be calling a method.

This is what it would look like in a real world scenario:

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
  <p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
  var app = new Vue({_x000D_
    el: "#app",_x000D_
    data: function(){_x000D_
      return {_x000D_
        extendedCost: 0,_x000D_
      }_x000D_
    },_x000D_
    methods: {_x000D_
      _onInputExtendedCost: function($event) {_x000D_
        this.extendedCost = parseInt($event.target.value);_x000D_
        // Go update other inputs here_x000D_
    }_x000D_
  }_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to Make A Chevron Arrow Using CSS?

I needed to change an input to an arrow in my project. Below is final work.

_x000D_
_x000D_
#in_submit {_x000D_
  background-color: white;_x000D_
  border-left: #B4C8E9;_x000D_
  border-top: #B4C8E9;_x000D_
  border-right: 3px solid black;_x000D_
  border-bottom: 3px solid black;_x000D_
  width: 15px;_x000D_
  height: 15px;_x000D_
  transform: rotate(-45deg);_x000D_
  margin-top: 4px;_x000D_
  margin-left: 4px;_x000D_
  position: absolute;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<input id="in_submit" type="button" class="convert_btn">
_x000D_
_x000D_
_x000D_

Here Fiddle

What is the C++ function to raise a number to a power?

You should be able to use normal C methods in math.

#include <cmath>

pow(2,3)

if you're on a unix-like system, man cmath

Is that what you're asking?

Sujal

jQuery: How can I create a simple overlay?

Please check this jQuery plugin,

blockUI

with this you can overlay all the page or elements, works great for me,

Examples: Block a div: $('div.test').block({ message: null });

Block the page: $.blockUI({ message: '<h1><img src="busy.gif" /> Just a moment...</h1>' }); Hope that help someone

Greetings

Saving the PuTTY session logging

I always have to check my cheatsheet :-)

Step 1: right-click on the top of putty window and select 'Change settings'.

Step 2: type the name of the session and save.

That's it!. Enjoy!

Check array position for null/empty

You can use boost::optional (or std::optional for newer versions), which was developed in particular for decision of your problem:

boost::optional<int> y[50];
....
geoGraph.y[x] = nums[x];
....
const size_t size_y = sizeof(y)/sizeof(y[0]); //!!!! correct size of y!!!!
for(int i=0; i<size_y;i++){
   if(y[i]) { //check for null
      p[i].SetPoint(Recto.Height()-x,*y[i]);
      ....
   }
}

P.S. Do not use C-type array -> use std::array or std::vector:

std::array<int, 50> y;   //not int y[50] !!!

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Accessing inventory host variable in Ansible playbook

You are on the right track about hostvars.
This magic variable is used to access information about other hosts.

hostvars is a hash with inventory hostnames as keys.
To access fields of each host, use hostvars['test-1'], hostvars['test2-1'], etc.

ansible_ssh_host is deprecated in favor of ansible_host since 2.0.
So you should first remove "_ssh" from inventory hosts arguments (i.e. to become "ansible_user", "ansible_host", and "ansible_port"), then in your role call it with:

{{ hostvars['your_host_group'].ansible_host }}

What is Gradle in Android Studio?

You can find everything you need to know about Gradle here: Gradle Plugin User Guide

Goals of the new Build System

The goals of the new build system are:

  • Make it easy to reuse code and resources
  • Make it easy to create several variants of an application, either for multi-apk distribution or for different flavors of an application
  • Make it easy to configure, extend and customize the build process
  • Good IDE integration

Why Gradle?

Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins.

Here are some of its features that made us choose Gradle:

  • Domain Specific Language (DSL) to describe and manipulate the build logic
  • Build files are Groovy based and allow mixing of declarative elements through the DSL and using code to manipulate the DSL elements to provide custom logic.
  • Built-in dependency management through Maven and/or Ivy.
  • Very flexible. Allows using best practices but doesn’t force its own way of doing things.
  • Plugins can expose their own DSL and their own API for build files to use.
  • Good Tooling API allowing IDE integration

How to use 'find' to search for files created on a specific date?

You could do this:

find ./ -type f -ls |grep '10 Sep'

Example:

[root@pbx etc]# find /var/ -type f -ls | grep "Dec 24"
791235    4 -rw-r--r--   1 root     root           29 Dec 24 03:24 /var/lib/prelink/full
798227  288 -rw-r--r--   1 root     root       292323 Dec 24 23:53 /var/log/sa/sar24
797244  320 -rw-r--r--   1 root     root       321300 Dec 24 23:50 /var/log/sa/sa24

What is the best way to find the users home directory in Java?

The concept of a HOME directory seems to be a bit vague when it comes to Windows. If the environment variables (HOMEDRIVE/HOMEPATH/USERPROFILE) aren't enough, you may have to resort to using native functions via JNI or JNA. SHGetFolderPath allows you to retrieve special folders, like My Documents (CSIDL_PERSONAL) or Local Settings\Application Data (CSIDL_LOCAL_APPDATA).

Sample JNA code:

public class PrintAppDataDir {

    public static void main(String[] args) {
        if (com.sun.jna.Platform.isWindows()) {
            HWND hwndOwner = null;
            int nFolder = Shell32.CSIDL_LOCAL_APPDATA;
            HANDLE hToken = null;
            int dwFlags = Shell32.SHGFP_TYPE_CURRENT;
            char[] pszPath = new char[Shell32.MAX_PATH];
            int hResult = Shell32.INSTANCE.SHGetFolderPath(hwndOwner, nFolder,
                    hToken, dwFlags, pszPath);
            if (Shell32.S_OK == hResult) {
                String path = new String(pszPath);
                int len = path.indexOf('\0');
                path = path.substring(0, len);
                System.out.println(path);
            } else {
                System.err.println("Error: " + hResult);
            }
        }
    }

    private static Map<String, Object> OPTIONS = new HashMap<String, Object>();
    static {
        OPTIONS.put(Library.OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
        OPTIONS.put(Library.OPTION_FUNCTION_MAPPER,
                W32APIFunctionMapper.UNICODE);
    }

    static class HANDLE extends PointerType implements NativeMapped {
    }

    static class HWND extends HANDLE {
    }

    static interface Shell32 extends Library {

        public static final int MAX_PATH = 260;
        public static final int CSIDL_LOCAL_APPDATA = 0x001c;
        public static final int SHGFP_TYPE_CURRENT = 0;
        public static final int SHGFP_TYPE_DEFAULT = 1;
        public static final int S_OK = 0;

        static Shell32 INSTANCE = (Shell32) Native.loadLibrary("shell32",
                Shell32.class, OPTIONS);

        /**
         * see http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx
         * 
         * HRESULT SHGetFolderPath( HWND hwndOwner, int nFolder, HANDLE hToken,
         * DWORD dwFlags, LPTSTR pszPath);
         */
        public int SHGetFolderPath(HWND hwndOwner, int nFolder, HANDLE hToken,
                int dwFlags, char[] pszPath);

    }

}

Clearing UIWebview cache

For swift 2.0:

let cacheSizeMemory = 4*1024*1024; // 4MB
let cacheSizeDisk = 32*1024*1024; // 32MB
let sharedCache = NSURLCache(memoryCapacity: cacheSizeMemory, diskCapacity: cacheSizeDisk, diskPath: "nsurlcache")
NSURLCache.setSharedURLCache(sharedCache)

Creating a ZIP archive in memory using System.IO.Compression

Function to return stream that contain zip file

public static Stream ZipGenerator(List<string> files)
    {
        ZipArchiveEntry fileInArchive;
        Stream entryStream;
        int i = 0;
        List<byte[]> byteArray = new List<byte[]>();

        foreach (var file in files)
        {
            byteArray.Add(File.ReadAllBytes(file));
        }

        var outStream = new MemoryStream();

        using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
        {
            foreach (var file in files)
            {
                fileInArchive=(archive.CreateEntry(Path.GetFileName(file), CompressionLevel.Optimal));

                using (entryStream = fileInArchive.Open())
                {
                        using (var fileToCompressStream = new MemoryStream(byteArray[i]))
                        {
                            fileToCompressStream.CopyTo(entryStream);
                        }
                        i++;
                }
            }
        }
        outStream.Position = 0;
        return outStream;
    }

If you want , write zip to file stream.

using (var fileStream = new FileStream(@"D:\Tools\DBExtractor\DBExtractor\bin\Debug\test.zip", FileMode.Create))
{
   outStream.Position = 0;
   outStream.WriteTo(fileStream);
}

`

Using union and order by clause in mysql

(select add_date,col2 from table_name) 
  union 
(select add_date,col2 from table_name) 
  union 
(select add_date,col2 from table_name) 

order by add_date

How to concatenate strings with padding in sqlite

Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...

SELECT 
  (
    col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
  ) AS my_column 
FROM
  mytable;

Tested on SQLite 3.8.8.3, Thanks!

Moving Git repository content to another repository preserving history

It looks like you're close. Assuming that it's not just a typo in your submission, step 3 should be cd repo2 instead of repo1. And step 6 should be git pull not push. Reworked list:

1. git clone repo1
2. git clone repo2
3. cd repo2
4. git remote rm origin
5. git remote add repo1
6. git pull
7. git remote rm repo1
8. git remote add newremote

"Error: Main method not found in class MyClass, please define the main method as..."

I feel the above answers miss a scenario where this error occurs even when your code has a main(). When you are using JNI that uses Reflection to invoke a method. During runtime if the method is not found, you will get a

java.lang.NoSuchMethodError: No virtual method

Insert into C# with SQLCommand

Try confirm the data type (SqlDbType) for each parameter in the database and do it this way;

 using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connSpionshopString"].ConnectionString))
 {
            connection.Open();
            string sql =  "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
            using(SqlCommand cmd = new SqlCommand(sql,connection)) 
            {
                  cmd.Parameters.Add("@param1", SqlDbType.Int).value = klantId;  
                  cmd.Parameters.Add("@param2", SqlDbType.Varchar, 50).value = klantNaam;
                  cmd.Parameters.Add("@param3", SqlDbType.Varchar, 50).value = klantVoornaam;
                  cmd.CommandType = CommandType.Text;
                  cmd.ExecuteNonQuery(); 
            }
 }

Calculating Page Table Size

Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***

Null or empty check for a string variable

Try this:

ISNULL(IIF (ColunmValue!='',ColunmValue, 'no units exists') , 'no units exists') AS 'ColunmValueName' 

Where is virtualenvwrapper.sh after pip install?

Using

find / -name virtualenvwrapper.sh

I got a TON of "permissions denied"s, and exactly one printout of the file location. I missed it until I found that file location when I uninstall/installed it again with pip.

In case you were curious, it was in

/usr/local/share/python/virtualenvwrapper.sh

React.js: Set innerHTML vs dangerouslySetInnerHTML

Based on (dangerouslySetInnerHTML).

It's a prop that does exactly what you want. However they name it to convey that it should be use with caution

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

You can replace

document.getElementById(this.state.baction).addPrecent(10);

with

this.refs[this.state.baction].addPrecent(10);


  <Progressbar completed={25} ref="Progress1" id="Progress1"/>

how to change namespace of entire project?

When I wanted to change namespace and the solution name I did as follows:
1) changed the namespace by selecting it and renaming it and I did the same with solution name
2) clicked on the light bulb and renamed all the instances of old namespace
3) removed all the projects from the solution
4) closed the visual studio
5) renamed all the projects in windows explorer
6) opened visual studio and added all the projects again
7) rename namespaces in all projects in their properties
8) removed bin folder (from all projects)
9) build the project again

That worked for me without any problems and my project had as well source control. All was fine after pushing those changes to the remote.

What is the Angular equivalent to an AngularJS $watch?

If you want to make it 2 way binding, you can use [(yourVar)], but you have to implement yourVarChange event and call it everytime your variable change.

Something like this to track the hero change

@Output() heroChange = new EventEmitter();

and then when your hero get changed, call this.heroChange.emit(this.hero);

the [(hero)] binding will do the rest for you

see example here:

http://plnkr.co/edit/efOGIJ0POh1XQeRZctSx?p=preview

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

In my case, I had to exclude an older hamcrest from junit-vintage:

<dependency>
  <groupId>org.junit.vintage</groupId>
  <artifactId>junit-vintage-engine</artifactId>
  <scope>test</scope>
  <exclusions>
    <exclusion>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest</artifactId>
  <version>2.1</version>
  <scope>test</scope>
</dependency>

How to change the font color of a disabled TextBox?

If you want to display text that cannot be edited or selected you can simply use a label

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

If you need profile-specific control the in your application-{profile}.properties file

org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false

Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/

ActiveX component can't create object

Check your browser settings.

For me, using IE, the fix was to go into Tools/Internet Options, Security tab, for the relevant zone, "custom level" and check the ActiveX settings. Setting "Initialize and script ActiveX controls not marked as safe for scripting" to "Enable" fixed this problem for me.

AngularJS open modal on button click

Set Jquery in scope

$scope.$ = $;

and call in html

ng-click="$('#novoModelo').modal('show')"

Styling multi-line conditions in 'if' statements?

Here's another approach:

cond_list = ['cond1 == "val1"','cond2=="val2"','cond3=="val3"','cond4=="val4"']
if all([eval(i) for i in cond_list]):
 do something

This also makes it easy to add another condition easily without changing the if statement by simply appending another condition to the list:

cond_list.append('cond5=="val5"')

Difference between classification and clustering in data mining?

I believe classification is classifying records in a data set into predefined classes or even defining classes on the go. I look at it as pre-requisite for any valuable data mining, I like to think of it at unsupervised learning i.e. one does not know what he/she is looking for while mining the data and classification serves as a good starting point

Clustering on the other end falls under supervised learning i.e. one know what parameters to look for, the correlation between them along with critical levels. I believe it requires some understanding of statistics and maths

Print text in Oracle SQL Developer SQL Worksheet window

The main answer left out a step for new installs where one has to open up the dbms output window.

enter image description here

Then the script I used:

dbms_output.put_line('Start');

Another script:

set serveroutput on format wrapped;
begin
    DBMS_OUTPUT.put_line('jabberwocky');
end;

show and hide divs based on radio button click

Your selector for the .show() and .hide() are not pointing to anything in the code.

Fixed version in jsFiddle

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

This happened to me because I had a ddd() or dd();die; in my routes/web.php file I forgot about.

Mockito: Mock private field initialization

I already found the solution to this problem which I forgot to post here.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {

@Mock
Person person;

@Test
public void testPrintName() throws Exception {
    PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
    Test test= new Test();
    test.testMethod();
    }
}

Key points to this solution are:

  1. Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)

  2. Instruct Powermock to prepare Test.class for manipulation of private fields: @PrepareForTest({ Test.class })

  3. And finally mock the constructor for Person class:

    PowerMockito.mockStatic(Person.class); PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

Full disclosure - I'm the author of the previously mentioned talk in TLV DroidCon.

I had a chance to examine this issue across many Android applications, and discuss it with other developers who encountered it - and we all got to the same point: this issue cannot be avoided, only minimized.

I took a closer look at the default implementation of the Android Garbage collector code, to understand better why this exception is thrown and on what could be the possible causes. I even found a possible root cause during experimentation.

The root of the problem is at the point a device "Goes to Sleep" for a while - this means that the OS has decided to lower the battery consumption by stopping most User Land processes for a while, and turning Screen off, reducing CPU cycles, etc. The way this is done - is on a Linux system level where the processes are Paused mid run. This can happen at any time during normal Application execution, but it will stop at a Native system call, as the context switching is done on the kernel level. So - this is where the Dalvik GC joins the story.

The Dalvik GC code (as implemented in the Dalvik project in the AOSP site) is not a complicated piece of code. The basic way it work is covered in my DroidCon slides. What I did not cover is the basic GC loop - at the point where the collector has a list of Objects to finalize (and destroy). The loop logic at the base can be simplified like this:

  1. take starting_timestamp,
  2. remove object for list of objects to release,
  3. release object - finalize() and call native destroy() if required,
  4. take end_timestamp,
  5. calculate (end_timestamp - starting_timestamp) and compare against a hard coded timeout value of 10 seconds,
  6. if timeout has reached - throw the java.util.concurrent.TimeoutException and kill the process.

Now consider the following scenario:

Application runs along doing its thing.

This is not a user facing application, it runs in the background.

During this background operation, objects are created, used and need to be collected to release memory.

Application does not bother with a WakeLock - as this will affect the battery adversely, and seems unnecessary.

This means the Application will invoke the GC from time to time.

Normally the GC runs is completed without a hitch.

Sometimes (very rarely) the system will decide to sleep in the middle of the GC run.

This will happen if you run your application long enough, and monitor the Dalvik memory logs closely.

Now - consider the timestamp logic of the basic GC loop - it is possible for the device to start the run, take a start_stamp, and go to sleep at the destroy() native call on a system object.

When it wakes up and resumes the run, the destroy() will finish, and the next end_stamp will be the time it took the destroy() call + the sleep time.

If the sleep time was long (more than 10 seconds), the java.util.concurrent.TimeoutException will be thrown.

I have seen this in the graphs generated from the analysis python script - for Android System Applications, not just my own monitored apps.

Collect enough logs and you will eventually see it.

Bottom line:

The issue cannot be avoided - you will encounter it if your app runs in the background.

You can mitigate by taking a WakeLock, and prevent the device from sleeping, but that is a different story altogether, and a new headache, and maybe another talk in another con.

You can minimize the problem by reducing GC calls - making the scenario less likely (tips are in the slides).

I have not yet had the chance to go over the Dalvik 2 (a.k.a ART) GC code - which boasts a new Generational Compacting feature, or performed any experiments on an Android Lollipop.

Added 7/5/2015:

After reviewing the Crash reports aggregation for this crash type, it looks like these crashes from version 5.0+ of Android OS (Lollipop with ART) only account for 0.5% of this crash type. This means that the ART GC changes has reduced the frequency of these crashes.

Added 6/1/2016:

Looks like the Android project has added a lot of info on how the GC works in Dalvik 2.0 (a.k.a ART).

You can read about it here - Debugging ART Garbage Collection.

It also discusses some tools to get information on the GC behavior for your app.

Sending a SIGQUIT to your app process will essentially cause an ANR, and dump the application state to a log file for analysis.

Sorting Python list based on the length of the string

I can do it using below two methods, using function

def lensort(x):
    list1 = []
    for i in x:
        list1.append([len(i),i])
    return sorted(list1)

lista = ['a', 'bb', 'ccc', 'dddd']
a=lensort(lista)
print([l[1] for l in a])

In one Liner using Lambda, as below, a already answered above.

 lista = ['a', 'bb', 'ccc', 'dddd']
 lista.sort(key = lambda x:len(x))
 print(lista)

Unsafe JavaScript attempt to access frame with URL

I was getting the same error message when I tried to change the domain for iframe.src.

For me, the answer was to change the iframe.src to a url on the same domain, but which was actually an html re-direct page to the desired domain. The other domain then showed up in my iframe without any errors.

Worked like a charm.:)

How do I execute a stored procedure once for each row returned by query?

I like the dynamic query way of Dave Rincon as it does not use cursors and is small and easy. Thank you Dave for sharing.

But for my needs on Azure SQL and with a "distinct" in the query, i had to modify the code like this:

Declare @SQL nvarchar(max);
-- Set SQL Variable
-- Prepare exec command for each distinctive tenantid found in Machines 
SELECT @SQL = (Select distinct 'exec dbo.sp_S2_Laser_to_cache ' + 
              convert(varchar(8),tenantid) + ';' 
              from Dim_Machine
              where iscurrent = 1
              FOR XML PATH(''))

--for debugging print the sql 
print @SQL;

--execute the generated sql script
exec sp_executesql @SQL;

I hope this helps someone...

Visual Studio 2015 installer hangs during install?

Same thing happened to me, and I also tried to terminate secondary process from task manager. Do not do that. It is not a solution, but rather a hack which may cause issues later. In my case, I was not even able to uninstall Visual Studio. I tried both web installation and ISO, same issue.

Here is how it worked finally. I restored my Windows 7 to earliest restore point as possible, when there was nothing installed, so I was sure that there would be no conflicts between the different tools (Java, Android API, etc.)

I started the installation of Visual Studio 2015 Community Release Candidate at 10 p.m. At 7 a.m., it was working on Android API 19-21. A hour later, it was finally preparing Visual Studio.

This means that all you need to do is to actually wait 8 to 9 hours. Don't terminate the secondary installer at risk of breaking your Visual Studio; just wait.

How to detect if a string contains special characters?

SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)

What is __gxx_personality_v0 for?

It is used in the stack unwiding tables, which you can see for instance in the assembly output of my answer to another question. As mentioned on that answer, its use is defined by the Itanium C++ ABI, where it is called the Personality Routine.

The reason it "works" by defining it as a global NULL void pointer is probably because nothing is throwing an exception. When something tries to throw an exception, then you will see it misbehave.

Of course, if nothing is using exceptions, you can disable them with -fno-exceptions (and if nothing is using RTTI, you can also add -fno-rtti). If you are using them, you have to (as other answers already noted) link with g++ instead of gcc, which will add -lstdc++ for you.

Change the icon of the exe file generated from Visual Studio 2010

Check the project properties. It's configurable there if you are using another .net windows application for example

jQuery find file extension (from string)

You can use a combination of substring and lastIndexOf

Sample

var fileName = "test.jpg";
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1); 

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

PHP7, in php.ini file, remove the ";" before extension=openssl

python encoding utf-8

You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode before it can encode it back to UTF-8. That is what is failing here:

>>> data = u'\u00c3'            # Unicode data
>>> data = data.encode('utf8')  # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8')         # Try to *re*-encode it
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Just write your data directly to the file, there is no need to encode already-encoded data.

If you instead build up unicode values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open() instead, which returns a file object that will encode unicode values to UTF-8 for you.

You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).

For your MySQL insert problem, you need to do two things:

  • Add charset='utf8' to your MySQLdb.connect() call.

  • Use unicode objects, not str objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:

    artiste = artiste.decode('utf8')  # it is already UTF8, decode to unicode
    
    c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    
    # ...
    
    c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
    

It may actually work better if you used codecs.open() to decode the contents automatically instead:

import codecs

sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')

with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
    for line in findex:
        if u'#artiste' not in line:
            continue

        artiste=line.split(u'[:::]')[1].strip()

    cursor = sql.cursor()
    cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    if not cursor.fetchone()[0]:
        cursor = sql.cursor()
        cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
        artists_inserted += 1

You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:

How to extract multiple JSON objects from one file?

Added streaming support based on the answer of @dunes:

import re
from json import JSONDecoder, JSONDecodeError

NOT_WHITESPACE = re.compile(r"[^\s]")


def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
    buf = ""
    ex = None
    while True:
        block = file_obj.read(buf_size)
        if not block:
            break
        buf += block
        pos = 0
        while True:
            match = NOT_WHITESPACE.search(buf, pos)
            if not match:
                break
            pos = match.start()
            try:
                obj, pos = decoder.raw_decode(buf, pos)
            except JSONDecodeError as e:
                ex = e
                break
            else:
                ex = None
                yield obj
        buf = buf[pos:]
    if ex is not None:
        raise ex

How do you set a default value for a MySQL Datetime column?

If you have already created the table then you can use

To change default value to current date time

ALTER TABLE <TABLE_NAME> 
CHANGE COLUMN <COLUMN_NAME> <COLUMN_NAME> DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

To change default value to '2015-05-11 13:01:01'

ALTER TABLE <TABLE_NAME> 
CHANGE COLUMN <COLUMN_NAME> <COLUMN_NAME> DATETIME NOT NULL DEFAULT '2015-05-11 13:01:01';

python save image from url

Anyone who is wondering how to get the image extension then you can try split method of string on image url:

str_arr = str(img_url).split('.')
img_ext = '.' + str_arr[3] #www.bigbasket.com/patanjali-atta.jpg (jpg is after 3rd dot so)
img_data = requests.get(img_url).content
with open(img_name + img_ext, 'wb') as handler:
    handler.write(img_data)

How to exclude a directory in find . command

One option would be to exclude all results that contain the directory name with grep. For example:

find . -name '*.js' | grep -v excludeddir

Extract a substring according to a pattern

This should do:

gsub("[A-Z][1-9]:", "", string)

gives

[1] "E001" "E002" "E003"

How to debug an apache virtual host configuration?

Here's a command I think could be of some help :

apachectl -t -D DUMP_VHOSTS

You'll get a list of all the vhosts, you'll know which one is the default one and you'll make sure that your syntax is correct (same as apachectl configtest suggested by yojimbo87).

You'll also know where each vhost is declared. It can be handy if your config files are a mess. ;)

IndexOf function in T-SQL

One very small nit to pick:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

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

Gets last digit of a number

Just return (number % 10); i.e. take the modulus. This will be much faster than parsing in and out of a string.

If number can be negative then use (Math.abs(number) % 10);

Usage of MySQL's "IF EXISTS"

You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

Turn the EXISTS clause into a subquery instead within an IF function

SELECT IF( EXISTS(
             SELECT *
             FROM gdata_calendars
             WHERE `group` =  ? AND id = ?), 1, 0)

In fact, booleans are returned as 1 or 0

SELECT EXISTS(
         SELECT *
         FROM gdata_calendars
         WHERE `group` =  ? AND id = ?)

MySQL order by before group by

First, don't use * in select, affects their performance and hinder the use of the group by and order by. Try this query:

SELECT wp_posts.post_author, wp_posts.post_date as pdate FROM wp_posts
WHERE wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author           
ORDER BY pdate DESC

When you don't specifies the table in ORDER BY, just the alias, they will order the result of the select.

Multiple files upload in Codeigniter

_x000D_
_x000D_
<?php

if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
            $image_path = array();          
            $count = count($_FILES[$input_name]['name']);   
            for($key =0; $key <$count; $key++){     
                $_FILES['file']['name']     = $_FILES[$input_name]['name'][$key]; 
                $_FILES['file']['type']     = $_FILES[$input_name]['type'][$key]; 
                $_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key]; 
                $_FILES['file']['error']     = $_FILES[$input_name]['error'][$key]; 
                $_FILES['file']['size']     = $_FILES[$input_name]['size'][$key]; 
                    
                $config['file_name'] = $_FILES[$input_name]['name'][$key];                      
                $this->upload->initialize($config); 
                
                if($this->upload->do_upload('file')) {
                    $data = $this->upload->data();
                    $image_path[$key] = $path ."$data[file_name]";                  
                }else{
                    $error =  $this->upload->display_errors();
                $this->session->set_flashdata('msg_error',"image upload! ".$error);
                }   
            }
            return json_encode($image_path);
        }
    
    
   ?>
_x000D_
_x000D_
_x000D_

How to add google-play-services.jar project dependency so my project will run and present map

Be Careful, Follow these steps and save your time

  1. Right Click on your Project Explorer.

  2. Select New-> Project -> Android Application Project from Existing Code

  3. Browse upto this path only - "C:\Users**your path**\Local\Android\android-sdk\extras\google\google_play_services"

  4. Be careful brose only upto - google_play_services and not upto google_play_services_lib

  5. And this way you are able to import the google play service lib.

Let me know if you have any queries regarding the same.

Thanks

cannot convert data (type interface {}) to type string: need type assertion

As asked for by @??s???? an explanation can be found at https://golang.org/pkg/fmt/#Sprint. Related explanations can be found at https://stackoverflow.com/a/44027953/12817546 and at https://stackoverflow.com/a/42302709/12817546. Here is @Yuanbo's answer in full.

package main

import "fmt"

func main() {
    var data interface{} = 2
    str := fmt.Sprint(data)
    fmt.Println(str)
}

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim directly as below:

UPDATE *tablename*
   SET *columnname* = trim(*columnname*);

Maven compile with multiple src directories

I naively do it this way :

<build>
  <finalName>osmwse</finalName>
  <sourceDirectory>src/main/java, src/interfaces, src/services</sourceDirectory>
</build>

Accessing a property in a parent Component

On Angular 6, I access parent properties by injecting the parent via constructor. Not the best solution but it works:

 constructor(@Optional() public parentComponentInjectionObject: ParentComponent){
    // And access like this:
    parentComponentInjectionObject.thePropertyYouWantToAccess;
}

How can I check whether a option already exist in select by JQuery

Another way using jQuery:

var exists = false; 
$('#yourSelect  option').each(function(){
  if (this.value == yourValue) {
    exists = true;
  }
});

Get resultset from oracle stored procedure

In SQL Plus:

SQL> create procedure myproc (prc out sys_refcursor)
  2  is
  3  begin
  4     open prc for select * from emp;
  5  end;
  6  /

Procedure created.

SQL> var rc refcursor
SQL> execute myproc(:rc)

PL/SQL procedure successfully completed.

SQL> print rc

     EMPNO ENAME      JOB              MGR HIREDATE           SAL       COMM     DEPTNO
---------- ---------- --------- ---------- ----------- ---------- ---------- ----------
      7839 KING       PRESIDENT            17-NOV-1981       4999                    10
      7698 BLAKE      MANAGER         7839 01-MAY-1981       2849                    30
      7782 CLARKE     MANAGER         7839 09-JUN-1981       2449                    10
      7566 JONES      MANAGER         7839 02-APR-1981       2974                    20
      7788 SCOTT      ANALYST         7566 09-DEC-1982       2999                    20
      7902 FORD       ANALYST         7566 03-DEC-1981       2999                    20
      7369 SMITHY     CLERK           7902 17-DEC-1980       9988         11         20
      7499 ALLEN      SALESMAN        7698 20-FEB-1981       1599       3009         30
      7521 WARDS      SALESMAN        7698 22-FEB-1981       1249        551         30
      7654 MARTIN     SALESMAN        7698 28-SEP-1981       1249       1400         30
      7844 TURNER     SALESMAN        7698 08-SEP-1981       1499          0         30
      7876 ADAMS      CLERK           7788 12-JAN-1983       1099                    20
      7900 JAMES      CLERK           7698 03-DEC-1981        949                    30
      7934 MILLER     CLERK           7782 23-JAN-1982       1299                    10
      6668 Umberto    CLERK           7566 11-JUN-2009      19999          0         10
      9567 ALLBRIGHT  ANALYST         7788 02-JUN-2009      76999         24         10

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

my helpful code for others(just one aspx to do text area post)::

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication45.WebForm1" %>

<!DOCTYPE html>

    enter code here

<html ng-app="htmldoc" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
    <script src="angular-sanitize.min.js"></script>
    <script>
        angular.module('htmldoc', ['ngSanitize']).controller('x', function ($scope, $sce) {
            //$scope.htmlContent = '<script> (function () { location = \"http://moneycontrol.com\"; } )()<\/script> In last valid content';
            $scope.htmlContent = '';
            $scope.withoutSanitize = function () {
                return $sce.getTrustedHtml($scope.htmlContent);
            };
            $scope.postMessage = function () {
                var ValidContent = $sce.trustAsHtml($scope.htmlContent);

                //your ajax call here
            };
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        Example to show posting valid content to server with two way binding
        <div ng-controller="x">
            <p ng-bind-html="htmlContent"></p>
            <textarea ng-model="htmlContent" ng-trim="false"></textarea>
            <button ng-click="postMessage()">Send</button>
        </div>
    </form>
</body>
</html>

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

This works perfectly as we want:

Unzip files:

find . -name "*.zip" | xargs -P 5 -I FILENAME sh -c 'unzip -o -d "$(dirname "FILENAME")" "FILENAME"'

Above command does not create duplicate directories.

Remove all zip files:

find . -depth -name '*.zip' -exec rm {} \;

Changing Node.js listening port

I usually manually set the port that I am listening on in the app.js file (assuming you are using express.js

var server = app.listen(8080, function() {
    console.log('Ready on port %d', server.address().port);
});

This will log Ready on port 8080 to your console.

How to get date in BAT file

This will give you DD MM YYYY YY HH Min Sec variables and works on any Windows machine from XP Pro and later.

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

How to Diff between local uncommitted changes and origin

To see non-staged (non-added) changes to existing files

git diff

Note that this does not track new files. To see staged, non-commited changes

git diff --cached

Sorting A ListView By Column

I slightly modified the example from Microsoft: https://support.microsoft.com/en-us/kb/319401

This method will only sort once to sort ascending. My modifications make it sort both ways.

public class ListViewItemComparer : IComparer
{
    private int col;
    bool bAsc = false;
    public ListViewItemComparer()
    {
        col = 0;
    }
    public ListViewItemComparer(int column, bool b)
    {
        col = column;
        bAsc = b;
    }
    public int Compare(object x, object y)
    {
        if (bAsc)
        {
            return String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
            bAsc = false;
        }
        else
        {
            return String.Compare(((ListViewItem)y).SubItems[col].Text, ((ListViewItem)x).SubItems[col].Text);
            bAsc = true;
        }
    }

}

Then I create an object of this class whenever a column header is clicked

        bool sortAscending = false;
        private void inventoryList_ColumnClick(object sender, ColumnClickEventArgs e)
        {

            if (!sortAscending)
            {
                sortAscending = true;
            }
            else
            {
                sortAscending = false;
            }
            this.inventoryList.ListViewItemSorter = new ListViewItemComparer(e.Column, sortAscending);

        }

Get folder up one level

Also you can use dirname(__DIR__, $level) for access any folding level without traversing

Could not resolve this reference. Could not locate the assembly

You most likely get this message when the project points to an old location of the assembly where it no longer exists. Since you were able to build it once, the assembly has already been copied into your bin\Debug / bin\Release folders so your project can still find a copy.

If you open the references node of the project in your solution explorer, there should be a yellow icon next to the reference. Remove the reference and add it again from the correct location.

If you want to know the location it was referenced from, you'd have to open the .csproj file in a text editor and look for the HintPath for that assembly - the IDE for some reason does not show this information.

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

How to get a function name as a string?

sys._getframe() is not guaranteed to be available in all implementations of Python (see ref) ,you can use the traceback module to do the same thing, eg.

import traceback
def who_am_i():
   stack = traceback.extract_stack()
   filename, codeline, funcName, text = stack[-2]

   return funcName

A call to stack[-1] will return the current process details.

How to Generate unique file names in C#

I've written a simple recursive function that generates file names like Windows does, by appending a sequence number prior to the file extension.

Given a desired file path of C:\MyDir\MyFile.txt, and the file already exists, it returns a final file path of C:\MyDir\MyFile_1.txt.

It is called like this:

var desiredPath = @"C:\MyDir\MyFile.txt";
var finalPath = UniqueFileName(desiredPath);

private static string UniqueFileName(string path, int count = 0)
{
    if (count == 0)
    {
        if (!File.Exists(path))
        {
            return path;
        }
    }
    else
    {
        var candidatePath = string.Format(
            @"{0}\{1}_{2}{3}",
            Path.GetDirectoryName(path),
            Path.GetFileNameWithoutExtension(path),
            count,
            Path.GetExtension(path));

        if (!File.Exists(candidatePath))
        {
            return candidatePath;
        }
    }

    count++;
    return UniqueFileName(path, count);
}

Return rows in random order

The usual method is to use the NEWID() function, which generates a unique GUID. So,

SELECT * FROM dbo.Foo ORDER BY NEWID();

m2e lifecycle-mapping not found

Maven is trying to download m2e's lifecycle-mapping artifact, which M2E uses to determine how to process plugins within Eclipse (adding source folders, etc.). For some reason this artifact cannot be downloaded. Do you have an internet connection? Can other artifacts be downloaded from repositories? Proxy settings?

For more details from Maven, try turning M2E debug output on (Settings/Maven/Debug Output checkbox) and it might give you more details as to why it cannot download from the repository.

Filtering Table rows using Jquery

I used Beetroot-Betroot's solution, but instead of using contains, I used containsNC, which makes it case insensitive.

$.extend($.expr[":"], {
"containsNC": function(elem, i, match, array) {
return (elem.textContent || elem.innerText ||
"").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});

Integer expression expected error in shell script

Try this:

If [ $a -lt 4 ] || [ $a -gt 64 ] ; then \n
     Something something \n
elif [ $a -gt 4 ] || [ $a -lt 64 ] ; then \n
     Something something \n
else \n
    Yes it works for me :) \n

Android - R cannot be resolved to a variable

Fought the same problem for about an hour. I finally realized that I was referencing some image files in an xml file that I did not yet have in my R.drawable folder. As soon as I copied the files into the folder, the problem went away. You need to make sure you have all the necessary files present.

PNG transparency issue in IE8

please try below code.

 background: transparent\0/;
 filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png');   /* IE7 */      
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png')"; /* IE8 */   

Is there a destructor for Java?

There is no exactly destructor class in Java, class destroyed in java automatically by garbage collector . but you could do that using below one but it's not exact same thing :

finalize()

There was a question that spawned in-depth discussion of finalize , so that you should get more depth if required...

Uploading files to file server using webclient class

when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.

When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).

Bootstrap 3 Collapse show state with Chevron icon

I wanted a pure html approach as I wanted to collapse and expand html that was added on the fly via a template! I came up with this...

https://jsfiddle.net/3mguht2y/1/

var noJavascript = ":)";

Which might be of use to someone :)

Adding content to a linear layout dynamically?

You can achieve LinearLayout cascading like this:

LinearLayout root = (LinearLayout) findViewById(R.id.my_root);    
LinearLayout llay1 = new LinearLayout(this);    
root.addView(llay1);
LinearLayout llay2 = new LinearLayout(this);    
llay1.addView(llay2);