Programs & Examples On #Jquery blockui

The jQuery BlockUI Plugin lets you simulate synchronous behavior when using AJAX by blocking user interaction and showing a user-defined wait indication.

TypeError: $.browser is undefined

$().live(function(){}); and jQuery.browser is undefined in jquery 1.9.0 - $.browser was deprecated in jquery update

sounds like you are using a different version of jquery 1.9 in godaddy so either change your code or include the migrate plugin http://code.jquery.com/jquery-migrate-1.0.0.js

CSS - Overflow: Scroll; - Always show vertical scroll bar?

This will work with iPad on Safari on iOS 7.1.x from my testing, I'm not sure about iOS 6 though. However, it will not work on Firefox. There is a jQuery plugin which aims to be cross browser compliant called jScrollPane.

Also, there is a duplicate post here on Stack Overflow which has some other details.

MySQL - How to select rows where value is in array?

If you use the FIND_IN_SET function:

FIND_IN_SET(a, columnname) yields all the records that have "a" in them, alone or with others

AND

FIND_IN_SET(columnname, a) yields only the records that have "a" in them alone, NOT the ones with the others

So if record1 is (a,b,c) and record2 is (a)

FIND_IN_SET(columnname, a) yields only record2 whereas FIND_IN_SET(a, columnname) yields both records.

jQuery datepicker to prevent past date

This should work <input type="text" id="datepicker">

var dateToday = new Date();
$("#datepicker").datepicker({
    minDate: dateToday,
    onSelect: function(selectedDate) {
    var option = this.id == "datepicker" ? "minDate" : "maxDate",
    instance = $(this).data("datepicker"),
    date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
    dates.not(this).datepicker("option", option, date);
    }
});

Select subset of columns in data.table R

Use with=FALSE:

cols = paste("V", c(1,2,3,5), sep="")

dt[, !cols, with=FALSE]

I suggest going through the "Introduction to data.table" vignette.


Update: From v1.10.2 onwards, you can also do:

dt[, ..cols]

See the first NEWS item under v1.10.2 here for additional explanation.

How do I create a SQL table under a different schema?

Try running CREATE TABLE [schemaname].[tableName]; GO;

This assumes the schemaname exists in your database. Please use CREATE SCHEMA [schemaname] if you need to create a schema as well.

EDIT: updated to note SQL Server 11.03 requiring this be the only statement in the batch.

Add number of days to a date

You may try this.

$i=30;
echo  date("Y-m-d",mktime(0,0,0,date('m'),date('d')+$i,date('Y')));

How to remove the hash from window.location (URL) with JavaScript without page refresh?

I think, it would be more safe

if (window.history) {
    window.history.pushState('', document.title, window.location.href.replace(window.location.hash, ''));
} else {
    window.location.hash = '';
}

R - Markdown avoiding package loading messages

This is an old question, but here's another way to do it.

You can modify the R code itself instead of the chunk options, by wrapping the source call in suppressPackageStartupMessages(), suppressMessages(), and/or suppressWarnings(). E.g:

```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```

You can also put those functions around your library() calls inside the "source.R" script.

How do I check in python if an element of a list is empty?

Just check if that element is equal to None type or make use of NOT operator ,which is equivalent to the NULL type you observe in other languages.

if not A[i]:
    ## do whatever

Anyway if you know the size of your list then you don't need to do all this.

Fragment Inside Fragment

AFAIK, fragments cannot hold other fragments.


UPDATE

With current versions of the Android Support package -- or native fragments on API Level 17 and higher -- you can nest fragments, by means of getChildFragmentManager(). Note that this means that you need to use the Android Support package version of fragments on API Levels 11-16, because even though there is a native version of fragments on those devices, that version does not have getChildFragmentManager().

Get list from pandas DataFrame column headers

list(df.columns)

This gives you the list of column names of a data frame df.

How to create a project from existing source in Eclipse and then find it?

This answer is going to be for the question

How to create a new eclipse project and add a folder or a new package into the project, or how to build a new project for existing java files.

  1. Create a new project from the menu File->New-> Java Project
  2. If you are going to add a new pakcage, then create the same package name here by File->New-> Package
  3. Click the name of the package in project navigator, and right click, and import... Import->General->File system (choose your file or package)

this worked for me I hope it helps others. Thank you.

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

how to rotate text left 90 degree and cell size is adjusted according to text in html

Without calculating height. Strict CSS and HTML. <span/> only for Chrome, because the chrome isn't able change text direction for <th/>.

_x000D_
_x000D_
th _x000D_
{_x000D_
  vertical-align: bottom;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
th span _x000D_
{_x000D_
  -ms-writing-mode: tb-rl;_x000D_
  -webkit-writing-mode: vertical-rl;_x000D_
  writing-mode: vertical-rl;_x000D_
  transform: rotate(180deg);_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <th><span>Rotated text by 90 deg.</span></th>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Private properties in JavaScript ES6 classes

WeakMap

  • supported in IE11 (Symbols are not)
  • hard-private (props using Symbols are soft-private due to Object.getOwnPropertySymbols)
  • can look really clean (unlike closures which require all props and methods in the constructor)

First, define a function to wrap WeakMap:

function Private() {
  const map = new WeakMap();
  return obj => {
    let props = map.get(obj);
    if (!props) {
      props = {};
      map.set(obj, props);
    }
    return props;
  };
}

Then, construct a reference outside your class:

const p = new Private();

class Person {
  constructor(name, age) {
    this.name = name;
    p(this).age = age; // it's easy to set a private variable
  }

  getAge() {
    return p(this).age; // and get a private variable
  }
}

Note: class isn't supported by IE11, but it looks cleaner in the example.

AppFabric installation failed because installer MSI returned with error code : 1603

I also hit this error…

The installation msi will try to create a new task in the Windows Task scheduler to remind you to give customer feedback. This install step executes regardless of whether you do or do not click the check box to participate in customer feedback. In many corporate environments (including mine) creating new windows tasks is denied to all but domain administrators. As a result, running as a local admin is not sufficient and the entire installation fails when adding the task returns “access denied”. This shows up in the install log as a 1603.

The only workaround we could find was to manually pull all the files out of the msi, remove the “add schedule task” from the install script, and then create a new msi. After that one line change, it worked fine.

How to emulate a do-while loop in Python?

See if this helps :

Set a flag inside the exception handler and check it before working on the s.

flagBreak = false;
while True :

    if flagBreak : break

    if s :
        print s
    try :
        s = i.next()
    except StopIteration :
        flagBreak = true

print "done"

How to control border height?

Only using line-height

line-height: 10px;

enter image description here

Description Box using "onmouseover"

Well, I made a simple two liner script for this, Its small and does what u want.

Check it http://jsfiddle.net/9RxLM/

Its a jquery solution :D

ShowAllData method of Worksheet class failed

I am also the same problem. I think the reason are,

1) When my activecell is within the table, "ActiveSheet.ShowAllData" can be work. 2) When my activecell not within the table, "ActiveSheet.ShowAllData" cannot work.Using this code, ActiveSheet.ListObjects("Srv").Range.AutoFilter Field:=1 can clear the filter.

Swift extract regex matches

update @Mike Chirico's to Swift 5

extension String{



  func regex(pattern: String) -> [String]?{
    do {
        let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: 0))
        let all = NSRange(location: 0, length: count)
        var matches = [String]()
        regex.enumerateMatches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: all) {
            (result : NSTextCheckingResult?, _, _) in
              if let r = result {
                    let nsstr = self as NSString
                    let result = nsstr.substring(with: r.range) as String
                    matches.append(result)
              }
        }
        return matches
    } catch {
        return nil
    }
  }
}

Loop code for each file in a directory

scandir:

$files = scandir('folder/');
foreach($files as $file) {
  //do your work here
}

or glob may be even better for your needs:

$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
  //do your work here
}

Combine two integer arrays

Find the total size of both array and set array1and2 to the total size of both array added. Then loop array1 and then array2 and add the values into array1and2.

Windows equivalent of linux cksum command

It looks as if there is an unsupported tool for checksums from MS. It's light on features but appears to do what you're asking for. It was published in August of 2012. It's called "Microsoft File Checksum Integrity Verifier".

http://www.microsoft.com/en-us/download/details.aspx?id=11533

How can I upload files asynchronously?

Note: This answer is outdated, it is now possible to upload files using XHR.


You cannot upload files using XMLHttpRequest (Ajax). You can simulate the effect using an iframe or Flash. The excellent jQuery Form Plugin that posts your files through an iframe to get the effect.

What is the Git equivalent for revision number?

This is what I did in my makefile based on others solutions. Note not only does this give your code a revision number, it also appends the hash which allows you to recreate the release.

# Set the source control revision similar to subversion to use in 'c'
# files as a define.
# You must build in the master branch otherwise the build branch will
# be prepended to the revision and/or "dirty" appended. This is to
# clearly ID developer builds.
REPO_REVISION_:=$(shell git rev-list HEAD --count)
BUILD_BRANCH:=$(shell git rev-parse --abbrev-ref HEAD)
BUILD_REV_ID:=$(shell git rev-parse HEAD)
BUILD_REV_ID_SHORT:=$(shell git describe --long --tags --dirty --always)
ifeq ($(BUILD_BRANCH), master)
REPO_REVISION:=$(REPO_REVISION_)_g$(BUILD_REV_ID_SHORT)
else
REPO_REVISION:=$(BUILD_BRANCH)_$(REPO_REVISION_)_r$(BUILD_REV_ID_SHORT)
endif
export REPO_REVISION
export BUILD_BRANCH
export BUILD_REV_ID

How do I change the figure size for a seaborn plot?

You can set the context to be poster or manually set fig_size.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10


# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)    
sns.despine()

fig.savefig('example.png')

enter image description here

Convert list to array in Java

I came across this code snippet that solves it.

//Creating a sample ArrayList 
List<Long> list = new ArrayList<Long>();

//Adding some long type values
list.add(100l);
list.add(200l);
list.add(300l);

//Converting the ArrayList to a Long
Long[] array = (Long[]) list.toArray(new Long[list.size()]);

//Printing the results
System.out.println(array[0] + " " + array[1] + " " + array[2]);

The conversion works as follows:

  1. It creates a new Long array, with the size of the original list
  2. It converts the original ArrayList to an array using the newly created one
  3. It casts that array into a Long array (Long[]), which I appropriately named 'array'

add title attribute from css

You can't. CSS is a presentation language. It isn't designed to add content (except for the very trivial with :before and :after).

Getting HTTP code in PHP using curl

First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:

if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
    return false;
}

Make sure you only fetch the headers, not the body content:

@curl_setopt($ch, CURLOPT_HEADER  , true);  // we want headers
@curl_setopt($ch, CURLOPT_NOBODY  , true);  // we don't need body

For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):


As a whole:

$url = 'http://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true);    // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo 'HTTP code: ' . $httpcode;

How to insert table values from one database to another database?

Mostly we need this type of query in migration script

INSERT INTO  db1.table1(col1,col2,col3,col4)
SELECT col5,col6,col7,col8
  FROM db1.table2

In this query column count must be same in both table

Xcode project not showing list of simulators

Deployment Target version change to a lower one helped for me:

Window -> Devices and Simulators -> Simulators. Check what are the latest versions of existing simulators.

simulators

Then go to your project's Target. Under Deployment Info, change Target to the version you saw the latest within your simulators. Mine was set to iOS 13.6 when the simulator was iOS 13.5 only.

deployment-target

Fatal error: Class 'PHPMailer' not found

I suggest you look into getting composer. https://getcomposer.org Composer makes getting third-party libraries a LOT easier and using a single autoloader for all of them. It also standardizes on where all your dependencies are located, along with some automatization capabilities.

Download https://getcomposer.org/composer.phar to C:\Inetpub\wwwroot\php

Delete your C:\Inetpub\wwwroot\php\PHPMailer\ directory.

Use composer.phar to get the phpmailer package using the command line to execute

cd C:\Inetpub\wwwroot\php
php composer.phar require phpmailer/phpmailer

After it is finished it will create a C:\Inetpub\wwwroot\php\vendor directory along with all of the phpmailer files and generate an autoloader.

Next in your main project configuration file you need to include the autoload file.

require_once 'C:\Inetpub\wwwroot\php\vendor\autoload.php';

The vendor\autoload.php will include the information for you to use $mail = new \PHPMailer;

Additional information on the PHPMailer package can be found at https://packagist.org/packages/phpmailer/phpmailer

Local and global temporary tables in SQL Server

I find this explanation quite clear (it's pure copy from Technet):

There are two types of temporary tables: local and global. Local temporary tables are visible only to their creators during the same connection to an instance of SQL Server as when the tables were first created or referenced. Local temporary tables are deleted after the user disconnects from the instance of SQL Server. Global temporary tables are visible to any user and any connection after they are created, and are deleted when all users that are referencing the table disconnect from the instance of SQL Server.

Get size of a View in React Native

for me setting the Dimensions to use % is what worked for me width:'100%'

How to get an Instagram Access Token

Almost all of the replies that people have posted so far only cover how to handle access tokens on the front end, following Instagram's client-side "implicit authentication" procedure. This method is less secure and unrecommended according to Instagram's API docs.

Assuming you are using a server, the Instagram docs sort of fail in providing a clear answer about exchanging a code for a token, as they only give an example of a cURL request. Essentially you have to make a POST request to their server with the provided code and all of your app's information, and they will return a user object including user information and the token.

I don't know what language you are writing in, but I solved this in Node.js with the request npm module which you can find here.

I parsed through the url and used this information to send the post request

var code = req.url.split('code=')[1];

request.post(
  { form: { client_id: configAuth.instagramAuth.clientID,
            client_secret: configAuth.instagramAuth.clientSecret,
            grant_type: 'authorization_code',
            redirect_uri: configAuth.instagramAuth.callbackURL,
            code: code
          },
    url: 'https://api.instagram.com/oauth/access_token'
  },
  function (err, response, body) {
    if (err) {
      console.log("error in Post", err)
    }else{
      console.log(JSON.parse(body))
    }
  }
);

Of course replace the configAuth stuff with your own information. You probably aren't using Node.js, but hopefully this solution will help you translate your own solution into whatever language you are using it in.

How to localise a string inside the iOS info.plist file?

Step by step localize Info.plist:

  1. Find in the Xcode the folder Resources (is placed in root)
  2. Select the folder Resources
  3. Then press the main menu File->New->File...
  4. Select in section "Resource" Strings File and press Next
  5. Then in Save As field write InfoPlist ONLY ("I" capital and "P" capital)
  6. Then press Create
  7. Then select the file InfoPlist.strings that created in Resources folder and press in the right menu the button "Localize"
  8. Then you Select the Project from the Project Navigator and select the The project from project list
  9. In the info tab at the bottom you can as many as language you want (There is in section Localizations)
  10. The language you can see in Resources Folder
  11. To localize the values ("key") from info.plist file you can open with a text editor and get all the keys you want to localize
  12. You write any key as the example in any InfoPlist.strings like the above example

"NSLocationAlwaysAndWhenInUseUsageDescription"="blabla";

"NSLocationAlwaysUsageDescription"="blabla2";

That's all work and you have localize your info.plist file!

How to break a while loop from an if condition inside the while loop?

while(something.hasnext())
do something...
   if(contains something to process){
      do something...
      break;
   }
}

Just use the break statement;

For eg:this just prints "Breaking..."

while (true) {
     if (true) {
         System.out.println("Breaking...");
         break;
     }
     System.out.println("Did this print?");
}

CSS selector for text input fields?

The attribute selectors are often used for inputs. This is the list of attribute selectors:

[title] All elements with the title attribute are selected.

[title=banana] All elements which have the 'banana' value of the title attribute.

[title~=banana] All elements which contain 'banana' in the value of the title attribute.

[title|=banana] All elements which value of the title attribute starts with 'banana'.

[title^=banana] All elements which value of the title attribute begins with 'banana'.

[title$=banana] All elements which value of the title attribute ends with 'banana'.

[title*=banana] All elements which value of the title attribute contains the substring 'banana'.

Reference: https://kolosek.com/css-selectors/

How to check whether a Storage item is set?

I've used in my project and works perfectly for me

var returnObjName= JSON.parse(localStorage.getItem('ObjName'));
if(returnObjName && Object.keys(returnObjName).length > 0){
   //Exist data in local storage
}else{
  //Non Exist data block
}

Force file download with php using header()

Here is a snippet from me in testing... obviously passing via get to the script may not be the best... should post or just send an id and grab guid from db... anyhow.. this worked. I take the URL and convert it to a path.

// Initialize a file URL to the variable
$file = $_GET['url'];
$file = str_replace(Polepluginforrvms_Plugin::$install_url, $DOC_ROOT.'/pole-permitter/', $file );

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size   = filesize($file);

header( "Content-type: application/octet-stream" );
header( "Content-Disposition: attachment; filename={$quoted}" );
header( "Content-length: " . $size );
header( "Pragma: no-cache" );
header( "Expires: 0" );
readfile( "{$file}" );

How to create Custom Ratings bar in Android

I need to add my solution which is WAY eaiser than the one above. We don't even need to use styles.

Create a selector file in the drawable folder:

custom_ratingbar_selector.xml

<?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@android:id/background"
    android:drawable="@drawable/star_off" />

 <item android:id="@android:id/secondaryProgress"
    android:drawable="@drawable/star_off" />

 <item android:id="@android:id/progress"
    android:drawable="@drawable/star_on" />

</layer-list>

In the layout set the selector file as progressDrawable:

 <RatingBar
        android:id="@+id/ratingBar2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:progressDrawable="@drawable/custom_ratingbar_selector"
        android:numStars="8"
        android:stepSize="0.2"
        android:rating="3.0" />

And that's all we need.

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

GO ends a batch, you would only very rarely need to use it in code. Be aware that if you use it in a stored proc, no code after the GO will be executed when you execute the proc.

BEGIN and END are needed for any procedural type statements with multipe lines of code to process. You will need them for WHILE loops and cursors (which you will avoid if at all possible of course) and IF statements (well techincally you don't need them for an IF statment that only has one line of code, but it is easier to maintain the code if you always put them in after an IF). CASE statements also use an END but do not have a BEGIN.

Use of 'const' for function parameters

Being a VB.NET programmer that needs to use a C++ program with 50+ exposed functions, and a .h file that sporadically uses the const qualifier, it is difficult to know when to access a variable using ByRef or ByVal.

Of course the program tells you by generating an exception error on the line where you made the mistake, but then you need to guess which of the 2-10 parameters is wrong.

So now I have the distasteful task of trying to convince a developer that they should really define their variables (in the .h file) in a manner that allows an automated method of creating all of the VB.NET function definitions easily. They will then smugly say, "read the ... documentation."

I have written an awk script that parses a .h file, and creates all of the Declare Function commands, but without an indicator as to which variables are R/O vs R/W, it only does half the job.

EDIT:

At the encouragement of another user I am adding the following;

Here is an example of a (IMO) poorly formed .h entry;

typedef int (EE_STDCALL *Do_SomethingPtr)( int smfID, const char* cursor_name, const char* sql );

The resultant VB from my script;

    Declare Function Do_Something Lib "SomeOther.DLL" (ByRef smfID As Integer, ByVal cursor_name As String, ByVal sql As String) As Integer

Note the missing "const" on the first parameter. Without it, a program (or another developer) has no Idea the 1st parameter should be passed "ByVal." By adding the "const" it makes the .h file self documenting so that developers using other languages can easily write working code.

Is there an addHeaderView equivalent for RecyclerView?

I have implemented the same approach proposed by EC84B4 answer, but I abstracted RecycleViewAdapter and make it easily resuable by means of interfaces.

So in order to use my approach you should add following base classes and interfaces to your project:

1) Interface that provides data for Adapter (collection of generic type T, and additional parameters (if needed) of generic type P)

public interface IRecycleViewListHolder<T,P>{
            P getAdapterParameters();
            T getItem(int position);
            int getSize();
    }

2) Factory for binding your items (header/item):

public interface IViewHolderBinderFactory<T,P> {
        void bindView(RecyclerView.ViewHolder holder, int position,IRecycleViewListHolder<T,P> dataHolder);
}

3) Factory for viewHolders (header/items):

public interface IViewHolderFactory {
    RecyclerView.ViewHolder provideInflatedViewHolder(int viewType, LayoutInflater layoutInflater,@NonNull ViewGroup parent);
}

4) Base class for Adapter with Header:

public class RecycleViewHeaderBased<T,P> extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    public final static int HEADER_TYPE = 1;
    public final static int ITEM_TYPE = 0;
    private final IRecycleViewListHolder<T, P> dataHolder;
    private final IViewHolderBinderFactory<T,P> binderFactory;
    private final IViewHolderFactory viewHolderFactory;

    public RecycleViewHeaderBased(IRecycleViewListHolder<T,P> dataHolder, IViewHolderBinderFactory<T,P> binderFactory, IViewHolderFactory viewHolderFactory) {
        this.dataHolder = dataHolder;
        this.binderFactory = binderFactory;
        this.viewHolderFactory = viewHolderFactory;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        return viewHolderFactory.provideInflatedViewHolder(viewType,layoutInflater,parent);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            binderFactory.bindView(holder, position,dataHolder);
    }

    @Override
    public int getItemViewType(int position) {
        if(position == 0)
            return HEADER_TYPE;
        return ITEM_TYPE;
    }

    @Override
    public int getItemCount() {
        return dataHolder.getSize()+1;
    }
}

Usage example:

1) IRecycleViewListHolder implementation:

public class AssetTaskListData implements IRecycleViewListHolder<Map.Entry<Integer, Integer>, GroupedRecord> {
    private List<Map.Entry<Integer, Integer>> assetCountList;
    private GroupedRecord record;

    public AssetTaskListData(Map<Integer, Integer> assetCountListSrc, GroupedRecord record) {
        this.assetCountList =  new ArrayList<>();
        for(Object  entry: assetCountListSrc.entrySet().toArray()){
            Map.Entry<Integer,Integer> entryTyped = (Map.Entry<Integer,Integer>)entry;
            assetCountList.add(entryTyped);
        }
        this.record = record;
    }

    @Override
    public GroupedRecord getAdapterParameters() {
        return record;
    }

    @Override
    public Map.Entry<Integer, Integer> getItem(int position) {
        return assetCountList.get(position-1);
    }

    @Override
    public int getSize() {
        return assetCountList.size();
    }
}

2) IViewHolderBinderFactory implementation:

public class AssetTaskListBinderFactory implements IViewHolderBinderFactory<Map.Entry<Integer, Integer>, GroupedRecord> {
    @Override
    public void bindView(RecyclerView.ViewHolder holder, int position, IRecycleViewListHolder<Map.Entry<Integer, Integer>, GroupedRecord> dataHolder) {
        if (holder instanceof AssetItemViewHolder) {
            Integer assetId = dataHolder.getItem(position).getKey();
            Integer assetCount = dataHolder.getItem(position).getValue();
            ((AssetItemViewHolder) holder).bindItem(dataHolder.getAdapterParameters().getRecordId(), assetId, assetCount);
        } else {
            ((AssetHeaderViewHolder) holder).bindItem(dataHolder.getAdapterParameters());
        }
    }
}

3) IViewHolderFactory implementation:

public class AssetTaskListViewHolderFactory implements IViewHolderFactory {
    private IPropertyTypeIconMapper iconMapper;
    private ITypeCaster caster;

    public AssetTaskListViewHolderFactory(IPropertyTypeIconMapper iconMapper, ITypeCaster caster) {
        this.iconMapper = iconMapper;
        this.caster = caster;
    }

    @Override
    public RecyclerView.ViewHolder provideInflatedViewHolder(int viewType, LayoutInflater layoutInflater, @NonNull ViewGroup parent) {
        if (viewType == RecycleViewHeaderBased.HEADER_TYPE) {
            AssetBasedHeaderItemBinding item = DataBindingUtil.inflate(layoutInflater, R.layout.asset_based_header_item, parent, false);
            return new AssetHeaderViewHolder(item.getRoot(), item, caster);
        }
        AssetBasedListItemBinding item = DataBindingUtil.inflate(layoutInflater, R.layout.asset_based_list_item, parent, false);
        return new AssetItemViewHolder(item.getRoot(), item, iconMapper, parent.getContext());
    }
}

4) Deriving adapter

public class AssetHeaderTaskListAdapter extends RecycleViewHeaderBased<Map.Entry<Integer, Integer>, GroupedRecord> {
   public AssetHeaderTaskListAdapter(IRecycleViewListHolder<Map.Entry<Integer, Integer>, GroupedRecord> dataHolder,
                                      IViewHolderBinderFactory binderFactory,
                                      IViewHolderFactory viewHolderFactory) {
        super(dataHolder, binderFactory, viewHolderFactory);
    }
}

5) Instantiate adapter class:

private void setUpAdapter() {
        Map<Integer, Integer> objectTypesCountForGroupedTask = groupedTaskRepository.getObjectTypesCountForGroupedTask(this.groupedRecordId);
        AssetTaskListData assetTaskListData = new AssetTaskListData(objectTypesCountForGroupedTask, getGroupedRecord());
        adapter = new AssetHeaderTaskListAdapter(assetTaskListData,new AssetTaskListBinderFactory(),new AssetTaskListViewHolderFactory(iconMapper,caster));
        assetTaskListRecycler.setAdapter(adapter);
    }

P.S.: AssetItemViewHolder, AssetBasedListItemBinding, etc. my application own structures that should be swapped by your own, for your own purposes.

Node.js - SyntaxError: Unexpected token import

I've been trying to get this working. Here's what works:

  1. Use a recent node version. I'm using v14.15.5. Verify your version by running: node --version
  2. Name the files so that they all end with .mjs rather than .js

Example:

mod.mjs

export const STR = 'Hello World'

test.mjs

import {STR} from './mod.mjs'
console.log(STR)

Run: node test.mjs

You should see "Hello World".

MySQL Trigger after update only if row has changed

I cant comment, so just beware, that if your column supports NULL values, OLD.x<>NEW.x isnt enough, because

SELECT IF(1<>NULL,1,0)

returns 0 as same as

NULL<>NULL 1<>NULL 0<>NULL 'AAA'<>NULL

So it will not track changes FROM and TO NULL

The correct way in this scenario is

((OLD.x IS NULL AND NEW.x IS NOT NULL) OR (OLD.x IS NOT NULL AND NEW.x IS NULL) OR (OLD.x<>NEW.x))

How to set character limit on the_content() and the_excerpt() in wordpress

wp_trim_words This function trims text to a certain number of words and returns the trimmed text.

Example:-

echo wp_trim_words( get_the_content(), 40, '...' );

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

jquery input select all on focus

This version works on ios and also fixes standard drag-to-select on windows chrome

var srcEvent = null;

$("input[type=text],input[type=number]")

    .mousedown(function (event) {
        srcEvent = event;
    })

    .mouseup(function (event) {
        var delta = Math.abs(event.clientX - srcEvent.clientX) 
                  + Math.abs(event.clientY - srcEvent.clientY);

        var threshold = 2;
        if (delta <= threshold) {
                   try {
                        // ios likes this but windows-chrome does not on number fields
                        $(this)[0].selectionStart = 0;
                        $(this)[0].selectionEnd = 1000;
                    } catch (e) {
                        // windows-chrome likes this
                        $(this).select();
                    }
        }
    });

http://jsfiddle.net/Zx2sc/2/

Setting paper size in FPDF

/*$mpdf = new mPDF('',    // mode - default ''
 '',    // format - A4, for example, default ''
 0,     // font size - default 0
 '',    // default font family
 15,    // margin_left
 15,    // margin right
 16,     // margin top
 16,    // margin bottom
 9,     // margin header
 9,     // margin footer
 'L');  // L - landscape, P - portrait*/

HTTP Basic: Access denied fatal: Authentication failed

Before digging into the solution lets first see why this happens.

Before any transaction with git that your machine does git checks for your authentication which can be done using

  1. An SSH key token present in your machine and shared with git-repo(most preferred) OR
  2. Using your username/password (mostly used)

Why did this happen

In simple words, this happened because the credentials stored in your machine are not authentic i.e.there are chances that your password stored in the machine has changed from whats there in git therefore

Solution

Head towards, control panel and search for Credential Manager look for your use git url and change the creds.

There you go this works with mostly every that windows keep track off

How to run a Maven project from Eclipse?

Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).

To enable this, the <packaging> element in your pom.xml should be jar (or similar).

Then, right-click the project and select Maven > Update Project Configuration

For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.

How to put wildcard entry into /etc/hosts?

Here is the configuration for those trying to accomplish the original goal (wildcards all pointing to same codebase -- install nothing, dev environment ie, XAMPP)

hosts file (add an entry)

file: /etc/hosts (non-windows)

127.0.0.1   example.local

httpd.conf configuration (enable vhosts)

file: /XAMPP/etc/httpd.conf

# Virtual hosts
Include etc/extra/httpd-vhosts.conf

httpd-vhosts.conf configuration

file: XAMPP/etc/extra/httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "/path_to_XAMPP/htdocs"
    ServerName example.local
    ServerAlias *.example.local
#    SetEnv APP_ENVIRONMENT development
#    ErrorLog "logs/example.local-error_log"
#    CustomLog "logs/example.local-access_log" common
</VirtualHost>

restart apache

create pac file:

save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)

function FindProxyForURL(url, host) {
  if (shExpMatch(host, "*example.local")) {
    return "PROXY example.local";
  }
  return "DIRECT";
}

How to read multiple Integer values from a single line of input in Java?

You're probably looking for String.split(String regex). Use " " for your regex. This will give you an array of strings that you can parse individually into ints.

Copy files on Windows Command Line with Progress

I used the copy command with the /z switch for copying over network drives. Also works for copying between local drives. Tested on XP Home edition.

React Router v4 - How to get current route?

In react router 4 the current route is in - this.props.location.pathname. Just get this.props and verify. If you still do not see location.pathname then you should use the decorator withRouter.

This might look something like this:

import {withRouter} from 'react-router-dom';

const SomeComponent = withRouter(props => <MyComponent {...props}/>);

class MyComponent extends React.Component {
  SomeMethod () {
    const {pathname} = this.props.location;
  }
}

Showing which files have changed between two revisions

git diff revision_n revision_m

if revision_n and revision_m are successive commits then it outputs same as git show revision_m

How to get multiline input from user

no_of_lines = 5
lines = ""
for i in xrange(5):
    lines+=input()+"\n"
    a=raw_input("if u want to continue (Y/n)")
    ""
    if(a=='y'):
        continue
    else:
        break
    print lines

Does mobile Google Chrome support browser extensions?

You can use bookmarklets (javascript code in a bookmark) - this also means they sync across devices.

I have loads - I prefix the name with zzz, so they are eazy to type in to the address bar and show in drop down predictions.

To get them to operate on a page you need to go to the page and then in the address bar type the bookmarklet name - this will cause the bookmarklet to execute in the context of the page.

edit

Just to highlight - for this to work, the bookmarklet name must be typed into the address bar while the page you want to operate in is being displayed - if you go off to select the bookmarklet in some other way the page context gets lost, and the bookmarklet operates on a new empty page.

I use zzzpocket - send to pocket. zzztwitter tweet this page zzzmail email this page zzzpressthis send this page to wordpress zzztrello send this page to trello and more...

and it works in chrome whatever platform I am currently logged on to.

.gitignore after commit

I had to remove .idea and target folders and after reading all comments this worked for me:

git rm -r .idea
git rm -r target
git commit -m 'removed .idea folder'

and then push to master

Does delete on a pointer to a subclass call the base class destructor?

The destructor for the object of class A will only be called if delete is called for that object. Make sure to delete that pointer in the destructor of class B.

For a little more information on what happens when delete is called on an object, see: http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.9

How to display .svg image using swift

My solution to show .svg in UIImageView from URL. You need to install SVGKit pod

Then just use it like this:

import SVGKit

 let svg = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!
 let data = try? Data(contentsOf: svg)
 let receivedimage: SVGKImage = SVGKImage(data: data)
 imageview.image = receivedimage.uiImage

or you can use extension for async download

extension UIImageView {
func downloadedsvg(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
    contentMode = mode
    URLSession.shared.dataTask(with: url) { data, response, error in
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let receivedicon: SVGKImage = SVGKImage(data: data),
            let image = receivedicon.uiImage
            else { return }
        DispatchQueue.main.async() {
            self.image = image
        }
    }.resume()
}
}

How to use:

let svg = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!

imageview.downloadedsvg(from: svg)

Adding onClick event dynamically using jQuery

Try below approach,

$('#bfCaptchaEntry').on('click', myfunction);

or in case jQuery is not an absolute necessaity then try below,

document.getElementById('bfCaptchaEntry').onclick = myfunction;

However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...

Read more on this post https://stackoverflow.com/a/6348597/297641

Select the first 10 rows - Laravel Eloquent

The simplest way in laravel 5 is:

$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

Cannot authenticate into mongo, "auth fails"

The proper way to login into mongo shell is

mongo localhost:27017 -u 'uuuuu' -p '>xxxxxx' --authenticationDatabase dbname

jquery smooth scroll to an anchor?

Try this one. It is a code from CSS tricks that I modified, it is pretty straight forward and does both horizontal and vertial scrolling. Needs JQuery. Here is a demo

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top-10, scrollLeft:target.offset().left-10
        }, 1000);
        return false;
      }
    }
  });
});

This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

this issue occur for me after downgrade Java JDK, after upgrade JDK my problem resolved.

Text in Border CSS HTML

You can do something like this, where you set a negative margin on the h1 (or whatever header you are using)

div{
    height:100px;
    width:100px;
    border:2px solid black;
}

h1{
    width:30px;
    margin-top:-10px;
    margin-left:5px;
    background:white;
}

Note: you need to set a background as well as a width on the h1

Example: http://jsfiddle.net/ZgEMM/


EDIT

To make it work with hiding the div, you could use some jQuery like this

$('a').click(function(){
    var a = $('h1').detach();
    $('div').hide();
    $(a).prependTo('body');    
});

(You will need to modify...)

Example #2: http://jsfiddle.net/ZgEMM/4/

How to get only the last part of a path in Python?

str = "/folderA/folderB/folderC/folderD/"
print str.split("/")[-2]

Simple (I think) Horizontal Line in WPF?

For anyone else struggling with this: Qwertie's comment worked well for me.

<Border Width="1" Margin="2" Background="#8888"/>

This creates a vertical seperator which you can talior to suit your needs.

Assign output of a program to a variable using a MS batch file

I wrote the script that pings google.com every 5 seconds and logging results with current time. Here you can find output to variables "commandLineStr" (with indices)

@echo off

:LOOPSTART

echo %DATE:~0% %TIME:~0,8% >> Pingtest.log

SETLOCAL ENABLEDELAYEDEXPANSION
SET scriptCount=1
FOR /F "tokens=* USEBACKQ" %%F IN (`ping google.com -n 1`) DO (
  SET commandLineStr!scriptCount!=%%F
  SET /a scriptCount=!scriptCount!+1
)
@ECHO %commandLineStr1% >> PingTest.log
@ECHO %commandLineStr2% >> PingTest.log
ENDLOCAL

timeout 5 > nul

GOTO LOOPSTART

Get connection string from App.config

//Get Connection from web.config file
public static OdbcConnection getConnection()
{
    OdbcConnection con = new OdbcConnection();
    con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    return con;     
}

Error "The input device is not a TTY"

I know this is not directly answering the question at hand but for anyone that comes upon this question who is using WSL running Docker for windows and cmder or conemu.

The trick is not to use Docker which is installed on windows at /mnt/c/Program Files/Docker/Docker/resources/bin/docker.exe but rather to install the ubuntu/linux Docker. It's worth pointing out that you can't run Docker itself from within WSL but you can connect to Docker for windows from the linux Docker client.

Install Docker on Linux

sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt-get update
sudo apt-get install docker-ce

Connect to Docker for windows on the port 2375 which needs to be enabled from the settings in docker for windows.

docker -H localhost:2375 run -it -v /mnt/c/code:/var/app -w "/var/app" centos:7

Or set the docker_host variable which will allow you to omit the -H switch

export DOCKER_HOST=tcp://localhost:2375

You should now be able to connect interactively with a tty terminal session.

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

@RequestParam vs @PathVariable

@RequestParam is use for query parameter(static values) like: http://localhost:8080/calculation/pow?base=2&ext=4

@PathVariable is use for dynamic values like : http://localhost:8080/calculation/sqrt/8

@RequestMapping(value="/pow", method=RequestMethod.GET)
public int pow(@RequestParam(value="base") int base1, @RequestParam(value="ext") int ext1){
    int pow = (int) Math.pow(base1, ext1);
    return pow;
}

@RequestMapping("/sqrt/{num}")
public double sqrt(@PathVariable(value="num") int num1){
    double sqrtnum=Math.sqrt(num1);
    return sqrtnum;
}

Setting onClickListener for the Drawable right of an EditText

public class CustomEditText extends androidx.appcompat.widget.AppCompatEditText {

    private Drawable drawableRight;
    private Drawable drawableLeft;
    private Drawable drawableTop;
    private Drawable drawableBottom;

    int actionX, actionY;

    private DrawableClickListener clickListener;

    public CustomEditText (Context context, AttributeSet attrs) {
        super(context, attrs);
        // this Contructure required when you are using this view in xml
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);        
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    public void setCompoundDrawables(Drawable left, Drawable top,
            Drawable right, Drawable bottom) {
        if (left != null) {
            drawableLeft = left;
        }
        if (right != null) {
            drawableRight = right;
        }
        if (top != null) {
            drawableTop = top;
        }
        if (bottom != null) {
            drawableBottom = bottom;
        }
        super.setCompoundDrawables(left, top, right, bottom);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Rect bounds;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            actionX = (int) event.getX();
            actionY = (int) event.getY();
            if (drawableBottom != null
                    && drawableBottom.getBounds().contains(actionX, actionY)) {
                clickListener.onClick(DrawablePosition.BOTTOM);
                return super.onTouchEvent(event);
            }

            if (drawableTop != null
                    && drawableTop.getBounds().contains(actionX, actionY)) {
                clickListener.onClick(DrawablePosition.TOP);
                return super.onTouchEvent(event);
            }

            // this works for left since container shares 0,0 origin with bounds
            if (drawableLeft != null) {
                bounds = null;
                bounds = drawableLeft.getBounds();

                int x, y;
                int extraTapArea = (int) (13 * getResources().getDisplayMetrics().density  + 0.5);

                x = actionX;
                y = actionY;

                if (!bounds.contains(actionX, actionY)) {
                    /** Gives the +20 area for tapping. */
                    x = (int) (actionX - extraTapArea);
                    y = (int) (actionY - extraTapArea);

                    if (x <= 0)
                        x = actionX;
                    if (y <= 0)
                        y = actionY;

                    /** Creates square from the smallest value */
                    if (x < y) {
                        y = x;
                    }
                }

                if (bounds.contains(x, y) && clickListener != null) {
                    clickListener
                            .onClick(DrawableClickListener.DrawablePosition.LEFT);
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;

                }
            }

            if (drawableRight != null) {

                bounds = null;
                bounds = drawableRight.getBounds();

                int x, y;
                int extraTapArea = 13;

                /**
                 * IF USER CLICKS JUST OUT SIDE THE RECTANGLE OF THE DRAWABLE
                 * THAN ADD X AND SUBTRACT THE Y WITH SOME VALUE SO THAT AFTER
                 * CALCULATING X AND Y CO-ORDINATE LIES INTO THE DRAWBABLE
                 * BOUND. - this process help to increase the tappable area of
                 * the rectangle.
                 */
                x = (int) (actionX + extraTapArea);
                y = (int) (actionY - extraTapArea);

                /**Since this is right drawable subtract the value of x from the width 
                * of view. so that width - tappedarea will result in x co-ordinate in drawable bound. 
                */
                x = getWidth() - x;
                
                 /*x can be negative if user taps at x co-ordinate just near the width.
                 * e.g views width = 300 and user taps 290. Then as per previous calculation
                 * 290 + 13 = 303. So subtract X from getWidth() will result in negative value.
                 * So to avoid this add the value previous added when x goes negative.
                 */
                 
                if(x <= 0){
                    x += extraTapArea;
                }
                
                 /* If result after calculating for extra tappable area is negative.
                 * assign the original value so that after subtracting
                 * extratapping area value doesn't go into negative value.
                 */               
                 
                if (y <= 0)
                    y = actionY;                

                /**If drawble bounds contains the x and y points then move ahead.*/
                if (bounds.contains(x, y) && clickListener != null) {
                    clickListener
                            .onClick(DrawableClickListener.DrawablePosition.RIGHT);
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;
                }
                return super.onTouchEvent(event);
            }           

        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        drawableRight = null;
        drawableBottom = null;
        drawableLeft = null;
        drawableTop = null;
        super.finalize();
    }

    public void setDrawableClickListener(DrawableClickListener listener) {
        this.clickListener = listener;
    }

}

Also Create an Interface with

public interface DrawableClickListener {

    public static enum DrawablePosition { TOP, BOTTOM, LEFT, RIGHT };
    public void onClick(DrawablePosition target); 
    }

Still if u need any help, comment

Also set the drawableClickListener on the view in activity file.

editText.setDrawableClickListener(new DrawableClickListener() {
        
         
        public void onClick(DrawablePosition target) {
            switch (target) {
            case LEFT:
                //Do something here
                break;

            default:
                break;
            }
        }
        
    });

Count all occurrences of a string in lots of files with grep

Here is a faster-than-grep AWK alternative way of doing this, which handles multiple matches of <url> per line, within a collection of XML files in a directory:

awk '/<url>/{m=gsub("<url>","");total+=m}END{print total}' some_directory/*.xml

This works well in cases where some XML files don't have line breaks.

php - get numeric index of associative array

While Fosco's answer is not wrong there is a case to be considered with this one: mixed arrays. Imagine I have an array like this:

$a = array(
  "nice",
  "car" => "fast",
  "none"
);

Now, PHP allows this kind of syntax but it has one problem: if I run Fosco's code I get 0 which is wrong for me, but why this happens?
Because when doing comparisons between strings and integers PHP converts strings to integers (and this is kinda stupid in my opinion), so when array_search() searches for the index it stops at the first one because apparently ("car" == 0) is true.
Setting array_search() to strict mode won't solve the problem because then array_search("0", array_keys($a)) would return false even if an element with index 0 exists.
So my solution just converts all indexes from array_keys() to strings and then compares them correctly:

echo array_search("car", array_map("strval", array_keys($a)));

Prints 1, which is correct.

EDIT:
As Shaun pointed out in the comment below, the same thing applies to the index value, if you happen to search for an int index like this:

$a = array(
  "foo" => "bar",
  "nice",
  "car" => "fast",
  "none"
);
$ind = 0;
echo array_search($ind, array_map("strval", array_keys($a)));

You will always get 0, which is wrong, so the solution would be to cast the index (if you use a variable) to a string like this:

$ind = 0;
echo array_search((string)$ind, array_map("strval", array_keys($a)));

Jquery Ajax Loading image

Try something like this:

<div id="LoadingImage" style="display: none">
  <img src="" />
</div>

<script>
  function ajaxCall(){
    $("#LoadingImage").show();
      $.ajax({ 
        type: "GET", 
        url: surl, 
        dataType: "jsonp", 
        cache : false, 
        jsonp : "onJSONPLoad", 
        jsonpCallback: "newarticlescallback", 
        crossDomain: "true", 
        success: function(response) { 
          $("#LoadingImage").hide();
          alert("Success"); 
        }, 
        error: function (xhr, status) {  
          $("#LoadingImage").hide();
          alert('Unknown error ' + status); 
        }    
      });  
    }
</script>

How can I align text directly beneath an image?

I am not an expert in HTML but here is what worked for me:

<div class="img-with-text-below">
    <img src="your-image.jpg" alt="alt-text" />
    <p><center>Your text</center></p>
</div>

Spring 3 MVC resources and tag <mvc:resources />

@Nanocom's answer works for me. It may be that lines have to be at the end, or could be because has to be after of some the bean class like this:

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class="org.springframework.web.servlet.resource.ResourceHttpRequestHandler" />    

<mvc:resources mapping="/resources/**" 
               location="/resources/" 
               cache-period="10000" />

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

Create a string and append text to it

Use the string concatenation operator:

Dim str As String = New String("") & "some other string"

Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.

This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.

See "How to: Concatenate Multiple Strings" for more information on both methods.

Open application after clicking on Notification

See below code. I am using that and it is opening my HomeActivity.

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    Intent notificationIntent = new Intent(context, HomeActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);

    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);

Go to beginning of line without opening new line in VI

A simple 0 takes you to the beginning of a line.

:help 0 for more information

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

Changing default shell in Linux

Try linux command chsh.

The detailed command is chsh -s /bin/bash. It will prompt you to enter your password. Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

How can I send an email through the UNIX mailx command?

echo "Sending emails ..."
NOW=$(date +"%F %H:%M")
echo $NOW  " Running service" >> open_files.log
header=`echo "Service Restarting: " $NOW`


mail -s "$header" [email protected],   \
              [email protected], \ < open_files.log

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

Easiest way to use SVG in Android?

Rather than adding libraries which increases your apk size, I will suggest you to convert Svg to drawable using http://inloop.github.io/svg2android/ . and add vectorDrawables.useSupportLibrary = true in gradle,

Shell Script: Execute a python program from within a shell script

Imho, writing

python /path/to/script.py

Is quite wrong, especially in these days. Which python? python2.6? 2.7? 3.0? 3.1? Most of times you need to specify the python version in shebang tag of python file. I encourage to use

#!/usr/bin/env python2 #or python2.6 or python3 or even python3.1
for compatibility.

In such case, is much better to have the script executable and invoke it directly:

#!/bin/bash

/path/to/script.py

This way the version of python you need is only written in one file. Most of system these days are having python2 and python3 in the meantime, and it happens that the symlink python points to python3, while most people expect it pointing to python2.

How do I read input character-by-character in Java?

In java 5 new feature added that is Scanner method who gives the chance to read input character by character in java.

for instance; for use Scanner method import java.util.Scanner; after in main method:define

Scanner myScanner = new Scanner(System.in); //for read character

char anything=myScanner.findInLine(".").charAt(0);

you anything store single character, if you want more read more character declare more object like anything1,anything2... more example for your answer please check in your hand(copy/paste)

     import java.util.Scanner;
     class ReverseWord  {

    public static void main(String args[]){
    Scanner myScanner=new Scanner(System.in);
    char c1,c2,c3,c4;

    c1 = myScanner.findInLine(".").charAt(0);
        c2 = myScanner.findInLine(".").charAt(0);
    c3 = myScanner.findInLine(".").charAt(0);
    c4 = myScanner.findInLine(".").charAt(0);

    System.out.print(c4);
    System.out.print(c3);
    System.out.print(c2);
    System.out.print(c1);
    System.out.println();

   }
  }

Which Android IDE is better - Android Studio or Eclipse?

Both are equally good. With Android Studio you have ADT tools integrated, and with eclipse you need to integrate them manually. With Android Studio, it feels like a tool designed from the outset with Android development in mind. Go ahead, they have same features.

Parsing Query String in node.js

require('url').parse('/status?name=ryan', {parseQueryString: true}).query

returns

{ name: 'ryan' }

ref: https://nodejs.org/api/url.html#url_urlobject_query

How to get IntPtr from byte[] in C#

Another way,

GCHandle pinnedArray = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
// Do your stuff...
pinnedArray.Free();

Link and execute external JavaScript file hosted on GitHub

GitHub Pages is GitHub’s official solution to this problem.

raw.githubusercontent makes all files use the text/plain MIME type, even if the file is a CSS or JavaScript file. So going to https://raw.githubusercontent.com/‹user›/‹repo›/‹branch›/‹filepath› will not be the correct MIME type but instead a plaintext file, and linking it via <link href="..."/> or <script src="..."></script> won’t work—the CSS won’t apply / the JS won’t run.

GitHub Pages hosts your repo at a special URL, so all you have to do is check-in your files and push. Note that in most cases, GitHub Pages requires you to commit to a special branch, gh-pages.

On your new site, which is usually https://‹user›.github.io/‹repo›, every file committed to the gh-pages branch (the most recent commit) is present at this url. So then you can link to your js file via <script src="https://‹user›.github.io/‹repo›/file.js"></script>, and this will be the correct MIME type.

Do you have build files?

Personally, my recommendation is to run this branch parallel to master. On the gh-pages branch, you can edit your .gitignore file to check in all the dist/build files you need for your site (e.g. if you have any minified/compiled files), while keeping them ignored on your master branch. This is useful because you typically don’t want to track changes in build files in your regular repo. Every time you want to update your hosted files, simply merge master into gh-pages, rebuild, commit, and then push.

(protip: you can merge and rebuild in the same commit with these steps:)

$ git checkout gh-pages
$ git merge --no-ff --no-commit master  # prepare the merge but don’t commit it (as if there were a merge conflict)
$ npm run build                         # (or whatever your build process is)
$ git add .                             # stage the newly built files
$ git merge --continue                  # commit the merge
$ git push origin gh-pages

How to convert md5 string to normal text?

I you send passwords to users in an email, you might as well have no passwords at all.

You cannot reverse the MD5 function, so your only option is to generate a new password and send that to the user (preferably over some secure channel).

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

How do I remove background-image in css?

Since in css3 one might set multiple background images setting "none" will only create a new layer and hide nothing.

http://www.css3.info/preview/multiple-backgrounds/ http://www.w3.org/TR/css3-background/#backgrounds

I have not found a solution yet...

Why does sed not replace all occurrences?

You should add the g modifier so that sed performs a global substitution of the contents of the pattern buffer:

echo dog dog dos | sed -e 's:dog:log:g'

For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6

The official documentation for GNU sed is available at http://www.gnu.org/software/sed/manual/

JavaScript push to array

Use the push() function to append to an array:

// initialize array
var arr = [
    "Hi",
    "Hello",
    "Bonjour"
];

// append new value to the array
arr.push("Hola");

Now array is

var arr = [
    "Hi",
    "Hello",
    "Bonjour"
    "Hola"
];

// append multiple values to the array
arr.push("Salut", "Hey");

Now array is

var arr = [
    "Hi",
    "Hello",
    "Bonjour"
    "Hola"
    "Salut"
    "Hey"
];

// display all values
for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

Will print:

Hi
Hello
Bonjour
Hola 
Salut
Hey

Update

If you want to add the items of one array to another array, you can use Array.concat:

var arr = [
    "apple",
    "banana",
    "cherry"
];

arr = arr.concat([
    "dragonfruit",
    "elderberry",
    "fig"
]);

console.log(arr);

Will print

["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]

How to cin to a vector

These were two methods I tried. Both are fine to use.

int main() {
       
        int size,temp;
        cin>>size;
        vector<int> ar(size);
    //method 1 
      for(auto i=0;i<size;i++)
          {   cin>>temp;
              ar.insert(ar.begin()+i,temp);
          }
          for (auto i:ar) 
            cout <<i<<" "; 
            
     //method 2
     for(int i=0;i<size;i++)
     {
        cin>>ar[i];
     }
     
     for (auto i:ar) 
            cout <<i<<" "; 
        return 0;
    }

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Yep, confirmed that simply using hh instead of HH fixed my issue.

Changed from this:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm aa");

To this:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

You can still use HH to store the time if you don't want to bother storing and dealing with the AM/PM. Then when you retrieve it, use hh.

SQL Error: ORA-00933: SQL command not properly ended

Not exactly the case of actual context of this question, but this exception can be reproduced by the next query:

update users set dismissal_reason='he can't and don't want' where userid=123

Single quotes in words can't and don't broke the string. In case string have only one inside quote e.g. 'he don't want' oracle throws more relevant quoted string not properly terminated error, but in case of two SQL command not properly ended is thrown.

Summary: check your query for double single quotes.

Spring Boot - How to get the running port

I solved it with a kind of proxy bean. The client gets initialized when it is needed, by then the port should be available:

@Component
public class GraphQLClient {

    private ApolloClient apolloClient;
    private final Environment environment;

    public GraphQLClient(Environment environment) {
        this.environment = environment;
    }

    public ApolloClient getApolloClient() {
        if (apolloClient == null) {
            String port = environment.getProperty("local.server.port");
            initApolloClient(port);
        }
        return apolloClient;
    }

    public synchronized void initApolloClient(String port) {
        this.apolloClient = ApolloClient.builder()
                .serverUrl("http://localhost:" + port + "/graphql")
                .build();
    }

    public <D extends Operation.Data, T, V extends Operation.Variables> GraphQLCallback<T> graphql(Operation<D, T, V> operation) {
        GraphQLCallback<T> graphQLCallback = new GraphQLCallback<>();
        if (operation instanceof Query) {
            Query<D, T, V> query = (Query<D, T, V>) operation;
            getApolloClient()
                    .query(query)
                    .enqueue(graphQLCallback);
        } else {
            Mutation<D, T, V> mutation = (Mutation<D, T, V>) operation;
            getApolloClient()
                    .mutate(mutation)
                    .enqueue(graphQLCallback);

        }
        return graphQLCallback;
    }
}

C# get string from textbox

I show you this with an example:

string userName= textBox1.text;

and then use it as you wish

How can I use jQuery in Greasemonkey?

Rob's solution is the right one--use @require with the jQuery library and be sure to reinstall your script so the directive gets processed.

One thing I think is worth adding is that you can use jQuery normally once you have included it in your script, except for AJAX methods. By default jQuery looks for XMLHttpRequest, which doesn't exist in the Greasemonkey context. I wrote about a workaround where you create a wrapper for GM_xmlhttpRequest (the Greasemonkey version of XHR) and use jQuery's ajaxSetup() to specify your wrapped version as the default. Once you do this, you can use $.get and $.post as usual.

You may also have problems with jQuery's $.getJSON because it loads JSONP using <script> tags. This leads to errors because jQuery defines the callback function in the scope of the Greasemonkey window, and the loaded scripts looks for the callback in the scope of the main window. Your best bet is to use $.get instead and parse the result with JSON.parse().

How to create checkbox inside dropdown?

You can always use multiple or multiple = "true" option with a select tag, but there is one jquery plugin which makes it more beautiful. It is called chosen and can be found here.

This fiddle-example might help you to get started

Thank you.

C# Select elements in list as List of string

List<string> empnames = (from e in emplist select e.Enaame).ToList();

Or

string[] empnames = (from e in emplist select e.Enaame).ToArray();

Etc...

No route matches "/users/sign_out" devise rails 3

  devise_for :users
  devise_scope :user do
    get '/users/sign_out' => 'devise/sessions#destroy'
  end

Swift how to sort array of custom objects by property value

If you are going to be sorting this array in more than one place, it may make sense to make your array type Comparable.

class MyImageType: Comparable, Printable {
    var fileID: Int

    // For Printable
    var description: String {
        get {
            return "ID: \(fileID)"
        }
    }

    init(fileID: Int) {
        self.fileID = fileID
    }
}

// For Comparable
func <(left: MyImageType, right: MyImageType) -> Bool {
    return left.fileID < right.fileID
}

// For Comparable
func ==(left: MyImageType, right: MyImageType) -> Bool {
    return left.fileID == right.fileID
}

let one = MyImageType(fileID: 1)
let two = MyImageType(fileID: 2)
let twoA = MyImageType(fileID: 2)
let three = MyImageType(fileID: 3)

let a1 = [one, three, two]

// return a sorted array
println(sorted(a1)) // "[ID: 1, ID: 2, ID: 3]"

var a2 = [two, one, twoA, three]

// sort the array 'in place'
sort(&a2)
println(a2) // "[ID: 1, ID: 2, ID: 2, ID: 3]"

Validate email address textbox using JavaScript

If you wish to allow accent (see RFC 5322) and allow new domain extension like .quebec. use this expression:

/\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/
  • The '\u00C0-\u017F' part is for alowing accent. We use the unicode range for that.
  • The '{2,}' simply say a minimum of 2 char for the domain extension. You can replace this by '{2,63}' if you dont like the infinitive range.

Based on this article

JsFidler

_x000D_
_x000D_
$(document).ready(function() {_x000D_
var input = $('.input_field');_x000D_
var result = $('.test_result');_x000D_
        var regExpression = /\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/;_x000D_
    _x000D_
   $('.btnTest').click(function(){_x000D_
          var isValid = regExpression.test(input.val());_x000D_
          if (isValid)_x000D_
              result.html('<span style="color:green;">This email is valid</span>');_x000D_
           else_x000D_
              result.html('<span style="color:red;">This email is not valid</span>');_x000D_
_x000D_
   });_x000D_
_x000D_
});
_x000D_
body {_x000D_
    padding: 40px;_x000D_
}_x000D_
_x000D_
label {_x000D_
    font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type=text] {_x000D_
    width: 20em_x000D_
}_x000D_
.test_result {_x000D_
  font-size:4em;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label for="search_field">Input</label>_x000D_
<input type='text' class='input_field' />_x000D_
<button type="button" class="btnTest">_x000D_
Test_x000D_
</button>_x000D_
<br/>_x000D_
<div class="test_result">_x000D_
Not Tested_x000D_
</div>
_x000D_
_x000D_
_x000D_

Easiest way to loop through a filtered list with VBA?

I used the RowHeight property of a range (which means cells as well). If it's zero then it's hidden. So just loop through all rows as you would normally but in the if condition check for that property as in If myRange.RowHeight > 0 then DoStuff where DoStuff is something you want to do with the visible cells.

Adding a tooltip to an input box

<input type="name" placeholder="First Name" title="First Name" />

title="First Name" solves my proble. it worked with bootstrap.

Windows batch script to move files

Create a file called MoveFiles.bat with the syntax

move c:\Sourcefoldernam\*.* e:\destinationFolder

then schedule a task to run that MoveFiles.bat every 10 hours.

@ViewChild in *ngIf

I think using defer from lodash makes a lot of sense especially in my case where my @ViewChild() was inside async pipe

Declaring and initializing arrays in C

In C99 you can do it using a compound literal in combination with memcpy

memcpy(myarray, (int[]) { 1, 2, 3, 4 }, sizeof myarray);

(assuming that the size of the source and the size of the target is the same).

In C89/90 you can emulate that by declaring an additional "source" array

const int SOURCE[SIZE] = { 1, 2, 3, 4 }; /* maybe `static`? */
int myArray[SIZE];
...
memcpy(myarray, SOURCE, sizeof myarray);

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

In my case a switch from openjdk7 to openjdk6 helped. Afterwards I changed the compliance level to 1.6 and all compiled fine.

Space between border and content? / Border distance from content?

Add padding. Padding the element will increase the space between its content and its border. However, note that a box-shadow will begin outside the border, not the content, meaning you can't put space between the shadow and the box. Alternatively you could use :before or :after pseudo selectors on the element to create a slightly bigger box that you place the shadow on, like so: http://jsbin.com/aqemew/edit#source

What is offsetHeight, clientHeight, scrollHeight?

My descriptions for the three:

  • offsetHeight: How much of the parent's "relative positioning" space is taken up by the element. (ie. it ignores the element's position: absolute descendents)
  • clientHeight: Same as offset-height, except it excludes the element's own border, margin, and the height of its horizontal scroll-bar (if it has one).
  • scrollHeight: How much space is needed to see all of the element's content/descendents (including position: absolute ones) without scrolling.

Then there is also:

How to change date format using jQuery?

You don't need any date-specific functions for this, it's just string manipulation:

var parts = fecha2.value.split('-');
var newdate = parts[1]+'-'+parts[2]+'-'+(parseInt(parts[0], 10)%100);

Is there an embeddable Webkit component for Windows / C# development?

There's a WebKit-Sharp component on Mono's Subversion Server. I can't find any web-viewable documentation on it, and I'm not even sure if it's WinForms or GTK# (can't grab the source from here to check at the moment), but it's probably your best bet, either way.

I think this component is CLI wrapper around webkit for Ubuntu. So this wrapper most likely could be not working on win32

Try check another variant - project awesomium - wrapper around google project "Chromium" that use webkit. Also awesomium has features like to should interavtive web pages on 3D objects under WPF

How to debug a stored procedure in Toad?

Open a PL/SQL object in the Editor.

Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

Compile the object on the database.

Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

Recommended method for escaping HTML in Java

There is a newer version of the Apache Commons Lang library and it uses a different package name (org.apache.commons.lang3). The StringEscapeUtils now has different static methods for escaping different types of documents (http://commons.apache.org/proper/commons-lang/javadocs/api-3.0/index.html). So to escape HTML version 4.0 string:

import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;

String output = escapeHtml4("The less than sign (<) and ampersand (&) must be escaped before using them in HTML");

IIS URL Rewrite and Web.config

Just wanted to point out one thing missing in LazyOne's answer (I would have just commented under the answer but don't have enough rep)

In rule #2 for permanent redirect there is thing missing:

redirectType="Permanent"

So rule #2 should look like this:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Edit

For more information on how to use the URL Rewrite Module see this excellent documentation: URL Rewrite Module Configuration Reference

In response to @kneidels question from the comments; To match the url: topic.php?id=39 something like the following could be used:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="SpecificRedirect" stopProcessing="true">
        <match url="^topic.php$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{QUERY_STRING}" pattern="(?:id)=(\d{2})" />
        </conditions>
        <action type="Redirect" url="/newpage/{C:1}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

This will match topic.php?id=ab where a is any number between 0-9 and b is also any number between 0-9. It will then redirect to /newpage/xy where xy comes from the original url. I have not tested this but it should work.

How to uninstall a Windows Service when there is no executable for it left on the system?

Remove Windows Service via Registry

Its very easy to remove a service from registry if you know the right path. Here is how I did that:

  1. Run Regedit or Regedt32

  2. Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"

  3. Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).

Delete Windows Service via Command Window

Alternatively, you can also use command prompt and delete a service using following command:

sc delete

You can also create service by using following command

sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"

Note: You may have to reboot the system to get the list updated in service manager.

Fragments within Fragments

.. you can cleanup your nested fragment in the parent fragment's destroyview method:

@Override
    public void onDestroyView() {

      try{
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();

        transaction.remove(nestedFragment);

        transaction.commit();
      }catch(Exception e){
      }

        super.onDestroyView();
    }

Vertical align text in block element

According to the CSS Flexible Box Layout Module, you can declare the a element as a flex container (see figure) and use align-items to vertically align text along the cross axis (which is perpendicular to the main axis).

enter image description here

All you need to do is:

display: flex;
align-items: center;

See this fiddle.

non static method cannot be referenced from a static context

You are calling nextInt statically by using Random.nextInt.

Instead, create a variable, Random r = new Random(); and then call r.nextInt(10).

It would be definitely worth while to check out:

Update:

You really should replace this line,

Random Random = new Random(); 

with something like this,

Random r = new Random();

If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.

asp.net mvc3 return raw html to view

There's no much point in doing that, because View should be generating html, not the controller. But anyways, you could use Controller.Content method, which gives you ability to specify result html, also content-type and encoding

public ActionResult Index()
{
    return Content("<html></html>");
}

Or you could use the trick built in asp.net-mvc framework - make the action return string directly. It will deliver string contents into users's browser.

public string Index()
{
    return "<html></html>";
}

In fact, for any action result other than ActionResult, framework tries to serialize it into string and write to response.

How can I make a DateTimePicker display an empty string?

When I want to display an empty date value I do this

            if (sStrDate != "")
            {
                dateCreated.Value = DateTime.Parse(sStrDate);
            }
            else
            {
                dateCreated.CustomFormat = " ";
                dateCreated.Format = DateTimePickerFormat.Custom;
            }

Then when the user clicks on the control I have this:

            private void dateControl_MouseDown(object sender, MouseEventArgs e)
            {
                ((DateTimePicker)sender).Format = DateTimePickerFormat.Long;    
            }

This allows you to display and use an empty date value, but still allow the user to be able to change the date to something when they wish.

Keep in mind that sStrDate has already been validated as a valid date string.

Only using @JsonIgnore during serialization, but not deserialization

Another easy way to handle this is to use the argument allowSetters=truein the annotation. This will allow the password to be deserialized into your dto but it will not serialize it into a response body that uses contains object.

example:

@JsonIgnoreProperties(allowSetters = true, value = {"bar"})
class Pojo{
    String foo;
    String bar;
}

Both foo and bar are populated in the object, but only foo is written into a response body.

Converting LastLogon to DateTime format

LastLogon is the last time that the user logged into whichever domain controller you happen to have been load balanced to at the moment that you ran the GET-ADUser cmdlet, and is not replicated across the domain. You really should use LastLogonTimestamp if you want the time the last user logged in to any domain controller in your domain.

How do I send an HTML email?

You can use setText(java.lang.String text, boolean html) from MimeMessageHelper:

MimeMessage mimeMsg = javaMailSender.createMimeMessage();
MimeMessageHelper msgHelper = new MimeMessageHelper(mimeMsg, false, "utf-8");
boolean isHTML = true;
msgHelper.setText("<h1>some html</h1>", isHTML);

But you need to:

mimeMsg.saveChanges();

Before:

javaMailSender.send(mimeMsg);

Elegant way to create empty pandas DataFrame with NaN of type float

You can try this line of code:

pdDataFrame = pd.DataFrame([np.nan] * 7)

This will create a pandas dataframe of size 7 with NaN of type float:

if you print pdDataFrame the output will be:

     0
0   NaN
1   NaN
2   NaN
3   NaN
4   NaN
5   NaN
6   NaN

Also the output for pdDataFrame.dtypes is:

0    float64
dtype: object

In c# is there a method to find the max of 3 numbers?

If, for whatever reason (e.g. Space Engineers API), System.array has no definition for Max nor do you have access to Enumerable, a solution for Max of n values is:

public int Max(int[] values) {
    if(values.Length < 1) {
        return 0;
    }
    if(values.Length < 2) {
        return values[0];
    }
    if(values.Length < 3) {
       return Math.Max(values[0], values[1]); 
    }
    int runningMax = values[0];
    for(int i=1; i<values.Length - 1; i++) {
       runningMax = Math.Max(runningMax, values[i]);
    }
    return runningMax;
}

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

How do I run two commands in one line in Windows CMD?

If you want to create a cmd shortcut (for example on your desktop) add /k parameter (/k means keep, /c will close window):

cmd /k echo hello && cd c:\ && cd Windows

Simple way to compare 2 ArrayLists

The simplest way is to iterate through source and destination lists one by one like this:

List<String> newAddedElementsList = new ArrayList<String>();
List<String> removedElementsList = new ArrayList<String>();
for(String ele : sourceList){
    if(destinationList.contains(ele)){
        continue;
    }else{
        removedElementsList.add(ele);
    }
}
for(String ele : destinationList){
    if(sourceList.contains(ele)){
        continue;
    }else{
        newAddedElementsList.add(ele);
    }
}

Though it might not be very efficient if your source and destination lists have many elements but surely its simpler.

Move to another EditText when Soft Keyboard Next is clicked on Android

In Kotlin I have used Bellow like..

  1. xml:

    <EditText
      android:id="@+id/et_amount"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:imeOptions="actionNext"
      android:inputType="number"
      android:singleLine="true" />
    
  2. in kotlin:

    et_amount.setOnEditorActionListener { v, actionId, event ->
    
        if (actionId == EditorInfo.IME_ACTION_NEXT) {
            // do some code
            true
        } else {
            false
        }
    }
    

label or @html.Label ASP.net MVC 4

@html.label and @html.textbox are use when you want bind it to your model in a easy way...which cannot be achieve by input etc. in one line

What does "<>" mean in Oracle

not equals. See here for a list of conditions

HTTP Error 503, the service is unavailable

This might be because of number of connections to the database. I had such a situation and so, wrote a de-constructor and killed db open connection and it resolved.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

this solution work for me ,

To revise IIS

Select Application Pools.
Clic in ASP .NET V4.0 Classic.
Select Advanced Settings.
In General, option Enable 32-Bit Applications, default is false. Select TRUE.
Refresh and check site.

Comment:

Platform: Windows Server 2012 Standart- 64Bit - IIS 8

Java 8 lambdas, Function.identity() or t->t

As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here.

The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x, equivalent to return identifier;) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.

So using Function.identity() instead of x -> x might save some memory but that shouldn’t drive your decision if you really think that x -> x is more readable than Function.identity().

You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function instance while debugging. In contrast, when encountering the instance returned by Function.identity() during debugging an operation, you won’t know who has called that method and passed the instance to the operation.

Difference between == and ===

For example, if you create two instances of a class e.g. myClass:

var inst1 = myClass()
var inst2 = myClass()

you can compare those instances,

if inst1 === inst2

cited:

which you use to test whether two object references both refer to the same object instance.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/sk/jEUH0.l

Bash: Strip trailing linebreak from output

If your expected output is a single line, you can simply remove all newline characters from the output. It would not be uncommon to pipe to the tr utility, or to Perl if preferred:

wc -l < log.txt | tr -d '\n'

wc -l < log.txt | perl -pe 'chomp'

You can also use command substitution to remove the trailing newline:

echo -n "$(wc -l < log.txt)"

printf "%s" "$(wc -l < log.txt)"

If your expected output may contain multiple lines, you have another decision to make:

If you want to remove MULTIPLE newline characters from the end of the file, again use cmd substitution:

printf "%s" "$(< log.txt)"

If you want to strictly remove THE LAST newline character from a file, use Perl:

perl -pe 'chomp if eof' log.txt

Note that if you are certain you have a trailing newline character you want to remove, you can use head from GNU coreutils to select everything except the last byte. This should be quite quick:

head -c -1 log.txt

Also, for completeness, you can quickly check where your newline (or other special) characters are in your file using cat and the 'show-all' flag -A. The dollar sign character will indicate the end of each line:

cat -A log.txt

Can I load a UIImage from a URL?

get DLImageLoader and try folowing code

   [DLImageLoader loadImageFromURL:imageURL
                          completed:^(NSError *error, NSData *imgData) {
                              imageView.image = [UIImage imageWithData:imgData];
                              [imageView setContentMode:UIViewContentModeCenter];

                          }];

Another typical real-world example of using DLImageLoader, which may help someone...

PFObject *aFacebookUser = [self.fbFriends objectAtIndex:thisRow];
NSString *facebookImageURL = [NSString stringWithFormat:
    @"http://graph.facebook.com/%@/picture?type=large",
    [aFacebookUser objectForKey:@"id"] ];

__weak UIImageView *loadMe = self.userSmallAvatarImage;
// ~~note~~ you my, but usually DO NOT, want a weak ref
[DLImageLoader loadImageFromURL:facebookImageURL
   completed:^(NSError *error, NSData *imgData)
    {
    if ( loadMe == nil ) return;

    if (error == nil)
        {
        UIImage *image = [UIImage imageWithData:imgData];
        image = [image ourImageScaler];
        loadMe.image = image;
        }
    else
        {
        // an error when loading the image from the net
        }
    }];

As I mention above another great library to consider these days is Haneke (unfortunately it's not as lightweight).

How to link to a <div> on another page?

Create an anchor:

<a name="anchor" id="anchor"></a> 

then link to it:

<a href="http://server/page.html#anchor">Link text</a>

Interface vs Abstract Class (general OO)

Interface Types vs. Abstract Base Classes

Adapted from the Pro C# 5.0 and the .NET 4.5 Framework book.

The interface type might seem very similar to an abstract base class. Recall that when a class is marked as abstract, it may define any number of abstract members to provide a polymorphic interface to all derived types. However, even when a class does define a set of abstract members, it is also free to define any number of constructors, field data, nonabstract members (with implementation), and so on. Interfaces, on the other hand, contain only abstract member definitions. The polymorphic interface established by an abstract parent class suffers from one major limitation in that only derived types support the members defined by the abstract parent. However, in larger software systems, it is very common to develop multiple class hierarchies that have no common parent beyond System.Object. Given that abstract members in an abstract base class apply only to derived types, we have no way to configure types in different hierarchies to support the same polymorphic interface. By way of example, assume you have defined the following abstract class:

public abstract class CloneableType
{
// Only derived types can support this
// "polymorphic interface." Classes in other
// hierarchies have no access to this abstract
// member.
   public abstract object Clone();
}

Given this definition, only members that extend CloneableType are able to support the Clone() method. If you create a new set of classes that do not extend this base class, you can’t gain this polymorphic interface. Also, you might recall that C# does not support multiple inheritance for classes. Therefore, if you wanted to create a MiniVan that is-a Car and is-a CloneableType, you are unable to do so:

// Nope! Multiple inheritance is not possible in C#
// for classes.
public class MiniVan : Car, CloneableType
{
}

As you would guess, interface types come to the rescue. After an interface has been defined, it can be implemented by any class or structure, in any hierarchy, within any namespace or any assembly (written in any .NET programming language). As you can see, interfaces are highly polymorphic. Consider the standard .NET interface named ICloneable, defined in the System namespace. This interface defines a single method named Clone():

public interface ICloneable
{
object Clone();
}

How do multiple clients connect simultaneously to one port, say 80, on a server?

Normally, for every connecting client the server forks a child process that communicates with the client (TCP). The parent server hands off to the child process an established socket that communicates back to the client.

When you send the data to a socket from your child server, the TCP stack in the OS creates a packet going back to the client and sets the "from port" to 80.

MySQL delete multiple rows in one query conditions unique to each row

You were very close, you can use this:

DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))

Please see this fiddle.

What is default session timeout in ASP.NET?

  1. The Default Expiration Period for Session is 20 Minutes.
  2. The Default Expiration Period for Cookie is 30 Minutes.
  3. Maximum Size of ViewState is 25% of Page Size

Change background of LinearLayout in Android

1- Select LinearLayout findViewById

LinearLayout llayout =(LinearLayout) findViewById(R.id.llayoutId); 

2- Set color from R.color.colorId

llayout.setBackgroundColor(getResources().getColor(R.color.colorId));

Convert HashBytes to VarChar

With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:

@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.

The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.

How to serve up a JSON response using Go?

Other users commenting that the Content-Type is plain/text when encoding. You have to set the Content-Type first w.Header().Set, then the HTTP response code w.WriteHeader.

If you call w.WriteHeader first then call w.Header().Set after you will get plain/text.

An example handler might look like this;

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    data := SomeStruct{}
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(data)
}

How to see JavaDoc in IntelliJ IDEA?

Use View | Quick Documentation or the corresponding keyboard shortcut (by default: Ctrl+Q on Windows/Linux and Ctrl+J on macOS or F1 in the recent IDE versions). See the documentation for more information.

It's also possible to enable automatic JavaDoc popup on explicit (invoked by a shortcut) code completion in Settings | Editor | General | Code completion (Autopopup documentation):

autopopup documentation

Yet another way to see the quick doc is on mouse move:

on mouse move

Why do multiple-table joins produce duplicate rows?

This might sound like a really basic "DUH" answer, but make sure that the column you're using to Lookup from on the merging file is actually full of unique values!

I noticed earlier today that PowerQuery won't throw you an error (like in PowerPivot) and will happily allow you to run a Many-Many merge. This will result in multiple rows being produced for each record that matches with a non-unique value.

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

cursor.execute(sql,array)

Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)

HTML5 iFrame Seamless Attribute

I thought this might be useful to someone:

in chrome version 32, a 2-pixels border automatically appears around iframes without the seamless attribute. It can be easily removed by adding this CSS rule:

iframe:not([seamless]) { border:none; }

Chrome uses the same selector with these default user-agent styles:

iframe:not([seamless]) {
  border: 2px inset;
  border-image-source: initial;
  border-image-slice: initial;
  border-image-width: initial;
  border-image-outset: initial;
  border-image-repeat: initial;
}

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Kinda late, but you need to access the original event, not the jQuery massaged one. Also, since these are multi-touch events, other changes need to be made:

$('#box').live('touchstart', function(e) {
  var xPos = e.originalEvent.touches[0].pageX;
});

If you want other fingers, you can find them in other indices of the touches list.

UPDATE FOR NEWER JQUERY:

$(document).on('touchstart', '#box', function(e) {
  var xPos = e.originalEvent.touches[0].pageX;
});

SQL server stored procedure return a table

Though this question is very old but as a new in Software Development I can't stop my self to share what I have learnt :D

Creation of Stored Procedure:

CREAET PROC usp_ValidateUSer
(
    @UserName nVARCHAR(50),
    @Password nVARCHAR(50)
)
AS

BEGIN
    IF EXISTS(SELECT '#' FROM Users WHERE Username=@UserName AND Password=@Password)
    BEGIN
        SELECT u.UserId, u.Username, r.UserRole
        FROM Users u
        INNER JOIN UserRoles r
        ON u.UserRoleId=r.UserRoleId
    END
END

Execution of Stored Procedure:

(If you want to test the execution of Stored Procedure in SQL)

EXEC usp_ValidateUSer @UserName='admin', @Password='admin'

Th Output:

enter image description here

How to force page refreshes or reloads in jQuery?

Replace that line with:

$("#someElement").click(function() {
    window.location.href = window.location.href;
});

or:

$("#someElement").click(function() {
    window.location.reload();
});

Select single item from a list

List<string> items = new List<string>();

items.Find(p => p == "blah");

or

items.Find(p => p.Contains("b"));

but this allows you to define what you are looking for via a match predicate...

I guess if you are talking linqToSql then:

example looking for Account...

DataContext dc = new DataContext();

Account item = dc.Accounts.FirstOrDefault(p => p.id == 5);

If you need to make sure that there is only 1 item (throws exception when more than 1)

DataContext dc = new DataContext();

Account item = dc.Accounts.SingleOrDefault(p => p.id == 5);

Differences in string compare methods in C#

In the forms you listed here, there's not much difference between the two. CompareTo ends up calling a CompareInfo method that does a comparison using the current culture; Equals is called by the == operator.

If you consider overloads, then things get different. Compare and == can only use the current culture to compare a string. Equals and String.Compare can take a StringComparison enumeration argument that let you specify culture-insensitive or case-insensitive comparisons. Only String.Compare allows you to specify a CultureInfo and perform comparisons using a culture other than the default culture.

Because of its versatility, I find I use String.Compare more than any other comparison method; it lets me specify exactly what I want.

How to calculate the running time of my program?

At the beginning of your main method, add this line of code :

final long startTime = System.nanoTime();

And then, at the last line of your main method, you can add :

final long duration = System.nanoTime() - startTime;

duration now contains the time in nanoseconds that your program ran. You can for example print this value like this:

System.out.println(duration);

If you want to show duration time in seconds, you must divide the value by 1'000'000'000. Or if you want a Date object: Date myTime = new Date(duration / 1000); You can then access the various methods of Date to print number of minutes, hours, etc.

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

F1 → open Keyboard Shortcuts → search for 'Indent Line', and change keybinding to Tab.

Right click > "Change when expression" to editorHasSelection && editorTextFocus && !editorReadonly

It will allow you to indent line when something in that line is selected (multiple lines still work).

How to refresh materialized view in oracle

You can refresh a materialized view completely as follows:

EXECUTE  
DBMS_SNAPSHOT.REFRESH('Materialized_VIEW_OWNER_NAME.Materialized_VIEW_NAME','COMPLETE');

SOAP PHP fault parsing WSDL: failed to load external entity?

Just had a similar problem trying to use SoapClient. Everything was working fine but in production, sometimes on page refresh, I would get the "SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from .." error.

I was using the params:

new \SoapClient($WSDL, array('cache_wsdl' => WSDL_CACHE_NONE, 'trace' => true, "exception" => 0)); 

Removing all the params worked for me:

new \SoapClient($WSDL); 

jQuery Clone table row

The code below will clone last row and add after last row in table:

var $tableBody = $('#tbl').find("tbody"),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();

$trLast.after($trNew);

Working example : http://jsfiddle.net/kQpfE/2/

Invalid application of sizeof to incomplete type with a struct

Your error is also shown when trying to access the sizeof() of an non-initialized extern array:

extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'

Note that you would get an array size missing error without the extern keyword.

Post parameter is always null

I've ran into this problem as well, and this is how I solved my problem

webapi code:

public void Post([FromBody] dynamic data)
{
    string value = data.value;
    /* do stuff */
}

client code:

$.post( "webapi/address", { value: "some value" } );

How to get the root dir of the Symfony2 application?

In Symfony 3.3 you can use

$projectRoot = $this->get('kernel')->getProjectDir();

to get the web/project root.

How to monitor Java memory usage?

You can take a look at stagemonitor. It is a open source java (web) application performance monitor. It captures response time metrics, JVM metrics, request details (including a call stack captured by the request profiler) and more. The overhead is very low.

Optionally, you can use the great timeseries database graphite with it to store a long history of datapoints that you can look at with fancy dashboards.

Example: JVM Memory Dashboard

Take a look at the project website to see screenshots, feature descriptions and documentation.

Note: I am the developer of stagemonitor

Pandas conditional creation of a series/dataframe column

Another way in which this could be achieved is

df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')

JAX-WS and BASIC authentication, when user names and passwords are in a database

I think you are looking for JAX-WS authentication in application level, not HTTP basic in server level. See following complete example :

Application Authentication with JAX-WS

On the web service client site, just put your “username” and “password” into request header.

Map<String, Object> req_ctx = ((BindingProvider)port).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);

Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Username", Collections.singletonList("someUser"));
headers.put("Password", Collections.singletonList("somePass"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

On the web service server site, get the request header parameters via WebServiceContext.

@Resource
WebServiceContext wsctx;

@WebMethod
public String method() {
    MessageContext mctx = wsctx.getMessageContext();

    Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
    List userList = (List) http_headers.get("Username");
    List passList = (List) http_headers.get("Password");
    //...

check android application is in foreground or not?

From Android 19, you can register an app life cycle callback in your Application class's onCreate() like this:

@Override
public void onCreate() {
    super.onCreate();
    registerActivityLifecycleCallbacks(new AppLifecycleCallback());
}

The AppLifecycleCallback looks like this:

class AppLifecycleCallback implements Application.ActivityLifecycleCallbacks {
    private int numStarted = 0;

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (numStarted == 0) {
           //app went to foreground
        }
        numStarted++;
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        numStarted--;
        if (numStarted == 0) {
            // app went to background
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}

How do I format a date with Dart?

handling yearly quarters, from string to DateTime, I didn't find proper solution so made this:

    List<String> dateAsList = 'Q1 2001'.split(' ');
    DateTime dateTime = DateTime.now();
    String quarter = dateAsList[0];
    int year = int.parse(dateAsList[1]);
    switch(quarter) {
      case "Q1": dateTime = DateTime(year, 1);
      break;
      case "Q2": dateTime = DateTime(year, 4);
      break;
      case "Q3": dateTime = DateTime(year, 7);
      break;
      case "Q4": dateTime = DateTime(year, 10);
      break;
    }

SQL select join: is it possible to prefix all columns as 'prefix.*'?

Cant do this without aliasing , simply because, how are you going to reference a field in the where clause, if that field exists in the 2 or 3 tables you are joining? It will be unclear for mysql which one you are trying to reference.

How do I assert equality on two classes without an equals method?

I tried all the answers and nothing really worked for me.

So I've created my own method that compares simple java objects without going deep into nested structures...

Method returns null if all fields match or string containing mismatch details.

Only properties that have a getter method are compared.

How to use

        assertNull(TestUtils.diff(obj1,obj2,ignore_field1, ignore_field2));

Sample output if there is a mismatch

Output shows property names and respective values of compared objects

alert_id(1:2), city(Moscow:London)

Code (Java 8 and above):

 public static String diff(Object x1, Object x2, String ... ignored) throws Exception{
        final StringBuilder response = new StringBuilder();
        for (Method m:Arrays.stream(x1.getClass().getMethods()).filter(m->m.getName().startsWith("get")
        && m.getParameterCount()==0).collect(toList())){

            final String field = m.getName().substring(3).toLowerCase();
            if (Arrays.stream(ignored).map(x->x.toLowerCase()).noneMatch(ignoredField->ignoredField.equals(field))){
                Object v1 = m.invoke(x1);
                Object v2 = m.invoke(x2);
                if ( (v1!=null && !v1.equals(v2)) || (v2!=null && !v2.equals(v1))){
                    response.append(field).append("(").append(v1).append(":").append(v2).append(")").append(", ");
                }
            }
        }
        return response.length()==0?null:response.substring(0,response.length()-2);
    }

Should I add the Visual Studio .suo and .user files to source control?

Visual Studio will automatically create them. I don't recommend putting them in source control. There have been numerous times where a local developer's SOU file was causing VS to behave erratically on that developers box. Deleting the file and then letting VS recreate it always fixed the issues.

How to use Bootstrap in an Angular project?

There are several ways to configure angular2 with Bootstrap, one of the most complete ways to get the most of it is to use ng-bootstrap, using this configuration we give to algular2 complete control over our DOM, avoiding the need to use JQuery and Boostrap.js.

1-Take as a starting point a new project created with Angular-CLI and using the command line, install ng-bootstrap:

npm install @ng-bootstrap/ng-bootstrap --save

Note: More info at https://ng-bootstrap.github.io/#/getting-started

2-Then we need to install bootstrap for the css and the grid system.

npm install [email protected] --save

Note: More info at https://getbootstrap.com/docs/4.0/getting-started/download/

Now we have the setup the environment and for that we have to change the .angular-cli.json adding to the style:

"../node_modules/bootstrap/dist/css/bootstrap.min.css"

Here is an example:

"apps": [
    {
      "root": "src",
        ...
      ],
      "index": "index.html",
       ...
      "prefix": "app",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ]

The next step is to add the ng-boostrap module to our project, to do so we need to add on the app.module.ts:

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

Then add the new module to the application app: NgbModule.forRoot()

Example:

@NgModule({
  declarations: [
    AppComponent,
    AppNavbarComponent
  ],
  imports: [
    BrowserModule,
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Now we can start using bootstrap4 on our angular2/5 project.

how to set textbox value in jquery

I think you want to set the response of the call to the URL 'compz.php?prodid=' + x + '&qbuys=' + y as value of the textbox right? If so, you have to do something like:

$.get('compz.php?prodid=' + x + '&qbuys=' + y, function(data) {
    $('#subtotal').val(data);
});

Reference: get()

You have two errors in your code:

  • load() puts the HTML returned from the Ajax into the specified element:

    Load data from the server and place the returned HTML into the matched element.

    You cannot set the value of a textbox with that method.

  • $(selector).load() returns the a jQuery object. By default an object is converted to [object Object] when treated as string.

Further clarification:

Assuming your URL returns 5.

If your HTML looks like:

<div id="foo"></div>

then the result of

$('#foo').load('/your/url');

will be

<div id="foo">5</div>

But in your code, you have an input element. Theoretically (it is not valid HTML and does not work as you noticed), an equivalent call would result in

<input id="foo">5</input>

But you actually need

<input id="foo" value="5" />

Therefore, you cannot use load(). You have to use another method, get the response and set it as value yourself.

How to remove first 10 characters from a string?

Calling SubString() allocates a new string. For optimal performance, you should avoid that extra allocation. Starting with C# 7.2 you can take advantage of the Span pattern.

When targeting .NET Framework, include the System.Memory NuGet package. For .NET Core projects this works out of the box.

static void Main(string[] args)
{
    var str = "hello world!";
    var span = str.AsSpan(10); // No allocation!

    // Outputs: d!
    foreach (var c in span)
    {
        Console.Write(c);
    }

    Console.WriteLine();
}

Spring not autowiring in unit tests with JUnit

You need to add annotations to the Junit class, telling it to use the SpringJunitRunner. The ones you want are:

@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)

This tells Junit to use the test-context.xml file in same directory as your test. This file should be similar to the real context.xml you're using for spring, but pointing to test resources, naturally.

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

Try to export the correct profile i.e. $ export AWS_PROFILE="default" If you only have a default profile make sure the keys are correct and rerun aws configure

Python virtualenv questions

on Windows I have python 3.7 installed and I still couldn't activate virtualenv from Gitbash with ./Scripts/activate although it worked from Powershell after running Set-ExecutionPolicy Unrestricted in Powershell and changing the setting to "Yes To All".

I don't like Powershell and I like to use Gitbash, so to activate virtualenv in Gitbash first navigate to your project folder, use ls to list the contents of the folder and be sure you see "Scripts". Change directory to "Scripts" using cd Scripts, once you're in the "Scripts" path use . activate to activate virtualenv. Don't forget the space after the dot.

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

Insert Unicode character into JavaScript

Although @ruakh gave a good answer, I will add some alternatives for completeness:

You could in fact use even var Omega = '&#937;' in JavaScript, but only if your JavaScript code is:

  • inside an event attribute, as in onclick="var Omega = '&#937'; alert(Omega)" or
  • in a script element inside an XHTML (or XHTML + XML) document served with an XML content type.

In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like &#937; are recognized. The restrictions make this an impractical approach in most cases.

You can also enter the O character as such, as in var Omega = 'O', but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.

Using the \u notation, as in var Omega = '\u03A9', works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)

You can also construct a character using the String.fromCharCode() method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937) or in hexadecimal as in var Omega = String.fromCharCode(0x3A9). This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.

Inline style to act as :hover in CSS

If it's for debugging, just add a css class for hovering (since elements can have more than one class):

a.hovertest:hover
{
text-decoration:underline;
}

<a href="http://example.com" class="foo bar hovertest">blah</a>

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

I'm going to expand your question a bit and also include the compile function.

  • compile function - use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive. (If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link' attribute is ignored if the 'compile' attribute is defined.)

  • link function - normally use for registering listener callbacks (i.e., $watch expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned. E.g., inside an <li ng-repeat...>, the link function is executed after the <li> template (tElement) has been cloned (into an iElement) for that particular <li> element. A $watch allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.

  • controller function - must be used when another directive needs to interact with this directive. E.g., on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.

    For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this (rather than on $scope), please see 'this' vs $scope in AngularJS controllers.

In general, you can put methods, $watches, etc. into either the directive's controller or link function. The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives). As Josh mentioned in a comment, you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.

excel formula to subtract number of days from a date

You can paste it like this:

= "2010-12-20" - 180

And don't forget to format the cell as a Date [CTRL]+[F1] / Number Tab

delete all from table

There is a mySQL bug report from 2004 that still seems to have some validity. It seems that in 4.x, this was fastest:

DROP table_name
CREATE TABLE table_name

TRUNCATE table_name was DELETE FROM internally back then, providing no performance gain.

This seems to have changed, but only in 5.0.3 and younger. From the bug report:

[11 Jan 2005 16:10] Marko Mäkelä

I've now implemented fast TRUNCATE TABLE, which will hopefully be included in MySQL 5.0.3.

How can I write to the console in PHP?

Short and easy, for arrays, strings or also objects.

function console_log( $data ) {
  $output  = "<script>console.log( 'PHP debugger: ";
  $output .= json_encode(print_r($data, true));
  $output .= "' );</script>";
  echo $output;
}

How to replace multiple strings in a file using PowerShell

A third option, for a pipelined one-liner is to nest the -replaces:

PS> ("ABC" -replace "B","C") -replace "C","D"
ADD

And:

PS> ("ABC" -replace "C","D") -replace "B","C"
ACD

This preserves execution order, is easy to read, and fits neatly into a pipeline. I prefer to use parentheses for explicit control, self-documentation, etc. It works without them, but how far do you trust that?

-Replace is a Comparison Operator, which accepts an object and returns a presumably modified object. This is why you can stack or nest them as shown above.

Please see:

help about_operators