Programs & Examples On #Server.mappath

The Server.MapPath method maps the specified relative or virtual path to the corresponding physical directory on the server.

Server.Mappath in C# classlibrary

By calling it?

var path = System.Web.HttpContext.Current.Server.MapPath("default.aspx");

Make sure you add a reference to the System.Web assembly.

Using Server.MapPath() inside a static field in ASP.NET MVC

Try HostingEnvironment.MapPath, which is static.

See this SO question for confirmation that HostingEnvironment.MapPath returns the same value as Server.MapPath: What is the difference between Server.MapPath and HostingEnvironment.MapPath?

Cannot use Server.MapPath

You need to add reference (System.Web) Reference to System.Web

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

How to add a recyclerView inside another recyclerView

I ran into similar problem a while back and what was happening in my case was the outer recycler view was working perfectly fine but the the adapter of inner/second recycler view had minor issues all the methods like constructor got initiated and even getCount() method was being called, although the final methods responsible to generate view ie..

1. onBindViewHolder() methods never got called. --> Problem 1.

2. When it got called finally it never show the list items/rows of recycler view. --> Problem 2.

Reason why this happened :: When you put a recycler view inside another recycler view, then height of the first/outer recycler view is not auto adjusted. It is defined when the first/outer view is created and then it remains fixed. At that point your second/inner recycler view has not yet loaded its items and thus its height is set as zero and never changes even when it gets data. Then when onBindViewHolder() in your second/inner recycler view is called, it gets items but it doesn't have the space to show them because its height is still zero. So the items in the second recycler view are never shown even when the onBindViewHolder() has added them to it.

Solution :: you have to create your custom LinearLayoutManager for the second recycler view and that is it. To create your own LinearLayoutManager: Create a Java class with the name CustomLinearLayoutManager and paste the code below into it. NO CHANGES REQUIRED

public class CustomLinearLayoutManager extends LinearLayoutManager {

    private static final String TAG = CustomLinearLayoutManager.class.getSimpleName();

    public CustomLinearLayoutManager(Context context) {
        super(context);

    }

    public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {

        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            measureScrapChild(recycler, i, View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);


            if (getOrientation() == HORIZONTAL) {
                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }
        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        try {
            View view = recycler.getViewForPosition(position);

            if (view != null) {
                RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();

                int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                        getPaddingLeft() + getPaddingRight(), p.width);

                int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                        getPaddingTop() + getPaddingBottom(), p.height);

                view.measure(childWidthSpec, childHeightSpec);
                measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
                measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
                recycler.recycleView(view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Disposing WPF User Controls

Dispatcher.ShutdownStarted event is fired only at the end of application. It's worth to call the disposing logic just when control gets out of use. In particular it frees resources when control is used many times during application runtime. So ioWint's solution is preferable. Here's the code:

public MyWpfControl()
{
     InitializeComponent();
     Loaded += (s, e) => { // only at this point the control is ready
         Window.GetWindow(this) // get the parent window
               .Closing += (s1, e1) => Somewhere(); //disposing logic here
     };
}

Xampp localhost/dashboard

If you want to display directory than edit htdocs/index.php file

Below code is display all directory in table

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to Nims Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="server/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- START PAGE SOURCE -->
<div id="wrap">
  <div id="top">
    <h1 id="sitename">Nims <em>Server</em> Directory list</h1>
    <div id="searchbar">
      <form action="#">
        <div id="searchfield">
          <input type="text" name="keyword" class="keyword" />
          <input class="searchbutton" type="image" src="server/images/searchgo.gif"  alt="search" />
        </div>
      </form>
    </div>
  </div>

<div class="background">
<div class="transbox">
<table width="100%" border="0" cellspacing="3" cellpadding="5" style="border:0px solid #333333;background: #F9F9F9;"> 
<tr>
<?php
//echo md5("saketbook007");

//File functuion DIR is used here.
$d = dir($_SERVER['DOCUMENT_ROOT']); 
$i=-1;
//Loop start with read function
while ($entry = $d->read()) {
if($entry == "." || $entry ==".."){
}else{
?>
<td  class="site" width="33%"><a href="<?php echo $entry;?>" ><?php echo ucfirst($entry); ?></a></td>  
<?php 
}
if($i%3 == 0){
echo "</tr><tr>";
}
$i++;
}?>
</tr> 
</table>

<?php $d->close();
?> 

</div>
</div>
</div>
   </div></div></body>
</html>

Style:

@import url("fontface.css");
* {
    padding:0;
    margin:0;
}
.clear {
    clear:both;
}

body {
    background:url(images/bg.jpg) repeat;
    font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
    color:#212713;
}
#wrap {
    width:1300px;
    margin:auto;
}

#sitename {
    font: normal 46px chunk;
    color:#1b2502;
    text-shadow:#5d7a17 1px 1px 1px;
    display:block;
    padding:45px 0 0 0;
    width:60%;
    float:left;
}
#searchbar {
    width:39%;
    float:right;
}
#sitename em {
    font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
}
#top {
    height:145px;
}
img {

    width:90%;
    height:250px;
    padding:10px;
    border:1px solid #000;
    margin:0 0 0 50px;
}


.post h2 a {
    color:#656f42;
    text-decoration:none;
}
#searchbar {
    padding:55px 0 0 0;
}
#searchfield {
    background:url(images/searchbar.gif) no-repeat;
    width:239px;
    height:35px;
    float:right;
}
#searchfield .keyword {
    width:170px;
    background:transparent;
    border:none;
    padding:8px 0 0 10px;
    color:#fff;
    display:block;
    float:left;
}
#searchfield .searchbutton {
    display:block;
    float:left;
    margin:7px 0 0 5px;
}

div.background
{
  background:url(h.jpg) repeat-x;
  border: 2px solid black;

  width:99%;
}
div.transbox
{
  margin: 15px;
  background-color: #ffffff;

  border: 1px solid black;
  opacity:0.8;
  filter:alpha(opacity=60); /* For IE8 and earlier */
  height:500px;
}

.site{

border:1px solid #CCC; 
}

.site a{text-decoration:none;font-weight:bold; color:#000; line-height:2}
.site:hover{background:#000; border:1px solid #03C;}
.site:hover a{color:#FFF}

Output : enter image description here

How can I force division to be floating point? Division keeps rounding down to 0?

Add a dot (.) to indicate floating point numbers

>>> 4/3.
1.3333333333333333

jQuery: Change button text on click

This should work for you:

    $('.SeeMore2').click(function(){
        var $this = $(this);
        $this.toggleClass('SeeMore2');
        if($this.hasClass('SeeMore2')){
            $this.text('See More');         
        } else {
            $this.text('See Less');
        }
});

Your password does not satisfy the current policy requirements

didn't work for me on ubuntu fresh install of mysqld, had to add this: to /etc/mysql/mysql.conf.d/mysqld.cnf or the server wouldn't start (guess the plugin didn't load at the right time when I simply added it without the plugin-load-add directive)

plugin-load-add=validate_password.so
validate_password_policy=LOW
validate_password_length=8
validate_password_mixed_case_count=0
validate_password_number_count=0
validate_password_special_char_count=0

iPhone SDK:How do you play video inside a view? Rather than fullscreen

NSString * pathv = [[NSBundle mainBundle] pathForResource:@"vfile" ofType:@"mov"];
playerv = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:pathv]];

[self presentMoviePlayerViewControllerAnimated:playerv];

Import module from subfolder

Just create an empty __init__.py file and add it in root as well as all the sub directory/folder of your python application where you have other python modules. See https://docs.python.org/3/tutorial/modules.html#packages

Windows Scheduled task succeeds but returns result 0x1

For Powershell scripts

I have seen this problem multiple times while scheduling Powershell scripts with parameters on multiple Windows servers. The solution has always been to use the -File parameter:

  1. Under "Actions" --> "Program / Script" Type: "Powershell"
  2. Under "Add arguments", instead of just typeing "C:/script/test.ps1" use -File "C:/script/test.ps1"

Happy scheduling!

enter image description here

Seeking useful Eclipse Java code templates

Create everything for an event

Since events are kinda a pain to create in Java--all those interfaces, methods, and stuff to write just for 1 event--I made a simple template to create everything needed for 1 event.

${:import(java.util.List, java.util.LinkedList, java.util.EventListener, java.util.EventObject)}

private final List<${eventname}Listener> ${eventname}Listeners = new LinkedList<${eventname}Listener>();

public final void add${eventname}Listener(${eventname}Listener listener)
{
    synchronized(${eventname}Listeners) {
        ${eventname}Listeners.add(listener);
    }
}

public final void remove${eventname}Listener(${eventname}Listener listener)
{
    synchronized(${eventname}Listeners) {
        ${eventname}Listeners.remove(listener);
    }
}

private void raise${eventname}Event(${eventname}Args args)
{
    synchronized(${eventname}Listeners) {
        for(${eventname}Listener listener : ${eventname}Listeners)
            listener.on${eventname}(args);
    }
}

public interface ${eventname}Listener extends EventListener
{
    public void on${eventname}(${eventname}Args args);
}

public class ${eventname}Args extends EventObject
{
    public ${eventname}Args(Object source${cursor})
    {
        super(source);
    }
}

If you have events that share a single EventObject, just delete the customized one inserted by the template and change the appropriate parts of raise___() and on____().

I had written a nice, little, elegant eventing mechanism using a generic interface and generic class, but it wouldn't work due to the way Java handles generics. =(

Edit: 1) I ran into the issue where threads were adding/removing listeners while an event was taking place. The List can't be modified while in use, so I added synchronized blocks where the list of listeners is being accessed or used, locking on the list itself.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

You seems to be missing implementation for interface UserDao. If you look at the exception closely it says

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency:

The way @Autowired works is that it would automatically look for implementation of a dependency you inject via an interface. In this case since there is no valid implementation of interface UserDao you get the error.Ensure you have a valid implementation for this class and your error should go.

Hope that helps.

How to install PIP on Python 3.6?

There are situations when your pip doesn't get downloaded along with python installation. Even your whole script folder can be empty.

You can do so manually as well.

Just head to Command Prompt and type python -m ensurepip --default-pip Press Enter.

Make sure that value of path variable is updated.

This will do the Trick

How to get bean using application context in spring boot

Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:

@Component
public class SpringContext implements ApplicationContextAware{

   private static ApplicationContext applicationContext;

   @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws 
     BeansException {
    this.applicationContext=applicationContext;
   }
 }

you can then implement a getter method in the same class as per your need to get the bean. Like:

    applicationContext.getBean(String serviceName,Interface.Class)

How to install PHP mbstring on CentOS 6.2

do the following:

sudo nano /etc/yum.repos.d/CentOS-Base.repo

under the section updates, comment out the mirrorlist line (put a # in front of the line), then on a new line write:

baseurl=http://centos.intergenia.de/$releasever/updates/$basearch/

now try:

yum install php-mbstring

(afterwards you'll probably want to uncomment the mirrorlist and comment out the baseurl)

localhost refused to connect Error in visual studio

I had to add https bindings in my local IIS

SQL where datetime column equals today's date?

There might be another way, but this should work:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET] 
WHERE day(Submission_date)=day(now) and 
     month(Submission_date)=month(now)
     and year(Submission_date)=year(now)

On Duplicate Key Update same as insert

Here is a solution to your problem:

I've tried to solve problem like yours & I want to suggest to test from simple aspect.

Follow these steps: Learn from simple solution.

Step 1: Create a table schema using this SQL Query:

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` varchar(32) NOT NULL,
  `status` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `no_duplicate` (`username`,`password`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

A table <code>user</code> with data

Step 2: Create an index of two columns to prevent duplicate data using following SQL Query:

ALTER TABLE `user` ADD INDEX no_duplicate (`username`, `password`);

or, Create an index of two column from GUI as follows: Create index from GUI Select columns to create index Indexes of table <code>user</code>

Step 3: Update if exist, insert if not using following queries:

INSERT INTO `user`(`username`, `password`) VALUES ('ersks','Nepal') ON DUPLICATE KEY UPDATE `username`='master',`password`='Nepal';

INSERT INTO `user`(`username`, `password`) VALUES ('master','Nepal') ON DUPLICATE KEY UPDATE `username`='ersks',`password`='Nepal';

Table <code>user</code> after running above query

Is there a CSS selector for elements containing certain text?

If you don't create the DOM yourself (e.g. in a userscript) you can do the following with pure JS:

_x000D_
_x000D_
for ( td of document.querySelectorAll('td') ) {_x000D_
  console.debug("text:", td, td.innerText)_x000D_
  td.setAttribute('text', td.innerText)_x000D_
}_x000D_
for ( td of document.querySelectorAll('td[text="male"]') )_x000D_
  console.debug("male:", td, td.innerText)
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Peter</td>_x000D_
    <td>male</td>_x000D_
    <td>34</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Susanne</td>_x000D_
    <td>female</td>_x000D_
    <td>12</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Console output

text: <td> Peter
text: <td> male
text: <td> 34
text: <td> Susanne
text: <td> female
text: <td> 12
male: <td text="male"> male

What does the ">" (greater-than sign) CSS selector mean?

It matches p elements with class some_class that are directly under a div.

How do I hide an element when printing a web page?

The best thing to do is to create a "print-only" version of the page.

Oh, wait... this isn't 1999 anymore. Use a print CSS with "display: none".

Python error: "IndexError: string index out of range"

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

word = 'hello'
so_far = "-" * len(word)       # Create variable so_far to contain the current guess

while word != so_far:          # if still not complete
    print(so_far)
    guess = input('>> ')       # get a char guess

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        new = ""
        for i in range(len(word)):  
            if guess == word[i]:
                new += guess        # fill the position with new value
            else:
                new += so_far[i]    # same value as before
        so_far = new
    else:
        print("try_again")

print('finish')

I tried to write it for py3k with a py2k ide, be careful with errors.

How to give Jenkins more heap space when it´s started as a service under Windows?

In your Jenkins installation directory there is a jenkins.xml, where you can set various options. Add the parameter -Xmx with the size you want to the arguments-tag (or increase the size if its already there).

Adding rows to dataset

To add rows to existing DataTable in Dataset:

DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);

How to view files in binary from bash?

to convert a file to its binary codes(hexadecimal representation) we say:

xxd filename                                         #

e.g:

xxd hello.c                                          #

to see all the contents and codes in a binary file , we could use commands like readelf and objdump, hexdump ,... .

for example if we want to see all the convert all the contents of a binary file(executable, shared libraries, object files) we say:

hexdump binaryfilename

e.g.

hexdump /bin/bash

but readelf is the best utility for analyzing elf(executable and linking format) files. so if we say:

readelf -a /bin/bash

all the contents in the binary file bash would be shown to us, also we could provide different flags for readelf to see all the sections and headers of an elf file separately, for example if we want to see only the elf header we say:

readelf -h /bin/bash

for reading all the segments of the file:

readelf -l /bin/bash

for reading all the sections of the file:

readelf -S /bin/sh

but again as summary , for reading a normal file like "hello.c" and a binary file like bash in path /bin/bash in linux we say:

xxd hello.c

readelf -a /bin/bash

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Happy coding..

Why is the parent div height zero when it has floated children

Ordinarily, floats aren't counted in the layout of their parents.

To prevent that, add overflow: hidden to the parent.

What is Express.js?

1) What is Express.js?

Express.js is a Node.js framework. It's the most popular framework as of now (the most starred on NPM).

Enter image description here.

It's built around configuration and granular simplicity of Connect middleware. Some people compare Express.js to Ruby Sinatra vs. the bulky and opinionated Ruby on Rails.

2) What is the purpose of it with Node.js?

That you don't have to repeat same code over and over again. Node.js is a low-level I/O mechanism which has an HTTP module. If you just use an HTTP module, a lot of work like parsing the payload, cookies, storing sessions (in memory or in Redis), selecting the right route pattern based on regular expressions will have to be re-implemented. With Express.js, it is just there for you to use.

3) Why do we actually need Express.js? How it is useful for us to use with Node.js?

The first answer should answer your question. If no, then try to write a small REST API server in plain Node.js (that is, using only core modules) and then in Express.js. The latter will take you 5-10x less time and lines of code.

What is Redis? Does it come with Express.js?

Redis is a fast persistent key-value storage. You can optionally use it for storing sessions with Express.js, but you don't need to. By default, Express.js has memory storage for sessions. Redis also can be use for queueing jobs, for example, email jobs.

Check out my tutorial on REST API server with Express.js.

MVC but not by itself

Express.js is not an model-view-controller framework by itself. You need to bring your own object-relational mapping libraries such as Mongoose for MongoDB, Sequelize (http://sequelizejs.com) for SQL databases, Waterline (https://github.com/balderdashy/waterline) for many databases into the stack.

Alternatives

Other Node.js frameworks to consider (https://www.quora.com/Node-js/Which-Node-js-framework-is-best-for-building-a-RESTful-API):

UPDATE: I put together this resource that aid people in choosing Node.js frameworks: http://nodeframework.com

UPDATE2: We added some GitHub stats to nodeframework.com so now you can compare the level of social proof (GitHub stars) for 30+ frameworks on one page.

enter image description here

Full-stack:

Just REST API:

Ruby on Rails like:

Sinatra like:

Other:

Middleware:

Static site generators:

Vertical alignment of text and icon in button

Alternativly if your using bootstrap then you can just add align-middle to vertical align the element.

<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">Continue
    <i class="icon-ok align-middle" style="font-size:40px;"></i>
</button>

Transpose a matrix in Python

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis  = [[1,2,3], 
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

Saving and Reading Bitmaps/Images from Internal memory in Android

// mutiple image retrieve

 File folPath = new File(getIntent().getStringExtra("folder_path"));
 File[] imagep = folPath.listFiles();

 for (int i = 0; i < imagep.length ; i++) {
     imageModelList.add(new ImageModel(imagep[i].getAbsolutePath(), Uri.parse(imagep[i].getAbsolutePath())));
 }
 imagesAdapter.notifyDataSetChanged();

Checking if any elements in one list are in another

I wrote the following code in one of my projects. It basically compares each individual element of the list. Feel free to use it, if it works for your requirement.

def reachedGoal(a,b):
    if(len(a)!=len(b)):
        raise ValueError("Wrong lists provided")

    for val1 in range(0,len(a)):
        temp1=a[val1]
        temp2=b[val1]
        for val2 in range(0,len(b)):
            if(temp1[val2]!=temp2[val2]):
                return False
    return True

To check if string contains particular word

It's been correctly pointed out above that finding a given word in a sentence is not the same as finding the charsequence, and can be done as follows if you don't want to mess around with regular expressions.

boolean checkWordExistence(String word, String sentence) {
    if (sentence.contains(word)) {
        int start = sentence.indexOf(word);
        int end = start + word.length();

        boolean valid_left = ((start == 0) || (sentence.charAt(start - 1) == ' '));
        boolean valid_right = ((end == sentence.length()) || (sentence.charAt(end) == ' '));

        return valid_left && valid_right;
    }
    return false;
}

Output:

checkWordExistence("the", "the earth is our planet"); true
checkWordExistence("ear", "the earth is our planet"); false
checkWordExistence("earth", "the earth is our planet"); true

P.S Make sure you have filtered out any commas or full stops beforehand.

How to set entire application in portrait mode only?

Yes you can do this both programmatically and for all your activities making an AbstractActivity that all your activities extends.

public abstract class AbstractActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}

This abstract activity can also be used for a global menu.

Add custom buttons on Slick Carousel

its very easy. Use the bellow code, Its works for me. Here I have used fontawesome icon but you can use anything as image or any other Icon's code.

$(document).ready(function(){
    $('.slider').slick({
        autoplay:true,
        arrows: true,
        prevArrow:"<button type='button' class='slick-prev pull-left'><i class='fa fa-angle-left' aria-hidden='true'></i></button>",
        nextArrow:"<button type='button' class='slick-next pull-right'><i class='fa fa-angle-right' aria-hidden='true'></i></button>"
    });
});

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

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

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

How to limit depth for recursive file list?

Make use of find's options

There is actually no exec of /bin/ls needed;

Find has an option that does just that:

find . -maxdepth 2 -type d -ls

To see only the one level of subdirectories you are interested in, add -mindepth to the same level as -maxdepth:

find . -mindepth 2 -maxdepth 2 -type d -ls

Use output formatting

When the details that get shown should be different, -printf can show any detail about a file in custom format; To show the symbolic permissions and the owner name of the file, use -printf with %M and %u in the format.

I noticed later you want the full ownership information, which includes the group. Use %g in the format for the symbolic name, or %G for the group id (like also %U for numeric user id)

find . -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'

This should give you just the details you need, for just the right files.

I will give an example that shows actually different values for user and group:

$ sudo find /tmp -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
drwx------ www-data  www-data /tmp/user/33
drwx------ octopussy root     /tmp/user/126
drwx------ root      root     /tmp/user/0
drwx------ siegel    root     /tmp/user/1000
drwxrwxrwt root      root     /tmp/systemd-[...].service-HRUQmm/tmp

(Edited for readability: indented, shortened last line)


Notes on performance

Although the execution time is mostly irrelevant for this kind of command, increase in performance is large enough here to make it worth pointing it out:

Not only do we save creating a new process for each name - a huge task - the information does not even need to be read, as find already knows it.

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

It's because of being too sure about what you (me) are doing!

On my machine there is IIS 7 installed but the required ASP.NET component (Control Panel->Programs->Turn On/Off->ASP.NET) was not.

So installing this solved the problem

Git push results in "Authentication Failed"

This the way, I resolved my access denied problem in GIT GUI and git bash. SSH KEy

This SSH key is copy-pasted in the GitHub access token.Access Token

For me everything was fine, I also tried the Windows Credentials Manager but then also the problem was not resolved. Then suddenly, I got pop up from the firewall, which was the main culprit behind all. After I clicked on allow manually then I could fetch or push to GitHub.

How to remove empty cells in UITableView?

override func viewWillAppear(animated: Bool) {
    self.tableView.tableFooterView = UIView(frame: CGRect.zeroRect)

/// OR 

    self.tableView.tableFooterView = UIView()
}

Calculate median in c#

I have an histogram with the variable : group
Here how I calculate my median :

int[] group = new int[nbr]; 

// -- Fill the group with values---

// sum all data in median
int median = 0;
for (int i =0;i<nbr;i++) median += group[i];

// then divide by 2 
median = median / 2;

// find 50% first part 
for (int i = 0; i < nbr; i++)
{
   median -= group[i];
   if (median <= 0)
   {
      median = i;
      break;
   }
}

median is the group index of median

Why should I prefer to use member initialization lists?

// Without Initializer List
class MyClass {
    Type variable;
public:
    MyClass(Type a) {  // Assume that Type is an already
                     // declared class and it has appropriate 
                     // constructors and operators
        variable = a;
    }
};

Here compiler follows following steps to create an object of type MyClass
1. Type’s constructor is called first for “a”.
2. The assignment operator of “Type” is called inside body of MyClass() constructor to assign

variable = a;
  1. And then finally destructor of “Type” is called for “a” since it goes out of scope.

    Now consider the same code with MyClass() constructor with Initializer List

    // With Initializer List
     class MyClass {
    Type variable;
    public:
    MyClass(Type a):variable(a) {   // Assume that Type is an already
                     // declared class and it has appropriate
                     // constructors and operators
    }
    };
    

    With the Initializer List, following steps are followed by compiler:

    1. Copy constructor of “Type” class is called to initialize : variable(a). The arguments in initializer list are used to copy construct “variable” directly.
    2. Destructor of “Type” is called for “a” since it goes out of scope.

How to set session timeout in web.config

If you are using MVC, you put this in the web.config file in the Root directory of the web application, not the web.config in the Views directory. It also needs to be IN the system.web node, not under like George2 stated in his question: "I wrote under system.web section in the web.config"

The timeout parameter value represents minutes.

There are other attributes that can be set in the sessionState element. You can find information here: docs.microsoft.com sessionState

<configuration>
   <system.web>
      <sessionState timeout="20"></sessionState>
   </system.web>
</configuration>

You can then catch the begining of a new session in the Global.asax file by adding the following method:

void Session_Start(object sender, EventArgs e)
{
    if (Session.IsNewSession)
    {
        //do things that need to happen
        //when a new session starts.
    }
}

Android WebView, how to handle redirects in app instead of opening a browser

Create a class that implements webviewclient and add the following code that allows ovveriding the url string as shown below. You can see these [example][1]

public class myWebClient extends WebViewClient {

    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         view.loadUrl(url); 
         return true;
     }
}

On your constructor, create a webview object as shown below.

   web = new WebView(this); web.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); 

Then add the following code to perform loading of urls inside your app

       WebSettings settings=web.getSettings(); 
    settings.setJavaScriptEnabled(true); 
    
    web.loadUrl("http://www.facebook.com");
    web.setWebViewClient(new myWebClient()); 
   
 web.setWebChromeClient(new WebChromeClient() {
      // 
      //
    }

How to print third column to last column?

Well, you can easily accomplish the same effect using a regular expression. Assuming the separator is a space, it would look like:

awk '{ sub(/[^ ]+ +[^ ]+ +/, ""); print }'

How can I install a CPAN module into a local directory?

For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:

perl Makefile.PL INSTALL_BASE=/mydir/perl

Functions that return a function

Snippet one:

function a() {
  
    alert('A!');

    function b(){
        alert('B!'); 
    }

    return b(); //return nothing here as b not defined a return value
}

var s = a(); //s got nothing assigned as b() and thus a() return nothing.
alert('break');
s(); // s equals nothing so nothing will be executed, JavaScript interpreter will complain

the statement 'b()' means to execute the function named 'b' which shows a dialog box with text 'B!'

the statement 'return b();' means to execute a function named 'b' and then return what function 'b' return. but 'b' returns nothing, then this statement 'return b()' returns nothing either. If b() return a number, then ‘return b()’ is a number too.

Now ‘s’ is assigned the value of what 'a()' return, which returns 'b()', which is nothing, so 's' is nothing (in JavaScript it’s a thing actually, it's an 'undefined'. So when you ask JavaScript to interpret what data type the 's' is, JavaScript interpreter will tell you 's' is an undefined.) As 's' is an undefined, when you ask JavaScript to execute this statement 's()', you're asking JavaScript to execute a function named as 's', but 's' here is an 'undefined', not a function, so JavaScript will complain, "hey, s is not a function, I don't know how to do with this s", then a "Uncaught TypeError: s is not a function" error message will be shown by JavaScript (tested in Firefox and Chrome)


Snippet Two

function a() {
  
    alert('A!');

    function b(){
        alert('B!'); 
    }

    return b; //return pointer to function b here
}

var s = a();  //s get the value of pointer to b
alert('break');
s(); // b() function is executed

now, function 'a' returning a pointer/alias to a function named 'b'. so when execute 's=a()', 's' will get a value pointing to b, i.e. 's' is an alias of 'b' now, calling 's' equals calling 'b'. i.e. 's' is a function now. Execute 's()' means to run function 'b' (same as executing 'b()'), a dialog box showing 'B!' will appeared (i.e. running the 'alert('B!'); statement in the function 'b')

Simplest way to display current month and year like "Aug 2016" in PHP?

Full version:

<? echo date('F Y'); ?>

Short version:

<? echo date('M Y'); ?>

Here is a good reference for the different date options.

update

To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp parameter for the date() function. Like this:

echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));

This will also work (it's typically used to get the last day of the previous month):

echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));

Hope that helps.

How do I make the scrollbar on a div only visible when necessary?

I found that there is height of div still showing, when it have text or not. So you can use this for best results.

<div style=" overflow:auto;max-height:300px; max-width:300px;"></div>

Create a Cumulative Sum Column in MySQL

MySQL 8.0/MariaDB supports windowed SUM(col) OVER():

SELECT *, SUM(cnt) OVER(ORDER BY id) AS cumulative_sum
FROM tab;

Output:

+-----------------------------+
¦ id  ¦ cnt  ¦ cumulative_sum ¦
+-----+------+----------------¦
¦  1  ¦ 100  ¦            100 ¦
¦  2  ¦  50  ¦            150 ¦
¦  3  ¦  10  ¦            160 ¦
+-----------------------------+

db<>fiddle

Google map V3 Set Center to specific Marker

geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

What does the "assert" keyword do?

It ensures that the expression returns true. Otherwise, it throws a java.lang.AssertionError.

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.10

What is the best free SQL GUI for Linux for various DBMS systems

I use SQLite Database Browser for SQLite3 currently and it's pretty useful. Works across Windows/OS X/Linux and is lightweight and fast. Slightly unstable with executing SQL on the DB if it's incorrectly formatted.

Edit: I have recently discovered SQLite Manager, a plugin for Firefox. Obviously you need to run Firefox, but you can close all windows and just run it "standalone". It's very feature complete, amazingly stable and it remembers your databases! It has tonnes of features so I've moved away from SQLite Database Browser as the instability and lack of features is too much to bear.

How to search in an array with preg_match?

In this post I'll provide you with three different methods of doing what you ask for. I actually recommend using the last snippet, since it's easiest to comprehend as well as being quite neat in code.

How do I see what elements in an array that matches my regular expression?

There is a function dedicated for just this purpose, preg_grep. It will take a regular expression as first parameter, and an array as the second.

See the below example:

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

$matches  = preg_grep ('/^hello (\w+)/i', $haystack);

print_r ($matches);

output

Array
(
    [1] => hello stackoverflow
    [2] => hello world
)

Documentation


But I just want to get the value of the specified groups. How?

array_reduce with preg_match can solve this issue in clean manner; see the snippet below.

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

function _matcher ($m, $str) {
  if (preg_match ('/^hello (\w+)/i', $str, $matches))
    $m[] = $matches[1];

  return $m;
}

// N O T E :
// ------------------------------------------------------------------------------
// you could specify '_matcher' as an anonymous function directly to
// array_reduce though that kind of decreases readability and is therefore
// not recommended, but it is possible.

$matches = array_reduce ($haystack, '_matcher', array ());

print_r ($matches);

output

Array
(
    [0] => stackoverflow
    [1] => world
)

Documentation


Using array_reduce seems tedious, isn't there another way?

Yes, and this one is actually cleaner though it doesn't involve using any pre-existing array_* or preg_* function.

Wrap it in a function if you are going to use this method more than once.

$matches = array ();

foreach ($haystack as $str) 
  if (preg_match ('/^hello (\w+)/i', $str, $m))
    $matches[] = $m[1];

Documentation

How to create standard Borderless buttons (like in the design guideline mentioned)?

A great slide show on how to achieve the desired effect from Googles Nick Butcher (start at slide 20). He uses the standard android @attr to style the button and divider.

Annotations from javax.validation.constraints not working

for method parameters you can use Objects.requireNonNull() like this: test(String str) { Objects.requireNonNull(str); } But this is only checked at runtime and throws an NPE if null. It is like a preconditions check. But that might be what you are looking for.

How to convert a List<String> into a comma separated string without iterating List explicitly

You can use below code if object has attibutes under it.

String getCommonSeperatedString(List<ActionObject> actionObjects) {
    StringBuffer sb = new StringBuffer();
    for (ActionObject actionObject : actionObjects){
        sb.append(actionObject.Id).append(",");
    }
    sb.deleteCharAt(sb.lastIndexOf(","));
    return sb.toString();
}

Creating multiline strings in JavaScript

The Rule is: when inside a string, use \n wherever you want a new line; you do not have to put a space before or after the \n, JavaScript's interpreter is smart enough to know how long the unprintable character representation is.

Javascript Object push() function

I hope this one might help you.

_x000D_
_x000D_
let data = [];
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };

let tempData = [];

tempData= data.filter((item)=>item.Status!='Invalid')

console.log(tempData)
_x000D_
_x000D_
_x000D_

What does the question mark and the colon (?: ternary operator) mean in objective-c?

Simply, the logic would be

(condition) ? {code for YES} : {code for NO}

How to find all occurrences of an element in a list

How about:

In [1]: l=[1,2,3,4,3,2,5,6,7]

In [2]: [i for i,val in enumerate(l) if val==3]
Out[2]: [2, 4]

How to getText on an input in protractor

getText() function won't work like the way it used to be for webdriver, in order to get it work for protractor you will need to wrap it in a function and return the text something like we did for our protractor framework we have kept it in a common function like -

getText : function(element, callback) {
        element.getText().then (function(text){             
            callback(text);
         });        

    },

By this you can have the text of an element.

Let me know if it is still unclear.

Using JQuery to check if no radio button in a group has been checked

Use .length refer to http://api.jquery.com/checked-selector/

if ($('input[name="html_elements"]:checked').length === 0) alert("Not checked");
else alert("Checked");

Best JavaScript compressor

Try JSMin, got C#, Java, C and other ports and readily available too.

How to squash commits in git after they have been pushed?

For squashing two commits, one of which was already pushed, on a single branch the following worked:

git rebase -i HEAD~2
    [ pick     older-commit  ]
    [ squash   newest-commit ]
git push --force

By default, this will include the commit message of the newest commit as a comment on the older commit.

Python: finding lowest integer

Cast the variable to a float before doing the comparison:

if float(i) < float(x):

The problem is that you are comparing strings to floats, which will not work.

eval command in Bash and its typical uses

I like the "evaluating your expression one additional time before execution" answer, and would like to clarify with another example.

var="\"par1 par2\""
echo $var # prints nicely "par1 par2"

function cntpars() {
  echo "  > Count: $#"
  echo "  > Pars : $*"
  echo "  > par1 : $1"
  echo "  > par2 : $2"

  if [[ $# = 1 && $1 = "par1 par2" ]]; then
    echo "  > PASS"
  else
    echo "  > FAIL"
    return 1
  fi
}

# Option 1: Will Pass
echo "eval \"cntpars \$var\""
eval "cntpars $var"

# Option 2: Will Fail, with curious results
echo "cntpars \$var"
cntpars $var

The Curious results in Option 2 are that we would have passed 2 parameters as follows:

  • First Parameter: "value
  • Second Parameter: content"

How is that for counter intuitive? The additional eval will fix that.

Adapted from https://stackoverflow.com/a/40646371/744133

Add quotation at the start and end of each line in Notepad++

  1. Put your cursor at the begining of line 1.
  2. click Edit>ColumnEditor. Put " in the text and hit enter.
  3. Repeat 2 but put the cursor at the end of line1 and put ", and hit enter.

Argument list too long error for rm, cp, mv commands

A bit safer version than using xargs, also not recursive: ls -p | grep -v '/$' | grep '\.pdf$' | while read file; do rm "$file"; done

Filtering our directories here is a bit unnecessary as 'rm' won't delete it anyway, and it can be removed for simplicity, but why run something that will definitely return error?

Repair all tables in one go

No need to type in the password, just use any one of these commands (self explanatory):

mysqlcheck --all-databases -a #analyze
mysqlcheck --all-databases -r #repair
mysqlcheck --all-databases -o #optimize

Difference between logger.info and logger.debug

I suggest you look at the article called "Short Introduction to log4j". It contains a short explanation of log levels and demonstrates how they can be used in practice. The basic idea of log levels is that you want to be able to configure how much detail the logs contain depending on the situation. For example, if you are trying to troubleshoot an issue, you would want the logs to be very verbose. In production, you might only want to see warnings and errors.

The log level for each component of your system is usually controlled through a parameter in a configuration file, so it's easy to change. Your code would contain various logging statements with different levels. When responding to an Exception, you might call Logger.error. If you want to print the value of a variable at any given point, you might call Logger.debug. This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.

In the case of log4j at least, the ordering of log levels is:

DEBUG < INFO < WARN < ERROR < FATAL

Here is a short example from that article demonstrating how log levels work.

   // get a logger instance named "com.foo"
   Logger logger = Logger.getLogger("com.foo");

   // Now set its level. Normally you do not need to set the
   // level of a logger programmatically. This is usually done
   // in configuration files.
   logger.setLevel(Level.INFO);

   Logger barlogger = Logger.getLogger("com.foo.Bar");

   // This request is enabled, because WARN >= INFO.
   logger.warn("Low fuel level.");

   // This request is disabled, because DEBUG < INFO.
   logger.debug("Starting search for nearest gas station.");

   // The logger instance barlogger, named "com.foo.Bar",
   // will inherit its level from the logger named
   // "com.foo" Thus, the following request is enabled
   // because INFO >= INFO.
   barlogger.info("Located nearest gas station.");

   // This request is disabled, because DEBUG < INFO.
   barlogger.debug("Exiting gas station search");

How to create a printable Twitter-Bootstrap page

In case someone is looking for a solution for Bootstrap v2.X.X here. I am leaving the solution I was using. This is not fully tested on all browsers however it could be a good start.

1) make sure the media attribute of bootstrap-responsive.css is screen.

<link href="/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen" />

2) create a print.css and make sure its media attribute print

<link href="/css/print.css" rel="stylesheet" media="print" />

3) inside print.css, add the "width" of your website in html & body

html, 
body {
    width: 1200px !important;
}

4.) reproduce the necessary media query classes in print.css because they were inside bootstrap-responsive.css and we have disabled it when printing.

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

Here is full version of print.css:

html, 
body {
    width: 1200px !important;
}

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

Finish all previous activities

Use:

Intent intent = new Intent(getApplicationContext(), Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

This will clear all the activities on top of home.

Assuming you are finishing the login screen when the user logs in and home is created and afterwards all the screens from 1 to 5 on top of that one. The code i posted will return you to home screen finishing all the other activites. You can add an extra in the intent and read that in the home screen activity and finish it also (maybe launch login screen again from there or something).

I am not sure but you can also try going to login with this flag. I don't know how the activities will be ordered in that case. So don't know if it will clear the ones below the screen you are on including the one you are currently on but its definitely the way to go.

Hope this helps.

Powershell v3 Invoke-WebRequest HTTPS error

  1. Run this command

New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname {your-site-hostname}

in powershell using admin rights, This will generate all certificates in Personal directory

  1. To get rid of Privacy error, select these certificates, right click ? Copy. And paste in Trusted Root Certification Authority/Certificates.
  2. Last step is to select correct bindings in IIS. Go to IIS website, select Bindings, Select SNI checkbox and set the individual certificates for each website.

Make sure website hostname and certificate dns-name should exactly match

Using filesystem in node.js with async / await

This is the TypeScript version to the question. It is usable after Node 11.0:

import { promises as fs } from 'fs';

async function loadMonoCounter() {
    const data = await fs.readFile('monolitic.txt', 'binary');
    return Buffer.from(data);
}

MySql difference between two timestamps in days?

If you're happy to ignore the time portion in the columns, DATEDIFF() will give you the difference you're looking for in days.

SELECT DATEDIFF('2010-10-08 18:23:13', '2010-09-21 21:40:36') AS days;
+------+
| days |
+------+
|   17 |
+------+

how to return a char array from a function in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
    int n,k=0;
    char *ch1;
    ch1=(char*)malloc((j-i+1)*1);
    n=j-i+1;

    while(k<n)
    {
        ch1[k]=ch[i];
        i++;k++;
    }

    return (char *)ch1;
}

int main()
{
    int i=0,j=2;
    char s[]="String";
    char *test;

    test=substring(i,j,s);
    printf("%s",test);
    free(test); //free the test 
    return 0;
}

This will compile fine without any warning

  1. #include stdlib.h
  2. pass test=substring(i,j,s);
  3. remove m as it is unused
  4. either declare char substring(int i,int j,char *ch) or define it before main

How to share my Docker-Image without using the Docker-Hub?

[Update]

More recently, there is Amazon AWS ECR (Elastic Container Registry), which provides a Docker image registry to which you can control access by means of the AWS IAM access management service. ECR can also run a CVE (vulnerabilities) check on your image when you push it.

Once you create your ECR, and obtain the "URL" you can push and pull as required, subject to the permissions you create: hence making it private or public as you wish.

Pricing is by amount of data stored, and data transfer costs.

https://aws.amazon.com/ecr/

[Original answer]

If you do not want to use the Docker Hub itself, you can host your own Docker repository under Artifactory by JFrog:

https://www.jfrog.com/confluence/display/RTF/Docker+Repositories

which will then run on your own server(s).

Other hosting suppliers are available, eg CoreOS:

http://www.theregister.co.uk/2014/10/30/coreos_enterprise_registry/

which bought quay.io

"The operation is not valid for the state of the transaction" error and transaction scope

For me, this error came up when I was trying to rollback a transaction block after encountering an exception, inside another transaction block.

All I had to do to fix it was to remove my inner transaction block.

Things can get quite messy when using nested transactions, best to avoid this and just restructure your code.

How to push a new folder (containing other folders and files) to an existing git repo?

You can directly go to Web IDE and upload your folder there.

Steps:

  1. Go to Web IDE(Mostly located below the clone option).
  2. Create new directory at your path
  3. Upload your files and folders

In some cases you may not be able to directly upload entire folder containing folders, In such cases, you will have to create directory structure yourself.

How do I check if an integer is even or odd?

Use bit arithmetic:

if((x & 1) == 0)
    printf("EVEN!\n");
else
    printf("ODD!\n");

This is faster than using division or modulus.

Get the position of a div/span tag

This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.

function getPos(el) {
    // yay readability
    for (var lx=0, ly=0;
         el != null;
         lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
    return {x: lx,y: ly};
}

However, if you just wanted the x,y position of the element relative to its container, then all you need is:

var x = el.offsetLeft, y = el.offsetTop;

To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.

var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;

Test if something is not undefined in JavaScript

Just check if response[0] is undefined:

if(response[0] !== undefined) { ... }

If you still need to explicitly check the title, do so after the initial check:

if(response[0] !== undefined && response[0].title !== undefined){ ... }

GridLayout and Row/Column Span Woe

It feels pretty hacky, but I managed to get the correct look by adding an extra column and row beyond what is needed. Then I filled the extra column with a Space in each row defining a height and filled the extra row with a Space in each col defining a width. For extra flexibility, I imagine these Space sizes could be set in code to provide something similar to weights. I tried to add a screenshot, but I do not have the reputation necessary.

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnCount="9"
android:orientation="horizontal"
android:rowCount="8" >

<Button
    android:layout_columnSpan="2"
    android:layout_gravity="fill"
    android:layout_rowSpan="2"
    android:text="1" />

<Button
    android:layout_columnSpan="2"
    android:layout_gravity="fill_horizontal"
    android:text="2" />

<Button
    android:layout_gravity="fill_vertical"
    android:layout_rowSpan="4"
    android:text="3" />

<Button
    android:layout_columnSpan="3"
    android:layout_gravity="fill"
    android:layout_rowSpan="2"
    android:text="4" />

<Button
    android:layout_columnSpan="3"
    android:layout_gravity="fill_horizontal"
    android:text="5" />

<Button
    android:layout_columnSpan="2"
    android:layout_gravity="fill_horizontal"
    android:text="6" />

<Space
    android:layout_width="36dp"
    android:layout_column="0"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="1"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="2"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="3"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="4"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="5"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="6"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="7"
    android:layout_row="7" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="0" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="1" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="2" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="3" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="4" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="5" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="6" />

</GridLayout>

screenshot

MAC addresses in JavaScript

The quick and simple answer is No.

Javascript is quite a high level language and does not have access to this sort of information.

cannot load such file -- bundler/setup (LoadError)

It could be that there was a previous Ruby env installed on your system prior to your installation of 2.0? This might have had an existing GEM_PATH that lead to the /1.8 directory which the installation of version 2.0 simply kept.

The problem you where likely having, then, was that Passenger/Apache was looking in the /2.0 directory when in fact the gems were in the /1.8 directory. Your explicitly telling apache to use the /1.8 directory thus makes sense to fix the problem.

SetEnv GEM_HOME /usr/lib/ruby/gems/1.8

You might also try using the Ruby Version Manager to handle multiple Ruby envs.

Some things I found in Google:

node.js vs. meteor.js what's the difference?

Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.

Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).

So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...

How to generate all permutations of a list?

For performance, a numpy solution inspired by Knuth, (p22) :

from numpy import empty, uint8
from math import factorial

def perms(n):
    f = 1
    p = empty((2*n-1, factorial(n)), uint8)
    for i in range(n):
        p[i, :f] = i
        p[i+1:2*i+1, :f] = p[:i, :f]  # constitution de blocs
        for j in range(i):
            p[:i+1, f*(j+1):f*(j+2)] = p[j+1:j+i+2, :f]  # copie de blocs
        f = f*(i+1)
    return p[:n, :]

Copying large blocs of memory saves time - it's 20x faster than list(itertools.permutations(range(n)) :

In [1]: %timeit -n10 list(permutations(range(10)))
10 loops, best of 3: 815 ms per loop

In [2]: %timeit -n100 perms(10) 
100 loops, best of 3: 40 ms per loop

Equals(=) vs. LIKE

Depends on the database system.

Generally with no special characters, yes, = and LIKE are the same.

Some database systems, however, may treat collation settings differently with the different operators.

For instance, in MySQL comparisons with = on strings is always case-insensitive by default, so LIKE without special characters is the same. On some other RDBMS's LIKE is case-insensitive while = is not.

Looking for a good Python Tree data structure

Would BTrees help? They're part of the Zope Object Database code. Downloading the whole ZODB package is a bit of overkill, but I hope the BTrees module would be at least somewhat separable.

Sharing a URL with a query string on Twitter

It's working for me:

<div class="links">
    <ul>
    <li class="social-share facebook">Share on Facebook</li>
    <li class="social-share twitter">Share on Twitter</li>
    <li class="social-share linkedin">Share on LinkedIn</li>
    </ul>
</div>

And in js file add this:


setShareLinks();

    function socialWindow(url) {
    var left = (screen.width -570) / 2;
    var top = (screen.height -570) / 2;
    var params = "menubar=no,toolbar=no,status=no,width=570,height=570,top=" + top + ",left=" + left;  window.open(url,"NewWindow",params);}

function setShareLinks() {
    var pageUrl = encodeURIComponent(document.URL);
    var tweet = encodeURIComponent($("meta[property='og:description']").attr("content"));

$(".social-share.facebook").on("click", function() { url="https://www.facebook.com/sharer.php?u=" + pageUrl;
socialWindow(url);
});

$(".social-share.twitter").on("click", function() {
url = "https://twitter.com/intent/tweet?url=" + pageUrl + "&text=" + tweet;
socialWindow(url);
});

$(".social-share.linkedin").on("click", function() {
    url = "https://www.linkedin.com/shareArticle?mini=true&url=" + pageUrl;
socialWindow(url);
})
}

Hope this will work well.

how do I initialize a float to its max/min value?

You can use std::numeric_limits which is defined in <limits> to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a - in front for negative infinity).

#include <limits>

//...

std::numeric_limits<float>::max();
std::numeric_limits<float>::min();
std::numeric_limits<float>::infinity();

As noted in the comments, min() returns the lowest possible positive value. In other words the positive value closest to 0 that can be represented. The lowest possible value is the negative of the maximum possible value.

There is of course the std::max_element and min_element functions (defined in <algorithm>) which may be a better choice for finding the largest or smallest value in an array.

Calling onclick on a radiobutton list using javascript

I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick event handler for the radio buttons:

<html>
 <head>
  <script type="text/javascript">
    window.onload = function() {

        var ex1 = document.getElementById('example1');
        var ex2 = document.getElementById('example2');
        var ex3 = document.getElementById('example3');

        ex1.onclick = handler;
        ex2.onclick = handler;
        ex3.onclick = handler;

    }

    function handler() {
        alert('clicked');
    }
  </script>
 </head>
 <body>
  <input type="radio" name="example1" id="example1" value="Example 1" />
  <label for="example1">Example 1</label>
  <input type="radio" name="example2" id="example2" value="Example 2" />
  <label for="example1">Example 2</label>
  <input type="radio" name="example3" id="example3" value="Example 3" />
  <label for="example1">Example 3</label>
 </body>
</html>

Exporting functions from a DLL with dllexport

I had exactly the same problem, my solution was to use module definition file (.def) instead of __declspec(dllexport) to define exports(http://msdn.microsoft.com/en-us/library/d91k01sh.aspx). I have no idea why this works, but it does

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

PHP - Indirect modification of overloaded property

I've had this same error, without your whole code it is difficult to pinpoint exactly how to fix it but it is caused by not having a __set function.

The way that I have gotten around it in the past is I have done things like this:

$user = createUser();
$role = $user->role;
$role->rolename = 'Test';

now if you do this:

echo $user->role->rolename;

you should see 'Test'

Is there a way to check if a file is in use?

I'm interested to see if this triggers any WTF reflexes. I have a process which creates and subsequently launches a PDF document from a console app. However, I was dealing with a frailty where if the user were to run the process multiple times, generating the same file without first closing the previously generated file, the app would throw an exception and die. This was a rather frequent occurrence because file names are based on sales quote numbers.

Rather than failing in such an ungraceful manner, I decided to rely on auto-incremented file versioning:

private static string WriteFileToDisk(byte[] data, string fileName, int version = 0)
{
    try
    {
        var versionExtension = version > 0 ? $"_{version:000}" : string.Empty;
        var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{fileName}{versionExtension}.pdf");
        using (var writer = new FileStream(filePath, FileMode.Create))
        {
            writer.Write(data, 0, data.Length);
        }
        return filePath;
    }
    catch (IOException)
    {
        return WriteFileToDisk(data, fileName, ++version);
    }
}

Probably some more care can be given to the catch block to ensure I'm catching the correct IOException(s). I'll probably also clear out the app storage on startup since these files are intended to be temporary anyways.

I realize this goes beyond the scope of the OP's question of simply checking if the file is in use but this was indeed the problem I was looking to solve when I arrived here so perhaps it will be useful to someone else.

Java get String CompareTo as a comparator object

You may write your own comparator

public class ExampleComparator  implements Comparator<String> {
  public int compare(String obj1, String obj2) {
    if (obj1 == obj2) {
        return 0;
    }
    if (obj1 == null) {
        return -1;
    }
    if (obj2 == null) {
        return 1;
    }
    return obj1.compareTo(obj2);
  }
}

How to use WHERE IN with Doctrine 2

This is how I used it:

->where('b.status IN (:statuses)')
->setParameters([
                'customerId' => $customerId,
                'storeId'    => $storeId,
                'statuses'   => [Status::OPEN, Status::AWAITING_APPROVAL, Status::APPROVED]
            ]);

How do I find the location of my Python site-packages directory?

I had to do something slightly different for a project I was working on: find the relative site-packages directory relative to the base install prefix. If the site-packages folder was in /usr/lib/python2.7/site-packages, I wanted the /lib/python2.7/site-packages part. I have, in fact, encountered systems where site-packages was in /usr/lib64, and the accepted answer did NOT work on those systems.

Similar to cheater's answer, my solution peeks deep into the guts of Distutils, to find the path that actually gets passed around inside setup.py. It was such a pain to figure out that I don't want anyone to ever have to figure this out again.

import sys
import os
from distutils.command.install import INSTALL_SCHEMES

if os.name == 'nt':
    scheme_key = 'nt'
else:
    scheme_key = 'unix_prefix'

print(INSTALL_SCHEMES[scheme_key]['purelib'].replace('$py_version_short', (str.split(sys.version))[0][0:3]).replace('$base', ''))

That should print something like /Lib/site-packages or /lib/python3.6/site-packages.

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

I usually face this issue on Android 5.0+ version devices. Since it has multi-user profiles accounts on the same devices. Every app will install as a separate instance for all users. Make sure to uninstall for all the users as below screenshot.

enter image description here

How to extract or unpack an .ab file (Android Backup file)

I have had to unpack a .ab-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.

Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab-file is password-protected.

Usage:
java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]

Example:

Let's say, you've got a file test.ab, which is not password-protected, you're using Windows and want the resulting .tar-Archive to be called test.tar. Then your command should be:

java.exe -jar abe.jar unpack test.ab test.tar ""

Detect if value is number in MySQL

Try Dividing /1

select if(value/1>0 or value=0,'its a number', 'its not a number') from table

Google Map API v3 — set bounds and center

My suggestion for google maps api v3 would be(don't think it can be done more effeciently):

gmap : {
    fitBounds: function(bounds, mapId)
    {
        //incoming: bounds - bounds object/array; mapid - map id if it was initialized in global variable before "var maps = [];"
        if (bounds==null) return false;
        maps[mapId].fitBounds(bounds);
    }
}

In the result u will fit all points in bounds in your map window.

Example works perfectly and u freely can check it here www.zemelapis.lt

Install pip in docker

This command worked fine for me:

RUN apt-get -y install python3-pip

Create thumbnail image

Here is a complete example of how to create a smaller image (thumbnail). This snippet resizes the Image, rotates it when needed (if a phone was held vertically) and pads the image if you want to create square thumbs. This snippet creates a JPEG, but it can easily be modified for other file types. Even if the image would be smaller than the max allowed size the image will still be compressed and it's resolution altered to create images of the same dpi and compression level.

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

//set the resolution, 72 is usually good enough for displaying images on monitors
float imageResolution = 72;

//set the compression level. higher compression = better quality = bigger images
long compressionLevel = 80L;


public Image resizeImage(Image image, int maxWidth, int maxHeight, bool padImage)
{
    int newWidth;
    int newHeight;

    //first we check if the image needs rotating (eg phone held vertical when taking a picture for example)
    foreach (var prop in image.PropertyItems)
    {
        if (prop.Id == 0x0112)
        {
            int orientationValue = image.GetPropertyItem(prop.Id).Value[0];
            RotateFlipType rotateFlipType = getRotateFlipType(orientationValue);
            image.RotateFlip(rotateFlipType);
            break;
        }
    }

    //apply the padding to make a square image
    if (padImage == true)
    {
        image = applyPaddingToImage(image, Color.Red);
    }

    //check if the with or height of the image exceeds the maximum specified, if so calculate the new dimensions
    if (image.Width > maxWidth || image.Height > maxHeight)
    {
        double ratioX = (double)maxWidth / image.Width;
        double ratioY = (double)maxHeight / image.Height;
        double ratio = Math.Min(ratioX, ratioY);

        newWidth = (int)(image.Width * ratio);
        newHeight = (int)(image.Height * ratio);
    }
    else
    {
        newWidth = image.Width;
        newHeight = image.Height;
    }

    //start the resize with a new image
    Bitmap newImage = new Bitmap(newWidth, newHeight);

    //set the new resolution
    newImage.SetResolution(imageResolution, imageResolution);

    //start the resizing
    using (var graphics = Graphics.FromImage(newImage))
    {
        //set some encoding specs
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        graphics.DrawImage(image, 0, 0, newWidth, newHeight);
    }

    //save the image to a memorystream to apply the compression level
    using (MemoryStream ms = new MemoryStream())
    {
        EncoderParameters encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, compressionLevel);

        newImage.Save(ms, getEncoderInfo("image/jpeg"), encoderParameters);

        //save the image as byte array here if you want the return type to be a Byte Array instead of Image
        //byte[] imageAsByteArray = ms.ToArray();
    }

    //return the image
    return newImage;
}


//=== image padding
public Image applyPaddingToImage(Image image, Color backColor)
{
    //get the maximum size of the image dimensions
    int maxSize = Math.Max(image.Height, image.Width);
    Size squareSize = new Size(maxSize, maxSize);

    //create a new square image
    Bitmap squareImage = new Bitmap(squareSize.Width, squareSize.Height);

    using (Graphics graphics = Graphics.FromImage(squareImage))
    {
        //fill the new square with a color
        graphics.FillRectangle(new SolidBrush(backColor), 0, 0, squareSize.Width, squareSize.Height);

        //put the original image on top of the new square
        graphics.DrawImage(image, (squareSize.Width / 2) - (image.Width / 2), (squareSize.Height / 2) - (image.Height / 2), image.Width, image.Height);
    }

    //return the image
    return squareImage;
}


//=== get encoder info
private ImageCodecInfo getEncoderInfo(string mimeType)
{
    ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();

    for (int j = 0; j < encoders.Length; ++j)
    {
        if (encoders[j].MimeType.ToLower() == mimeType.ToLower())
        {
            return encoders[j];
        }
    }

    return null;
}


//=== determine image rotation
private RotateFlipType getRotateFlipType(int rotateValue)
{
    RotateFlipType flipType = RotateFlipType.RotateNoneFlipNone;

    switch (rotateValue)
    {
        case 1:
            flipType = RotateFlipType.RotateNoneFlipNone;
            break;
        case 2:
            flipType = RotateFlipType.RotateNoneFlipX;
            break;
        case 3:
            flipType = RotateFlipType.Rotate180FlipNone;
            break;
        case 4:
            flipType = RotateFlipType.Rotate180FlipX;
            break;
        case 5:
            flipType = RotateFlipType.Rotate90FlipX;
            break;
        case 6:
            flipType = RotateFlipType.Rotate90FlipNone;
            break;
        case 7:
            flipType = RotateFlipType.Rotate270FlipX;
            break;
        case 8:
            flipType = RotateFlipType.Rotate270FlipNone;
            break;
        default:
            flipType = RotateFlipType.RotateNoneFlipNone;
            break;
    }

    return flipType;
}


//== convert image to base64
public string convertImageToBase64(Image image)
{
    using (MemoryStream ms = new MemoryStream())
    {
        //convert the image to byte array
        image.Save(ms, ImageFormat.Jpeg);
        byte[] bin = ms.ToArray();

        //convert byte array to base64 string
        return Convert.ToBase64String(bin);
    }
}

For the asp.net users a little example of how to upload a file, resize it and display the result on the page.

//== the button click method
protected void Button1_Click(object sender, EventArgs e)
{
    //check if there is an actual file being uploaded
    if (FileUpload1.HasFile == false)
    {
        return;
    }

    using (Bitmap bitmap = new Bitmap(FileUpload1.PostedFile.InputStream))
    {
        try
        {
            //start the resize
            Image image = resizeImage(bitmap, 256, 256, true);

            //to visualize the result, display as base64 image
            Label1.Text = "<img src=\"data:image/jpg;base64," + convertImageToBase64(image) + "\">";

            //save your image to file sytem, database etc here
        }
        catch (Exception ex)
        {
            Label1.Text = "Oops! There was an error when resizing the Image.<br>Error: " + ex.Message;
        }
    }
}

Div width 100% minus fixed amount of pixels

While Guffa's answer works in many situations, in some cases you may not want the left and/or right pieces of padding to be the parent of the center div. In these cases, you can use a block formatting context on the center and float the padding divs left and right. Here's the code

The HTML:

<div class="container">
    <div class="left"></div>
    <div class="right"></div>
    <div class="center"></div>
</div>

The CSS:

.container {
    width: 100px;
    height: 20px;
}

.left, .right {
    width: 20px;
    height: 100%;
    float: left;
    background: black;   
}

.right {
    float: right;
}

.center {
    overflow: auto;
    height: 100%;
    background: blue;
}

I feel that this element hierarchy is more natural when compared to nested nested divs, and better represents what's on the page. Because of this, borders, padding, and margin can be applied normally to all elements (ie: this 'naturality' goes beyond style and has ramifications).

Note that this only works on divs and other elements that share its 'fill 100% of the width by default' property. Inputs, tables, and possibly others will require you to wrap them in a container div and add a little more css to restore this quality. If you're unlucky enough to be in that situation, contact me and I'll dig up the css.

jsfiddle here: jsfiddle.net/RgdeQ

Enjoy!

Construct a manual legend for a complicated plot

In case you were struggling to change linetypes, the following answer should be helpful. (This is an addition to the solution by Andy W.)

We will try to extend the learned pattern:

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) +           #red
  geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) +           #blue
  scale_colour_manual(name="Error Bars",values=cols, 
                  guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_linetype_manual(values=line_types)+
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

However, what we get is the following result: manual without name

The problem is that the linetype is not merged in the main legend. Note that we did not give any name to the method scale_linetype_manual. The trick which works here is to give it the same name as what you used for naming scale_colour_manual. More specifically, if we change the corresponding line to the following we get the desired result:

scale_linetype_manual(name="Error Bars",values=line_types)

manual with the same name

Now, it is easy to change the size of the line with the same idea.

Note that the geom_bar has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.

CSS: auto height on containing div, 100% height on background div inside containing div

Okay so someone is probably going to slap me for this answer, but I use jQuery to solve all my irritating problems and it turns out that I just used something today to fix a similar issue. Assuming you use jquery:

$("#content").sibling("#backgroundContainer").css("height",$("#content").outerHeight());

this is untested but I think you can see the concept here. Basically after it is loaded, you can get the height (outerHeight includes padding + borders, innerHeight for the content only). Hope that helps.

Here is how you bind it to the window resize event:

$(window).resize(function() {
  $("#content").sibling("#backgroundContainer").css("height",$("#content").outerHeight());
});

Double quotes within php script echo

You need to escape the quotes in the string by adding a backslash \ before ".

Like:

"<font color=\"red\">"

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I had a similar problem but found the issue was that I had neglected to provide a default constructor for the DTO that was annotated with @RequestBody.

Setting the target version of Java in ant javac

To find the version of the java in the classfiles I used:

javap -verbose <classname>

which announces the version at the start as

minor version: 0
major version: 49

which corresponds to Java 1.5

Limit Decimal Places in Android EditText

This is to build on pinhassi's answer - the issue that I came across was that you couldn't add values before the decimal once the decimal limit has been reached. To fix the issue, we need to construct the final string before doing the pattern match.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.InputFilter;
import android.text.Spanned;

public class DecimalLimiter implements InputFilter
{
    Pattern mPattern;

    public DecimalLimiter(int digitsBeforeZero,int digitsAfterZero) 
    {
        mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero) + "}+((\\.[0-9]{0," + (digitsAfterZero) + "})?)||(\\.)?");
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) 
    {
        StringBuilder sb = new StringBuilder(dest);
        sb.insert(dstart, source, start, end);

        Matcher matcher = mPattern.matcher(sb.toString());
        if(!matcher.matches())
            return "";
        return null;
    }
}

How to use a findBy method with comparative criteria

The Symfony documentation now explicitly shows how to do this:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
    'SELECT p
    FROM AppBundle:Product p
    WHERE p.price > :price
    ORDER BY p.price ASC'
)->setParameter('price', '19.99');    
$products = $query->getResult();

From http://symfony.com/doc/2.8/book/doctrine.html#querying-for-objects-with-dql

How do I connect to a MySQL Database in Python?

PyMySQL 0.10.1 - Released: Sep 10, 2020, has support for python3 as well.

python3 -m pip install PyMySQL

Simple code:

import pymysql

# Connect to the database
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='fax')

# Create a Cursor object
cur = conn.cursor()

# Execute the query
cur.execute("SELECT * FROM fax.student")

# Read and print records
for row in cur.fetchall():
    print(row)

output:

(1, 'Petar', 'Petrovic', 1813, 'Njegusi')
(2, 'Donald', 'Tramp', 1946, 'New York')
(3, 'Bill', 'Gates', 1955, 'Seattle')

SQL Error: ORA-12899: value too large for column

This answer still comes up high in the list for ORA-12899 and lot of non helpful comments above, even if they are old. The most helpful comment was #4 for any professional trying to find out why they are getting this when loading data.

Some characters are more than 1 byte in length, especially true on SQL Server. And what might fit in a varchar(20) in SQLServer won't fit into a similar varchar2(20) in Oracle.

I ran across this error yesterday with SSIS loading an Oracle database with the Attunity drivers and thought I would save folks some time.

Using variables in Nginx location rules

This is many years late but since I found the solution I'll post it here. By using maps it is possible to do what was asked:

map $http_host $variable_name {
    hostnames;

    default       /ap/;
    example.com   /api/;
    *.example.org /whatever/;
}

server {
    location $variable_name/test {
        proxy_pass $auth_proxy;
    }
}

If you need to share the same endpoint across multiple servers, you can also reduce the cost by simply defaulting the value:

map "" $variable_name {
    default       /test/;
}

Map can be used to initialise a variable based on the content of a string and can be used inside http scope allowing variables to be global and sharable across servers.

IntelliJ: Never use wildcard imports

This applies for "Intellij Idea- 2020.1.2" on window

Navigate to "IntelliJ IDEA->File->Settings->Editor->Code Style->java".

enter image description here

How do I unlock a SQLite database?

If you want to remove a "database is locked" error then follow these steps:

  1. Copy your database file to some other location.
  2. Replace the database with the copied database. This will dereference all processes which were accessing your database file.

How do you add a timed delay to a C++ program?

I found that "_sleep(milliseconds);" (without the quotes) works well for Win32 if you include the chrono library

E.g:

#include <chrono>

using namespace std;

main
{
    cout << "text" << endl;
    _sleep(10000); // pauses for 10 seconds
}

Make sure you include the underscore before sleep.

libxml install error using pip

pymemcompat.h:10: fatal error: Python.h: ?????????

Boy you should post your error log with LANG=C or people can't get the real cause from your log. The log above says: No such file or directory.

That means you should install the develop package of Python. That's usually "python-dev" on Debian flavored distro, and "python-devel" on RHEL flavored distro.

How to convert BigDecimal to Double in Java?

You need to use the doubleValue() method to get the double value from a BigDecimal object.

BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want

Default visibility for C# classes and members (fields, methods, etc.)?

By default is private. Unless they're nested, classes are internal.

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

Getting Django admin url for an object

Essentially the same as Mike Ramirez's answer, but simpler and closer in stylistics to django standard get_absolute_url method:

from django.urls import reverse

def get_admin_url(self):
    return reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name),
                   args=[self.id])

Return a "NULL" object if search result not found

As you have figured out that you cannot do it the way you have done in Java (or C#). Here is another suggestion, you could pass in the reference of the object as an argument and return bool value. If the result is found in your collection, you could assign it to the reference being passed and return ‘true’, otherwise return ‘false’. Please consider this code.

typedef std::map<string, Operator> OPERATORS_MAP;

bool OperatorList::tryGetOperator(string token, Operator& op)
{
    bool val = false;

    OPERATORS_MAP::iterator it = m_operators.find(token);
    if (it != m_operators.end())
    {
        op = it->second;
        val = true;
    }
    return val;
}

The function above has to find the Operator against the key 'token', if it finds the one it returns true and assign the value to parameter Operator& op.

The caller code for this routine looks like this

Operator opr;
if (OperatorList::tryGetOperator(strOperator, opr))
{
    //Do something here if true is returned.
}

iOS 7 status bar back to iOS 6 default style in iPhone app?

As using presentViewController:animated:completion: messed-up the window.rootViewController.view, I had to find a different approach to this issue. I finally got it to work with modals and rotations by subclassing the UIView of my rootViewController.

.h

@interface RootView : UIView

@end

.m

@implementation RootView

-(void)setFrame:(CGRect)frame
{
    if (self.superview && self.superview != self.window)
    {
        frame = self.superview.bounds;
        frame.origin.y += 20.f;
        frame.size.height -= 20.f;
    }
    else
    {
        frame = [UIScreen mainScreen].applicationFrame;
    }

    [super setFrame:frame];
}

- (void)layoutSubviews
{
    self.frame = self.frame;

    [super layoutSubviews];
}

@end

You now have a strong workaround for iOS7 animations.

get all the elements of a particular form

let formFields     = form.querySelectorAll(`input:not([type='hidden']), select`)

ES6 version that has the advantage of ignoring the hidden fields if that is what you want

Installing MySQL-python

In python3 with virtualenv on a Ubuntu Bionic machine the following commands worked for me:

sudo apt install build-essential python-dev libmysqlclient-dev
sudo apt-get install libssl-dev
pip install mysqlclient

How to set header and options in axios?

try this code

in example code use axios get rest API.

in mounted

  mounted(){
    var config = {
    headers: { 
      'x-rapidapi-host': 'covid-19-coronavirus-statistics.p.rapidapi.com',
      'x-rapidapi-key': '5156f83861mshd5c5731412d4c5fp18132ejsn8ae65e661a54' 
      }
   };
   axios.get('https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats? 
    country=Thailand',  config)
    .then((response) => {
    console.log(response.data);
  });
}

Hope is help.

Current Subversion revision command

I think I have to do svn info and then retrieve the number with a string manipulation from "Revision: xxxxxx" It would be just nice, if there were a command that returns just the number :)

What is time_t ultimately a typedef to?

Under Visual Studio 2008, it defaults to an __int64 unless you define _USE_32BIT_TIME_T. You're better off just pretending that you don't know what it's defined as, since it can (and will) change from platform to platform.

Implement Stack using Two Queues

Can we just use one queue to implement a stack? I can use two queues, but considering single queue would be more efficient. Here is the code:

    public void Push(T val)
    {
        queLower.Enqueue(val);
    }

    public  T Pop()
    {

        if (queLower.Count == 0 )
        {
            Console.Write("Stack is empty!");
            return default(T);

         }
        if (queLower.Count > 0)
        {
            for (int i = 0; i < queLower.Count - 1;i++ )
            {
                queLower.Enqueue(queLower.Dequeue ());
           }
                    }

        return queLower.Dequeue();

    }

Passing a string with spaces as a function argument in bash

you should put quotes and also, your function declaration is wrong.

myFunction()
{
    echo "$1"
    echo "$2"
    echo "$3"
}

And like the others, it works for me as well. Tell us what version of shell you are using.

How to read an entire file to a string using C#?

if you want to pick file from Bin folder of the application then you can try following and don't forget to do exception handling.

string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"FilesFolder\Sample.txt"));

CreateProcess error=206, The filename or extension is too long when running main() method

This is because of your long project directory name, which gives you a very long CLASSPATH altogether. Either you need to reduce jars added at CLASSPATH (make sure removing unnecessary jars only) Or the best way is to reduce the project directory and import the project again. This will reduce the CLASSPATH. It worked for me.

Determine if a String is an Integer in Java

You want to use the Integer.parseInt(String) method.

try{
  int num = Integer.parseInt(str);
  // is an integer!
} catch (NumberFormatException e) {
  // not an integer!
}

Sql script to find invalid email addresses

I find this approach more intuitive:

CREATE FUNCTION [dbo].[ContainsVailidEmail] (@Input varchar(250))
RETURNS bit
AS
BEGIN
  RETURN CASE
    WHEN @Input LIKE '%_@__%.__%' THEN 1
    ELSE 0
  END
END

I call it using the following:

SELECT [dbo].[ContainsVailidEmail] (Email) FROM [dbo].[User]

OR

If you are only going to use this once then why not it as a Computed Column, with the following specification:

(case when [Email] like '%_@__%.__%' then (1) else (0) end)

Then you can just use it without needing to call a function.

What are the rules for casting pointers in C?

I suspect you need a more general answer:

There are no rules on casting pointers in C! The language lets you cast any pointer to any other pointer without comment.

But the thing is: There is no data conversion or whatever done! Its solely your own responsibilty that the system does not misinterpret the data after the cast - which would generally be the case, leading to runtime error.

So when casting its totally up to you to take care that if data is used from a casted pointer the data is compatible!

C is optimized for performance, so it lacks runtime reflexivity of pointers/references. But that has a price - you as a programmer have to take better care of what you are doing. You have to know on your self if what you want to do is "legal"

Select all text inside EditText when it gets focus

Just add this to your editText in the .xml file

android:selectAllOnFocus="true"

Better way to Format Currency Input editText?

I used this to allow the user to enter the currency and to convert it from string into int to store in db and to change back from int into string again

https://github.com/nleigh/Restaurant/blob/master/Restaurant/src/uk/co/nathanleigh/restaurant/CurrencyFormat.java

Java optional parameters

You can use something like this:

public void addError(String path, String key, Object... params) { 
}

The params variable is optional. It is treated as a nullable array of Objects.

Strangely, I couldn't find anything about this in the documentation, but it works!

This is "new" in Java 1.5 and beyond (not supported in Java 1.4 or earlier).

I see user bhoot mentioned this too below.

Always show vertical scrollbar in <select>

It will work in IE7. But here you need to fixed the size less than the number of option and not use overflow-y:scroll. In your example you have 2 option but you set size=10, which will not work.

Suppose your select has 10 option, then fixed size=9.

Here, in your code reference you used height:100px with size:2. I remove the height css, because its not necessary and change the size:5 and it works fine.

Here is your modified code from jsfiddle:

<select size="5" style="width:100px;">
 <option>1</option>
 <option>2</option>
 <option>3</option>
 <option>4</option>
 <option>5</option>
 <option>6</option>
</select>

this will generate a larger select box than size:2 create.In case of small size the select box will not display the scrollbar,you have to check with appropriate size quantity.Without scrollbar it will work if click on the upper and lower icons of scrollbar.I show both example in your fiddle with size:2 and size greater than 2(e.g: 3,5).

Here is your desired result. I think this will help you:

CSS

  .wrapper{
    border: 1px dashed red;
    height: 150px;
    overflow-x: hidden;
    overflow-y: scroll;
    width: 150px;
 }
 .wrapper .selection{
   width:150px;
   border:1px solid #ccc
 }

HTML

<div class="wrapper">
<select size="15" class="selection">
    <option>Item 1</option>
    <option>Item 2</option>
    <option>Item 3</option>
</select>
</div>

How can I require at least one checkbox be checked before a form can be submitted?

The issue with the accepted solution above is that is does not allow for the else condition on form submit (if a box has been selected), thereby preventing form submission - at least when I tried it.

I discovered another solution that effects the desired result more completely IMHO, here:

Making sure at least one checkbox is checked

Code as follows:

function valthis() {
var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
var isChecked = false;
    for (var i = 0; i < checkBoxes.length; i++) {
        if ( checkBoxes[i].checked ) {
            isChecked = true;
        };
    };
    if ( isChecked ) {
        alert( 'At least one checkbox checked!' );
        } else {
            alert( 'Please, check at least one checkbox!' );
        }   
}

Fiddle

That code & answer by Vell

Serving favicon.ico in ASP.NET MVC

I think that favicon.ico should be in root folder. It just belongs there.

If you want to servere diferent icons - put it into controler. You can do that. If not - just leave it in the root folder.

Parsing JSON string in Java

To convert your JSON string to hashmap you can make use of this :

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;

Use this class :) (handles even lists , nested lists and json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

Cannot find the '@angular/common/http' module

Important: HttpClientModule is for Angular 4.3.0 and above. Check @Maximus' comments and @Pengyy's answer for more info.


Original answer:

You need to inject HttpClient in your component/service not the module. If you import HttpClientModule in your @NgModule

// app.module.ts:
 
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
 
// Import HttpClientModule from @angular/common/http
import {HttpClientModule} from '@angular/common/http';
 
@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module
    // after BrowserModule.
    HttpClientModule,
  ],
})
export class MyAppModule {}

So change

constructor(private httpClient: HttpModule) {}

to

constructor(private httpClient: HttpClient) {}

as it's been written in the documentation


However, since you imported the HttpModule

you need to inject constructor(private httpClient: Http) as @Maximus stated in the comments and @Pengyy in this answer.

And for more info on differences between HttpModule and HttpClientModule, check this answer

How to represent a fix number of repeats in regular expression?

In Java create the pattern with Pattern p = Pattern.compile("^\\w{14}$"); for further information see the javadoc

Redirect Windows cmd stdout and stderr to a single file

You want:

dir > a.txt 2>&1

The syntax 2>&1 will redirect 2 (stderr) to 1 (stdout). You can also hide messages by redirecting to NUL, more explanation and examples on MSDN.

Checking if a collection is null or empty in Groovy

!members.find()

I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

def lst1 = []
assert !lst1.find()

def lst2 = [null]
assert !lst2.find()

def lst3 = [null,2,null]
assert lst3.find()

def lst4 = [null,null,null]
assert !lst4.find()

def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42

def lst6 = null; 
assert !lst6.find()

Is the sizeof(some pointer) always equal to four?

Size of pointer and int is 2 bytes in Turbo C compiler on windows 32 bit machine.

So size of pointer is compiler specific. But generally most of the compilers are implemented to support 4 byte pointer variable in 32 bit and 8 byte pointer variable in 64 bit machine).

So size of pointer is not same in all machines.

Getting the index of the returned max or min item using max()/min() on a list

This is simply possible using the built-in enumerate() and max() function and the optional key argument of the max() function and a simple lambda expression:

theList = [1, 5, 10]
maxIndex, maxValue = max(enumerate(theList), key=lambda v: v[1])
# => (2, 10)

In the docs for max() it says that the key argument expects a function like in the list.sort() function. Also see the Sorting How To.

It works the same for min(). Btw it returns the first max/min value.

Converting dd/mm/yyyy formatted string to Datetime

You need to use DateTime.ParseExact with format "dd/MM/yyyy"

DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Its safer if you use d/M/yyyy for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.


Your date format day/Month/Year might be an acceptable date format for some cultures. For example for Canadian Culture en-CA DateTime.Parse would work like:

DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));

Or

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture

Both the above lines would work because the the string's format is acceptable for en-CA culture. Since you are not supplying any culture to your DateTime.Parse call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.


Another method for parsing is using DateTime.TryParseExact

DateTime dt;
if (DateTime.TryParseExact("24/01/2013", 
                            "d/M/yyyy", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None,
    out dt))
{
    //valid date
}
else
{
    //invalid date
}

The TryParse group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool value indicating success or failure in parsing.

Notice that I have used single d and M for day and month respectively. Single d and M works for both single/double digits day and month. So for the format d/M/yyyy valid values could be:

  • "24/01/2013"
  • "24/1/2013"
  • "4/12/2013" //4 December 2013
  • "04/12/2013"

For further reading you should see: Custom Date and Time Format Strings

Display Image On Text Link Hover CSS Only

CSS isn't going to be able to call other elements like that, you'll need to use JavaScript to reach beyond a child or sibling selector.

You could try something like this:

<a>Some Link
<div><img src="/you/image" /></div>
</a>

then...

a>div { display: none; }
a:hover>div { display: block; }

How to write MySQL query where A contains ( "a" or "b" )

Two options:

  1. Use the LIKE keyword, along with percent signs in the string

    select * from table where field like '%a%' or field like '%b%'.
    

    (note: If your search string contains percent signs, you'll need to escape them)

  2. If you're looking for more a complex combination of strings than you've specified in your example, you could regular expressions (regex):

    See the MySQL manual for more on how to use them: http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Of these, using LIKE is the most usual solution -- it's standard SQL, and in common use. Regex is less commonly used but much more powerful.

Note that whichever option you go with, you need to be aware of possible performance implications. Searching for sub-strings like this will mean that the query will have to scan the entire table. If you have a large table, this could make for a very slow query, and no amount of indexing is going to help.

If this is an issue for you, and you'r going to need to search for the same things over and over, you may prefer to do something like adding a flag field to the table which specifies that the string field contains the relevant sub-strings. If you keep this flag field up-to-date when you insert of update a record, you could simply query the flag when you want to search. This can be indexed, and would make your query much much quicker. Whether it's worth the effort to do that is up to you, it'll depend on how bad the performance is using LIKE.

How to parse JSON data with jQuery / JavaScript?

Here's how you would do this in JavaScript, this is a really efficient way to do it!

let data = "{ "name": "mark"}"
let object = JSON.parse(data);
console.log(object.name);

this would print mark

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

How can I produce an effect similar to the iOS 7 blur view?

Here is a really easy way of doing it:https://github.com/JagCesar/iOS-blur

Just copy the layer of UIToolbar and you're done, AMBlurView does it for you. Okay, it's not as blurry as control center, but is's blurry enough.

Remember that iOS7 is under NDA.

How to create a global variable?

if you want to use it in all of your classes you can use:

public var yourVariable = "something"

if you want to use just in one class you can use :

var yourVariable = "something"

Maven and adding JARs to system scope

mvn install:install-file -DgroupId=com.paic.maven -DartifactId=tplconfig-maven-plugin -Dversion=1.0 -Dpackaging=jar -Dfile=tplconfig-maven-plugin-1.0.jar -DgeneratePom=true

Install the jar to local repository.

File.Move Does Not Work - File Already Exists

According to the docs for File.Move there is no "overwrite if exists" parameter. You tried to specify the destination folder, but you have to give the full file specification.

Reading the docs again ("providing the option to specify a new file name"), I think, adding a backslash to the destination folder spec may work.

Display Bootstrap Modal using javascript onClick

You don't need an onclick. Assuming you're using Bootstrap 3 Bootstrap 3 Documentation

<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>

<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;  </button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

If you're using Bootstrap 2, you'd follow the markup here: http://getbootstrap.com/2.3.2/javascript.html#modals

T-SQL: Export to new Excel file

This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

Entity Framework and Connection Pooling

According to Daniel Simmons:

Create a new ObjectContext instance in a Using statement for each service method so that it is disposed of before the method returns. This step is critical for scalability of your service. It makes sure that database connections are not kept open across service calls and that temporary state used by a particular operation is garbage collected when that operation is over. The Entity Framework automatically caches metadata and other information it needs in the app domain, and ADO.NET pools database connections, so re-creating the context each time is a quick operation.

This is from his comprehensive article here:

http://msdn.microsoft.com/en-us/magazine/ee335715.aspx

I believe this advice extends to HTTP requests, so would be valid for ASP.NET. A stateful, fat-client application such as a WPF application might be the only case for a "shared" context.

jQuery selector for inputs with square brackets in the name attribute

Just separate it with different quotes:

<input name="myName[1][data]" value="myValue">

JQuery:

var value = $('input[name="myName[1][data]"]').val();

How to change the style of alert box?

Not possible. If you want to customize the dialog's visual appearance, you need to use a JS-based solution like jQuery.UI dialog.

Print a list in reverse order with range()?

You could use range(10)[::-1] which is the same thing as range(9, -1, -1) and arguably more readable (if you're familiar with the common sequence[::-1] Python idiom).

How many values can be represented with n bits?

Okay, since it already "leaked": You're missing zero, so the correct answer is 512 (511 is the greatest one, but it's 0 to 511, not 1 to 511).

By the way, an good followup exercise would be to generalize this:

How many different values can be represented in n binary digits (bits)?

iTerm2 keyboard shortcut - split pane navigation

From the documentation:

Cmd] and Cmd[ navigates among split panes in order of use.

I cannot start SQL Server browser

Clicking Properties, going to the Service tab and setting Start Mode to Automatic fixed the problem for me. Now the Start item in the context menu is active again.

How to consume a SOAP web service in Java

As some sugested you can use apache or jax-ws. You can also use tools that generate code from WSDL such as ws-import but in my opinion the best way to consume web service is to create a dynamic client and invoke only operations you want not everything from wsdl. You can do this by creating a dynamic client: Sample code:

String endpointUrl = ...;

QName serviceName = new QName("http://com/ibm/was/wssample/echo/",
 "EchoService");
QName portName = new QName("http://com/ibm/was/wssample/echo/",
 "EchoServicePort");

/** Create a service and add at least one port to it. **/ 
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointUrl);

/** Create a Dispatch instance from a service.**/ 
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, 
SOAPMessage.class, Service.Mode.MESSAGE);

/** Create SOAPMessage request. **/
// compose a request message
MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);

// Create a message.  This example works with the SOAPPART.
SOAPMessage request = mf.createMessage();
SOAPPart part = request.getSOAPPart();

// Obtain the SOAPEnvelope and header and body elements.
SOAPEnvelope env = part.getEnvelope();
SOAPHeader header = env.getHeader();
SOAPBody body = env.getBody();

// Construct the message payload.
SOAPElement operation = body.addChildElement("invoke", "ns1",
 "http://com/ibm/was/wssample/echo/");
SOAPElement value = operation.addChildElement("arg0");
value.addTextNode("ping");
request.saveChanges();

/** Invoke the service endpoint. **/
SOAPMessage response = dispatch.invoke(request);

/** Process the response. **/

how to call an ASP.NET c# method using javascript

The Jayrock RPC library is a great tool for doing this in a nice familliar way for C# developers. It allows you to create a .NET class with the methods you require, and add this class as a script (in a roundabout way) to your page. You can then create a js object of your type and call methods as you would any other object.

It essentially hides away ajax implementation and presents RPC in a familliar format. Mind you the best option really is to use ASP.NET MVC and use jQuery ajax calls to action methods - much more concise and less messing about!

Check if element found in array c++

You would just do the same thing, looping through the array to search for the term you want. Of course if it's a sorted array this would be much faster, so something similar to prehaps:

for(int i = 0; i < arraySize; i++){
     if(array[i] == itemToFind){
         break;
     }
}

Get value from a string after a special character

Assuming you have your hidden input in a jQuery object $myHidden, you then use JavaScript (not jQuery) to get the part after ?:

var myVal = $myHidden.val ();
var tmp = myVal.substr ( myVal.indexOf ( '?' ) + 1 ); // tmp now contains whatever is after ?

Process.start: how to get the output?

You can log process output using below code:

ProcessStartInfo pinfo = new ProcessStartInfo(item);
pinfo.CreateNoWindow = false;
pinfo.UseShellExecute = true;
pinfo.RedirectStandardOutput = true;
pinfo.RedirectStandardInput = true;
pinfo.RedirectStandardError = true;
pinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
var p = Process.Start(pinfo);
p.WaitForExit();
Process process = Process.Start(new ProcessStartInfo((item + '>' + item + ".txt"))
{
    UseShellExecute = false,
    RedirectStandardOutput = true
});
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
if (process.ExitCode != 0) { 
}

How do I launch a program from command line without opening a new cmd window?

If you're doing it via CMD as you say, then you can just enter the command like so:

path\to\your.exe 

which will open it within the same window. For example in C++:

system("path\\to\\your.exe"); // Double backslash for escaping

will open your.exe in the current CMD window. Likewise to start with a new window, just go for:

system("start path\\to\\your.exe");

If you go for the first option, you would have to clear your screen unless you wanted to have the command to open your.exe on the screen still.

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

I have something different stuff for you which is easy and effective.

    <style> 
    .case-after:after { // set your properties here like eg: 
        color:#3fd309 !important; 
     } 
     .case-before:before { // set your properties here like eg: 
        color:#151715 !important; 
     }
 </style>
  // case for after
    $('#button-id').on('click', function() {
        $(".target-div").toggleClass('case-after');
    });

     // case for before
    $('#button-id').on('click', function() {
        $(".target-div").toggleClass('case-before');
    });

Correct way to use get_or_create?

get_or_create() returns a tuple:

customer.source, created  = Source.objects.get_or_create(name="Website")
  • created ? has a boolean value, is created or not.

  • customer.source ? has an object of get_or_create() method.

How to get the current loop index when using Iterator?

Here's a way to do it using your own variable and keeping it concise:

List<String> list = Arrays.asList("zero", "one", "two");

int i = 0;
for (Iterator<String> it = list.iterator(); it.hasNext(); i++) {
    String s = it.next();
    System.out.println(i + ": " + s);
}

Output (you guessed it):

0: zero
1: one
2: two

The advantage is that you don't increment your index within the loop (although you need to be careful to only call Iterator#next once per loop - just do it at the top).

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

The query you are after will be

SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%'

How do you determine what SQL Tables have an identity column programmatically

This query seems to do the trick:

SELECT 
    sys.objects.name AS table_name, 
    sys.columns.name AS column_name
FROM sys.columns JOIN sys.objects 
    ON sys.columns.object_id=sys.objects.object_id
WHERE 
    sys.columns.is_identity=1
    AND
    sys.objects.type in (N'U')

How to duplicate a whole line in Vim?

yy

will yank the current line without deleting it

dd

will delete the current line

p

will put a line grabbed by either of the previous methods

android get real path by Uri.getPath()

This helped me to get uri from Gallery and convert to a file for Multipart upload

File file = FileUtils.getFile(this, fileUri);

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

Create a directory if it does not exist and then create the files in that directory as well

code:

// Create Directory if not exist then Copy a file.


public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {

    Path FROM = Paths.get(origin);
    Path TO = Paths.get(destination);
    File directory = new File(String.valueOf(destDir));

    if (!directory.exists()) {
        directory.mkdir();
    }
        //overwrite the destination file if it exists, and copy
        // the file attributes, including the rwx permissions
     CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES

        };
        Files.copy(FROM, TO, options);


}

How to scan multiple paths using the @ComponentScan annotation?

Another way of doing this is using the basePackages field; which is a field inside ComponentScan annotation.

@ComponentScan(basePackages={"com.firstpackage","com.secondpackage"})

If you look into the ComponentScan annotation .class from the jar file you will see a basePackages field that takes in an array of Strings

public @interface ComponentScan {
String[] basePackages() default {};
}

Or you can mention the classes explicitly. Which takes in array of classes

Class<?>[]  basePackageClasses

How to print Unicode character in Python?

Print a unicode character in Python:

Print a unicode character directly from python interpreter:

el@apollo:~$ python
Python 2.7.3
>>> print u'\u2713'
?

Unicode character u'\u2713' is a checkmark. The interpreter prints the checkmark on the screen.

Print a unicode character from a python script:

Put this in test.py:

#!/usr/bin/python
print("here is your checkmark: " + u'\u2713');

Run it like this:

el@apollo:~$ python test.py
here is your checkmark: ?

If it doesn't show a checkmark for you, then the problem could be elsewhere, like the terminal settings or something you are doing with stream redirection.

Store unicode characters in a file:

Save this to file: foo.py:

#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys 
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')

Run it and pipe output to file:

python foo.py > tmp.txt

Open tmp.txt and look inside, you see this:

el@apollo:~$ cat tmp.txt 
e with obfuscation: é

Thus you have saved unicode e with a obfuscation mark on it to a file.

How to justify navbar-nav in Bootstrap 3

It turns out that there is a float: left property by default on all navbar-nav>li elements, which is why they were all scrunching up to the left. Once I added the code below, it made the navbar both centered and not scrunched up.

.navbar-nav>li {
        float: none;
}

Hope this helps someone else who's looking to center a navbar.

Passing data to a jQuery UI Dialog

Looking at your code what you need to do is add the functionality to close the window and update the page. In your "Yes" function you should write:

        buttons: {
            "Ja": function() {
                $.post(a.href);
                $(a). // code to remove the table row
                $("#dialog").dialog("close");
            },
            "Nej": function() { $(this).dialog("close"); }
        },

The code to remove the table row isn't fun to write so I'll let you deal with the nitty gritty details, but basically, you need to tell the dialog what to do after you post it. It may be a smart dialog but it needs some kind of direction.

How should I escape commas and speech marks in CSV files so they work in Excel?

Below are the rules if you believe it's random. A utility function can be created on the basis of these rules.

  1. If the value contains a comma, newline or double quote, then the String value should be returned enclosed in double quotes.

  2. Any double quote characters in the value should be escaped with another double quote.

  3. If the value does not contain a comma, newline or double quote, then the String value should be returned unchanged.

jQuery callback on image load (even when the image is cached)

If you want a pure CSS solution, this trick works very well - use the transform object. This also works with images when they're cached or not:

CSS:

.main_container{
    position: relative;
    width: 500px;
    height: 300px;
    background-color: #cccccc;
}

.center_horizontally{
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: green;
  left: 50%;
  top: 0;
  transform: translate(-50%,0);
}

.center_vertically{
  position: absolute;
  top: 50%;
  left: 0;
  width: 100px;
  height: 100px;
  background-color: blue;
  transform: translate(0,-50%);
}

.center{
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 100px;
  background-color: red;
  transform: translate(-50%,-50%);
}

HTML:

<div class="main_container">
  <div class="center_horizontally"></div>
  <div class="center_vertically"></div>
  <div class="center"></div>
  </div>
</div

Codepen example

Codepen LESS example

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them

Laravel whereIn OR whereIn

Yes, orWhereIn is a method that you can use.

I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode to create a string and then explode it (this is a guess at your array structure):

$values = implode(',', array_map(function($value)
{
    return trim($value, ',');
}, $filters));

$query->whereIn('products.value', explode(',' $values));

What is the purpose of the "role" attribute in HTML?

Role attribute mainly improve accessibility for people using screen readers. For several cases we use it such as accessibility, device adaptation,server-side processing, and complex data description. Know more click: https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute.

What is the correct way to restore a deleted file from SVN?

You should be able to just check out the one file you want to restore. Try something like svn co svn://your_repos/path/to/file/you/want/to/restore@rev where rev is the last revision at which the file existed.

I had to do exactly this a little while ago and if I remember correctly, using the -r option to svn didn't work; I had to use the :rev syntax. (Although I might have remembered it backwards...)

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

my case seems to be invalid JRE version.

1.7+ required while I launched with 1.6

plus: I filtered some plugin jars which might be required. so changed to select all

How do I check if file exists in jQuery or pure JavaScript?

This is an adaptation to the accepted answer, but I couldn't get what I needed from the answer, and had to test this worked as it was a hunch, so i'm putting my solution up here.

We needed to verify a local file existed, and only allow the file (a PDF) to open if it existed. If you omit the URL of the website, the browser will automatically determine the host name - making it work in localhost and on the server:

$.ajax({

    url: 'YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf',
    type: 'HEAD',
    error: function () {
        //file not exists
        alert('PDF does not exist');

    },
    success: function () {
        //file exists
        window.open('YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf', "_blank", "fullscreen=yes");

    }
});