Programs & Examples On #Strlen

A standard C function that returns the length of a string.

Add ... if string is too long PHP

This will return a given string with ellipsis based on WORD count instead of characters:

<?php
/**
*    Return an elipsis given a string and a number of words
*/
function elipsis ($text, $words = 30) {
    // Check if string has more than X words
    if (str_word_count($text) > $words) {

        // Extract first X words from string
        preg_match("/(?:[^\s,\.;\?\!]+(?:[\s,\.;\?\!]+|$)){0,$words}/", $text, $matches);
        $text = trim($matches[0]);

        // Let's check if it ends in a comma or a dot.
        if (substr($text, -1) == ',') {
            // If it's a comma, let's remove it and add a ellipsis
            $text = rtrim($text, ',');
            $text .= '...';
        } else if (substr($text, -1) == '.') {
            // If it's a dot, let's remove it and add a ellipsis (optional)
            $text = rtrim($text, '.');
            $text .= '...';
        } else {
            // Doesn't end in dot or comma, just adding ellipsis here
            $text .= '...';
        }
    }
    // Returns "ellipsed" text, or just the string, if it's less than X words wide.
    return $text;
}

$description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quibusdam ut placeat consequuntur pariatur iure eum ducimus quasi perferendis, laborum obcaecati iusto ullam expedita excepturi debitis nisi deserunt fugiat velit assumenda. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, blanditiis nostrum. Nostrum cumque non rerum ducimus voluptas officia tempore modi, nulla nisi illum, voluptates dolor sapiente ut iusto earum. Esse? Lorem ipsum dolor sit amet, consectetur adipisicing elit. A eligendi perspiciatis natus autem. Necessitatibus eligendi doloribus corporis quia, quas laboriosam. Beatae repellat dolor alias. Perferendis, distinctio, laudantium? Dolorum, veniam, amet!';

echo elipsis($description, 30);
?>

How to add message box with 'OK' button?

I think there may be problem that you haven't added click listener for ok positive button.

dlgAlert.setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          //dismiss the dialog  
        }
    });

Replace a string in a file with nodejs

You could use simple regex:

var result = fileAsString.replace(/string to be replaced/g, 'replacement');

So...

var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/string to be replaced/g, 'replacement');

  fs.writeFile(someFile, result, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   
</form>

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

PHP check if url parameter exists

Why not just simplify it to if($_GET['id']). It will return true or false depending on status of the parameter's existence.

What is the difference between Task.Run() and Task.Factory.StartNew()

According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:

I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :) StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.

Here are the actual reasons:

  1. Does not understand async delegates. This is actually the same as point 1 in the reasons why you would want to use StartNew. The problem is that when you pass an async delegate to StartNew, it’s natural to assume that the returned task represents that delegate. However, since StartNew does not understand async delegates, what that task actually represents is just the beginning of that delegate. This is one of the first pitfalls that coders encounter when using StartNew in async code.
  2. Confusing default scheduler. OK, trick question time: in the code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);

private static void A() { }

Well, you know it’s a trick question, eh? If you answered “a thread pool thread”, I’m sorry, but that’s not correct. “A” will run on whatever TaskScheduler is currently executing!

So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.

In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().

For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html

How to post JSON to a server using C#?

If you need to call is asynchronously then use

var request = HttpWebRequest.Create("http://www.maplegraphservices.com/tokkri/webservices/updateProfile.php?oldEmailID=" + App.currentUser.email) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "text/json";
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        // End the stream request operation

        Stream postStream = request.EndGetRequestStream(asynchronousResult);


        // Create the post data
        string postData = JsonConvert.SerializeObject(edit).ToString();

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);


        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();

        //Start the web request
        request.BeginGetResponse(new AsyncCallback(GetResponceStreamCallback), request);
    }

    void GetResponceStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
        using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
        {
            string result = httpWebStreamReader.ReadToEnd();
            stat.Text = result;
        }

    }

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

I created an alternate colors library for bootstrap 2.3.2 it's available and simple to use for anyone interested in more colors for the old glyphicons library.

This project references NuGet package(s) that are missing on this computer

In my case it happened after I moved my solution folder from one location to another, re-organized it a bit and in the process its relative folder structure changed.

So I had to edit all entries similar to the following one in my .csproj file from

  <Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />

to

  <Import Project="packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />

(Note the change from ..\packages\ to packages\. It might be a different relative structure in your case, but you get the idea.)

How to get the second column from command output?

You don't need awk for that. Using read in Bash shell should be enough, e.g.

some_command | while read c1 c2; do echo $c2; done

or:

while read c1 c2; do echo $c2; done < in.txt

Printing to the console in Google Apps Script?

Just to build on vinnief's hacky solution above, I use MsgBox like this:

Browser.msgBox('BorderoToMatriz', Browser.Buttons.OK_CANCEL);

and it acts kinda like a break point, stops the script and outputs whatever string you need to a pop-up box. I find especially in Sheets, where I have trouble with Logger.log, this provides an adequate workaround most times.

What is the function of FormulaR1C1?

FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:

Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"

In R1C1 you would use:

Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"

It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.

The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :

Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"

javascript unexpected identifier

Yes, you have a } too many. Anyway, compressing yourself tends to result in errors.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
} // <-- end function?
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

Use Closure Compiler instead.

Check if a list contains an item in Ansible

You do not need {{}} in when conditions. What you are searching for is:

- fail: msg="unsupported version"
  when: version not in acceptable_versions

JavaFX Panel inside Panel auto resizing

It is quite simple because you are using the FXMLBuilder.

Just follow these simple steps:

  1. Open FXML file into FXMLBuilder.
  2. Select the stack pane.
  3. Open the Layout tab [left side tab of FXMLBuilder].
  4. Set the sides value by which you want to compute the pane size during stage resize like TOP, LEFT, RIGHT, BOTTOM.

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:

$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Just replace the version number if you need a different one.

Postgres ERROR: could not open file for reading: Permission denied

May be You are using pgadmin by connecting remote host then U are trying to update there from your system but it searches for that file in remote system's file system... its the error wat I faced May be its also for u check it

Select DataFrame rows between two dates

You can also use between:

df[df.some_date.between(start_date, end_date)]

"echo -n" prints "-n"

To achieve this there are basically two methods which I frequently use:

1. Using the cursor escape character (\c) with echo -e

Example :

for i in {0..10..2}; do
  echo -e "$i \c"              
done
# 0 2 4 6 8 10
  • -e flag enables the Escape characters in the string.
  • \c brings the Cursor back to the current line.

OR

2. Using the printf command

Example:

for ((i = 0; i < 5; ++i)); do
  printf "$i "
done
# 0 1 2 3 4

Set selected item of spinner programmatically

Here is the Kotlin extension I am using:

fun Spinner.setItem(list: Array<CharSequence>, value: String) {
    val index = list.indexOf(value)
    this.post { this.setSelection(index) }
}

Usage:

spinnerPressure.setItem(resources.getTextArray(R.array.array_pressure), pressureUnit)

How can I get the named parameters from a URL using Flask?

url:

http://0.0.0.0:5000/user/name/

code:

@app.route('/user/<string:name>/', methods=['GET', 'POST'])
def user_view(name):
    print(name)

(Edit: removed spaces in format string)

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

Access-control-allow-origin with multiple domains

You only need:

  • add a Global.asax to your project,
  • delete <add name="Access-Control-Allow-Origin" value="*" /> from your web.config.
  • afterward, add this in the Application_BeginRequest method of Global.asax:

    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin","*");
    
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
        HttpContext.Current.Response.End();
    }
    

I hope this help. that work for me.

PHP Echo text Color

this works for me every time try this.

echo "<font color='blue'>".$myvariable."</font>";

since font is not supported in html5 you can do this

echo "<p class="variablecolor">".$myvariable."</p>";

then in css do

.variablecolor{
color: blue;}

javax.servlet.ServletException cannot be resolved to a type in spring web app

It seems to me that eclipse doesn't recognize the java ee web api (servlets, el, and so on). If you're using maven and don't want to configure eclipse with a specified server runtime, put the dependecy below in your web project pom:

<dependency>  
    <groupId>javax</groupId>    
    <artifactId>javaee-web-api</artifactId>    
    <version>7.0</version> <!-- Put here the version of your Java EE app, in my case 7.0 -->
    <scope>provided</scope>
</dependency>

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

I know, I am a little late to the party ... what happen a lot, you just use default settings in your app pool in IIS. In IIS Administration utility, go to app pools->select pool-->advanced settings->Process Model/Identity and select a user identity which has right permissions. By default it is set to ApplicationPoolIdentity. If you're developer, you most likely admin on your machine, so you can select your account to run app pool. On the deployment servers, let admins to deal with it.

Is JavaScript guaranteed to be single-threaded?

Actually, a parent window can communicate with child or sibling windows or frames that have their own execution threads running.

Go / golang time.Now().UnixNano() convert to milliseconds?

As @Jono points out in @OneOfOne's answer, the correct answer should take into account the duration of a nanosecond. Eg:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

OneOfOne's answer works because time.Nanosecond happens to be 1, and dividing by 1 has no effect. I don't know enough about go to know how likely this is to change in the future, but for the strictly correct answer I would use this function, not OneOfOne's answer. I doubt there is any performance disadvantage as the compiler should be able to optimize this perfectly well.

See https://en.wikipedia.org/wiki/Dimensional_analysis

Another way of looking at this is that both time.Now().UnixNano() and time.Millisecond use the same units (Nanoseconds). As long as that is true, OneOfOne's answer should work perfectly well.

How do I get list of methods in a Python class?

I just keep this there, because top rated answers are not clear.

This is simple test with not usual class based on Enum.

# -*- coding: utf-8 -*-
import sys, inspect
from enum import Enum

class my_enum(Enum):
    """Enum base class my_enum"""
    M_ONE = -1
    ZERO = 0
    ONE = 1
    TWO = 2
    THREE = 3

    def is_natural(self):
            return (self.value > 0)
    def is_negative(self):
            return (self.value < 0)

def is_clean_name(name):
    return not name.startswith('_') and not name.endswith('_')
def clean_names(lst):
    return [ n for n in lst if is_clean_name(n) ]
def get_items(cls,lst):
    try:
            res = [ getattr(cls,n) for n in lst ]
    except Exception as e:
            res = (Exception, type(e), e)
            pass
    return res


print( sys.version )

dir_res = clean_names( dir(my_enum) )
inspect_res = clean_names( [ x[0] for x in inspect.getmembers(my_enum) ] )
dict_res = clean_names( my_enum.__dict__.keys() )

print( '## names ##' )
print( dir_res )
print( inspect_res )
print( dict_res )

print( '## items ##' )
print( get_items(my_enum,dir_res) )
print( get_items(my_enum,inspect_res) )
print( get_items(my_enum,dict_res) )

And this is output results.

3.7.7 (default, Mar 10 2020, 13:18:53) 
[GCC 9.2.1 20200306]
## names ##
['M_ONE', 'ONE', 'THREE', 'TWO', 'ZERO']
['M_ONE', 'ONE', 'THREE', 'TWO', 'ZERO', 'name', 'value']
['is_natural', 'is_negative', 'M_ONE', 'ZERO', 'ONE', 'TWO', 'THREE']
## items ##
[<my_enum.M_ONE: -1>, <my_enum.ONE: 1>, <my_enum.THREE: 3>, <my_enum.TWO: 2>, <my_enum.ZERO: 0>]
(<class 'Exception'>, <class 'AttributeError'>, AttributeError('name'))
[<function my_enum.is_natural at 0xb78a1fa4>, <function my_enum.is_negative at 0xb78ae854>, <my_enum.M_ONE: -1>, <my_enum.ZERO: 0>, <my_enum.ONE: 1>, <my_enum.TWO: 2>, <my_enum.THREE: 3>]

So what we have:

  • dir provide not complete data
  • inspect.getmembers provide not complete data and provide internal keys that are not accessible with getattr()
  • __dict__.keys() provide complete and reliable result

Why are votes so erroneous? And where i'm wrong? And where wrong other people which answers have so low votes?

wget command to download a file and save as a different filename

Also notice the order of parameters on the command line. At least on some systems (e.g. CentOS 6):

wget -O FILE URL

works. But:

wget URL -O FILE

does not work.

Filename too long in Git for Windows

Git has a limit of 4096 characters for a filename, except on Windows when Git is compiled with msys. It uses an older version of the Windows API and there's a limit of 260 characters for a filename.

So as far as I understand this, it's a limitation of msys and not of Git. You can read the details here: https://github.com/msysgit/git/pull/110

You can circumvent this by using another Git client on Windows or set core.longpaths to true as explained in other answers.

git config --system core.longpaths true

Git is build as a combination of scripts and compiled code. With the above change some of the scripts might fail. That's the reason for core.longpaths not to be enabled by default.

The windows documentation at https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file has some more information:

Starting in Windows 10, version 1607, MAX_PATH limitations have been removed from common Win32 file and directory functions. However, you must opt-in to the new behavior.

A registry key allows you to enable or disable the new long path behavior. To enable long path behavior set the registry key at HKLM\SYSTEM\CurrentControlSet\Control\FileSystem LongPathsEnabled (Type: REG_DWORD)

Having links relative to root?

Use

<a href="/fruits/index.html">Back to Fruits List</a>

or

<a href="../index.html">Back to Fruits List</a>

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I was facing a similar issue while migrating some code from VS 2008 to VS 2010 Making changes to the App.config file resolved the issue for me.

<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0.30319"
         sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup>
</configuration>

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use a ComboBox with its ComboBoxStyle (appears as DropDownStyle in later versions) set to DropDownList. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx

Extract MSI from EXE

Quick List: There are a number of common types of setup.exe files. Here are some of them in a "short-list". More fleshed-out details here (towards bottom).

Setup.exe Extract: (various flavors to try)

setup.exe /a
setup.exe /s /extract_all
setup.exe /s /extract_all:[path]
setup.exe /stage_only
setup.exe /extract "C:\My work"
setup.exe /x
setup.exe /x [path]
setup.exe /s /x /b"C:\FolderInWhichMSIWillBeExtracted" /v"/qn"

dark.exe -x outputfolder setup.exe

dark.exe is a WiX binary - install WiX to extract a WiX setup.exe (as of now). More (section 4).

There is always:

setup.exe /?

MSI Extract: msiexec.exe / File.msi extraction:

 msiexec /a File.msi
 msiexec /a File.msi TARGETDIR=C:\MyInstallPoint /qn

Many Setup Tools: It is impossible to cover all the different kinds of possible setup.exe files. They might feature all kinds of different command line switches. There are so many possible tools that can be used. (non-MSI,MSI, admin-tools, multi-platform, etc...).

NSIS / Inno: Commmon, free tools such as Inno Setup seem to make extraction hard (unofficial unpacker, not tried by me, run by virustotal.com). Whereas NSIS seems to use regular archives that standard archive software (7-zip et al) can open and extract.

General Tricks: One trick is to launch the setup.exe and look in the 1) system's temp folder for extracted files. Another trick is to use 2) 7-Zip, WinRAR, WinZip or similar archive tools to see if they can read the format. Some claim success by 3) opening the setup.exe in Visual Studio. Not a technique I use. 4) And there is obviously application repackaging - capturing the changes done to a computer after a setup has run and clean it up - requires a special tool (most of the free ones come and go, Advanced Installer Architect and AdminStudio are big players).


UPDATE: A quick presentation of various deployment tools used to create installers: How to create windows installer (comprehensive links).

And a simpler list view of the most used development tools as of now (2018), for quicker reading and overview.

And for safekeeping:


Just a disclaimer: A setup.exe file can contain an embedded MSI, it can be a legacy style (non-MSI) installer or it can be just a regular executable with no means of extraction whatsoever. The "discussion" below first presents the use of admin images for MSI files and how to extract MSI files from setup.exe files. Then it provides some links to handle other types of setup.exe files. Also see the comments section.

UPDATE: a few sections have now been added directly below, before the description of MSI file extract using administrative installation. Most significantly a blurb about extracting WiX setup.exe bundles (new kid on the block). Remember that a "last resort" to find extracted setup files, is to launch the installer and then look for extracted files in the temp folder (Hold down Windows Key, tap R, type %temp% or %tmp% and hit Enter) - try the other options first though - for reliability reasons.

Apologies for the "generalized mess" with all this heavy inter-linking. I do believe that you will find what you need if you dig enough in the links, but the content should really be cleaned up and organized better.

General links:

Extract content:

Vendor links:


WiX Toolkit & Burn Bundles (setup.exe files)

Tech Note: The WiX toolkit now delivers setup.exe files built with the bootstrapper tool Burn that you need the toolkit's own dark.exe decompiler to extract. Burn is used to build setup.exe files that can install several embedded MSI or executables in a specified sequence. Here is a sample extraction command:

dark.exe -x outputfolder MySetup.exe

Before you can run such an extraction, some prerequisite steps are required:

  1. Download and install the WiX toolkit (linking to a previous answer with some extra context information on WiX - as well as the download link).
  2. After installing WiX, just open a command prompt, CD to the folder where the setup.exe resides. Then specify the above command and press Enter
  3. The output folder will contain a couple of sub-folders containing both extracted MSI and EXE files and manifests and resource file for the Burn GUI (if any existed in the setup.exe file in the first place of course).
  4. You can now, in turn, extract the contents of the extracted MSI files (or EXE files). For an MSI that would mean running an admin install - as described below.

There is built-in MSI support for file extraction (admin install)

MSI or Windows Installer has built-in support for this - the extraction of files from an MSI file. This is called an administrative installation. It is basically intended as a way to create a network installation point from which the install can be run on many target computers. This ensures that the source files are always available for any repair operations.

Note that running an admin install versus using a zip tool to extract the files is very different! The latter will not adjust the media layout of the media table so that the package is set to use external source files - which is the correct way. Always prefer to run the actual admin install over any hacky zip extractions. As to compression, there are actually three different compression algorithms used for the cab files inside the MSI file format: MSZip, LZX, and Storing (uncompressed). All of these are handled correctly by doing an admin install.

Important: Windows Installer caches installed MSI files on the system for repair, modify and uninstall scenarios. Starting with Windows 7 (MSI version 5) the MSI files are now cached full size to avoid breaking the file signature that prevents the UAC prompt on setup launch (a known Vista problem). This may cause a tremendous increase in disk space consumption (several gigabytes for some systems). To prevent caching a huge MSI file, you should run an admin-install of the package before installing. This is how a company with proper deployment in a managed network would do things, and it will strip out the cab files and make a network install point with a small MSI file and files besides it.


Admin-installs have many uses

It is recommended to read more about admin-installs since it is a useful concept, and I have written a post on stackoverflow: What is the purpose of administrative installation initiated using msiexec /a?.

In essence the admin install is important for:

  • Extracting and inspecting the installer files
    • To get an idea of what is actually being installed and where
    • To ensure that the files look trustworthy and secure (no viruses - malware and viruses can still hide inside the MSI file though)
  • Deployment via systems management software (for example SCCM)
  • Corporate application repackaging
  • Repair, modify and self-repair operations
  • Patching & upgrades
  • MSI advertisement (among other details this involves the "run from source" feature where you can run directly from a network share and you only install shortcuts and registry data)
  • A number of other smaller details

Please read the stackoverflow post linked above for more details. It is quite an important concept for system administrators, application packagers, setup developers, release managers, and even the average user to see what they are installing etc...


Admin-install, practical how-to

You can perform an admin-install in a few different ways depending on how the installer is delivered. Essentially it is either delivered as an MSI file or wrapped in an setup.exe file.

Run these commands from an elevated command prompt, and follow the instructions in the GUI for the interactive command lines:

  • MSI files:

    msiexec /a File.msi
    

    that's to run with GUI, you can do it silently too:

    msiexec /a File.msi TARGETDIR=C:\MyInstallPoint /qn
    
  • setup.exe files:

    setup.exe /a
    

A setup.exe file can also be a legacy style setup (non-MSI) or the dreaded Installscript MSI file type - a well known buggy Installshield project type with hybrid non-standards-compliant MSI format. It is essentially an MSI with a custom, more advanced GUI, but it is also full of bugs.

For legacy setup.exe files the /a will do nothing, but you can try the /extract_all:[path] switch as explained in this pdf. It is a good reference for silent installation and other things as well. Another resource is this list of Installshield setup.exe command line parameters.

MSI patch files (*.MSP) can be applied to an admin image to properly extract its files. 7Zip will also be able to extract the files, but they will not be properly formatted.

Finally - the last resort - if no other way works, you can get hold of extracted setup files by cleaning out the temp folder on your system, launch the setup.exe interactively and then wait for the first dialog to show up. In most cases the installer will have extracted a bunch of files to a temp folder. Sometimes the files are plain, other times in CAB format, but Winzip, 7Zip or even Universal Extractor (haven't tested this product) - may be able to open these.

Sprintf equivalent in Java

// Store the formatted string in 'result'
String result = String.format("%4d", i * j);

// Write the result to standard output
System.out.println( result );

See format and its syntax

Performing a Stress Test on Web Application?

For a web based service, check out loader.io.

Summary:

loader.io is a free load testing service that allows you to stress test your web-apps/apis with thousands of concurrent connections.

They also have an API.

Set a div width, align div center and text align left

Set auto margins on the inner div:

<div id="header" style="width:864px;">
    <div id="centered" style="margin: 0 auto; width:855px;"></div>
</div>

Alternatively, text align center the parent, and force text align left on the inner div:

<div id="header" style="width:864px;text-align: center;">
    <div id="centered" style="text-align: left; width:855px;"></div>
</div>

Convert A String (like testing123) To Binary In Java

This is my implementation.

public class Test {
    public String toBinary(String text) {
        StringBuilder sb = new StringBuilder();

        for (char character : text.toCharArray()) {
            sb.append(Integer.toBinaryString(character) + "\n");
        }

        return sb.toString();

    }
}

How to cache Google map tiles for offline usage?

Unfortunately, I found this link which appears to indicate that we cannot cache these locally, therefore making this question moot.

http://support.google.com/enterprise/doc/gme/terms/maps_purchase_agreement.html

4.4 Cache Restrictions. Customer may not pre-fetch, retrieve, cache, index, or store any Content, or portion of the Services with the exception being Customer may store limited amounts of Content solely to improve the performance of the Customer Implementation due to network latency, and only if Customer does so temporarily, securely, and in a manner that (a) does not permit use of the Content outside of the Services; (b) is session-based only (once the browser is closed, any additional storage is prohibited); (c) does not manipulate or aggregate any Content or portion of the Services; (d) does not prevent Google from accurately tracking Page Views; and (e) does not modify or adjust attribution in any way.

So it appears we cannot use Google map tiles offline, legally.

What is context in _.each(list, iterator, [context])?

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

If you do not set the context, then this will refer to the window object.

Python: finding an element in a list

how's this one?

def global_index(lst, test):
    return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )

Usage:

>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

How did you declare the version?

<version>4.8.2</version>

Be aware of the meaning from this declaration explained here (see NOTES):

When declaring a "normal" version such as 3.8.2 for Junit, internally this is represented as "allow anything, but prefer 3.8.2." This means that when a conflict is detected, Maven is allowed to use the conflict algorithms to choose the best version. If you specify [3.8.2], it means that only 3.8.2 will be used and nothing else.

To force using the version 4.8.2 try

<version>[4.8.2]</version>

As you do not have any other dependencies in your project there shouldn't be any conflicts that cause your problem. The first declaration should work for you if you are able to get this version from a repository. Do you inherit dependencies from a parent pom?

How does Python's super() work with multiple inheritance?

In learningpythonthehardway I learn something called super() an in-built function if not mistaken. Calling super() function can help the inheritance to pass through the parent and 'siblings' and help you to see clearer. I am still a beginner but I love to share my experience on using this super() in python2.7.

If you have read through the comments in this page, you will hear of Method Resolution Order (MRO), the method being the function you wrote, MRO will be using Depth-First-Left-to-Right scheme to search and run. You can do more research on that.

By adding super() function

super(First, self).__init__() #example for class First.

You can connect multiple instances and 'families' with super(), by adding in each and everyone in them. And it will execute the methods, go through them and make sure you didn't miss out! However, adding them before or after does make a difference you will know if you have done the learningpythonthehardway exercise 44. Let the fun begins!!

Taking example below, you can copy & paste and try run it:

class First(object):
    def __init__(self):

        print("first")

class Second(First):
    def __init__(self):
        print("second (before)")
        super(Second, self).__init__()
        print("second (after)")

class Third(First):
    def __init__(self):
        print("third (before)")
        super(Third, self).__init__()
        print("third (after)")


class Fourth(First):
    def __init__(self):
        print("fourth (before)")
        super(Fourth, self).__init__()
        print("fourth (after)")


class Fifth(Second, Third, Fourth):
    def __init__(self):
        print("fifth (before)")
        super(Fifth, self).__init__()
        print("fifth (after)")

Fifth()

How does it run? The instance of fifth() will goes like this. Each step goes from class to class where the super function added.

1.) print("fifth (before)")
2.) super()>[Second, Third, Fourth] (Left to right)
3.) print("second (before)")
4.) super()> First (First is the Parent which inherit from object)

The parent was found and it will go continue to Third and Fourth!!

5.) print("third (before)")
6.) super()> First (Parent class)
7.) print ("Fourth (before)")
8.) super()> First (Parent class)

Now all the classes with super() have been accessed! The parent class has been found and executed and now it continues to unbox the function in the inheritances to finished the codes.

9.) print("first") (Parent)
10.) print ("Fourth (after)") (Class Fourth un-box)
11.) print("third (after)") (Class Third un-box)
12.) print("second (after)") (Class Second un-box)
13.) print("fifth (after)") (Class Fifth un-box)
14.) Fifth() executed

The outcome of the program above:

fifth (before)
second (before
third (before)
fourth (before)
first
fourth (after)
third (after)
second (after)
fifth (after)

For me by adding super() allows me to see clearer on how python would execute my coding and make sure the inheritance can access the method I intended.

How to execute a shell script from C in Linux?

It depends on what you want to do with the script (or any other program you want to run).

If you just want to run the script system is the easiest thing to do, but it does some other stuff too, including running a shell and having it run the command (/bin/sh under most *nix).

If you want to either feed the shell script via its standard input or consume its standard output you can use popen (and pclose) to set up a pipe. This also uses the shell (/bin/sh under most *nix) to run the command.

Both of these are library functions that do a lot under the hood, but if they don't meet your needs (or you just want to experiment and learn) you can also use system calls directly. This also allows you do avoid having the shell (/bin/sh) run your command for you.

The system calls of interest are fork, execve, and waitpid. You may want to use one of the library wrappers around execve (type man 3 exec for a list of them). You may also want to use one of the other wait functions (man 2 wait has them all). Additionally you may be interested in the system calls clone and vfork which are related to fork.

fork duplicates the current program, where the only main difference is that the new process gets 0 returned from the call to fork. The parent process gets the new process's process id (or an error) returned.

execve replaces the current program with a new program (keeping the same process id).

waitpid is used by a parent process to wait on a particular child process to finish.

Having the fork and execve steps separate allows programs to do some setup for the new process before it is created (without messing up itself). These include changing standard input, output, and stderr to be different files than the parent process used, changing the user or group of the process, closing files that the child won't need, changing the session, or changing the environmental variables.

You may also be interested in the pipe and dup2 system calls. pipe creates a pipe (with both an input and an output file descriptor). dup2 duplicates a file descriptor as a specific file descriptor (dup is similar but duplicates a file descriptor to the lowest available file descriptor).

Using an attribute of the current class instance as a default value for method's parameter

There are multiple false assumptions you're making here - First, function belong to a class and not to an instance, meaning the actual function involved is the same for any two instances of a class. Second, default parameters are evaluated at compile time and are constant (as in, a constant object reference - if the parameter is a mutable object you can change it). Thus you cannot access self in a default parameter and will never be able to.

Current date without time

it should be as simple as

DateTime.Today

How to run a PowerShell script without displaying a window?

I was having this same issue. I found out if you go to the Task in Task Scheduler that is running the powershell.exe script, you can click "Run whether user is logged on or not" and that will never show the powershell window when the task runs.

Search for a particular string in Oracle clob column

You can use the way like @Florin Ghita has suggested. But remember dbms_lob.substr has a limit of 4000 characters in the function For example :

dbms_lob.substr(clob_value_column,4000,1)

Otherwise you will find ORA-22835 (buffer too small)

You can also use the other sql way :

SELECT * FROM   your_table WHERE  clob_value_column LIKE '%your string%';

Note : There are performance problems associated with both the above ways like causing Full Table Scans, so please consider about Oracle Text Indexes as well:

https://docs.oracle.com/en/database/oracle/oracle-database/12.2/ccapp/indexing-with-oracle-text.html

Where can I find the assembly System.Web.Extensions dll?

I had this problem myself. Most of the information I could find online was related to people having this problem with an ASP.NET web application. I was creating a Win Forms stand alone app so most of the advice wasn't helpful for me.

Turns out that the problem was that my project was set to use the ".NET 4 Framework Client Profile" as the target framework and the System.Web.Extensions reference was not in the list for adding. I changed the target to ".NET 4 Framework" and then the reference was available by the normal methods.

Here is what worked for me step by step:

  1. Right Click you project Select Properties
  2. Change your Target Framework to ".NET Framework 4"
  3. Do whatever you need to do to save the changes and close the preferences tab
  4. Right click on the References item in your Solution Explorer
  5. Choose Add Reference...
  6. In the .NET tab, scroll down to System.Web.Extensions and add it.

Convert XmlDocument to String

If you are using Windows.Data.Xml.Dom.XmlDocument version of XmlDocument (used in UWP apps for example), you can use yourXmlDocument.GetXml() to get the XML as a string.

Get current index from foreach loop

Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)

list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});

foreach(var row in list)
{
    bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
    row.Index ...
}

How can I completely uninstall nodejs, npm and node in Ubuntu

Try the following commands:

$ sudo apt-get install nodejs
$ sudo apt-get install aptitude
$ sudo aptitude install npm

Mercurial: how to amend the last commit?

Assuming that you have not yet propagated your changes, here is what you can do.

  • Add to your .hgrc:

    [extensions]
    mq =
    
  • In your repository:

    hg qimport -r0:tip
    hg qpop -a
    

    Of course you need not start with revision zero or pop all patches, for the last just one pop (hg qpop) suffices (see below).

  • remove the last entry in the .hg/patches/series file, or the patches you do not like. Reordering is possible too.

  • hg qpush -a; hg qfinish -a
  • remove the .diff files (unapplied patches) still in .hg/patches (should be one in your case).

If you don't want to take back all of your patch, you can edit it by using hg qimport -r0:tip (or similar), then edit stuff and use hg qrefresh to merge the changes into the topmost patch on your stack. Read hg help qrefresh.

By editing .hg/patches/series, you can even remove several patches, or reorder some. If your last revision is 99, you may just use hg qimport -r98:tip; hg qpop; [edit series file]; hg qpush -a; hg qfinish -a.

Of course, this procedure is highly discouraged and risky. Make a backup of everything before you do this!

As a sidenote, I've done it zillions of times on private-only repositories.

Which HTTP methods match up to which CRUD methods?

The building blocks of REST are mainly the resources (and URI) and the hypermedia. In this context, GET is the way to get a representation of the resource (which can indeed be mapped to a SELECT in CRUD terms).

However, you shouldn't necessarily expect a one-to-one mapping between CRUD operations and HTTP verbs. The main difference between PUT and POST is about their idempotent property. POST is also more commonly used for partial updates, as PUT generally implies sending a full new representation of the resource.

I'd suggest reading this:

The HTTP specification is also a useful reference:

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

[...]

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,

Fragment MyFragment not attached to Activity

if (getActivity() == null) return;

works also in some cases. Just breaks the code execution from it and make sure the app not crash

How to make layout with rounded corners..?

You can do it with a custom view, like this RoundAppBar and RoundBottomAppBar. Here a path is used to clipPath the canvas.

Round Corner View

How to make html table vertically scrollable

Why don't you place your table in a div?

<div style="height:100px;overflow:auto;">

 ... Your code goes here ...

</div>

How to completely remove node.js from Windows

The best thing to do is to remove Node.js from the control panel. Once deleted download the desired version of Node.js and install it and it works.

Using regular expression in css?

As complement of this answer you can use $ to get the end matches and * to get matches anywhere in the value name.

Matches anywhere: .col-md, .left-col, .col, .tricolor, etc.

[class*="col"]

Matches at the beginning: .col-md, .col-sm-6, etc.

[class^="col-"]

Matches at the ending: .left-col, .right-col, etc.

[class$="-col"]

How to vertically center a "div" element for all browsers using CSS?

CSS Grid

_x000D_
_x000D_
body, html { margin: 0; }_x000D_
_x000D_
body {_x000D_
  display: grid;_x000D_
  min-height: 100vh;_x000D_
  align-items: center;_x000D_
}
_x000D_
<div>Div to be aligned vertically</div>
_x000D_
_x000D_
_x000D_

How can I remove or replace SVG content?

I had two charts.

<div id="barChart"></div>
<div id="bubbleChart"></div>

This removed all charts.

d3.select("svg").remove(); 

This worked for removing the existing bar chart, but then I couldn't re-add the bar chart after

d3.select("#barChart").remove();

Tried this. It not only let me remove the existing bar chart, but also let me re-add a new bar chart.

d3.select("#barChart").select("svg").remove();

var svg = d3.select('#barChart')
       .append('svg')
       .attr('width', width + margins.left + margins.right)
       .attr('height', height + margins.top + margins.bottom)
       .append('g')
       .attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');

Not sure if this is the correct way to remove, and re-add a chart in d3. It worked in Chrome, but have not tested in IE.

How to check for palindrome using Python logic

doing the Watterloo course for python, the same questions is raised as a "Lesseon" find the info here:

http://cscircles.cemc.uwaterloo.ca/13-lists/

being a novice i solved the problem the following way:

def isPalindrome(S):
    pali = True
    for i in range (0, len(S) // 2):
        if S[i] == S[(i * -1) - 1] and pali is True:
            pali = True
        else:
            pali = False
    print(pali)
    return pali

The function is called isPalindrome(S) and requires a string "S". The return value is by default TRUE, to have the initial check on the first if statement.

After that, the for loop runs half the string length to check if the character from string "S" at the position "i" is the same at from the front and from the back. If once this is not the case, the function stops, prints out FALSE and returns false.

Cheers.kg

Combine Regexp?

Doesn't contain @: /(^[^@]*$)/

Combining works if the intended result of combination is that any of them matching results in the whole regexp matching.

Add content to a new open window

Here is what you can try

  • Write a function say init() inside mypage.html that do the html thing ( append or what ever)
  • instead of OpenWindow.document.write(output); call OpenWindow.init() when the dom is ready

So the parent window will have

    OpenWindow.onload = function(){
       OpenWindow.init('test');
    }

and in the child

    function init(txt){
        $('#test').text(txt);
    }

Remove Select arrow on IE

In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before css to match yours.

In case if it is IE10 then using below css3 it is possible

select::-ms-expand {
    display: none;
}

However if you're interested in jQuery plugin, try Chosen.js or you can create your own in js.

$rootScope.$broadcast vs. $scope.$emit

enter image description here

$scope.$emit: This method dispatches the event in the upwards direction (from child to parent)

enter image description here $scope.$broadcast: Method dispatches the event in the downwards direction (from parent to child) to all the child controllers.

enter image description here $scope.$on: Method registers to listen to some event. All the controllers which are listening to that event get notification of the broadcast or emit based on the where those fit in the child-parent hierarchy.

The $emit event can be cancelled by any one of the $scope who is listening to the event.

The $on provides the "stopPropagation" method. By calling this method the event can be stopped from propagating further.

Plunker :https://embed.plnkr.co/0Pdrrtj3GEnMp2UpILp4/

In case of sibling scopes (the scopes which are not in the direct parent-child hierarchy) then $emit and $broadcast will not communicate to the sibling scopes.

enter image description here

For more details please refer to http://yogeshtutorials.blogspot.in/2015/12/event-based-communication-between-angularjs-controllers.html

onchange event for html.dropdownlist

try this :

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() 
{ Text = "Newest to Oldest", Value = "0" }, new SelectListItem() 
{ Text = "Oldest to Newest", Value = "1" }},
new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })

ngFor with index as value in attribute

with laravel pagination

file.component.ts file

    datasource: any = {
        data: []
    }

    loadData() {
        this.service.find(this.params).subscribe((res: any) => {
            this.datasource = res;
        });
    }

html file

   <tr *ngFor="let item of datasource.data; let i = index">
       <th>{{ datasource.from + i }}</th>
   </tr>

Countdown timer in React

The problem is in your "this" value. Timer function cannot access the "state" prop because run in a different context. I suggest you to do something like this:

...
startTimer = () => {
  let interval = setInterval(this.timer.bind(this), 1000);
  this.setState({ interval });
};

As you can see I've added a "bind" method to your timer function. This allows the timer, when called, to access the same "this" of your react component (This is the primary problem/improvement when working with javascript in general).

Another option is to use another arrow function:

startTimer = () => {
  let interval = setInterval(() => this.timer(), 1000);
  this.setState({ interval });
};

Prevent jQuery UI dialog from setting focus to first textbox

I had similar problem. On my page first input is text box with jQuery UI calendar. Second element is button. As date already have value, I set focus on button, but first add trigger for blur on text box. This solve problem in all browsers and probably in all version of jQuery. Tested in version 1.8.2.

<div style="padding-bottom: 30px; height: 40px; width: 100%;">
@using (Html.BeginForm("Statistics", "Admin", FormMethod.Post, new { id = "FormStatistics" }))
{
    <label style="float: left;">@Translation.StatisticsChooseDate</label>
    @Html.TextBoxFor(m => m.SelectDate, new { @class = "js-date-time",  @tabindex=1 })
    <input class="button gray-button button-large button-left-margin text-bold" style="position:relative; top:-5px;" type="submit" id="ButtonStatisticsSearchTrips" value="@Translation.StatisticsSearchTrips"  tabindex="2"/>
}

<script type="text/javascript">
$(document).ready(function () {        
    $("#SelectDate").blur(function () {
        $("#SelectDate").datepicker("hide");
    });
    $("#ButtonStatisticsSearchTrips").focus();

});   

How to randomly select an item from a list?

Random item selection:

import random

my_list = [1, 2, 3, 4, 5]
num_selections = 2

new_list = random.sample(my_list, num_selections)

To preserve the order of the list, you could do:

randIndex = random.sample(range(len(my_list)), n_selections)
randIndex.sort()
new_list = [my_list[i] for i in randIndex]

Duplicate of https://stackoverflow.com/a/49682832/4383027

Detect Route Change with react-router

This is an old question and I don't quite understand the business need of listening for route changes to push a route change; seems roundabout.

BUT if you ended up here because all you wanted was to update the 'page_path' on a react-router route change for google analytics / global site tag / something similar, here's a hook you can now use. I wrote it based on the accepted answer:

useTracking.js

import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'

export const useTracking = (trackingId) => {
  const { listen } = useHistory()

  useEffect(() => {
    const unlisten = listen((location) => {
      // if you pasted the google snippet on your index.html
      // you've declared this function in the global
      if (!window.gtag) return

      window.gtag('config', trackingId, { page_path: location.pathname })
    })

    // remember, hooks that add listeners
    // should have cleanup to remove them
    return unlisten
  }, [trackingId, listen])
}

You should use this hook once in your app, somewhere near the top but still inside a router. I have it on an App.js that looks like this:

App.js

import * as React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'

import Home from './Home/Home'
import About from './About/About'
// this is the file above
import { useTracking } from './useTracking'

export const App = () => {
  useTracking('UA-USE-YOURS-HERE')

  return (
    <Switch>
      <Route path="/about">
        <About />
      </Route>
      <Route path="/">
        <Home />
      </Route>
    </Switch>
  )
}

// I find it handy to have a named export of the App
// and then the default export which wraps it with
// all the providers I need.
// Mostly for testing purposes, but in this case,
// it allows us to use the hook above,
// since you may only use it when inside a Router
export default () => (
  <BrowserRouter>
    <App />
  </BrowserRouter>
)

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

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

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

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

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

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

postgresql port confusion 5433 or 5432?

The default port of Postgres is commonly configured in:

sudo vi /<path to your installation>/data/postgresql.conf

On Ubuntu this might be:

sudo vi /<path to your installation>/main/postgresql.conf

Search for port in this file.

How can I make an EXE file from a Python program?

Also known as Frozen Binaries but not the same as as the output of a true compiler- they run byte code through a virtual machine (PVM). Run the same as a compiled program just larger because the program is being compiled along with the PVM. Py2exe can freeze standalone programs that use the tkinter, PMW, wxPython, and PyGTK GUI libraties; programs that use the pygame game programming toolkit; win32com client programs; and more. The Stackless Python system is a standard CPython implementation variant that does not save state on the C language call stack. This makes Python more easy to port to small stack architectures, provides efficient multiprocessing options, and fosters novel programming structures such as coroutines. Other systems of study that are working on future development: Pyrex is working on the Cython system, the Parrot project, the PyPy is working on replacing the PVM altogether, and of course the founder of Python is working with Google to get Python to run 5 times faster than C with the Unladen Swallow project. In short, py2exe is the easiest and Cython is more efficient for now until these projects improve the Python Virtual Machine (PVM) for standalone files.

Remove HTML tags from a String

To get formateed plain html text you can do that:

String BR_ESCAPED = "&lt;br/&gt;";
Element el=Jsoup.parse(html).select("body");
el.select("br").append(BR_ESCAPED);
el.select("p").append(BR_ESCAPED+BR_ESCAPED);
el.select("h1").append(BR_ESCAPED+BR_ESCAPED);
el.select("h2").append(BR_ESCAPED+BR_ESCAPED);
el.select("h3").append(BR_ESCAPED+BR_ESCAPED);
el.select("h4").append(BR_ESCAPED+BR_ESCAPED);
el.select("h5").append(BR_ESCAPED+BR_ESCAPED);
String nodeValue=el.text();
nodeValue=nodeValue.replaceAll(BR_ESCAPED, "<br/>");
nodeValue=nodeValue.replaceAll("(\\s*<br[^>]*>){3,}", "<br/><br/>");

To get formateed plain text change <br/> by \n and change last line by:

nodeValue=nodeValue.replaceAll("(\\s*\n){3,}", "<br/><br/>");

How to convert a char to a String?

I've tried the suggestions but ended up implementing it as follows

editView.setFilters(new InputFilter[]{new InputFilter()
        {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend)
            {
                String prefix = "http://";

                //make sure our prefix is visible
                String destination = dest.toString();

                //Check If we already have our prefix - make sure it doesn't
                //get deleted
                if (destination.startsWith(prefix) && (dstart <= prefix.length() - 1))
                {
                    //Yep - our prefix gets modified - try preventing it.
                    int newEnd = (dend >= prefix.length()) ? dend : prefix.length();

                    SpannableStringBuilder builder = new SpannableStringBuilder(
                            destination.substring(dstart, newEnd));
                    builder.append(source);
                    if (source instanceof Spanned)
                    {
                        TextUtils.copySpansFrom(
                                (Spanned) source, 0, source.length(), null, builder, newEnd);
                    }

                    return builder;
                }
                else
                {
                    //Accept original replacement (by returning null)
                    return null;
                }
            }
        }});

How do I bind to list of checkbox values with AngularJS?

Here is yet another solution. The upside of my solution:

  • It does not need any additional watches (which may have an impact on performance)
  • It does not require any code in the controller keeping it clean
  • The code is still somewhat short
  • It is requires very little code to reuse in multiple places because it is just a directive

Here is the directive:

function ensureArray(o) {
    var lAngular = angular;
    if (lAngular.isArray(o) || o === null || lAngular.isUndefined(o)) {
        return o;
    }
    return [o];
}

function checkboxArraySetDirective() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            var name = attrs.checkboxArraySet;

            ngModel.$formatters.push(function(value) {
                return (ensureArray(value) || []).indexOf(name) >= 0;
            });

            ngModel.$parsers.push(function(value) {
                var modelValue = ensureArray(ngModel.$modelValue) || [],
                    oldPos = modelValue.indexOf(name),
                    wasSet = oldPos >= 0;
                if (value) {
                    if (!wasSet) {
                        modelValue = angular.copy(modelValue);
                        modelValue.push(name);
                    }
                } else if (wasSet) {
                    modelValue = angular.copy(modelValue);
                    modelValue.splice(oldPos, 1);
                }
                return modelValue;
            });
        }
    }
}

At the end then just use it like this:

<input ng-repeat="fruit in ['apple', 'banana', '...']" type="checkbox" ng-model="fruits" checkbox-array-set="{{fruit}}" />

And that is all there is. The only addition is the checkbox-array-set attribute.

variable or field declared void

This is not actually a problem with the function being "void", but a problem with the function parameters. I think it's just g++ giving an unhelpful error message.

EDIT: As in the accepted answer, the fix is to use std::string instead of just string.

Represent space and tab in XML tag

I had the same issue and none of the above answers solved the problem, so I tried something very straight-forward: I just putted in my strings.xml \n\t

The complete String looks like this <string name="premium_features_listing_3">- Automatische Aktualisierung der\n\tDatenbank</string>

Results in:

  • Automatische Aktualisierung der

    Datenbank

(with no extra line in between)

Maybe it will help others. Regards

Add an image in a WPF button

Try ContentTemplate:

<Button Grid.Row="2" Grid.Column="0" Width="20" Height="20"
        Template="{StaticResource SomeTemplate}">
    <Button.ContentTemplate>
        <DataTemplate>
            <Image Source="../Folder1/Img1.png" Width="20" />
        </DataTemplate>
    </Button.ContentTemplate>
</Button>

Converting string format to datetime in mm/dd/yyyy

You are looking for the DateTime.Parse() method (MSDN Article)

So you can do:

var dateTime = DateTime.Parse("01/01/2001");

Which will give you a DateTime typed object.

If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)

Which you would use in a situation like this (Where you are using a British style date format):

string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);

change directory in batch file using variable

simple way to do this... here are the example

cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause

this will mount the ISO image to the specific drive...use

run main class of Maven project

Try the maven-exec-plugin. From there:

mvn exec:java -Dexec.mainClass="com.example.Main"

This will run your class in the JVM. You can use -Dexec.args="arg0 arg1" to pass arguments.

If you're on Windows, apply quotes for exec.mainClass and exec.args:

mvn exec:java -D"exec.mainClass"="com.example.Main"

If you're doing this regularly, you can add the parameters into the pom.xml as well:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.2.1</version>
  <executions>
    <execution>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>com.example.Main</mainClass>
    <arguments>
      <argument>foo</argument>
      <argument>bar</argument>
    </arguments>
  </configuration>
</plugin>

HorizontalScrollView within ScrollView Touch Handling

Thanks to Neevek his answer worked for me but it doesn't lock the vertical scrolling when user has started scrolling the horizontal view(ViewPager) in horizontal direction and then without lifting the finger scroll vertically it starts to scroll the underlying container view(ScrollView). I fixed it by making a slight change in Neevak's code:

private float xDistance, yDistance, lastX, lastY;

int lastEvent=-1;

boolean isLastEventIntercepted=false;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            xDistance = yDistance = 0f;
            lastX = ev.getX();
            lastY = ev.getY();


            break;

        case MotionEvent.ACTION_MOVE:
            final float curX = ev.getX();
            final float curY = ev.getY();
            xDistance += Math.abs(curX - lastX);
            yDistance += Math.abs(curY - lastY);
            lastX = curX;
            lastY = curY;

            if(isLastEventIntercepted && lastEvent== MotionEvent.ACTION_MOVE){
                return false;
            }

            if(xDistance > yDistance )
                {

                isLastEventIntercepted=true;
                lastEvent = MotionEvent.ACTION_MOVE;
                return false;
                }


    }

    lastEvent=ev.getAction();

    isLastEventIntercepted=false;
    return super.onInterceptTouchEvent(ev);

}

JSONResult to String

json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";            
return new MemoryStream(Encoding.UTF8.GetBytes(json));

Jenkins "Console Output" log location in filesystem

@Bruno Lavit has a great answer, but if you want you can just access the log and download it as txt file to your workspace from the job's URL:

${BUILD_URL}/consoleText

Then it's only a matter of downloading this page to your ${Workspace}

  • You can use "Invoke ANT" and use the GET target
  • On Linux you can use wget to download it to your workspace
  • etc.

Good luck!

Edit: The actual log file on the file system is not on the slave, but kept in the Master machine. You can find it under: $JENKINS_HOME/jobs/$JOB_NAME/builds/lastSuccessfulBuild/log

If you're looking for another build just replace lastSuccessfulBuild with the build you're looking for.

How can I slice an ArrayList out of an ArrayList in Java?

In Java, it is good practice to use interface types rather than concrete classes in APIs.

Your problem is that you are using ArrayList (probably in lots of places) where you should really be using List. As a result you created problems for yourself with an unnecessary constraint that the list is an ArrayList.

This is what your code should look like:

List input = new ArrayList(...);

public void doSomething(List input) {
   List inputA = input.subList(0, input.size()/2);
   ...
}

this.doSomething(input);

Your proposed "solution" to the problem was/is this:

new ArrayList(input.subList(0, input.size()/2))

That works by making a copy of the sublist. It is not a slice in the normal sense. Furthermore, if the sublist is big, then making the copy will be expensive.


If you are constrained by APIs that you cannot change, such that you have to declare inputA as an ArrayList, you might be able to implement a custom subclass of ArrayList in which the subList method returns a subclass of ArrayList. However:

  1. It would be a lot of work to design, implement and test.
  2. You have now added significant new class to your code base, possibly with dependencies on undocumented aspects (and therefore "subject to change") aspects of the ArrayList class.
  3. You would need to change relevant places in your codebase where you are creating ArrayList instances to create instances of your subclass instead.

The "copy the array" solution is more practical ... bearing in mind that these are not true slices.

Android Studio cannot resolve R in imported project?

Goto File -> Settings -> Compiler now check use external build

then rebuild project

Is 'bool' a basic datatype in C++?

yes, it was introduced in 1993.

for further reference: Boolean Datatype

What are all codecs and formats supported by FFmpeg?

You can see the list of supported codecs in the official documentation:

Supported video codecs

Supported audio codecs

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

I usually don't specify height, but do specify width: ... and rows and cols.

Usually, in my cases, only width and rows are needed, for the textarea to look nice in relation to other elems. (And cols is a fallback if someone doesn't use CSS, as explained in the other answers.)

((Specifying both rows and height feels a little bit like duplicating data I think?))

Open CSV file via VBA (performance)

Sometimes all the solutions with Workbooks.open is not working no matter how many parameters are set. For me, the fastest solution was to change the List separator in Region & language settings. Region window / Additional settings... / List separator.

If csv is not opening in proper way You probly have set ',' as a list separator. Just change it to ';' and everything is solved. Just the easiest way when "everything is against You" :P

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

IntelliJ IDEA generating serialVersionUID

I am not sure if you have an old version of IntelliJ IDEA, but if I go to menu File ? Settings... ? Inspections ? Serialization issues ? Serializable class without 'serialVersionUID'` enabled, the class you provide give me warnings.

Enter image description here

If I try the first class I see:

Enter image description here

BTW: It didn't show me a warning until I added { } to the end of each class to fix the compile error.

"Fatal error: Unable to find local grunt." when running "grunt" command

if you are a exists project, maybe should execute npm install.

guntjs getting started step 2.

How to format column to number format in Excel sheet?

This will format column A as text, B as General, C as a number.

Sub formatColumns()
 Columns(1).NumberFormat = "@"
 Columns(2).NumberFormat = "General"
 Columns(3).NumberFormat = "0"
End Sub

What is the strict aliasing rule?

Strict aliasing is not allowing different pointer types to the same data.

This article should help you understand the issue in full detail.

TypeError: $.browser is undefined

Somewhere the code--either your code or a jQuery plugin--is calling $.browser to get the current browser type.

However, early has year the $.browser function was deprecated. Since then some bugs have been filed against it but because it is deprecated, the jQuery team has decided not to fix them. I've decided not to rely on the function at all.

I don't see any references to $.browser in your code, so the problem probably lies in one of your plugins. To find it, look at the source code for each plugin that you've referenced with a <script> tag.

As for how to fix it: well, it depends on the context. E.g., maybe there's an updated version of the problematic plugin. Or perhaps you can use another plugin that does something similar but doesn't depend on $.browser.

How do I put variable values into a text string in MATLAB?

You can use fprintf/sprintf with familiar C syntax. Maybe something like:

fprintf('x = %d, y = %d \n x+y=%d \n x*y=%d \n x/y=%f\n', x,y,d,e,f)

reading your comment, this is how you use your functions from the main program:

x = 2;
y = 2;
[d e f] = answer(x,y);
fprintf('%d + %d = %d\n', x,y,d)
fprintf('%d * %d = %d\n', x,y,e)
fprintf('%d / %d = %f\n', x,y,f)

Also for the answer() function, you can assign the output values to a vector instead of three distinct variables:

function result=answer(x,y)
result(1)=addxy(x,y);
result(2)=mxy(x,y);
result(3)=dxy(x,y);

and call it simply as:

out = answer(x,y);

How do I set a ViewModel on a window in XAML using DataContext property?

In addition to the solution that other people provided (which are good, and correct), there is a way to specify the ViewModel in XAML, yet still separate the specific ViewModel from the View. Separating them is useful for when you want to write isolated test cases.

In App.xaml:

<Application
    x:Class="BuildAssistantUI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:BuildAssistantUI.ViewModels"
    StartupUri="MainWindow.xaml"
    >
    <Application.Resources>
        <local:MainViewModel x:Key="MainViewModel" />
    </Application.Resources>
</Application>

In MainWindow.xaml:

<Window x:Class="BuildAssistantUI.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{StaticResource MainViewModel}"
    />

How to sum all the values in a dictionary?

You could consider 'for loop' for this:

  d = {'data': 100, 'data2': 200, 'data3': 500}
  total = 0
  for i in d.values():
        total += i

total = 800

Python: Pandas Dataframe how to multiply entire column with a scalar

More recent pandas versions have the pd.DataFrame.multiply function.

df['quantity'] = df['quantity'].multiply(-1)

How to check if a string contains text from an array of substrings in JavaScript?

Drawing from T.J. Crowder's solution, I created a prototype to deal with this problem:

Array.prototype.check = function (s) {
  return this.some((v) => {
    return s.indexOf(v) >= 0;
  });
};

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

How do I convert a Swift Array to a String?

Swift 2.0 Xcode 7.0 beta 6 onwards uses joinWithSeparator() instead of join():

var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

joinWithSeparator is defined as an extension on SequenceType

extension SequenceType where Generator.Element == String {
    /// Interpose the `separator` between elements of `self`, then concatenate
    /// the result.  For example:
    ///
    ///     ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"
    @warn_unused_result
    public func joinWithSeparator(separator: String) -> String
}

How do I set browser width and height in Selenium WebDriver?

For me, the only thing that worked in Java 7 on OS X 10.9 was this:

// driver = new RemoteWebDriver(new URL(grid), capability);
driver.manage().window().setPosition(new Point(0,0));
driver.manage().window().setSize(new Dimension(1024,768));

Where 1024 is the width, and 768 is the height.

Xcode 7.2 no matching provisioning profiles found

Try restarting XCode first, before trying these other answers. I was about to follow the advice given in other answers, then noticed multiple people saying that restarting XCode was necessary after all the steps. All I did was restart XCode and it fixed the problem. Who knows if it'll fix the problem for you, but it's worth a shot before trying the other solutions. I'm on XCode 7.2.1.

Using boolean values in C

Just a complement to other answers and some clarification, if you are allowed to use C99.

+-------+----------------+-------------------------+--------------------+
|  Name | Characteristic | Dependence in stdbool.h |        Value       |
+-------+----------------+-------------------------+--------------------+
| _Bool |   Native type  |    Don't need header    |                    |
+-------+----------------+-------------------------+--------------------+
|  bool |      Macro     |           Yes           | Translate to _Bool |
+-------+----------------+-------------------------+--------------------+
|  true |      Macro     |           Yes           |   Translate to 1   |
+-------+----------------+-------------------------+--------------------+
| false |      Macro     |           Yes           |   Translate to 0   |
+-------+----------------+-------------------------+--------------------+

Some of my preferences:

  • _Bool or bool? Both are fine, but bool looks better than the keyword _Bool.
  • Accepted values for bool and _Bool are: false or true. Assigning 0 or 1 instead of false or true is valid, but is harder to read and understand the logic flow.

Some info from the standard:

  • _Bool is NOT unsigned int, but is part of the group unsigned integer types. It is large enough to hold the values 0 or 1.
  • DO NOT, but yes, you are able to redefine bool true and false but sure is not a good idea. This ability is considered obsolescent and will be removed in future.
  • Assigning an scalar type (arithmetic types and pointer types) to _Bool or bool, if the scalar value is equal to 0 or compares to 0 it will be 0, otherwise the result is 1: _Bool x = 9; 9 is converted to 1 when assigned to x.
  • _Bool is 1 byte (8 bits), usually the programmer is tempted to try to use the other bits, but is not recommended, because the only guaranteed that is given is that only one bit is use to store data, not like type char that have 8 bits available.

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

Have you thought about creating a view with 'Folder = Show all items without folders', that would get all your documents out of their folders and then perhaps you could create your filter(s) over that view.

Change collations of all columns of all tables in SQL Server

Following script will work with table schema along with latest Types like (MAX), IMAGE, and etc. change your collation type according to your need on this line (SET @collate = 'DATABASE_DEFAULT';)

SQL SCRIPT HERE:

BEGIN
DECLARE @collate nvarchar(100);
declare @schema nvarchar(255);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length varchar(100);
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);

SET @collate = 'DATABASE_DEFAULT';

DECLARE tbl_cursor CURSOR FOR SELECT (s.[name])schemaName, (o.[name])[tableName]
FROM sysobjects sy 
INNER JOIN sys.objects  o on o.name = sy.name
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE OBJECTPROPERTY(sy.id, N'IsUserTable') = 1

OPEN tbl_cursor FETCH NEXT FROM tbl_cursor INTO @schema,@table

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE tbl_cursor_changed CURSOR FOR
        SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
            , c.name column_name
            , t.Name data_type
            , c.max_length
            , c.column_id
        FROM sys.columns c
        JOIN sys.types t ON c.system_type_id = t.system_type_id
        LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
        LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id like OBJECT_ID(@schema+'.'+@table)
    ORDER BY c.column_id


    OPEN tbl_cursor_changed 
     FETCH NEXT FROM tbl_cursor_changed
    INTO @row_id, @column_name, @data_type, @max_length, @column_id



    WHILE @@FETCH_STATUS = 0
    BEGIN
    IF (@max_length = -1) SET @max_length = 'MAX';
        IF (@data_type LIKE '%char%')
        BEGIN TRY
            SET @sql = 'ALTER TABLE ' +@schema+'.'+ @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
            print @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR:'
          PRINT @sql
        END CATCH

        FETCH NEXT FROM tbl_cursor_changed
        INTO @row_id, @column_name, @data_type, @max_length, @column_id

    END

    CLOSE tbl_cursor_changed
    DEALLOCATE tbl_cursor_changed

    FETCH NEXT FROM tbl_cursor
    INTO @schema, @table

END

CLOSE tbl_cursor
DEALLOCATE tbl_cursor

PRINT 'Collation For All Tables Done!'
END

Actual meaning of 'shell=True' in subprocess

The benefit of not calling via the shell is that you are not invoking a 'mystery program.' On POSIX, the environment variable SHELL controls which binary is invoked as the "shell." On Windows, there is no bourne shell descendent, only cmd.exe.

So invoking the shell invokes a program of the user's choosing and is platform-dependent. Generally speaking, avoid invocations via the shell.

Invoking via the shell does allow you to expand environment variables and file globs according to the shell's usual mechanism. On POSIX systems, the shell expands file globs to a list of files. On Windows, a file glob (e.g., "*.*") is not expanded by the shell, anyway (but environment variables on a command line are expanded by cmd.exe).

If you think you want environment variable expansions and file globs, research the ILS attacks of 1992-ish on network services which performed subprogram invocations via the shell. Examples include the various sendmail backdoors involving ILS.

In summary, use shell=False.

How to find MAC address of an Android device programmatically

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress(); 

Also, add below permission in your manifest file

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

Please refer to Android 6.0 Changes.

To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.

Getting View's coordinates relative to the root layout

View rootLayout = view.getRootView().findViewById(android.R.id.content);

int[] viewLocation = new int[2]; 
view.getLocationInWindow(viewLocation);

int[] rootLocation = new int[2];
rootLayout.getLocationInWindow(rootLocation);

int relativeLeft = viewLocation[0] - rootLocation[0];
int relativeTop  = viewLocation[1] - rootLocation[1];

First I get the root layout then calculate the coordinates difference with the view.
You can also use the getLocationOnScreen() instead of getLocationInWindow().

C++ [Error] no matching function for call to

to add to John's answer:

what you want to pass to the shuffle function is a deck of cards from the class deckOfCards that you've declared in main; however, the deck of cards or vector<Card> deck that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:

class deckOfCards
{
    private:
        vector<Card> deck;

    public:
        deckOfCards();
        static int count;
        static int next;
        void shuffle(vector<Card>& deck);
        Card dealCard();
        bool moreCards();
        vector<Card>& getDeck() {   //GETTER
            return deck;
        }
};

this will in turn allow you to call your shuffle function from main like this:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck

however, you have more problems, specifically when calling cout. first, you're calling the dealCard function wrongly; as dealCard is a memeber function of a class, you should be calling it like this cardDeck.dealCard(); instead of this dealCard(cardDeck);.

now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card by using the following instruction:

cout << cardDeck.dealCard();// deal the cards in the deck

yet, the cout doesn't know how to print it, as it's not a standard type. this means you should overload your << operator to print whatever you want it to print when calling with a Card type.

How can I remove the "No file chosen" tooltip from a file input in Chrome?

I found a solution that is very easy, just set an empty string into the title attribute.

<input type="file" value="" title=" " />

How do I parse JSON from a Java HTTPResponse?

Use JSON Simple,

http://code.google.com/p/json-simple/

Which has a small foot-print, no dependencies so it's perfect for Android.

You can do something like this,

Object obj=JSONValue.parse(buffer.tString());
JSONArray finalResult=(JSONArray)obj;

OPTION (RECOMPILE) is Always Faster; Why?

To add to the excellent list (given by @CodeCowboyOrg) of situations where OPTION(RECOMPILE) can be very helpful,

  1. Table Variables. When you are using table variables, there will not be any pre-built statistics for the table variable, often leading to large differences between estimated and actual rows in the query plan. Using OPTION(RECOMPILE) on queries with table variables allows generation of a query plan that has a much better estimate of the row numbers involved. I had a particularly critical use of a table variable that was unusable, and which I was going to abandon, until I added OPTION(RECOMPILE). The run time went from hours to just a few minutes. That is probably unusual, but in any case, if you are using table variables and working on optimizing, it's well worth seeing whether OPTION(RECOMPILE) makes a difference.

How to write to a CSV line by line?

You could just write to the file as you would write any normal file.

with open('csvfile.csv','wb') as file:
    for l in text:
        file.write(l)
        file.write('\n')

If just in case, it is a list of lists, you could directly use built-in csv module

import csv

with open("csvfile.csv", "wb") as file:
    writer = csv.writer(file)
    writer.writerows(text)

How do I read the source code of shell commands?

You can have it on github using the command

git clone https://github.com/coreutils/coreutils.git

You can find all the source codes in the src folder.

You need to have git installed.

Things have changed since 2012, ls source code has now 5309 lines

How to execute a remote command over ssh with arguments?

This is an example that works on the AWS Cloud. The scenario is that some machine that booted from autoscaling needs to perform some action on another server, passing the newly spawned instance DNS via SSH

# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`


ssh \
    -o StrictHostKeyChecking=no \
    -i ~/.ssh/id_rsa \
    [email protected] \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!

EOF

Python Key Error=0 - Can't find Dict error in code

It only comes when your list or dictionary not available in the local function.

Inserting a blank table row with a smaller height

Just add the CSS rule (and the slightly improved mark-up) posted below and you should get the result that you're after.

CSS

.blank_row
{
    height: 10px !important; /* overwrites any other rules */
    background-color: #FFFFFF;
}

HTML

<tr class="blank_row">
    <td colspan="3"></td>
</tr>

Since I have no idea what your current stylesheet looks like I added the !important property just in case. If possible, though, you should remove it as one rarely wants to rely on !important declarations in a stylesheet considering the big possibility that they will mess it up later on.

What is the best way to redirect a page using React Router?

One of the simplest way: use Link as follows:

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

<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>

If we want to cover the whole div section as link:

 <div>
     <Card as={Link} to={'path-name'}>
         .... 
           card content here
         ....
     </Card>
 </div>

How to get bean using application context in spring boot

You can use the ApplicationContextAware class that can provide the application context.

public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext ctx = null;

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    @Override
    public void setApplicationContext(final ApplicationContext ctx) throws BeansException {
        ApplicationContextProvider.ctx = ctx;
    }

    /**
     * Tries to autowire the specified instance of the class if one of the specified
     * beans which need to be autowired are null.
     *
     * @param classToAutowire        the instance of the class which holds @Autowire
     *                               annotations
     * @param beansToAutowireInClass the beans which have the @Autowire annotation
     *                               in the specified {#classToAutowire}
     */
    public static void autowire(Object classToAutowire, Object... beansToAutowireInClass) {
        for (Object bean : beansToAutowireInClass) {
            if (bean == null) {
                ctx.getAutowireCapableBeanFactory().autowireBean(classToAutowire);
            }
        }
    }

}

How to remove the last character from a string?

Since we're on a subject, one can use regular expressions too

"aaabcd".replaceFirst(".$",""); //=> aaabc  

If condition inside of map() React

If you're a minimalist like me. Say you only want to render a record with a list containing entries.

<div>
  {data.map((record) => (
    record.list.length > 0
      ? (<YourRenderComponent record={record} key={record.id} />)
      : null
  ))}
</div>

Redirecting unauthorized controller in ASP.NET MVC

This problem has hounded me for some days now, so on finding the answer that affirmatively works with tvanfosson's answer above, I thought it would be worthwhile to emphasize the core part of the answer, and address some related catch ya's.

The core answer is this, sweet and simple:

filterContext.Result = new HttpUnauthorizedResult();

In my case I inherit from a base controller, so in each controller that inherits from it I override OnAuthorize:

protected override void OnAuthorization(AuthorizationContext filterContext)
{
    base.OnAuthorization(filterContext);
    YourAuth(filterContext); // do your own authorization logic here
}

The problem was that in 'YourAuth', I tried two things that I thought would not only work, but would also immediately terminate the request. Well, that is not how it works. So first, the two things that DO NOT work, unexpectedly:

filterContext.RequestContext.HttpContext.Response.Redirect("/Login"); // doesn't work!
FormsAuthentication.RedirectToLoginPage(); // doesn't work!

Not only do those not work, they don't end the request either. Which means the following:

if (!success) {
    filterContext.Result = new HttpUnauthorizedResult();
}
DoMoreStuffNowThatYouThinkYourAuthorized();

Well, even with the correct answer above, the flow of logic still continues! You will still hit DoMoreStuff... within OnAuthorize. So keep that in mind (DoMore... should be in an else therefore).

But with the correct answer, while OnAuthorize flow of logic continues till the end still, after that you really do get what you expect: a redirect to your login page (if you have one set in Forms auth in your webconfig).

But unexpectedly, 1) Response.Redirect("/Login") does not work: the Action method still gets called, and 2) FormsAuthentication.RedirectToLoginPage(); does the same thing: the Action method still gets called!

Which seems totally wrong to me, particularly with the latter: who would have thought that FormsAuthentication.RedirectToLoginPage does not end the request, or do the equivalant above of what filterContext.Result = new HttpUnauthorizedResult() does?

Convert timestamp to readable date/time PHP

echo 'Le '.date('d/m/Y', 1234567890).' &agrave; '.date('H:i:s', 1234567890);

MS-access reports - The search key was not found in any record - on save

Another possible cause of this error is a mismatched workgroup file. That is, if you try to use a secured (or partially-secured) MDB with a workgroup file other than the one used to secure it, you can trigger the error (I've seen it myself, years ago with Access 2000).

Rebuild all indexes in a Database

DECLARE @String NVARCHAR(MAX);
USE Databse Name;
SELECT @String
    =
(
    SELECT 'ALTER INDEX [' + dbindexes.[name] + '] ON [' + db.name + '].[' + dbschemas.[name] + '].[' + dbtables.[name]
           + '] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE);' + CHAR(10) AS [text()]
    FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
        INNER JOIN sys.tables dbtables
            ON dbtables.[object_id] = indexstats.[object_id]
        INNER JOIN sys.schemas dbschemas
            ON dbtables.[schema_id] = dbschemas.[schema_id]
        INNER JOIN sys.indexes AS dbindexes
            ON dbindexes.[object_id] = indexstats.[object_id]
               AND indexstats.index_id = dbindexes.index_id
        INNER JOIN sys.databases AS db
            ON db.database_id = indexstats.database_id
    WHERE dbindexes.name IS NOT NULL
          AND indexstats.database_id = DB_ID()
          AND indexstats.avg_fragmentation_in_percent >= 10
    ORDER BY indexstats.page_count DESC
    FOR XML PATH('')
);
EXEC (@String);

Creating a file name as a timestamp in a batch job

CP source.log %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%.log

But it's locale dependent. I'm not sure if %DATE% is localized, or depends on the format specified for the short date in Windows.

Here is a locale-independent way to extract the current date from this answer, but it depends on WMIC and FOR /F:

FOR /F %%A IN ('WMIC OS GET LocalDateTime ^| FINDSTR \.') DO @SET B=%%A
CP source.log %B:~0,4%-%B:~4,2%-%B:~6,2%.log

library not found for -lPods

I tired all the answers and in the end i was able to fix it by adding pod library into the Xcode Build scheme , after i was able to run it, tried to remove this from the build scheme and still it worked fine for me. couldn't figure out the exact reason.

Table 'mysql.user' doesn't exist:ERROR

Looks like something is messed up with your MySQL installation. The mysql.user table should definitely exist. Try running the command below on your server to create the tables in the database called mysql:

mysql_install_db

If that doesn't work, maybe the permissions on your MySQL data directory are messed up. Look at a "known good" installation as a reference for what the permissions should be.

You could also try re-installing MySQL completely.

Detect Click into Iframe using JavaScript

This is certainly possible. This works in Chrome, Firefox, and IE 11 (and probably others).

focus();
var listener = window.addEventListener('blur', function() {
    if (document.activeElement === document.getElementById('iframe')) {
        // clicked
    }
    window.removeEventListener('blur', listener);
});

JSFiddle


Caveat: This only detects the first click. As I understand, that is all you want.

Javascript ajax call on page onload

It's even easier to do without a library

window.onload = function() {
    // code
};

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Use Rescue mode with cd and mount the filesystem. Try to check if any binary files or folder are deleted. If deleted you will have to manually install the rpms to get those files back.

https://askubuntu.com/questions/92946/cannot-boot-because-kernel-panic-not-syncing-attempted-to-kill-init

Why is an OPTIONS request sent and can I disable it?

One solution I have used in the past - lets say your site is on mydomain.com, and you need to make an ajax request to foreigndomain.com

Configure an IIS rewrite from your domain to the foreign domain - e.g.

<rewrite>
  <rules>
    <rule name="ForeignRewrite" stopProcessing="true">
        <match url="^api/v1/(.*)$" />
        <action type="Rewrite" url="https://foreigndomain.com/{R:1}" />
    </rule>
  </rules>
</rewrite>

on your mydomain.com site - you can then make a same origin request, and there's no need for any options request :)

What is the simplest C# function to parse a JSON string into an object?

Just use the Json.NET library. It lets you parse Json format strings very easily:

JObject o = JObject.Parse(@"
{
    ""something"":""value"",
    ""jagged"":
    {
        ""someother"":""value2""
    }
}");

string something = (string)o["something"];

Documentation: Parsing JSON Object using JObject.Parse

An "and" operator for an "if" statement in Bash

Try this:

if [ $STATUS -ne 200 -a "$STRING" != "$VALUE" ]; then

How to override Bootstrap's Panel heading background color?

You can create a custom class for your panel heading. Using this css class you can style the panel heading. I have a simple Fiddle for this.

HTML:

<div class="panel panel-default">
   <div class="panel-heading panel-heading-custom">
       <h3 class="panel-title">Panel title</h3>
   </div>
   <div class="panel-body">
       Panel content
   </div>
</div>

CSS:

.panel-default > .panel-heading-custom {
background: #ff0000; color: #fff; }

Demo Link:

http://jsfiddle.net/kiranvarthi/t1Lq966k/

Try/catch does not seem to have an effect

If you want try/catch to work for all errors (not just the terminating errors) you can manually make all errors terminating by setting the ErrorActionPreference.

try {

   $ErrorActionPreference = "Stop"; #Make all errors terminating
   get-item filethatdoesntexist; # normally non-terminating
   write-host "You won't hit me";  
} catch{
   Write-Host "Caught the exception";
   Write-Host $Error[0].Exception;
}finally{
   $ErrorActionPreference = "Continue"; #Reset the error action pref to default
}

Alternatively... you can make your own trycatch function that accepts scriptblocks so that your try catch calls are not as kludge. I have mine return true/false just in case i need to check if there was an error... but it doesnt have to. Also, exception logging is optional, and can be taken care of in the catch, but i found myself always calling the logging function in the catch block, so i added it to the try catch function.

function log([System.String] $text){write-host $text;}

function logException{
    log "Logging current exception.";
    log $Error[0].Exception;
}


function mytrycatch ([System.Management.Automation.ScriptBlock] $try,
                    [System.Management.Automation.ScriptBlock] $catch,
                    [System.Management.Automation.ScriptBlock]  $finally = $({})){



# Make all errors terminating exceptions.
    $ErrorActionPreference = "Stop";

    # Set the trap
    trap [System.Exception]{
        # Log the exception.
        logException;

        # Execute the catch statement
        & $catch;

        # Execute the finally statement
        & $finally

        # There was an exception, return false
        return $false;
    }

    # Execute the scriptblock
    & $try;

    # Execute the finally statement
    & $finally

    # The following statement was hit.. so there were no errors with the scriptblock
    return $true;
}


#execute your own try catch
mytrycatch {
        gi filethatdoesnotexist; #normally non-terminating
        write-host "You won't hit me."
    } {
        Write-Host "Caught the exception";
    }

Finding element's position relative to the document

You can traverse the offsetParent up to the top level of the DOM.

function getOffsetLeft( elem )
{
    var offsetLeft = 0;
    do {
      if ( !isNaN( elem.offsetLeft ) )
      {
          offsetLeft += elem.offsetLeft;
      }
    } while( elem = elem.offsetParent );
    return offsetLeft;
}

java.lang.NoClassDefFoundError in junit

If you have more than one version of java, it may interfere with your program.

I suggest you download JCreator.

When you do, click configure, options, and JDK Profiles. Delete the old versions of Java from the list. Then click the play button. Your program should appear.

If it doesn't, press ctrl+alt+O and then press the play button again.

Transpose a range in VBA

Strictly in reference to prefacing "transpose", by the book, either one will work; i.e., application.transpose() OR worksheetfunction.transpose(), and by experience, if you really like typing, application.WorksheetFunction.Transpose() will work also-

Table fixed header and scrollable body

The latest addition position:'sticky' would be the simplest solution here

_x000D_
_x000D_
.outer{_x000D_
    overflow-y: auto;_x000D_
    height:100px;_x000D_
    }_x000D_
_x000D_
.outer table{_x000D_
    width: 100%;_x000D_
    table-layout: fixed; _x000D_
    border : 1px solid black;_x000D_
    border-spacing: 1px;_x000D_
}_x000D_
_x000D_
.outer table th {_x000D_
        text-align: left;_x000D_
        top:0;_x000D_
        position: sticky;_x000D_
        background-color: white;  _x000D_
}
_x000D_
 <div class = "outer">_x000D_
 <table>_x000D_
             <tr >_x000D_
              <th>col1</th>_x000D_
              <th>col2</th>_x000D_
              <th>col3</th>_x000D_
              <th>col4</th>_x000D_
               <th>col5</th>_x000D_
             <tr>_x000D_
                       _x000D_
            <tr >_x000D_
              <td>data</td>_x000D_
              <td>data</td>_x000D_
               <td>data</td>_x000D_
              <td>data</td>_x000D_
              <td>data</td>_x000D_
            <tr>_x000D_
             <tr >_x000D_
               <td>data</td>_x000D_
              <td>data</td>_x000D_
               <td>data</td>_x000D_
              <td>data</td>_x000D_
              <td>data</td>_x000D_
            <tr>_x000D_
             <tr >_x000D_
                <td>data</td>_x000D_
              <td>data</td>_x000D_
               <td>data</td>_x000D_
              <td>data</td>_x000D_
              <td>data</td>_x000D_
            <tr>_x000D_
             <tr >_x000D_
                <td>data</td>_x000D_
              <td>data</td>_x000D_
               <td>data</td>_x000D_
              <td>data</td>_x000D_
              <td>data</td>_x000D_
            <tr>_x000D_
             <tr >_x000D_
                 <td>data</td>_x000D_
              <td>data</td>_x000D_
               <td>data</td>_x000D_
              <td>data</td>_x000D_
              <td>data</td>_x000D_
            <tr>_x000D_
             <tr >_x000D_
                 <td>data</td>_x000D_
              <td>data</td>_x000D_
               <td>data</td>_x000D_
              <td>data</td>_x000D_
              <td>data</td>_x000D_
            <tr>_x000D_
 </table>_x000D_
 </div>
_x000D_
_x000D_
_x000D_

How do I search within an array of hashes by hash values in ruby?

(Adding to previous answers (hope that helps someone):)

Age is simpler but in case of string and with ignoring case:

  • Just to verify the presence:

@fathers.any? { |father| father[:name].casecmp("john") == 0 } should work for any case in start or anywhere in the string i.e. for "John", "john" or "JoHn" and so on.

  • To find first instance/index:

@fathers.find { |father| father[:name].casecmp("john") == 0 }

  • To select all such indices:

@fathers.select { |father| father[:name].casecmp("john") == 0 }

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

The problem is that value is ignored when ng-model is present.

Firefox, which doesn't currently support type="date", will convert all the values to string. Since you (rightly) want date to be a real Date object and not a string, I think the best choice is to create another variable, for instance dateString, and then link the two variables:

<input type="date" ng-model="dateString" />
function MainCtrl($scope, dateFilter) {
    $scope.date = new Date();

    $scope.$watch('date', function (date)
    {
        $scope.dateString = dateFilter(date, 'yyyy-MM-dd');
    });

    $scope.$watch('dateString', function (dateString)
    {
        $scope.date = new Date(dateString);
    });
}

Fiddle

The actual structure is for demonstration purposes only. You'd be better off creating your own directive, especially in order to:

Please notice that I've used yyyy-MM-dd, because it's a format directly supported by the JavaScript Date object. In case you want to use another one, you must make the conversion yourself.


EDIT

Here is a way to make a clean directive:

myModule.directive(
    'dateInput',
    function(dateFilter) {
        return {
            require: 'ngModel',
            template: '<input type="date"></input>',
            replace: true,
            link: function(scope, elm, attrs, ngModelCtrl) {
                ngModelCtrl.$formatters.unshift(function (modelValue) {
                    return dateFilter(modelValue, 'yyyy-MM-dd');
                });

                ngModelCtrl.$parsers.unshift(function(viewValue) {
                    return new Date(viewValue);
                });
            },
        };
});

Fiddle

That's a basic directive, there's still a lot of room for improvement, for example:

  • allow the use of a custom format instead of yyyy-MM-dd,
  • check that the date typed by the user is correct.

Replace a value in a data frame based on a conditional (`if`) statement

Short answer is:

junk$nm[junk$nm %in% "B"] <- "b"

Take a look at Index vectors in R Introduction (if you don't read it yet).


EDIT. As noticed in comments this solution works for character vectors so fail on your data.

For factor best way is to change level:

levels(junk$nm)[levels(junk$nm)=="B"] <- "b"

Insert line break inside placeholder attribute of a textarea?

Add only &#10 for breaking line, no need to write any CSS or javascript.

_x000D_
_x000D_
textarea{_x000D_
    width:300px;_x000D_
    height:100px;_x000D_
_x000D_
}
_x000D_
<textarea placeholder='This is a line this &#10should be a new line'></textarea>_x000D_
_x000D_
<textarea placeholder=' This is a line _x000D_
_x000D_
should this be a new line?'></textarea>
_x000D_
_x000D_
_x000D_

Is there a C# String.Format() equivalent in JavaScript?

Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

usage:

"{greeting} {who}!".format({greeting: "Hello", who: "world"})

_x000D_
_x000D_
String.prototype.format = function(placeholders) {_x000D_
    var s = this;_x000D_
    for(var propertyName in placeholders) {_x000D_
        var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
        s = s.replace(re, placeholders[propertyName]);_x000D_
    }    _x000D_
    return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

How do I convert a list of ascii values to a string in python?

Same basic solution as others, but I personally prefer to use map instead of the list comprehension:


>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'

SQL Query Where Date = Today Minus 7 Days

DECLARE @Daysforward int
SELECT @Daysforward = 25 (no of days required)
Select * from table name

where CAST( columnDate AS date) < DATEADD(day,1+@Daysforward,CAST(GETDATE() AS date))

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

for bootstrap 3, this is what i used

.carousel-fade .carousel-inner .item {
  opacity: 0;
  -webkit-transition-property: opacity;
  -moz-transition-property: opacity;
  -o-transition-property: opacity;
  transition-property: opacity;
}
.carousel-fade .carousel-inner .active {
  opacity: 1;
}
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  opacity: 0;
  z-index: 1;
}
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}
.carousel-fade .carousel-control {
  z-index: 2;
}

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I have got the solution for my query:

i have done something like this:

cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>"

function setDefaultImage(source){
        var badImg = new Image();
        badImg.src = "video.png";
        var cpyImg = new Image();
        cpyImg.src = source.src;

        if(!cpyImg.width)
        {
            source.src = badImg.src;
        }

    }


    function onImgError(source){
        source.src = "video.png";
        source.onerror = ""; 
        return true; 
    } 

This way it's working in all browsers.

MS Access: how to compact current database in VBA

There's also Michael Kaplan's SOON ("Shut One, Open New") add-in. You'd have to chain it, but it's one way to do this.

I can't say I've had much reason to ever want to do this programatically, since I'm programming for end users, and they are never using anything but the front end in the Access user interface, and there's no reason to regularly compact a properly-designed front end.

Call Javascript onchange event by programmatically changing textbox value

You're population is from the server-side. Using the registerclientscript will put the script at the beginning of the form.. you'll want to use RegisterStartupScript(Block) to have the script placed at the end of the page in question.

The former tries to run the script before the text area exists in the dom, the latter will run the script after that element in the page is created.

Else clause on Python while statement

I know this is old question but...

As Raymond Hettinger said, it should be called while/no_break instead of while/else.
I find it easy to understeand if you look at this snippet.

n = 5
while n > 0:
    print n
    n -= 1
    if n == 2:
        break
if n == 0:
    print n

Now instead of checking condition after while loop we can swap it with else and get rid of that check.

n = 5
while n > 0:
    print n
    n -= 1
    if n == 2:
        break
else:  # read it as "no_break"
    print n

I always read it as while/no_break to understand the code and that syntax makes much more sense to me.

How to change a text with jQuery

This should work fine (using .text():

$("#toptitle").text("New word");

How to cut a string after a specific character in unix

You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:

Parameter Expansion

...

${parameter#word}

Remove Smallest Prefix Pattern.
The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted.

In other words, you can write

$var="${var#*:}"

which will remove anything matching *: from $var (i.e. everything up to and including the first :). If you want to match up to the last :, then you could use ## in place of #.

This is all assuming that the part to remove does not contain : (true for IPv4 addresses, but not for IPv6 addresses)

How to set java_home on Windows 7?

While adding your Java directory to your PATH variable, you might want to put it right at the beginning of it. I've had the problem, that putting the Java directory at the end of the PATH would not work. After checking, I've found java.exe in my Windows\System32 directory and it looks like the first one wins, when there are several files with the same name in your PATH...

How to Lock/Unlock screen programmatically?

Use Activity.getWindow() to get the window of your activity; use Window.addFlags() to add whichever of the following flags in WindowManager.LayoutParams that you desire:

How to remove constraints from my MySQL table?

Some ORM's or frameworks use a different naming convention for foreign keys than the default FK_[parent table]_[referenced table]_[referencing field], because they can be altered.

Laravel for example uses [parent table]_[referencing field]_foreign as naming convention. You can show the names of the foreign keys by using this query, as shown here:

SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE REFERENCED_TABLE_SCHEMA = '<database>' AND REFERENCED_TABLE_NAME = '<table>';

Then remove the foreign key by running the before mentioned DROP FOREIGN KEY query and its proper name.

"ImportError: no module named 'requests'" after installing with pip

In Windows it worked for me only after trying the following: 1. Open cmd inside the folder where "requests" is unpacked. (CTRL+SHIFT+right mouse click, choose the appropriate popup menu item) 2. (Here is the path to your pip3.exe)\pip3.exe install requests Done

Cannot implicitly convert type 'int?' to 'int'.

this is because the return type of your method is int and OrdersPerHour is int? (nullable) , you can solve this by returning its value like below:

return OrdersPerHour.Value

also check if its not null to avoid exception like as below:

if(OrdersPerHour != null)
{

    return OrdersPerHour.Value;

}
else
{

  return 0; // depends on your choice

}

but in this case you will have to return some other value in the else part or after the if part otherwise compiler will flag an error that not all paths of code return value.

pointer to array c++

j[0]; dereferences a pointer to int, so its type is int.

(*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

Defining a percentage width for a LinearLayout?

You can't define width/height/margins/... using percents in your XML. But what you would want to use is the "weight" attribute, which is, IMO, the most similar thing.

Another method would be to set the sizes programmatically after you inflate the layout in your code, by getting the size of your screen and calculating needed margins.

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

Servers tab

--> doubleclick servername

--> Server Options: tick "Publish module contexts to separate XML files"

restart your server

How does "make" app know default target to build if no target is specified?

By default, it begins by processing the first target that does not begin with a . aka the default goal; to do that, it may have to process other targets - specifically, ones the first target depends on.

The GNU Make Manual covers all this stuff, and is a surprisingly easy and informative read.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

For WebAPI, check out this link: http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx

Basically, add this code to your Application_Start:

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

Combine two data frames by rows (rbind) when they have different sets of columns

An alternative with data.table:

library(data.table)
df1 = data.frame(a = c(1:5), b = c(6:10))
df2 = data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
rbindlist(list(df1, df2), fill = TRUE)

rbind will also work in data.table as long as the objects are converted to data.table objects, so

rbind(setDT(df1), setDT(df2), fill=TRUE)

will also work in this situation. This can be preferable when you have a couple of data.tables and don't want to construct a list.

Check if a varchar is a number (TSQL)

Neizan's code lets values of just a "." through. At the risk of getting too pedantic, I added one more AND clause.

declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar) 
values 
    (N'1234')
    , (N'000005')
    , (N'1,000')
    , (N'293.8457')
    , (N'x')
    , (N'+')
    , (N'293.8457.')
    , (N'......')
    , (N'.')
    ;

-- This shows that Neizan's answer allows "." to slip through.
select * from (
    select 
        MyVar
        , case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber 
    from 
        @MyTable
) t order by IsNumber;

-- Notice the addition of "and MyVar not like '.'".
select * from (
    select 
        MyVar
        , case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' and MyVar not like '.' then 1 else 0 end as IsNumber 
    from 
        @MyTable
) t 
order by IsNumber;

How to load a tsv file into a Pandas DataFrame?

As of 17.0 from_csv is discouraged.

Use pd.read_csv(fpath, sep='\t') or pd.read_table(fpath).

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

AttributeError: 'module' object has no attribute 'model'

I realized that by looking at the stack trace it was trying to load my own script in place of another module called the same way,i.e., my script was called random.py and when a module i used was trying to import the "random" package, it was loading my script causing a circular reference and so i renamed it and deleted a .pyc file it had created from the working folder and things worked just fine.

How do I hide certain files from the sidebar in Visual Studio Code?

I would also like to recommend vscode extension Peep, which allows you to toggle hide on the excluded files in your projects settings.json.

Hit F1 for vscode command line (command palette), then

ext install [enter] peep [enter]

You can bind "extension.peepToggle" to a key like Ctrl+Shift+P (same as F1 by default) for easy toggling. Hit Ctrl+K Ctrl+S for key bindings, enter peep, select Peep Toggle and add your binding.

How can I use the HTML5 canvas element in IE?

I just used flashcanvas, and I got that working. If you encounter problems, just make sure to read the caveats and whatnot. Particularly, if you create canvas elements dynamically, you need to initialize them explicitly:

if (typeof FlashCanvas != "undefined") {
    FlashCanvas.initElement(canvas);
}

Difference between File.separator and slash in paths

"Java SE8 for Programmers" claims that the Java will cope with either. (pp. 480, last paragraph). The example claims that:

c:\Program Files\Java\jdk1.6.0_11\demo/jfc

will parse just fine. Take note of the last (Unix-style) separator.

It's tacky, and probably error-prone, but it is what they (Deitel and Deitel) claim.

I think the confusion for people, rather than Java, is reason enough not to use this (mis?)feature.

How to compare two dates in php

The date_diff() function returns the difference between two DateTime objects.

If the first date is before the second date a positive number of days will be returned; otherwise a negative number of days:

<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>

output will be "+272 days" ;

changing $date1 = "2014-03-15"

 <?php
    $date1=date_create("2014-03-15");
    $date2=date_create("2013-12-12");
    $diff=date_diff($date1,$date2);
    echo $diff->format("%R%a days");
    ?>

Output will be "-93 days"

Pandas: sum DataFrame rows for given columns

This is a simpler way using iloc to select which columns to sum:

df['f']=df.iloc[:,0:2].sum(axis=1)
df['g']=df.iloc[:,[0,1]].sum(axis=1)
df['h']=df.iloc[:,[0,3]].sum(axis=1)

Produces:

   a  b   c  d   e  f  g   h
0  1  2  dd  5   8  3  3   6
1  2  3  ee  9  14  5  5  11
2  3  4  ff  1   8  7  7   4

I can't find a way to combine a range and specific columns that works e.g. something like:

df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
df['i']=df.iloc[:,[0:2,3]].sum(axis=1)

Get element from within an iFrame

Below code will help you to find out iframe data.

let iframe = document.getElementById('frameId');
let innerDoc = iframe.contentDocument || iframe.contentWindow.document;

How to make Python speak

PYTTSX3!

WHAT:

Pyttsx3 is a python module which is a modern clone of pyttsx, modified to work perfectly well in the latest versions of Python 3!

WHY:

It is 100% MULTI-PLATFORM and WORKS OFFLINE and IS ACTIVE/STILL BEING DEVELOPED and WORKS WITH ANY PYTHON VERSION

HOW:

It can be easily installed with pip install pyttsx3 and usage is the same as pyttsx:

import pyttsx3;
engine = pyttsx3.init();
engine.say("I will speak this text");
engine.runAndWait();

This is the best multi platform option!

How to find index of all occurrences of element in array?

We can use Stack and push "i" into the stack every time we encounter the condition "arr[i]==value"

Check this:

static void getindex(int arr[], int value)
{
    Stack<Integer>st= new Stack<Integer>();
    int n= arr.length;
    for(int i=n-1; i>=0 ;i--)
    {
        if(arr[i]==value)
        {
            st.push(i);
        }
    }   
    while(!st.isEmpty())
    {
        System.out.println(st.peek()+" ");
        st.pop(); 
    }
}

How to search a list of tuples in Python

You can use a list comprehension:

>>> a = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
>>> [x[0] for x in a]
[1, 22, 53, 44]
>>> [x[0] for x in a].index(53)
2

Best solution to protect PHP code without encryption

They distribute their software under a proprietary license. The law protects their rights and prevents their customers from redistributing the source, though there is no actual difficulty doing so.

But as you might be well aware, copyright infringement (piracy) of software products is a pretty common phenomenon.

PHP - regex to allow letters and numbers only

  • Missing end anchor $
  • Missing multiplier
  • Missing end delimiter

So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.

/^[a-z0-9]+$/i

Is right click a Javascript event?

Ya, though w3c says the right click can be detected by the click event, onClick is not triggered through right click in usual browsers.

In fact, right click only trigger onMouseDown onMouseUp and onContextMenu.

Thus, you can regard "onContextMenu" as the right click event. It's an HTML5.0 standard.

Global variables in header file

The currently-accepted answer to this question is wrong. C11 6.9.2/2:

If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

So the original code in the question behaves as if file1.c and file2.c each contained the line int i = 0; at the end, which causes undefined behaviour due to multiple external definitions (6.9/5).

Since this is a Semantic rule and not a Constraint, no diagnostic is required.

Here are two more questions about the same code with correct answers:

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

The CP1 means 'Code Page 1' - technically this translates to code page 1252

Meaning of = delete after function declaration

A deleted function is implicitly inline

(Addendum to existing answers)

... And a deleted function shall be the first declaration of the function (except for deleting explicit specializations of function templates - deletion should be at the first declaration of the specialization), meaning you cannot declare a function and later delete it, say, at its definition local to a translation unit.

Citing [dcl.fct.def.delete]/4:

A deleted function is implicitly inline. ( Note: The one-definition rule ([basic.def.odr]) applies to deleted definitions. — end note ] A deleted definition of a function shall be the first declaration of the function or, for an explicit specialization of a function template, the first declaration of that specialization. [ Example:

struct sometype {
  sometype();
};
sometype::sometype() = delete;      // ill-formed; not first declaration

end example )

A primary function template with a deleted definition can be specialized

Albeit a general rule of thumb is to avoid specializing function templates as specializations do not participate in the first step of overload resolution, there are arguable some contexts where it can be useful. E.g. when using a non-overloaded primary function template with no definition to match all types which one would not like implicitly converted to an otherwise matching-by-conversion overload; i.e., to implicitly remove a number of implicit-conversion matches by only implementing exact type matches in the explicit specialization of the non-defined, non-overloaded primary function template.

Before the deleted function concept of C++11, one could do this by simply omitting the definition of the primary function template, but this gave obscure undefined reference errors that arguably gave no semantic intent whatsoever from the author of primary function template (intentionally omitted?). If we instead explicitly delete the primary function template, the error messages in case no suitable explicit specialization is found becomes much nicer, and also shows that the omission/deletion of the primary function template's definition was intentional.

#include <iostream>
#include <string>

template< typename T >
void use_only_explicit_specializations(T t);

template<>
void use_only_explicit_specializations<int>(int t) {
    std::cout << "int: " << t;
}

int main()
{
    const int num = 42;
    const std::string str = "foo";
    use_only_explicit_specializations(num);  // int: 42
    //use_only_explicit_specializations(str); // undefined reference to `void use_only_explicit_specializations< ...
}

However, instead of simply omitting a definition for the primary function template above, yielding an obscure undefined reference error when no explicit specialization matches, the primary template definition can be deleted:

#include <iostream>
#include <string>

template< typename T >
void use_only_explicit_specializations(T t) = delete;

template<>
void use_only_explicit_specializations<int>(int t) {
    std::cout << "int: " << t;
}

int main()
{
    const int num = 42;
    const std::string str = "foo";
    use_only_explicit_specializations(num);  // int: 42
    use_only_explicit_specializations(str);
    /* error: call to deleted function 'use_only_explicit_specializations' 
       note: candidate function [with T = std::__1::basic_string<char>] has 
       been explicitly deleted
       void use_only_explicit_specializations(T t) = delete; */
}

Yielding a more more readable error message, where the deletion intent is also clearly visible (where an undefined reference error could lead to the developer thinking this an unthoughtful mistake).

Returning to why would we ever want to use this technique? Again, explicit specializations could be useful to implicitly remove implicit conversions.

#include <cstdint>
#include <iostream>

void warning_at_best(int8_t num) { 
    std::cout << "I better use -Werror and -pedantic... " << +num << "\n";
}

template< typename T >
void only_for_signed(T t) = delete;

template<>
void only_for_signed<int8_t>(int8_t t) {
    std::cout << "UB safe! 1 byte, " << +t << "\n";
}

template<>
void only_for_signed<int16_t>(int16_t t) {
    std::cout << "UB safe! 2 bytes, " << +t << "\n";
}

int main()
{
    const int8_t a = 42;
    const uint8_t b = 255U;
    const int16_t c = 255;
    const float d = 200.F;

    warning_at_best(a); // 42
    warning_at_best(b); // implementation-defined behaviour, no diagnostic required
    warning_at_best(c); // narrowing, -Wconstant-conversion warning
    warning_at_best(d); // undefined behaviour!

    only_for_signed(a);
    only_for_signed(c);

    //only_for_signed(b);  
    /* error: call to deleted function 'only_for_signed' 
       note: candidate function [with T = unsigned char] 
             has been explicitly deleted
       void only_for_signed(T t) = delete; */

    //only_for_signed(d);
    /* error: call to deleted function 'only_for_signed' 
       note: candidate function [with T = float] 
             has been explicitly deleted
       void only_for_signed(T t) = delete; */
}

Conditionally displaying JSF components

Yes, use the rendered attribute.

<h:form rendered="#{some boolean condition}">

You usually tie it to the model rather than letting the model grab the component and manipulate it.

E.g.

<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

Note the importance of keyword based EL operators such as gt, ge, le and lt instead of >, >=, <= and < as angle brackets < and > are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.

As to your specific use case, let's assume that the link is passing a parameter like below:

<a href="page.xhtml?form=1">link</a>

You can then show the form as below:

<h:form rendered="#{param.form eq '1'}">

(the #{param} is an implicit EL object referring to a Map representing the request parameters)

See also:

Why is quicksort better than mergesort?

From the Wikipedia entry on Quicksort:

Quicksort also competes with mergesort, another recursive sort algorithm but with the benefit of worst-case T(nlogn) running time. Mergesort is a stable sort, unlike quicksort and heapsort, and can be easily adapted to operate on linked lists and very large lists stored on slow-to-access media such as disk storage or network attached storage. Although quicksort can be written to operate on linked lists, it will often suffer from poor pivot choices without random access. The main disadvantage of mergesort is that, when operating on arrays, it requires T(n) auxiliary space in the best case, whereas the variant of quicksort with in-place partitioning and tail recursion uses only T(logn) space. (Note that when operating on linked lists, mergesort only requires a small, constant amount of auxiliary storage.)

How can I use a C++ library from node.js?

You could use emscripten to compile C++ code into js.

Creating a constant Dictionary in C#

This is the closest thing you can get to a "CONST Dictionary":

public static int GetValueByName(string name)
{
    switch (name)
    {
        case "bob": return 1;
        case "billy": return 2;
        default: return -1;
    }
}

The compiler will be smart enough to build the code as clean as possible.

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

If you have Underscore.js installed, you could:

$(window).resize(_.debounce(function(){
    alert("Resized");
},500));

How To Create Table with Identity Column

Unique key allows max 2 NULL values. Explaination:

create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)

insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')

select * from teppp
null string , address1
NULL,address2
NULL,address3

If you try inserting same values as below:

insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')

Every time you will get error like:

Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

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

Three ways to pass model data to partial view (there may be more)

This is view page

Method One Populate at view

@{    
    PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
    ctry1.CountryName="India";
    ctry1.ID=1;    

    PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
    ctry2.CountryName="Africa";
    ctry2.ID=2;

    List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}

Method Two Pass Through ViewBag

@{
    var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}

Method Three pass through model

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

enter image description here