Programs & Examples On #Onconfigurationchanged

Cannot catch toolbar home button click event

For anyone looking for a Xamarin implementation (since events are done differently in C#), I simply created this NavClickHandler class as follows:

public class NavClickHandler : Java.Lang.Object, View.IOnClickListener
{
    private Activity mActivity;
    public NavClickHandler(Activity activity)
    {
        this.mActivity = activity;
    }
    public void OnClick(View v)
    {
        DrawerLayout drawer = (DrawerLayout)mActivity.FindViewById(Resource.Id.drawer_layout);
        if (drawer.IsDrawerOpen(GravityCompat.Start))
        {
            drawer.CloseDrawer(GravityCompat.Start);
        }
        else
        {
            drawer.OpenDrawer(GravityCompat.Start);
        }
    }
}

Then, assigned a custom hamburger menu button like this:

        SupportActionBar.SetDisplayHomeAsUpEnabled(true);
        SupportActionBar.SetDefaultDisplayHomeAsUpEnabled(false);
        this.drawerToggle.DrawerIndicatorEnabled = false;
        this.drawerToggle.SetHomeAsUpIndicator(Resource.Drawable.MenuButton);

And finally, assigned the drawer menu toggler a ToolbarNavigationClickListener of the class type I created earlier:

        this.drawerToggle.ToolbarNavigationClickListener = new NavClickHandler(this);

And then you've got a custom menu button, with click events handled.

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

you must use import android.support.v7.app.ActionBarDrawerToggle;

and use the constructor

public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout)
{
    super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}

and if the drawer toggle button becomes dark then you must use the supportActionBar provided in the support library.

You can implement supportActionbar from this link: http://developer.android.com/training/basics/actionbar/setting-up.html

Same Navigation Drawer in different Activities

For anyone else looking to do what the original poster is asking, please consider to use fragments instead the way Kevin said. Here is an excellent tutorial on how to do that:

https://github.com/codepath/android_guides/wiki/Fragment-Navigation-Drawer

If you choose to instead use activities instead of fragments you are going to run into the problem of the nav drawer being re-created every time you navigate to a new activity. This results in an ugly/slow rendering of the nav drawer each time.

Force "portrait" orientation mode

I had this line in my AndroidManifest.xml

<activity 
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale"
    android:label="@string/app_name" android:name="Project Name"
    android:theme="@android:style/Theme.Black.NoTitleBar">

Which I changed to (just added android:screenOrientation="portrait")

<activity 
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale"
    android:label="@string/app_name" android:name="Project Name"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.Black.NoTitleBar">

This fixed things for me.

How can I get the current screen orientation?

getActivity().getResources().getConfiguration().orientation

this command returns int value 1 for Portrait and 2 for Landscape

Notepad++ add to every line

Please find the Screenshot below which Add a new word at the start and end of the line at a single shot

adding a new word at the start & end of the every line in Notepad++ at a single shot

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

How to pip install a package with min and max version range?

You can do:

$ pip install "package>=0.2,<0.3"

And pip will look for the best match, assuming the version is at least 0.2, and less than 0.3.

This also applies to pip requirements files. See the full details on version specifiers in PEP 440.

Convert list to array in Java

I came across this code snippet that solves it.

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

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

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

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

The conversion works as follows:

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

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

you want something like:

SELECT count(id), SUM(hour) as totHour, SUM(kind=1) as countKindOne;

Note that your second example was close, but the IF() function always takes three arguments, so it would have had to be COUNT(IF(kind=1,1,NULL)). I prefer the SUM() syntax shown above because it's concise.

Connect to network drive with user name and password

Use this code for Impersonation its tested in MVC.NET maybe for dot net core it required some change, If you want to dot net core let me know I will share.

 public static class ImpersonationAuthenticationNew
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool LogonUser(string usernamee, string domain, string password, LogonType dwLogonType, LogonProvider dwLogonProvider, ref IntPtr phToken);
        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);
        public static bool Login(string domain,string username, string password)
        {                
            IntPtr token = IntPtr.Zero;
            var IsSuccess = LogonUser(username, domain, password, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50, ref token);
            if (IsSuccess)
            {
                using (WindowsImpersonationContext person = new WindowsIdentity(token).Impersonate())
                {
                    var xIdentity = WindowsIdentity.GetCurrent();
                    #region Start ImpersonationContext  Scope
                    try
                    {

                        // TYPE YOUR CODE HERE 
                      return true;
                    }
                    catch (Exception ex) { throw (ex); }
                    finally {
                        person.Undo();
                        CloseHandle(token);
                       
                    }
                    #endregion
                }
            }
            return false;
        }
    }

    #region Enums
    public enum LogonType
    {
        /// <summary>
        /// This logon type is intended for users who will be interactively using the computer, such as a user being logged on  
        /// by a terminal server, remote shell, or similar process.
        /// This logon type has the additional expense of caching logon information for disconnected operations;
        /// therefore, it is inappropriate for some client/server applications,
        /// such as a mail server.
        /// </summary>
        LOGON32_LOGON_INTERACTIVE = 2,

        /// <summary>
        /// This logon type is intended for high performance servers to authenticate plaintext passwords.

        /// The LogonUser function does not cache credentials for this logon type.
        /// </summary>
        LOGON32_LOGON_NETWORK = 3,

        /// <summary>
        /// This logon type is intended for batch servers, where processes may be executing on behalf of a user without
        /// their direct intervention. This type is also for higher performance servers that process many plaintext
        /// authentication attempts at a time, such as mail or Web servers.
        /// The LogonUser function does not cache credentials for this logon type.
        /// </summary>
        LOGON32_LOGON_BATCH = 4,

        /// <summary>
        /// Indicates a service-type logon. The account provided must have the service privilege enabled.
        /// </summary>
        LOGON32_LOGON_SERVICE = 5,

        /// <summary>
        /// This logon type is for GINA DLLs that log on users who will be interactively using the computer.
        /// This logon type can generate a unique audit record that shows when the workstation was unlocked.
        /// </summary>
        LOGON32_LOGON_UNLOCK = 7,

        /// <summary>
        /// This logon type preserves the name and password in the authentication package, which allows the server to make
        /// connections to other network servers while impersonating the client. A server can accept plaintext credentials
        /// from a client, call LogonUser, verify that the user can access the system across the network, and still
        /// communicate with other servers.
        /// NOTE: Windows NT:  This value is not supported.
        /// </summary>
        LOGON32_LOGON_NETWORK_CLEARTEXT = 8,

        /// <summary>
        /// This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
        /// The new logon session has the same local identifier but uses different credentials for other network connections.
        /// NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
        /// NOTE: Windows NT:  This value is not supported.
        /// </summary>
        LOGON32_LOGON_NEW_CREDENTIALS = 9,
    }
    public enum LogonProvider
    {
        /// <summary>
        /// Use the standard logon provider for the system.
        /// The default security provider is negotiate, unless you pass NULL for the domain name and the user name
        /// is not in UPN format. In this case, the default provider is NTLM.
        /// NOTE: Windows 2000/NT:   The default security provider is NTLM.
        /// </summary>
        LOGON32_PROVIDER_DEFAULT = 0,
        LOGON32_PROVIDER_WINNT35 = 1,
        LOGON32_PROVIDER_WINNT40 = 2,
        LOGON32_PROVIDER_WINNT50 = 3
    }
    #endregion

jQuery .ready in a dynamically inserted iframe

In IFrames I usually solve this problem by putting a small script to the very end of the block:

<body>
The content of your IFrame
<script type="text/javascript">
//<![CDATA[
   fireOnReadyEvent();
   parent.IFrameLoaded();
//]]>
</script>
</body>

This work most of the time for me. Sometimes the simplest and most naive solution is the most appropriate.

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

How to clear all input fields in a specific div with jQuery?

Change this:

 <div class=fetch_results>

To this:

 <div id="fetch_results">

Then the following should work:

$("#fetch_results input").each(function() {
      this.value = "";
  })?

http://jsfiddle.net/NVqeR/

How can I determine if a variable is 'undefined' or 'null'?

I run this test in the Chrome console. Using (void 0) you can check undefined:

var c;
undefined
if (c === void 0) alert();
// output =  undefined
var c = 1;
// output =  undefined
if (c === void 0) alert();
// output =   undefined
// check c value  c
// output =  1
if (c === void 0) alert();
// output =  undefined
c = undefined;
// output =  undefined
if (c === void 0) alert();
// output =   undefined

A cron job for rails: best practices?

script/runner and rake tasks are perfectly fine to run as cron jobs.

Here's one very important thing you must remember when running cron jobs. They probably won't be called from the root directory of your app. This means all your requires for files (as opposed to libraries) should be done with the explicit path: e.g. File.dirname(__FILE__) + "/other_file". This also means you have to know how to explicitly call them from another directory :-)

Check if your code supports being run from another directory with

# from ~
/path/to/ruby /path/to/app/script/runner -e development "MyClass.class_method"
/path/to/ruby /path/to/rake -f /path/to/app/Rakefile rake:task RAILS_ENV=development

Also, cron jobs probably don't run as you, so don't depend on any shortcut you put in .bashrc. But that's just a standard cron tip ;-)

IntelliJ and Tomcat.. Howto..?

In Netbeans you can right click on the project and run it, but in IntelliJ IDEA you have to select the index.jsp file or the welcome file to run the project.

this is because Netbeans generate the following tag in web.xml and IntelliJ do not.

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

Change border-bottom color using jquery?

$('#elementid').css('border-bottom', 'solid 1px red');

C++ printing spaces or tabs given a user input integer

Simply add spaces for { 2 3 4 5 6 } like these:

cout<<"{";

for(){
    cout<<" "<<n;    //n is the element to print !
}

cout<<" }";

How to reset par(mfrow) in R

You can reset the plot by doing this:

dev.off()

Integrating MySQL with Python in Windows

You can try to use myPySQL. It's really easy to use; no compilation for windows, and even if you need to compile it for any reason, you only need Python and Visual C installed (not mysql).

http://code.google.com/p/mypysql/

Good luck

Omitting the first line from any Linux command output

Pipe it to awk:

awk '{if(NR>1)print}'

or sed

sed -n '1!p'

How to setup FTP on xampp

I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

Lua - Current time in milliseconds

In standard C lua, no. You will have to settle for seconds, unless you are willing to modify the lua interpreter yourself to have os.time use the resolution you want. That may be unacceptable, however, if you are writing code for other people to run on their own and not something like a web application where you have full control of the environment.

Edit: another option is to write your own small DLL in C that extends lua with a new function that would give you the values you want, and require that dll be distributed with your code to whomever is going to be using it.

How to set the height of an input (text) field in CSS?

Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height rule, some won't.

You can try line-height (may need display:block; or display:inline-block;) or top and bottom padding also. If none of those work, that's pretty much it - use a graphic, position the input in the center and set border:none; so it looks like the form control is big but it actually isn't...

Why does an SSH remote command get fewer environment variables then when run manually?

How about sourcing the profile before running the command?

ssh user@host "source /etc/profile; /path/script.sh"

You might find it best to change that to ~/.bash_profile, ~/.bashrc, or whatever.

(As here (linuxquestions.org))

How to enter a formula into a cell using VBA?

You aren't building your formula right.

Worksheets("EmployeeCosts").Range("B" & var1a).Formula =  "=SUM(H5:H" & var1a & ")"

This does the same as the following lines do:

Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"

which is what you are trying to do.

Also, you want to have the = at the beginning of the formala.

Get image data url in JavaScript?

This Function takes the URL then returns the image BASE64

function getBase64FromImageUrl(url) {
    var img = new Image();

    img.setAttribute('crossOrigin', 'anonymous');

    img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width =this.width;
        canvas.height =this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);

        var dataURL = canvas.toDataURL("image/png");

        alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
    };

    img.src = url;
}

Call it like this : getBase64FromImageUrl("images/slbltxt.png")

POST Content-Length exceeds the limit

There might be more than just one php.ini file. For example, when using WAMP there are 2 php.ini files in following directories:

  • C:\wamp\bin\apache\apache2.4.9\bin
  • C:\wamp\bin\php\php5.5.12

You need to edit the first one.

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

You could use a recursive scalar function:-

set nocount on

create table location (
    id int,
    name varchar(50),
    parent int
)
insert into location values
    (1,'france',null),
    (2,'paris',1),
    (3,'belleville',2),
    (4,'lyon',1),
    (5,'vaise',4),
    (6,'united kingdom',null),
    (7,'england',6),
    (8,'manchester',7),
    (9,'fallowfield',8),
    (10,'withington',8)
go
create function dbo.breadcrumb(@child int)
returns varchar(1024)
as begin
    declare @returnValue varchar(1024)=''
    declare @parent int
    select @returnValue+=' > '+name,@parent=parent
    from location
    where id=@child
    if @parent is not null
        set @returnValue=dbo.breadcrumb(@parent)+@returnValue
    return @returnValue
end
go

declare @location int=1
while @location<=10 begin
    print dbo.breadcrumb(@location)+' >'
    set @location+=1
end

produces:-

 > france >
 > france > paris >
 > france > paris > belleville >
 > france > lyon >
 > france > lyon > vaise >
 > united kingdom >
 > united kingdom > england >
 > united kingdom > england > manchester >
 > united kingdom > england > manchester > fallowfield >
 > united kingdom > england > manchester > withington >

MYSQL import data from csv using LOAD DATA INFILE

I was getting Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

This worked for me on windows 8.1 64 bit using wampserver 3.0.6 64bit.

Edited my.ini file from C:\wamp64\bin\mysql\mysql5.7.14

Delete entry secure_file_priv c:\wamp64\tmp\ (or whatever dir you have here)

Stopped everything -exit wamp etc.- and restarted everything; then punt my cvs file on C:\wamp64\bin\mysql\mysql5.7.14\data\u242349266_recur (the last dir being my database name)

executed LOAD DATA INFILE 'myfile.csv'

INTO TABLE alumnos

FIELDS TERMINATED BY ','

ENCLOSED BY '"'

LINES TERMINATED BY '\r\n'

IGNORE 1 LINES

... and VOILA!!!

What's the purpose of the LEA instruction?

The 8086 has a large family of instructions that accept a register operand and an effective address, perform some computations to compute the offset part of that effective address, and perform some operation involving the register and the memory referred to by the computed address. It was fairly simple to have one of the instructions in that family behave as above except for skipping that actual memory operation. Thus, the instructions:

mov ax,[bx+si+5]
lea ax,[bx+si+5]

were implemented almost identically internally. The difference is a skipped step. Both instructions work something like:

temp = fetched immediate operand (5)
temp += bx
temp += si
address_out = temp  (skipped for LEA)
trigger 16-bit read  (skipped for LEA)
temp = data_in  (skipped for LEA)
ax = temp

As for why Intel thought this instruction was worth including, I'm not exactly sure, but the fact that it was cheap to implement would have been a big factor. Another factor would have been the fact that Intel's assembler allowed symbols to be defined relative to the BP register. If fnord was defined as a BP-relative symbol (e.g. BP+8), one could say:

mov ax,fnord  ; Equivalent to "mov ax,[BP+8]"

If one wanted to use something like stosw to store data to a BP-relative address, being able to say

mov ax,0 ; Data to store
mov cx,16 ; Number of words
lea di,fnord
rep movs fnord  ; Address is ignored EXCEPT to note that it's an SS-relative word ptr

was more convenient than:

mov ax,0 ; Data to store
mov cx,16 ; Number of words
mov di,bp
add di,offset fnord (i.e. 8)
rep movs fnord  ; Address is ignored EXCEPT to note that it's an SS-relative word ptr

Note that forgetting the world "offset" would cause the contents of location [BP+8], rather than the value 8, to be added to DI. Oops.

How do you use script variables in psql?

Another approach is to (ab)use the PostgreSQL GUC mechanism to create variables. See this prior answer for details and examples.

You declare the GUC in postgresql.conf, then change its value at runtime with SET commands and get its value with current_setting(...).

I don't recommend this for general use, but it could be useful in narrow cases like the one mentioned in the linked question, where the poster wanted a way to provide the application-level username to triggers and functions.

Given a URL to a text file, what is the simplest way to read the contents of the text file?

import urllib2

f = urllib2.urlopen(target_url)
for l in f.readlines():
    print l

Configuration System Failed to Initialize

Easy solution for .Net Core WinForms / WPF / .Net Standard Class Library projects

step 1: Install System.Configuration.ConfigurationManager by Nuget Manager

step 2: Add a new App.Config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Bodrum" value="Yalikavak" />    
  </appSettings>
</configuration>

step3: Get the value

string value = ConfigurationManager.AppSettings.Get("Bodrum");
// value is Yalikavak

If you are calling it from a Class Library then add the App.Config file on your Main Project.

phonegap open link in browser

As answered in other posts, you have two different options for different platforms. What I do is:

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {

    // Mock device.platform property if not available
    if (!window.device) {
        window.device = { platform: 'Browser' };
    }

    handleExternalURLs();
}

function handleExternalURLs() {
    // Handle click events for all external URLs
    if (device.platform.toUpperCase() === 'ANDROID') {
        $(document).on('click', 'a[href^="http"]', function (e) {
            var url = $(this).attr('href');
            navigator.app.loadUrl(url, { openExternal: true });
            e.preventDefault();
        });
    }
    else if (device.platform.toUpperCase() === 'IOS') {
        $(document).on('click', 'a[href^="http"]', function (e) {
            var url = $(this).attr('href');
            window.open(url, '_system');
            e.preventDefault();
        });
    }
    else {
        // Leave standard behaviour
    }
}

So as you can see I am checking the device platform and depending on that I am using a different method. In case of a standard browser, I leave standard behaviour. From now on the solution will work fine on Android, iOS and in a browser, while HTML page won't be changed, so that it can have URLs represented as standard anchor

<a href="http://stackoverflow.com">

The solution requires InAppBrowser and Device plugins

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

Change the jquery show()/hide() animation?

You can also use a fadeIn/FadeOut Combo, too....

$('.test').bind('click', function(){
    $('.div1').fadeIn(500); 
    $('.div2').fadeOut(500);
    $('.div3').fadeOut(500);
    return false;
});

How can I Remove .DS_Store files from a Git repository?

The best solution to tackle this issue is to Globally ignore these files from all the git repos on your system. This can be done by creating a global gitignore file like:

vi ~/.gitignore_global

Adding Rules for ignoring files like:

# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so

# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip

# Logs and databases #
######################
*.log
*.sql
*.sqlite

# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

Now, add this file to your global git config:

git config --global core.excludesfile ~/.gitignore_global

Edit:

Removed Icons as they might need to be committed as application assets.

Extending an Object in Javascript

PLEASE ADD REASON FOR DOWNVOTE

  • No need to use any external library to extend

  • In JavaScript, everything is an object (except for the three primitive datatypes, and even they are automatically wrapped with objects when needed). Furthermore, all objects are mutable.

Class Person in JavaScript

function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype = {
    getName: function() {
        return this.name;
    },
    getAge: function() {
        return this.age;
    }
}

/* Instantiate the class. */
var alice = new Person('Alice', 93);
var bill = new Person('Bill', 30);

Modify a specific instance/object.

alice.displayGreeting = function() 
{
    alert(this.getGreeting());
}

Modify the class

Person.prototype.getGreeting = function() 
{
    return 'Hi ' + this.getName() + '!';
};

Or simply say : extend JSON and OBJECT both are same

var k = {
    name : 'jack',
    age : 30
}

k.gender = 'male'; /*object or json k got extended with new property gender*/

thanks to ross harmes , dustin diaz

To the power of in C?

You need pow(); function from math.h header.
syntax

#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);

Here x is base and y is exponent. result is x^y.

usage

pow(2,4);  

result is 2^4 = 16. //this is math notation only   
// In c ^ is a bitwise operator

And make sure you include math.h to avoid warning ("incompatible implicit declaration of built in function 'pow' ").

Link math library by using -lm while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.

How to get relative path from absolute path

.NET Core 2.0 has Path.GetRelativePath, else, use this.

/// <summary>
/// Creates a relative path from one file or folder to another.
/// </summary>
/// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
/// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
/// <returns>The relative path from the start directory to the end path or <c>toPath</c> if the paths are not related.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="UriFormatException"></exception>
/// <exception cref="InvalidOperationException"></exception>
public static String MakeRelativePath(String fromPath, String toPath)
{
    if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");
    if (String.IsNullOrEmpty(toPath))   throw new ArgumentNullException("toPath");

    Uri fromUri = new Uri(fromPath);
    Uri toUri = new Uri(toPath);

    if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.

    Uri relativeUri = fromUri.MakeRelativeUri(toUri);
    String relativePath = Uri.UnescapeDataString(relativeUri.ToString());

    if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
    {
        relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
    }

    return relativePath;
}

How do I set up IntelliJ IDEA for Android applications?

I've spent a day on trying to put all the pieces together, been in hundreds of sites and tutorials, but they all skip trivial steps.

So here's the full guide:

  1. Download and install Java JDK (Choose the Java platform)
  2. Download and install Android SDK (Installer is recommended)
  3. After android SD finishes installing, open SDK Manager under Android SDK Tools (sometimes needs to be opened under admin's privileges)
  4. Choose everything and mark Accept All and install.
  5. Download and install IntelliJ IDEA (The community edition is free)
  6. Wait for all downloads and installations and stuff to finish.

New Project:

  1. Run IntelliJ
  2. Create a new project (there's a tutorial here)
  3. Enter the name, choose Android type.
  4. There's a step missing in the tutorial, when you are asked to choose the JDK (before choosing the SDK) you need to choose the Java JDK you've installed earlier. Should be under C:\Program Files\Java\jdk{version}
  5. Choose a New platform ( if there's not one selected ) , the SDK platform is the android platform at C:\Program Files\Android\android-sdk-windows.
  6. Choose the android version.
  7. Now you can write your program.

Compiling:

  1. Near the Run button you need to select the drop-down-list, choose Edit Configurations
  2. In the Prefer Android Virtual device select the ... button
  3. Click on create, give it a name, press OK.
  4. Double click the new device to choose it.
  5. Press OK.
  6. You're ready to run the program.

android button selector

Create custom_selector.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@drawable/unselected" android:state_pressed="true" />
   <item android:drawable="@drawable/selected" />
</selector>

Create selected.xml shape in drawable folder

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="90dp">
   <solid android:color="@color/selected"/>
   <padding />
   <stroke android:color="#000" android:width="1dp"/>
   <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>
</shape>

Create unselected.xml shape in drawable folder

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="90dp">
   <solid android:color="@color/unselected"/>
   <padding />
   <stroke android:color="#000" android:width="1dp"/>
   <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>
</shape>

Add following colors for selected/unselected state in color.xml of values folder

<color name="selected">#a8cf45</color>
<color name="unselected">#ff8cae3b</color>

you can check complete solution from here

How to ssh from within a bash script?

  1. If you want the password prompt to go away then use key based authentication (described here).

  2. To run commands remotely over ssh you have to give them as an argument to ssh, like the following:

root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'

Check if Cell value exists in Column, and then get the value of the NEXT Cell

Use a different function, like VLOOKUP:

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", VLOOKUP(A1,B:C,2,FALSE))

MySQL - Using COUNT(*) in the WHERE clause

SELECT COUNT(*)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC;

EDIT (if you just want the gids):

SELECT MIN(gid)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC

How to vertically align into the center of the content of a div with defined width/height?

This could also be done using display: flex with only a few lines of code. Here is an example:

.container {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
}

Live Demo

How to create a Calendar table for 100 years in Sql

Here is a generic script you can use in SQL server. just amend the start and end dates:

IF EXISTS (SELECT * FROM information_schema.tables WHERE Table_Name = 'Calendar' AND Table_Type = 'BASE TABLE')
BEGIN
DROP TABLE [Calendar]
END

CREATE TABLE [Calendar]
(
    [CalendarDate] DATETIME
)

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = GETDATE()
SET @EndDate = DATEADD(d, 365, @StartDate)

WHILE @StartDate <= @EndDate
      BEGIN
             INSERT INTO [Calendar]
             (
                   CalendarDate
             )
             SELECT
                   @StartDate

             SET @StartDate = DATEADD(dd, 1, @StartDate)
      END

If you want a more advanced calendar here is one I found on the net a while ago:

CREATE SCHEMA Auxiliary
-- We put our auxiliary tables and stuff in a separate schema
-- One of the great new things in SQL Server 2005
go

CREATE FUNCTION Auxiliary.Computus
-- Computus (Latin for computation) is the calculation of the date of
-- Easter in the Christian calendar
-- http://en.wikipedia.org/wiki/Computus
-- I'm using the Meeus/Jones/Butcher Gregorian algorithm
(
    @Y INT -- The year we are calculating easter sunday for
)
RETURNS DATETIME
AS
BEGIN
DECLARE
@a INT,
@b INT,
@c INT,
@d INT,
@e INT,
@f INT,
@g INT,
@h INT,
@i INT,
@k INT,
@L INT,
@m INT

SET @a = @Y % 19
SET @b = @Y / 100
SET @c = @Y % 100
SET @d = @b / 4
SET @e = @b % 4
SET @f = (@b + 8) / 25
SET @g = (@b - @f + 1) / 3
SET @h = (19 * @a + @b - @d - @g + 15) % 30
SET @i = @c / 4
SET @k = @c % 4
SET @L = (32 + 2 * @e + 2 * @i - @h - @k) % 7
SET @m = (@a + 11 * @h + 22 * @L) / 451
RETURN(DATEADD(month, ((@h + @L - 7 * @m + 114) / 31)-1, cast(cast(@Y AS VARCHAR) AS Datetime)) + ((@h + @L - 7 * @m + 114) % 31))
END
GO


CREATE TABLE [Auxiliary].[Calendar] (
-- This is the calendar table
  [Date] datetime NOT NULL,
  [Year] int NOT NULL,
  [Quarter] int NOT NULL,
  [Month] int NOT NULL,
  [Week] int NOT NULL,
  [Day] int NOT NULL,
  [DayOfYear] int NOT NULL,
  [Weekday] int NOT NULL,
  [Fiscal_Year] int NOT NULL,
  [Fiscal_Quarter] int NOT NULL,
  [Fiscal_Month] int NOT NULL,
  [KindOfDay] varchar(10) NOT NULL,
  [Description] varchar(50) NULL,
  PRIMARY KEY CLUSTERED ([Date])
)
GO

ALTER TABLE [Auxiliary].[Calendar]
-- In Celkoish style I'm manic about constraints (Never use em ;-))
-- http://www.celko.com/

ADD CONSTRAINT [Calendar_ck] CHECK (  ([Year] > 1900)
AND ([Quarter] BETWEEN 1 AND 4)
AND ([Month] BETWEEN 1 AND 12)
AND ([Week]  BETWEEN 1 AND 53)
AND ([Day] BETWEEN 1 AND 31)
AND ([DayOfYear] BETWEEN 1 AND 366)
AND ([Weekday] BETWEEN 1 AND 7)
AND ([Fiscal_Year] > 1900)
AND ([Fiscal_Quarter] BETWEEN 1 AND 4)
AND ([Fiscal_Month] BETWEEN 1 AND 12)
AND ([KindOfDay] IN ('HOLIDAY', 'SATURDAY', 'SUNDAY', 'BANKDAY')))
GO




SET DATEFIRST 1;
-- I want my table to contain datedata acording to ISO 8601
-- http://en.wikipedia.org/wiki/ISO_8601
-- thus first day of a week is monday
WITH Dates(Date)
-- A recursive CTE that produce all dates between 1999 and 2020-12-31
AS
(
SELECT cast('1999' AS DateTime) Date -- SQL Server supports the ISO 8601 format so this is an unambigious shortcut for 1999-01-01
UNION ALL                            -- http://msdn2.microsoft.com/en-us/library/ms190977.aspx
SELECT (Date + 1) AS Date
FROM Dates
WHERE
Date < cast('2021' AS DateTime) -1
),

DatesAndThursdayInWeek(Date, Thursday)
-- The weeks can be found by counting the thursdays in a year so we find
-- the thursday in the week for a particular date
AS
(
SELECT
Date,
CASE DATEPART(weekday,Date)
WHEN 1 THEN Date + 3
WHEN 2 THEN Date + 2
WHEN 3 THEN Date + 1
WHEN 4 THEN Date
WHEN 5 THEN Date - 1
WHEN 6 THEN Date - 2
WHEN 7 THEN Date - 3
END AS Thursday
FROM Dates
),

Weeks(Week, Thursday)
-- Now we produce the weeknumers for the thursdays
-- ROW_NUMBER is new to SQL Server 2005
AS
(
SELECT ROW_NUMBER() OVER(partition by year(Date) order by Date) Week, Thursday
FROM DatesAndThursdayInWeek
WHERE DATEPART(weekday,Date) = 4
)
INSERT INTO Auxiliary.Calendar
SELECT
d.Date,
YEAR(d.Date) AS Year,
DATEPART(Quarter, d.Date) AS Quarter,
MONTH(d.Date) AS Month,
w.Week,
DAY(d.Date) AS Day,
DATEPART(DayOfYear, d.Date) AS DayOfYear,
DATEPART(Weekday, d.Date) AS Weekday,

-- Fiscal year may be different to the actual year in Norway the are the same
-- http://en.wikipedia.org/wiki/Fiscal_year
YEAR(d.Date) AS Fiscal_Year,
DATEPART(Quarter, d.Date) AS Fiscal_Quarter,
MONTH(d.Date) AS Fiscal_Month,

CASE
-- Holidays in Norway
-- For other countries and states: Wikipedia - List of holidays by country
-- http://en.wikipedia.org/wiki/List_of_holidays_by_country
    WHEN (DATEPART(DayOfYear, d.Date) = 1)          -- New Year's Day
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-7)  -- Palm Sunday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-3)  -- Maundy Thursday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-2)  -- Good Friday
    OR (d.Date = Auxiliary.Computus(YEAR(Date)))    -- Easter Sunday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+39) -- Ascension Day
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+49) -- Pentecost
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+50) -- Whitmonday
    OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 1)      -- Labour day
    OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 17)     -- Constitution day
    OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 25)    -- Cristmas day
    OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 26)    -- Boxing day
    THEN 'HOLIDAY'
    WHEN DATEPART(Weekday, d.Date) = 6 THEN 'SATURDAY'
    WHEN DATEPART(Weekday, d.Date) = 7 THEN 'SUNDAY'
    ELSE 'BANKDAY'
END KindOfDay,
CASE
-- Description of holidays in Norway
    WHEN (DATEPART(DayOfYear, d.Date) = 1)            THEN 'New Year''s Day'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-7)  THEN 'Palm Sunday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-3)  THEN 'Maundy Thursday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-2)  THEN 'Good Friday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date)))    THEN 'Easter Sunday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+39) THEN 'Ascension Day'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+49) THEN 'Pentecost'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+50) THEN 'Whitmonday'
    WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 1)      THEN 'Labour day'
    WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 17)     THEN 'Constitution day'
    WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 25)    THEN 'Cristmas day'
    WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 26)    THEN 'Boxing day'
END Description

FROM DatesAndThursdayInWeek d
-- This join is for getting the week into the result set
     inner join Weeks w
     on d.Thursday = w.Thursday

OPTION(MAXRECURSION 0)
GO

CREATE FUNCTION Auxiliary.Numbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS @RetNumbers TABLE
(
[Number] int PRIMARY KEY NOT NULL
)
AS
BEGIN
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
INSERT @RetNumbers
SELECT n from Numbers
OPTION(MAXRECURSION 0)
RETURN;
END
GO

CREATE FUNCTION Auxiliary.iNumbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS TABLE
AS
RETURN(
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
SELECT n AS Number from Numbers
)
GO

How to persist a property of type List<String> in JPA?

Thiago answer is correct, adding sample more specific to question, @ElementCollection will create new table in your database, but without mapping two tables, It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a collection of embeddable elements (class annotated with @Embeddable).

Here is the sample to persist list of String

@ElementCollection
private Collection<String> options = new ArrayList<String>();

Here is the sample to persist list of Custom object

@Embedded
@ElementCollection
private Collection<Car> carList = new ArrayList<Car>();

For this case we need to make class Embeddable

@Embeddable
public class Car {
}

If Radio Button is selected, perform validation on Checkboxes

You must use the equals operator not the assignment like

if(document.form1.radio1[0].checked == true) {
    alert("You have selected Option 1");
}

Regular expression to match balanced parentheses

While so many answers mention this in some form by saying that regex does not support recursive matching and so on, the primary reason for this lies in the roots of the Theory of Computation.

Language of the form {a^nb^n | n>=0} is not regular. Regex can only match things that form part of the regular set of languages.

Read more @ here

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

    // pop back stack all the way
    final FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
    int entryCount = fm.getBackStackEntryCount(); 
    while (entryCount-- > 0) {
        fm.popBackStack();
    }

ASP.NET Web API : Correct way to return a 401/unauthorised response

As an alternative to the other answers, you can also use this code if you want to return an IActionResult within an ASP.NET controller.

ASP.NET

 return Content(HttpStatusCode.Unauthorized, "My error message");

Update: ASP.NET Core

Above code does not work in ASP.NET Core, you can use one of these instead:

 return StatusCode((int)System.Net.HttpStatusCode.Unauthorized, "My error message");
 return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status401Unauthorized, "My error message");
 return StatusCode(401, "My error message");

Apparently the reason phrase is pretty optional (Can an HTTP response omit the Reason-Phrase?)

'Conda' is not recognized as internal or external command

If you don't want to add Anaconda to env. path and you are using Windows try this:

  • Open cmd;
  • Type path to your folder instalation. It's something like: C:\Users\your_home folder\Anaconda3\Scripts
  • Test Anaconda, for exemple type conda --version.
  • Update Anaconda: conda update conda or conda update --all or conda update anaconda.

Update Spyder:

  • conda update qt pyqt
  • conda update spyder

Where is the web server root directory in WAMP?

If you installed WAMP to c:\wamp then I believe your webserver root directory would be c:\wamp\www, however this might vary depending on version.

Yes, this is where you would put your site files to access them through a browser.

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

UPDATE multiple tables in MySQL using LEFT JOIN

Table A 
+--------+-----------+
| A-num  | text      | 
|    1   |           |
|    2   |           |
|    3   |           |
|    4   |           |
|    5   |           |
+--------+-----------+

Table B
+------+------+--------------+
| B-num|  date        |  A-num | 
|  22  |  01.08.2003  |     2  |
|  23  |  02.08.2003  |     2  | 
|  24  |  03.08.2003  |     1  |
|  25  |  04.08.2003  |     4  |
|  26  |  05.03.2003  |     4  |

I will update field text in table A with

UPDATE `Table A`,`Table B`
SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from                                           
",`Table B`.`date`,'/')
WHERE `Table A`.`A-num` = `Table B`.`A-num`

and come to this result:

Table A 
+--------+------------------------+
| A-num  | text                   | 
|    1   |  24 from 03 08 2003 /  |
|    2   |  22 from 01 08 2003 /  |       
|    3   |                        |
|    4   |  25 from 04 08 2003 /  |
|    5   |                        |
--------+-------------------------+

where only one field from Table B is accepted, but I will come to this result:

Table A 
+--------+--------------------------------------------+
| A-num  | text                                       | 
|    1   |  24 from 03 08 2003                        |
|    2   |  22 from 01 08 2003 / 23 from 02 08 2003 / |       
|    3   |                                            |
|    4   |  25 from 04 08 2003 / 26 from 05 03 2003 / |
|    5   |                                            |
+--------+--------------------------------------------+

tsconfig.json: Build:No inputs were found in config file

I have a tsconfig.json file that doesn't apply to any .ts files. It's in a separate folder. Instead I only use it as a base for other tsconfig files via "extends": "../Configs/tsconfig.json". As soon as I renamed the base config file to something else e.g. base-tsconfig.json (and updated the extends statements) the error went away and the extending still worked.

bash script read all the files in directory

A simple loop should be working:

for file in /var/*
do
    #whatever you need with "$file"
done

See bash filename expansion

How to correctly dismiss a DialogFragment?

Consider the below sample code snippet which demonstrates how to dismiss a dialog fragment safely:

DialogFragment dialogFragment = new DialogFragment();

/** 
 * do something
 */

// Now you want to dismiss the dialog fragment
if (dialogFragment.getDialog() != null && dialogFragment.getDialog().isShowing())
{
    // Dismiss the dialog
    dialogFragment.dismiss();
}

Happy Coding!

jquery save json data object in cookie

use JSON.stringify(userData) to coverty json object to string.

var dataStore = $.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));

and for getting back from cookie use JSON.parse()

var data=JSON.parse($.cookie("basket-data"))

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android and Facebook share intent

Facebook does not allow to share plain text data with Intent.EXTRA_TEXT but You can share text+link with facebook messanger using this, this works fine for me

            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, text+url link);
            sendIntent.setType("text/plain");
            sendIntent.setPackage("com.facebook.orca");
            startActivity(sendIntent);

How to join entries in a set into one string?

I wrote a method that handles the following edge-cases:

  • Set size one. A ", ".join({'abc'}) will return "a, b, c". My desired output was "abc".
  • Set including integers.
  • Empty set should returns ""
def set_to_str(set_to_convert, separator=", "):
        set_size = len(set_to_convert)
        if not set_size:
            return ""
        elif set_size == 1:
            (element,) = set_to_convert
            return str(element)
        else:
            return separator.join(map(str, set_to_convert))

Is Laravel really this slow?

Yes - Laravel IS really that slow. I built a POC app for this sake. Simple router, with a login form. I could only get 60 RPS with 10 concurrent connections on a $20 digital ocean server (few GB ram);

Setup:

2gb RAM
Php7.0
apache2.4
mysql 5.7
memcached server (for laravel session)

I ran optimizations, composer dump autoload etc, and it actually lowered the RPS to 43-ish.

The problem is the app responds in 200-400ms. I ran AB test from the local machine laravel was on (ie, not through web traffic); and I got only 112 RPS; with 200ms faster response time with an average of 300ms.

Comparatively, I tested my production PHP Native app running a few million requests a day on a AWS t2.medium (x3, load balanced). When I AB'd 25 concurrent connections from my local machine to that over web, through ELB, I got roughly 1200 RPS. Huge difference on a machine with load vs a laravel "login" page.

These are pages with Sessions (elasticache / memcached), Live DB lookups (cached queries via memcached), Assets pulled over CDNs, etc, etc, etc.

What I can tell, laravel sticks about 200-300ms load over things. Its fine for PHP Generated views, after all, that type of delay is tolerable on load. However, for PHP views that use Ajax/JS to handle small updates, it begins to feel sluggish.

I cant imagine what this system would look like with a multi tenant app while 200 bots crawl 100 pages each all at the same time.

Laravel is great for simple apps. Lumen is tolerable if you dont need to do anything fancy that would require middleware nonsense (IE, no multi tenant apps and custom domains, etc);

However, I never like starting with something that can bind and cause 300ms load for a "hello world" post.

If youre thinking "Who cares?"

.. Write a predictive search that relies on quick queries to respond to autocomplete suggestions across a few hundred thousand results. That 200-300ms lag will drive your users absolutely insane.

How to manually trigger validation with jQuery validate?

That library seems to allow validation for single elements. Just associate a click event to your button and try the following:

$("#myform").validate().element("#i1");

Examples here:

https://jqueryvalidation.org/Validator.element

Does Enter key trigger a click event?

Here is the correct SOLUTION! Since the button doesn't have a defined attribute type, angular maybe attempting to issue the keyup event as a submit request and triggers the click event on the button.

<button type="button" ...></button>

Big thanks to DeborahK!

Angular2 - Enter Key executes first (click) function present on the form

How can I use Bash syntax in Makefile targets?

One way that also works is putting it this way in the first line of the your target:

your-target: $(eval SHELL:=/bin/bash)
    @echo "here shell is $$0"

javascript: Disable Text Select

One might also use, works ok in all browsers, require javascript:

onselectstart = (e) => {e.preventDefault()}

Example:

_x000D_
_x000D_
onselectstart = (e) => {_x000D_
  e.preventDefault()_x000D_
  console.log("nope!")_x000D_
  }
_x000D_
Select me!
_x000D_
_x000D_
_x000D_


One other js alternative, by testing CSS supports, and disable userSelect, or MozUserSelect for Firefox.

_x000D_
_x000D_
let FF_x000D_
if (CSS.supports("( -moz-user-select: none )")){FF = 1} else {FF = 0}_x000D_
(FF===1) ? document.body.style.MozUserSelect="none" : document.body.style.userSelect="none"
_x000D_
Select me!
_x000D_
_x000D_
_x000D_


Pure css, same logic. Warning you will have to extend those rules to every browser, this can be verbose.

_x000D_
_x000D_
@supports (user-select:none) {_x000D_
  div {_x000D_
    user-select:none_x000D_
  }_x000D_
}_x000D_
_x000D_
@supports (-moz-user-select:none) {_x000D_
  div {_x000D_
    -moz-user-select:none_x000D_
  }_x000D_
}
_x000D_
<div>Select me!</div>
_x000D_
_x000D_
_x000D_

When to use MyISAM and InnoDB?

Read about Storage Engines.

MyISAM:

The MyISAM storage engine in MySQL.

  • Simpler to design and create, thus better for beginners. No worries about the foreign relationships between tables.
  • Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources. -- Mostly no longer true.
  • Full-text indexing. -- InnoDB has it now
  • Especially good for read-intensive (select) tables. -- Mostly no longer true.
  • Disk footprint is 2x-3x less than InnoDB's. -- As of Version 5.7, this is perhaps the only real advantage of MyISAM.

InnoDB:

The InnoDB storage engine in MySQL.

  • Support for transactions (giving you support for the ACID property).
  • Row-level locking. Having a more fine grained locking-mechanism gives you higher concurrency compared to, for instance, MyISAM.
  • Foreign key constraints. Allowing you to let the database ensure the integrity of the state of the database, and the relationships between tables.
  • InnoDB is more resistant to table corruption than MyISAM.
  • Support for large buffer pool for both data and indexes. MyISAM key buffer is only for indexes.
  • MyISAM is stagnant; all future enhancements will be in InnoDB. This was made abundantly clear with the roll out of Version 8.0.

MyISAM Limitations:

  • No foreign keys and cascading deletes/updates
  • No transactional integrity (ACID compliance)
  • No rollback abilities
  • 4,284,867,296 row limit (2^32) -- This is old default. The configurable limit (for many versions) has been 2**56 bytes.
  • Maximum of 64 indexes per table

InnoDB Limitations:

  • No full text indexing (Below-5.6 mysql version)
  • Cannot be compressed for fast, read-only (5.5.14 introduced ROW_FORMAT=COMPRESSED)
  • You cannot repair an InnoDB table

For brief understanding read below links:

  1. MySQL Engines: InnoDB vs. MyISAM – A Comparison of Pros and Cons
  2. MySQL Engines: MyISAM vs. InnoDB
  3. What are the main differences between InnoDB and MyISAM?
  4. MyISAM versus InnoDB
  5. What's the difference between MyISAM and InnoDB?
  6. MySql: MyISAM vs. Inno DB!

How to analyze information from a Java core dump?

Actually, VisualVM can process application core dump.

Just invoke "File/Add VM Coredump" and will add a new application in the application explorer. You can then take thread dump or heap dump of that JVM.

How do I put two increment statements in a C++ 'for' loop?

A common idiom is to use the comma operator which evaluates both operands, and returns the second operand. Thus:

for(int i = 0; i != 5; ++i,++j) 
    do_something(i,j);

But is it really a comma operator?

Now having wrote that, a commenter suggested it was actually some special syntactic sugar in the for statement, and not a comma operator at all. I checked that in GCC as follows:

int i=0;
int a=5;
int x=0;

for(i; i<5; x=i++,a++){
    printf("i=%d a=%d x=%d\n",i,a,x);
}

I was expecting x to pick up the original value of a, so it should have displayed 5,6,7.. for x. What I got was this

i=0 a=5 x=0
i=1 a=6 x=0
i=2 a=7 x=1
i=3 a=8 x=2
i=4 a=9 x=3

However, if I bracketed the expression to force the parser into really seeing a comma operator, I get this

int main(){
    int i=0;
    int a=5;
    int x=0;

    for(i=0; i<5; x=(i++,a++)){
        printf("i=%d a=%d x=%d\n",i,a,x);
    }
}

i=0 a=5 x=0
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8

Initially I thought that this showed it wasn't behaving as a comma operator at all, but as it turns out, this is simply a precedence issue - the comma operator has the lowest possible precedence, so the expression x=i++,a++ is effectively parsed as (x=i++),a++

Thanks for all the comments, it was an interesting learning experience, and I've been using C for many years!

update one table with data from another

UPDATE table1
SET 
`ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)

How/when to generate Gradle wrapper files?

  1. You generate it once, and again when you'd like to change the version of Gradle you use in the project. There's no need to generate is so often. Here are the docs. Just add wrapper task to build.gradle file and run this task to get the wrapper structure.

    Mind that you need to have Gradle installed to generate a wrapper. Great tool for managing g-ecosystem artifacts is SDKMAN!. To generate a gradle wrapper, add the following piece of code to build.gradle file:

    task wrapper(type: Wrapper) {
       gradleVersion = '2.0' //version required
    }
    

    and run:

    gradle wrapper
    

    task. Add the resulting files to SCM (e.g. git) and from now all developers will have the same version of Gradle when using Gradle Wrapper.

    With Gradle 2.4 (or higher) you can set up a wrapper without adding a dedicated task:

    gradle wrapper --gradle-version 2.3
    

    or

    gradle wrapper --gradle-distribution-url https://myEnterpriseRepository:7070/gradle/distributions/gradle-2.3-bin.zip
    

    All the details can be found here

From Gradle 3.1 --distribution-type option can be also used. The options are binary and all and bin. all additionally contains source code and documentation. all is also better when IDE is used, so the editor works better. Drawback is the build may last longer (need to download more data, pointless on CI server) and it will take more space.

  1. These are Gradle Wrapper files. You need to generate them once (for a particular version) and add to version control. If you need to change the version of Gradle Wrapper, change the version in build.gradle see (1.) and regenerate the files.

  2. Give a detailed example. Such file may have multiple purposes: multi-module project, responsibility separation, slightly modified script, etc.

  3. settings.gradle is responsible rather for structure of the project (modules, names, etc), while, gradle.properties is used for project's and Gradle's external details (version, command line arguments -XX, properties etc.)

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

Adding autocomplete="off" is not gonna cut it - it's ignored by Chrome.

Change input type attribute to type="search".
Google doesn't apply auto-fill to inputs with a type of search.

Method call if not null in C#

I agree with the answer by Kenny Eliasson. Go with Extension methods. Here is a brief overview of extension methods and your required IfNotNull method.

Extension Methods ( IfNotNull method )

Best Way to do Columns in HTML/CSS

You should probably consider using css3 for this though it does include the use of vendor prefixes.

I've knocked up a quick fiddle to demo but the crux is this.

<style>
.3col
{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count:3;
    column-gap:10px;
}
</style>
<div class="3col">
<p>col1</p>
<p>col2</p>
<p>col3</p>
</div>

Parallel foreach with asynchronous lambda

If you just want simple parallelism, you can do this:

var bag = new ConcurrentBag<object>();
var tasks = myCollection.Select(async item =>
{
  // some pre stuff
  var response = await GetData(item);
  bag.Add(response);
  // some post stuff
});
await Task.WhenAll(tasks);
var count = bag.Count;

If you need something more complex, check out Stephen Toub's ForEachAsync post.

What is the easiest way to ignore a JPA field during persistence?

use @Transient to make JPA ignoring the field.

but! Jackson will not serialize that field as well. to solve just add @JsonProperty

an example

@Transient
@JsonProperty
private boolean locked;

Simpler way to check if variable is not equal to multiple string values?

You need to multi value check. Try using the following code :

<?php
    $illstack=array(...............);
    $val=array('uk','bn','in');
    if(count(array_intersect($illstack,$val))===count($val)){ // all of $val is in $illstack}
?>

How to allow access outside localhost

  • Use ng serve --host<Your IP> --port<Required if any>.

  • ng serve --host=192.111.1.11 --port=4545.

  • You can now see the below line at the end of compilation.

Angular Live Development Server is listening on 192.111.1.11:4545, open your browser on http://192.111.1.11:4545/ **.

Is it possible to program iPhone in C++

I'm in the process of porting a computation-intensive Android app written in Java to iOS6. I'm doing this by porting the non-UI parts from Java to C++, writing the (minimal) UI parts in Obj-C, and wrapping the former in a (small) C interface using the standard C/C++ technique, so that it can be accessed from Obj-C, which is after all a superset of C.

This has been effective so far, and I haven't encountered any gotchas. It seems to be a legitimate approach, since Xcode lets you create C++ classes as well as Obj-C classes, and some of the official sample code does things this way. I haven't had to go outside any officially supported interfaces to do this.

There wouldn't seem to be much to gain from writing my remaining UI code in C++ even if it were possible, in view of the help given to you by the interface builder in Xcode, so my answer would be that you can use C++ for almost all your app, or as much of it as you find appropriate/convenient.

Execute method on startup in Spring

For a file StartupHousekeeper.java located in package com.app.startup,

Do this in StartupHousekeeper.java:

@Component
public class StartupHousekeeper {

  @EventListener(ContextRefreshedEvent.class)
  public void keepHouse() {
    System.out.println("This prints at startup.");
  }
}

And do this in myDispatcher-servlet.java:

<?xml version="1.0" encoding="UTF-8"?>
<beans>

    <mvc:annotation-driven />
    <context:component-scan base-package="com.app.startup" />

</beans>

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Blocks are the way to go. You can have complex parameters, type safety, and it's a lot simpler and safer than most of the old answers here. For example, you could just write:

[MONBlock performBlock:^{[obj setFrame:SOMETHING];} afterDelay:2];

Blocks allow you to capture arbitrary parameter lists, reference objects and variables.

Backing Implementation (basic):

@interface MONBlock : NSObject

+ (void)performBlock:(void(^)())pBlock afterDelay:(NSTimeInterval)pDelay;

@end

@implementation MONBlock

+ (void)imp_performBlock:(void(^)())pBlock
{
 pBlock();
}

+ (void)performBlock:(void(^)())pBlock afterDelay:(NSTimeInterval)pDelay
{
  [self performSelector:@selector(imp_performBlock:)
             withObject:[pBlock copy]
             afterDelay:pDelay];
}

@end

Example:

int main(int argc, const char * argv[])
{
 @autoreleasepool {
  __block bool didPrint = false;
  int pi = 3; // close enough =p

  [MONBlock performBlock:^{NSLog(@"Hello, World! pi is %i", pi); didPrint = true;} afterDelay:2];

  while (!didPrint) {
   [NSRunLoop.currentRunLoop runUntilDate:[NSDate dateWithTimeInterval:0.1 sinceDate:NSDate.date]];
  }

  NSLog(@"(Bye, World!)");
 }
 return 0;
}

Also see Michael's answer (+1) for another example.

Abstract methods in Python

You can't, with language primitives. As has been called out, the abc package provides this functionality in Python 2.6 and later, but there are no options for Python 2.5 and earlier. The abc package is not a new feature of Python; instead, it adds functionality by adding explicit "does this class say it does this?" checks, with manually-implemented consistency checks to cause an error during initialization if such declarations are made falsely.

Python is a militantly dynamically-typed language. It does not specify language primitives to allow you to prevent a program from compiling because an object does not match type requirements; this can only be discovered at run time. If you require that a subclass implement a method, document that, and then just call the method in the blind hope that it will be there.

If it's there, fantastic, it simply works; this is called duck typing, and your object has quacked enough like a duck to satisfy the interface. This works just fine even if self is the object you're calling such a method on, for the purposes of mandatory overrides due to base methods that need specific implementations of features (generic functions), because self is a convention, not anything actually special.

The exception is in __init__, because when your initializer is being called, the derived type's initializer hasn't, so it hasn't had the opportunity to staple its own methods onto the object yet.

If the method was't implemented, you'll get an AttributeError (if it's not there at all) or a TypeError (if something by that name is there but it's not a function or it didn't have that signature). It's up to you how you handle that- either call it programmer error and let it crash the program (and it "should" be obvious to a python developer what causes that kind of error there- an unmet duck interface), or catch and handle those exceptions when you discover that your object didn't support what you wish it did. Catching AttributeError and TypeError is important in a lot of situations, actually.

"UnboundLocalError: local variable referenced before assignment" after an if statement

FWIW: I got the same error for a different reason. I post the answer here not for the benefit of the OP, but for the benefit of those who may end up on this page due to its title... who might have made the same mistake I did.

I was confused why I was getting "local variable referenced before assignment" because I was calling a FUNCTION that I knew was already defined:

def job_fn(job):
  return job + ".job"

def do_something():
  a = 1
  b = 2
  job_fn = job_fn("foo")

do_something()

This was giving:

UnboundLocalError: local variable 'job_fn' referenced before assignment

Took me a while to see my obvious problem: I used a local variable named job_fn which masked the ability to see the prior function definition for job_fn.

NoClassDefFoundError for code in an Java library on Android

I have just figured out something with this error.

Just make sure that the library jar file contains the compiled R class under android.support.v7.appcompat package and copy all the res in the v7 appcompat support "project" in your ANDROID_SDK_HOME/extras/android/support/v7/appcompat folder.

I use Netbeans with the Android plugin and this solved my issue.

Absolute and Flexbox in React Native

This solution worked for me:

tabBarOptions: {
      showIcon: true,
      showLabel: false,
      style: {
        backgroundColor: '#000',
        borderTopLeftRadius: 40,
        borderTopRightRadius: 40,
        position: 'relative',
        zIndex: 2,
        marginTop: -48
      }
  }

Get list of all tables in Oracle?

Oracle database to display the names of all tables using below query

SELECT owner, table_name FROM dba_tables;

SELECT owner, table_name FROM all_tables;

SELECT table_name FROM user_tables;

vist more : http://www.plsqlinformation.com/2016/08/get-list-of-all-tables-in-oracle.html

The value violated the integrity constraints for the column

Delete empty rows from Excel after your last row of data!

Some times empty rows in Excel are still considered as data, therefore trying to import them in a table with one or more non nullable columns violates the constrains of the column.

Solution: select all of the empty rows on your sheet, even those after your last row of data, and click delete rows.

Obviously, if some of your data really does vioalte any of your table's constraints, then just fix your data to match the rules of your database..

Selenium and xPath - locating a link by containing text

Use this

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text(),'Some text')]

OR

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(.,'Some text')]

MySQL - How to parse a string value to DATETIME format inside an INSERT statement?

Use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert:

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
  (STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))

When should you NOT use a Rules Engine?

I don't really understand some points such as :
a) business people needs to understand business very well, or;
b) disagreement on business people don't need to know the rule.

For me, as a people just touching BRE, the benefit of BRE is so called to let system adapt to business change, hence it's focused on adaptive of change.
Does it matter if the rule set up at time x is different from the rule set up at time y because of:
a) business people don't understand business, or;
b) business people don't understand rules?

How do you create a Swift Date object?

This is best done using an extension to the existing NSDate class.

The following extension adds a new initializer which will create a date in the current locale using the date string in the format you specified.

extension NSDate
{
    convenience
      init(dateString:String) {
      let dateStringFormatter = NSDateFormatter()
      dateStringFormatter.dateFormat = "yyyy-MM-dd"
      dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
      let d = dateStringFormatter.dateFromString(dateString)!
      self.init(timeInterval:0, sinceDate:d)
    }
 }

Now you can create an NSDate from Swift just by doing:

NSDate(dateString:"2014-06-06")

Please note that this implementation does not cache the NSDateFormatter, which you might want to do for performance reasons if you expect to be creating many NSDates in this way.

Please also note that this implementation will simply crash if you try to initialize an NSDate by passing in a string that cannot be parsed correctly. This is because of the forced unwrap of the optional value returned by dateFromString. If you wanted to return a nil on bad parses, you would ideally use a failible initializer; but you cannot do that now (June 2015), because of a limitation in Swift 1.2, so then you're next best choice is to use a class factory method.

A more elaborate example, which addresses both issues, is here: https://gist.github.com/algal/09b08515460b7bd229fa .


Update for Swift 5

extension Date {
    init(_ dateString:String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
        let date = dateStringFormatter.date(from: dateString)!
        self.init(timeInterval:0, since:date)
    }
}

Open firewall port on CentOS 7

To view open ports, use the following command:

firewall-cmd --list-ports

We use the following to see services whose ports are open:

firewall-cmd --list-services

We use the following to see services whose ports are open and see open ports:

firewall-cmd --list-all

To add a service to the firewall, we use the following command, in which case the service will use any port to open in the firewall:

firewall-cmd --add-services=ntp 

For this service to be permanently open we use the following command:

firewall-cmd -add-service=ntp --permanent 

To add a port, use the following command:

firewall-cmd --add-port=132/tcp  --permanent

How can I permanently enable line numbers in IntelliJ?

1st way: Go to View => Active Editor => show line numbers

enter image description here

2nd way Go to Android Studio => Preferences => Editor=> Appearance => set Checked "Show Line Numbers"

enter image description here

enter image description here

How do I get the path of the assembly the code is in?

All of the proposed answers work when the developer can change the code to include the required snippet, but if you wanted to do this without changing any code you could use Process Explorer.

It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult.

I've written a full description of how do this for a dll inside II - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/

Fit image to table cell [Pure HTML]

Use your developer's tool of choice and check if the tr, td or img has any padding or margins.

Android REST client, Sample?

We have open-sourced our lightweight async REST client library for Android, you might find it useful if you have minimal requirements and don't want to handle the multithreading yourself - it is very OK for basic communications but not a full-blown REST client library.

It's called libRESTfulClient and can be found on GitHub.

PowerShell: Store Entire Text File Contents in Variable

On a side note, in PowerShell 3.0 you can use the Get-Content cmdlet with the new Raw switch:

$text = Get-Content .\file.txt -Raw 

Cannot lower case button text in android studio

You could set like this

button.setAllCaps(false);

programmatically

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

Failed to find 'ANDROID_HOME' environment variable

This solved my problem. Add below to your system path

PATH_TO_android\platforms

PATH_TO_android\platform-tools

Matplotlib/pyplot: How to enforce axis range?

To answer my own question, the trick is to turn auto scaling off...

p.axis([0.0,600.0, 10000.0,20000.0])
ax = p.gca()
ax.set_autoscale_on(False)

Drop Down Menu/Text Field in one

You can use the <datalist> tag instead of the <select> tag.

<input list="browsers" name="browser" id="browser">
<datalist id="browsers">
  <option value="Edge">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>

How to fix a collation conflict in a SQL Server query?

Adding to the accepted answer, you can used DATABASE_DEFAULT as encoding.

This allows database to make choice for you and your code becomes more portable.

SELECT MyColumn
FROM 
    FirstTable a
        INNER JOIN SecondTable b
            ON a.MyID COLLATE DATABASE_DEFAULT = b.YourID COLLATE DATABASE_DEFAULT

Play an audio file using jQuery when a button is clicked

Which approach?

You can play audio with <audio> tag or <object> or <embed>. Lazy loading(load when you need it) the sound is the best approach if its size is small. You can create the audio element dynamically, when its loaded you can start it with .play() and pause it with .pause().

Things we used

We will use canplay event to detect our file is ready to be played.

There is no .stop() function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop() function we first pause the file then reset its time.

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

Example Guide

  1. When document is ready we created an audio element dynamically
  2. We set its source with the audio we want to play.
  3. We used 'ended' event to start file again.

When the currentTime is equal to its duration audio file will stop playing. Whenever you use play(), it will start from the beginning.

  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var audioElement = document.createElement('audio');_x000D_
    audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');_x000D_
    _x000D_
    audioElement.addEventListener('ended', function() {_x000D_
        this.play();_x000D_
    }, false);_x000D_
    _x000D_
    audioElement.addEventListener("canplay",function(){_x000D_
        $("#length").text("Duration:" + audioElement.duration + " seconds");_x000D_
        $("#source").text("Source:" + audioElement.src);_x000D_
        $("#status").text("Status: Ready to play").css("color","green");_x000D_
    });_x000D_
    _x000D_
    audioElement.addEventListener("timeupdate",function(){_x000D_
        $("#currentTime").text("Current second:" + audioElement.currentTime);_x000D_
    });_x000D_
    _x000D_
    $('#play').click(function() {_x000D_
        audioElement.play();_x000D_
        $("#status").text("Status: Playing");_x000D_
    });_x000D_
    _x000D_
    $('#pause').click(function() {_x000D_
        audioElement.pause();_x000D_
        $("#status").text("Status: Paused");_x000D_
    });_x000D_
    _x000D_
    $('#restart').click(function() {_x000D_
        audioElement.currentTime = 0;_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
    <h2>Sound Information</h2>_x000D_
    <div id="length">Duration:</div>_x000D_
    <div id="source">Source:</div>_x000D_
    <div id="status" style="color:red;">Status: Loading</div>_x000D_
    <hr>_x000D_
    <h2>Control Buttons</h2>_x000D_
    <button id="play">Play</button>_x000D_
    <button id="pause">Pause</button>_x000D_
    <button id="restart">Restart</button>_x000D_
    <hr>_x000D_
    <h2>Playing Information</h2>_x000D_
    <div id="currentTime">0</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to test that a registered variable is not empty?

(ansible 2.9.6 ansible-lint 4.2.0)

See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string

    when: test_myscript.stderr != ""

Correct syntax and also "Ansible Galaxy Warning-Free" option is

    when: test_myscript.stderr | length > 0

Quoting from source code

"Use when: var|length > 0 rather than when: var != "" (or ' 'conversely when: var|length == 0 rather than when: var == "")"


Notes

  1. Test empty bare variable e.g.
    - debug:
        msg: "Empty string '{{ var }}' evaluates to False"
      when: not var
      vars:
        var: ''

    - debug:
        msg: "Empty list {{ var }} evaluates to False"
      when: not var
      vars:
        var: []

give

    "msg": "Empty string '' evaluates to False"
    "msg": "Empty list [] evaluates to False"
  1. But, testing non-empty bare variable string depends on CONDITIONAL_BARE_VARS. Setting ANSIBLE_CONDITIONAL_BARE_VARS=false the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true the condition will fail
    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var
      vars:
        var: 'abc'

gives

fatal: [localhost]: FAILED! => 
  msg: |-
    The conditional check 'var' failed. The error was: error while 
    evaluating conditional (var): 'abc' is undefined

Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'). When the filter bool is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true and ANSIBLE_CONDITIONAL_BARE_VARS=false have no effect

    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var|bool
      vars:
        var: 'abc'

gives

skipping: [localhost]
  1. Quoting from Porting guide 2.8 Bare variables in conditionals
  - include_tasks: teardown.yml
    when: teardown

  - include_tasks: provision.yml
    when: not teardown

" based on a variable you define as a string (with quotation marks around it):"

  • In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'

  • In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'

  • In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')

  1. Quoting from CONDITIONAL_BARE_VARS

"Expect that this setting eventually will be deprecated after 2.12"

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

First, you should know what an Optional value is. You can step to The Swift Programming Language for detail.

Second, you should know the optional value has two statuses. One is the full value, and the other is a nil value. So before you implement an optional value, you should check which state it is.

You can use if let ... or guard let ... else and so on.

One other way, if you don't want to check the variable state before your implementation, you can also use var buildingName = buildingName ?? "buildingName" instead.

Can my enums have friendly names?

You could use the Description attribute, as Yuriy suggested. The following extension method makes it easy to get the description for a given value of the enum:

public static string GetDescription(this Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
            DescriptionAttribute attr = 
                   Attribute.GetCustomAttribute(field, 
                     typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attr != null)
            {
                return attr.Description;
            }
        }
    }
    return null;
}

You can use it like this:

public enum MyEnum
{
    [Description("Description for Foo")]
    Foo,
    [Description("Description for Bar")]
    Bar
}

MyEnum x = MyEnum.Foo;
string description = x.GetDescription();

Difference between margin and padding?

One thing I just noticed but none of above answers mentioned. If I have a dynamically created DOM element which is initialized with empty inner html content, it's a good practice to use margin instead of padding if you don't want this empty element occupy any space except its content is created.

How to preserve insertion order in HashMap?

HashMap is unordered per the second line of the documentation:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. This link can help you find the most appropriate collection to use.

Java : Convert formatted xml file to one line string

Underscore-java library has static method U.formatXml(xmlstring). I am the maintainer of the project. Live example

import com.github.underscore.lodash.U;
import com.github.underscore.lodash.Xml;

public class MyClass {
    public static void main(String[] args) {
        System.out.println(U.formatXml("<a>\n  <b></b>\n  <b></b>\n</a>",
        Xml.XmlStringBuilder.Step.COMPACT));
    }
}

// output: <a><b></b><b></b></a>

How to pass an ArrayList to a varargs method parameter?

Source article: Passing a list as an argument to a vararg method


Use the toArray(T[] arr) method.

.getMap(locations.toArray(new WorldLocation[locations.size()]))

(toArray(new WorldLocation[0]) also works, but you would allocate a zero-length array for no reason.)


Here's a complete example:

public static void method(String... strs) {
    for (String s : strs)
        System.out.println(s);
}

...
    List<String> strs = new ArrayList<String>();
    strs.add("hello");
    strs.add("world");
    
    method(strs.toArray(new String[strs.size()]));
    //     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...

Troubleshooting "Illegal mix of collations" error in mysql

One another source of the issue with collations is mysql.proc table. Check collations of your storage procedures and functions:

SELECT
  p.db, p.db_collation, p.type, COUNT(*) cnt
FROM mysql.proc p
GROUP BY p.db, p.db_collation, p.type;

Also pay attention to mysql.proc.collation_connection and mysql.proc.character_set_client columns.

PHP Get Highest Value from Array

Don't sort the array to get the largest value.

Get the max value:

$value = max($array);

Get the corresponding key:

$key = array_search($value, $array);

Vertical Tabs with JQuery?

super simple function that will allow you to create your own tab / accordion structure here: http://jsfiddle.net/nabeezy/v36DF/

bindSets = function (tabClass, tabClassActive, contentClass, contentClassHidden) {
        //Dependent on jQuery
        //PARAMETERS
        //tabClass: 'the class name of the DOM elements that will be clicked',
        //tabClassActive: 'the class name that will be applied to the active tabClass element when clicked (must write your own css)',
        //contentClass: 'the class name of the DOM elements that will be modified when the corresponding tab is clicked',
        //contentClassHidden: 'the class name that will be applied to all contentClass elements except the active one (must write your own css)',
        //MUST call bindSets() after dom has rendered

        var tabs = $('.' + tabClass);
        var tabContent = $('.' + contentClass);
        if(tabs.length !== tabContent.length){console.log('JS bindSets: sets contain a different number of elements')};
        tabs.each(function (index) {
            this.matchedElement = tabContent[index];
            $(this).click(function () {
                tabs.each(function () {
                    this.classList.remove(tabClassActive);
                });
                tabContent.each(function () {
                    this.classList.add(contentClassHidden);
                });
                this.classList.add(tabClassActive);
                this.matchedElement.classList.remove(contentClassHidden);
            });
        })
        tabContent.each(function () {
            this.classList.add(contentClassHidden);
        });

        //tabs[0].click();
    }
bindSets('tabs','active','content','hidden');

How to get root access on Android emulator?

I found that default API 23 x86_64 emulator is rooted by default.

PHP header(Location: ...): Force URL change in address bar

I had the same problem with posting a form. What I did was that turning off the data-ajax.

How to handle click event in Button Column in Datagridview?

You've added a button to your DataGridView and you want to run some code when it's clicked.
Easy peasy - just follow these steps:

Don'ts:

First, here's what NOT to do:

I would avoid the suggestions in some of the other answers here and even provided by the documentation at MSDN to hardcode the column index or column name in order to determine if a button was clicked. The click event registers for the entire grid, so somehow you need to determine that a button was clicked, but you should not do so by assuming that your button lives in a particular column name or index... there's an easier way...

Also, be careful which event you want to handle. Again, the documentation and many examples get this wrong. Most examples handle the CellClick event which will fire:

when any part of a cell is clicked.

...but will also fire whenever the row header is clicked. This necessitates adding extra code simply to determine if the e.RowIndex value is less than 0

Instead handle the CellContentClick which only occurs:

when the content within a cell is clicked

For whatever reason, the column header is also considered 'content' within a cell, so we'll still have to check for that below.

Dos:

So here's what you should do:

First, cast the sender to type DataGridView to expose it's internal properties at design time. You can modify the type on the parameter, but that can sometimes make adding or removing handlers tricky.

Next, to see if a button was clicked, just check to make sure that the column raising the event is of type DataGridViewButtonColumn. Because we already cast the sender to type DataGridView, we can get the Columns collection and select the current column using e.ColumnIndex. Then check if that object is of type DataGridViewButtonColumn.

Of course, if you need to distinguish between multiple buttons per grid, you can then select based on the column name or index, but that shouldn't be your first check. Always make sure a button was clicked first and then handle anything else appropriately. In most cases where you only have a single button per grid, you can jump right off to the races.

Putting it all together:

C#:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    var senderGrid = (DataGridView)sender;

    if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
        e.RowIndex >= 0)
    {
        //TODO - Button Clicked - Execute Code Here
    }
}

VB:

Private Sub DataGridView1_CellContentClick(sender As System.Object, e As DataGridViewCellEventArgs) _
                                           Handles DataGridView1.CellContentClick
    Dim senderGrid = DirectCast(sender, DataGridView)

    If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso
       e.RowIndex >= 0 Then
        'TODO - Button Clicked - Execute Code Here
    End If

End Sub

Update 1 - Custom Event

If you wanted to have a little bit of fun, you can add your own event to be raised whenever a button is clicked on the DataGrid. You can't add it to the DataGrid itself, without getting messy with inheritance etc., but you can add a custom event to your form and fire it when appropriate. It's a little more code, but the upside is that you've separated out what you want to do when a button is clicked with how to determine if a button was clicked.

Just declare an event, raise it when appropriate, and handle it. It will look like this:

Event DataGridView1ButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs)

Private Sub DataGridView1_CellContentClick(sender As System.Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    Dim senderGrid = DirectCast(sender, DataGridView)
    If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso e.RowIndex >= 0 Then
        RaiseEvent DataGridView1ButtonClick(senderGrid, e)
    End If
End Sub

Private Sub DataGridView1_ButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs) Handles Me.DataGridView1ButtonClick
    'TODO - Button Clicked - Execute Code Here
End Sub

Update 2 - Extended Grid

What would be great is if we were working with a grid that just did these things for us. We could answer the initial question easily: you've added a button to your DataGridView and you want to run some code when it's clicked. Here's an approach that extends the DataGridView. It might not be worth the hassle of having to deliver a custom control with every library, but at least it maximally reuses the code used for determining if a button was clicked.

Just add this to your assembly:

Public Class DataGridViewExt : Inherits DataGridView

    Event CellButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs)

    Private Sub CellContentClicked(sender As System.Object, e As DataGridViewCellEventArgs) Handles Me.CellContentClick
        If TypeOf Me.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso e.RowIndex >= 0 Then
            RaiseEvent CellButtonClick(Me, e)
        End If
    End Sub

End Class

That's it. Never touch it again. Make sure your DataGrid is of type DataGridViewExt which should work exactly the same as a DataGridView. Except it will also raise an extra event that you can handle like this:

Private Sub DataGridView1_ButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs) _
                                      Handles DataGridView1.CellButtonClick
    'TODO - Button Clicked - Execute Code Here
End Sub

In VBA get rid of the case sensitivity when comparing words?

It is a bit of hack but will do the task.

Function equalsIgnoreCase(str1 As String, str2 As String) As Boolean
    equalsIgnoreCase = LCase(str1) = LCase(str2)
End Function

Non-static variable cannot be referenced from a static context

Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.

Static variables are marked as static and instance variables doesn't have specific keyword.

What is a practical use for a closure in JavaScript?

Suppose, you want to count the number of times user clicked a button on a webpage.

For this, you are triggering a function on onclick event of button to update the count of the variable

<button onclick="updateClickCount()">click me</button>

Now there could be many approaches like:

  1. You could use a global variable, and a function to increase the counter:

     var counter = 0;
    
     function updateClickCount() {
         ++counter;
         // Do something with counter
     }
    

    But, the pitfall is that any script on the page can change the counter, without calling updateClickCount().


  1. Now, you might be thinking of declaring the variable inside the function:

     function updateClickCount() {
         var counter = 0;
         ++counter;
         // Do something with counter
     }
    

    But, hey! Every time updateClickCount() function is called, the counter is set to 1 again.


  1. Thinking about nested functions?

    Nested functions have access to the scope "above" them.

    In this example, the inner function updateClickCount() has access to the counter variable in the parent function countWrapper():

     function countWrapper() {
         var counter = 0;
         function updateClickCount() {
             ++counter;
             // Do something with counter
         }
         updateClickCount();
         return counter;
     }
    

    This could have solved the counter dilemma, if you could reach the updateClickCount() function from the outside and you also need to find a way to execute counter = 0 only once not everytime.


  1. Closure to the rescue! (self-invoking function):

     var updateClickCount = (function(){
         var counter = 0;
    
         return function(){
             ++counter;
             // Do something with counter
         }
     })();
    

    The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.

    This way updateClickCount becomes a function. The "wonderful" part is that it can access the counter in the parent scope.

    This is called a JavaScript closure. It makes it possible for a function to have "private" variables.

    The counter is protected by the scope of the anonymous function, and can only be changed using the add function!

A more lively example on closures

_x000D_
_x000D_
<script>
var updateClickCount = (function(){
    var counter = 0;

    return function(){
        ++counter;
        document.getElementById("spnCount").innerHTML = counter;
    }
})();
</script>

<html>
<button onclick="updateClickCount()">click me</button>
<div> you've clicked
    <span id="spnCount"> 0 </span> times!
</div>
</html>
_x000D_
_x000D_
_x000D_


Reference: JavaScript Closures

Show/Hide Multiple Divs with Jquery

If you want to be able to show / hide singular divs and / or groups of divs with less code, just apply several classes to them, to insert them into groups if needed.

Example :

.group1 {}
.group2 {}
.group3 {}

<div class="group3"></div>
<div class="group1 group2"></div>
<div class="group1 group3 group2"></div>

Then you just need to use an identifier to link the action to he target, and with 5,6 lines of jquery code you have everything you need.

How to get the date 7 days earlier date from current date in Java

Or use JodaTime:

DateTime lastWeek = new DateTime().minusDays(7);

Removing numbers from string

Not sure if your teacher allows you to use filters but...

filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h")

returns-

'aaasdffgh'

Much more efficient than looping...

Example:

for i in range(10):
  a.replace(str(i),'')

What's the difference between "git reset" and "git checkout"?

The key difference in a nutshell is that reset moves the current branch reference, while checkout does not (it moves HEAD).

As the Pro Git book explains under Reset Demystified,

The first thing reset will do is move what HEAD points to. This isn’t the same as changing HEAD itself (which is what checkout does); reset moves the branch that HEAD is pointing to. This means if HEAD is set to the master branch (i.e. you’re currently on the master branch), running git reset 9e5e6a4 will start by making master point to 9e5e6a4. [emphasis added]

See also VonC's answer for a very helpful text and diagram excerpt from the same article, which I won't duplicate here.

Of course there are a lot more details about what effects checkout and reset can have on the index and the working tree, depending on what parameters are used. There can be lots of similarities and differences between the two commands. But as I see it, the most crucial difference is whether they move the tip of the current branch.

SQL Server: Cannot insert an explicit value into a timestamp column

You can't insert the values into timestamp column explicitly. It is auto-generated. Do not use this column in your insert statement. Refer http://msdn.microsoft.com/en-us/library/ms182776(SQL.90).aspx for more details.

You could use a datetime instead of a timestamp like this:

create table demo (
    ts datetime
)

insert into demo select current_timestamp

select ts from demo

Returns:

2014-04-04 09:20:01.153

php check if array contains all array values from another array

A bit shorter with array_diff

$musthave = array('a','b');
$test1 = array('a','b','c');
$test2 = array('a','c');

$containsAllNeeded = 0 == count(array_diff($musthave, $test1));

// this is TRUE

$containsAllNeeded = 0 == count(array_diff($musthave, $test2));

// this is FALSE

window.onload vs <body onload=""/>

Sorry for reincarnation of this thread again after another 3 years of sleeping, but perhaps I have finally found the indisputable benefit of window.onload=fn1; over <body onload="fn1()">. It concerns the JS modules or ES modules: when your onload handler resides in "classical" JS file (i.e. referred without <script type="module" … >, either way is possible; when your onload handler resides in "module" JS file (i.e. referred with <script type="module" … >, the <body onload="fn1()"> will fail with "fn1() is not defined" error. The reason perhaps is that the ES modules are not loaded before HTML is parsed … but it is just my guess. Anyhow, window.onload=fn1; works perfectly with modules ...

How to loop through elements of forms with JavaScript?

A modern ES6 approach. Select the form with any method you like. Use the spread operator to convert HTMLFormControlsCollection to an Array, then the forEach method is available. [...form.elements].forEach

Update: Array.from is a nicer alternative to spread Array.from(form.elements) it's slightly clearer behaviour.


An example below iterates over every input in the form. You can filter out certain input types by checking input.type != "submit"

_x000D_
_x000D_
const forms = document.querySelectorAll('form');
const form = forms[0];

Array.from(form.elements).forEach((input) => {
  console.log(input);
});
_x000D_
<div>
  <h1>Input Form Selection</h1>
  <form>
    <label>
      Foo
      <input type="text" placeholder="Foo" name="Foo" />
    </label>
    <label>
      Password
      <input type="password" placeholder="Password" />
    </label>
    <label>
      Foo
      <input type="text" placeholder="Bar" name="Bar" />
    </label>
    <span>Ts &amp; Cs</span>
    <input type="hidden" name="_id" />
    <input type="submit" name="_id" />
  </form>
</div>
_x000D_
_x000D_
_x000D_

Rotate and translate

The reason is because you are using the transform property twice. Due to CSS rules with the cascade, the last declaration wins if they have the same specificity. As both transform declarations are in the same rule set, this is the case.

What it is doing is this:

  1. rotate the text 90 degrees. Ok.
  2. translate 50% by 50%. Ok, this is same property as step one, so do this step and ignore step 1.

See http://jsfiddle.net/Lx76Y/ and open it in the debugger to see the first declaration overwritten

As the translate is overwriting the rotate, you have to combine them in the same declaration instead: http://jsfiddle.net/Lx76Y/1/

To do this you use a space separated list of transforms:

#rotatedtext {
    transform-origin: left;
    transform: translate(50%, 50%) rotate(90deg) ;
}

Remember that they are specified in a chain, so the translate is applied first, then the rotate after that.

Java ArrayList of Arrays?

ArrayList<String[]> action = new ArrayList<String[]>();

Don't need String[2];

Print string to text file

In case you want to pass multiple arguments you can use a tuple

price = 33.3
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))

More: Print multiple arguments in python

What is Unicode, UTF-8, UTF-16?

Originally, Unicode was intended to have a fixed-width 16-bit encoding (UCS-2). Early adopters of Unicode, like Java and Windows NT, built their libraries around 16-bit strings.

Later, the scope of Unicode was expanded to include historical characters, which would require more than the 65,536 code points a 16-bit encoding would support. To allow the additional characters to be represented on platforms that had used UCS-2, the UTF-16 encoding was introduced. It uses "surrogate pairs" to represent characters in the supplementary planes.

Meanwhile, a lot of older software and network protocols were using 8-bit strings. UTF-8 was made so these systems could support Unicode without having to use wide characters. It's backwards-compatible with 7-bit ASCII.

Oracle - Insert New Row with Auto Incremental ID

There is no built-in auto_increment in Oracle.

You need to use sequences and triggers.

Read here how to do it right. (Step-by-step how-to for "Creating auto-increment columns in Oracle")

How can I change the color of a Google Maps marker?

With version 3 of the Google Maps API, the easiest way to do this may be by grabbing a custom icon set, like the one that Benjamin Keen has created here:

http://www.benjaminkeen.com/?p=105

If you put all of those icons at the same place as your map page, you can colorize a Marker simply by using the appropriate icon option when creating it:

var beachMarker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  icon: 'brown_markerA.png'
});

This is super-easy, and is the approach I'm using for the project I'm working on currently.

How to use variables in SQL statement in Python?

Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

or (e.g. with sqlite3 from the Python standard library):

cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))

or others yet (after VALUES you could have (:1, :2, :3) , or "named styles" (:fee, :fie, :fo) or (%(fee)s, %(fie)s, %(fo)s) where you pass a dict instead of a map as the second argument to execute). Check the paramstyle string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!

How to return XML in ASP.NET?

Below is the server side code that would call the handler and recieve the stream data and loads into xml doc

 Stream stream = null;
       **Create a web request with the specified URL**
        WebRequest myWebRequest = WebRequest.Create(@"http://localhost/XMLProvider/XMLProcessorHandler.ashx");
        **Senda a web request and wait for response.**
        WebResponse webResponse = myWebRequest.GetResponse();
        **Get the stream object from response object**
        stream = webResponse.GetResponseStream();

       XmlDocument xmlDoc = new XmlDocument();
      **Load stream data into xml**
       xmlDoc.Load(stream);

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I was able to fix this on Windows 7 64-bit running Python 3.4.3 by running the set command at a command prompt to determine the existing Visual Studio tools environment variable; in my case it was VS140COMNTOOLS for Visual Studio Community 2015.

Then run the following (substituting the variable on the right-hand side if yours has a different name):

set VS100COMNTOOLS=%VS140COMNTOOLS%

This allowed me to install the PyCrypto module that was previously giving me the same error as the OP.

For a more permanent solution, add this environment variable to your Windows environment via Control Panel ("Edit the system environment variables"), though you might need to use the actual path instead of the variable substitution.

HTML5 and frameborder

How about using the same for technique for "fooling" the validator with Javascript by sticking a target attribute in XHTML <a onclick="this.target='_blank'">?

  • onsomething = " this.frameborder = '0' "

<iframe onload = " this.frameborder='0' " src="menu.html" id="menu"> </iframe>

Or getElementsByTagName]("iframe")1 adding this attribute for all iframes on the page?

Haven't tested this because I've done something which means that nothing is working in IE less than 9! :) So while I'm sorting that out ... :)

How to pass multiple values to single parameter in stored procedure

USE THIS

I have had this exact issue for almost 2 weeks, extremely frustrating but I FINALLY found this site and it was a clear walk-through of what to do.

http://blog.summitcloud.com/2010/01/multivalue-parameters-with-stored-procedures-in-ssrs-sql/

I hope this helps people because it was exactly what I was looking for

Oracle SQL: Use sequence in insert with Select Statement

Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like

INSERT INTO HISTORICAL_CAR_STATS (
    HISTORICAL_CAR_STATS_ID, 
    YEAR,
    MONTH, 
    MAKE,
    MODEL,
    REGION,
    AVG_MSRP,
    CNT) 
SELECT MY_SEQ.nextval,
       year,
       month,
       make,
       model,
       region,
       avg_msrp,
       cnt
  FROM (SELECT '2010' year,
               '12' month,
               'ALL' make,
               'ALL' model,
               REGION,
               sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
               sum(cnt) cnt
          FROM HISTORICAL_CAR_STATS
         WHERE YEAR = '2010' 
           AND MONTH = '12'
           AND MAKE != 'ALL' 
         GROUP BY REGION)

How to determine the last Row used in VBA including blank spaces in between

I use the following:

lastrow = ActiveSheet.Columns("A").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row

It'll find the last row in a specific column. If you want the last used row for any column then:

lastrow = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row

Set cellpadding and cellspacing in CSS?

CSS:

selector{
    padding:0 0 10px 0; // Top left bottom right 
}

jQuery access input hidden value

There is nothing special about <input type="hidden">:

$('input[type="hidden"]').val()

Swift extract regex matches

Most of the solutions above only give the full match as a result ignoring the capture groups e.g.: ^\d+\s+(\d+)

To get the capture group matches as expected you need something like (Swift4) :

public extension String {
    public func capturedGroups(withRegex pattern: String) -> [String] {
        var results = [String]()

        var regex: NSRegularExpression
        do {
            regex = try NSRegularExpression(pattern: pattern, options: [])
        } catch {
            return results
        }
        let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.count))

        guard let match = matches.first else { return results }

        let lastRangeIndex = match.numberOfRanges - 1
        guard lastRangeIndex >= 1 else { return results }

        for i in 1...lastRangeIndex {
            let capturedGroupIndex = match.range(at: i)
            let matchedString = (self as NSString).substring(with: capturedGroupIndex)
            results.append(matchedString)
        }

        return results
    }
}

How can I change default dialog button text color in android 5

The color of the buttons and other text can also be changed via theme:

values-21/styles.xml

<style name="AppTheme" parent="...">
  ...
  <item name="android:timePickerDialogTheme">@style/AlertDialogCustom</item>
  <item name="android:datePickerDialogTheme">@style/AlertDialogCustom</item>
  <item name="android:alertDialogTheme">@style/AlertDialogCustom</item>
</style>

<style name="AlertDialogCustom" parent="android:Theme.Material.Light.Dialog.Alert">
  <item name="android:colorPrimary">#00397F</item>
  <item name="android:colorAccent">#0AAEEF</item>
</style>

The result:

Dialog Date picker

How to change an application icon programmatically in Android?

As mentioned before you need use <activity-alias> to change the application icon. To avoid killing the application after enabling appropriate activity-alias you need to do this after the application is killed. To find out if the application was killed you can use this method

  1. Create activity aliases in AndroidManifest.xml
<activity android:name=".ui.MainActivity"/>

<activity-alias
    android:name=".one"
    android:icon="@mipmap/ic_launcher_one"
    android:targetActivity=".ui.MainActivity"
    android:enabled="true">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity-alias>

<activity-alias
    android:name=".two"
    android:icon="@mipmap/ic_launcher_two"
    android:targetActivity=".ui.MainActivity"
    android:enabled="false">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity-alias>
  1. ?reate a service that will change the active activity-alias after killing the application. You need store the name of new active activity-alias somewhere (e.g. SharedPreferences)
class ChangeAppIconService: Service() {
    private val aliases = arrayOf(".one", ".two")

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onTaskRemoved(rootIntent: Intent?) {
        changeAppIcon()
        stopSelf()
    }

    fun changeAppIcon() {
        val sp = getSharedPreferences("appSettings", Context.MODE_PRIVATE)

        sp.getString("activeActivityAlias", ".one").let { aliasName ->
            if (!isAliasEnabled(aliasName)) {
                setAliasEnabled(aliasName)
            }
        }
    }

    private fun isAliasEnabled(aliasName: String): Boolean {
        return packageManager.getComponentEnabledSetting(
            ComponentName(
                this,
                "${BuildConfig.APPLICATION_ID}$aliasName"
            )
        ) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
    }

    private fun setAliasEnabled(aliasName: String) {
        aliases.forEach {
            val action = if (it == aliasName)
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED
            else
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                
            packageManager.setComponentEnabledSetting(
                ComponentName(
                    this,
                    "${BuildConfig.APPLICATION_ID}$aliasName"
                ),
                action,
                PackageManager.DONT_KILL_APP
            )
        }
    }
}
  1. Add service to AndroidManifest.xml
<service 
    android:name=".ChangeAppIconService"
    android:stopWithTask="false"
    />
  1. Start ChangeAppIconService in MainActivity.onCreate
class MainActivity: Activity {

    ...

    override fun onCreate(savedInstanceState: Bundle?) {
       ...

       startService(Intent(this, ChangeAppIconService::class.java))

       ...
    }

    ...

}

Reading string by char till end of line C/C++

The answer to your original question

How to read a string one char at the time, and stop when you reach end of line?

is, in C++, very simply, namely: use getline. The link shows a simple example:

#include <iostream>
#include <string>
int main () {
  std::string name;
  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name);
  std::cout << "Hello, " << name << "!\n";
  return 0;
}

Do you really want to do this in C? I wouldn't! The thing is, in C, you have to allocate the memory in which to place the characters you read in? How many characters? You don't know ahead of time. If you allocate too few characters, you will have to allocate a new buffer every time to realize you reading more characters than you made room for. If you over-allocate, you are wasting space.

C is a language for low-level programming. If you are new to programming and writing simple applications for reading files line-by-line, just use C++. It does all that memory allocation for you.

Your later questions regarding "\0" and end-of-lines in general were answered by others and do apply to C as well as C++. But if you are using C, please remember that it's not just the end-of-line that matters, but memory allocation as well. And you will have to be careful not to overrun your buffer.

Coarse-grained vs fine-grained

Coarse-grained: A few ojects hold a lot of related data that's why services have broader scope in functionality. Example: A single "Account" object holds the customer name, address, account balance, opening date, last change date, etc. Thus: Increased design complexity, smaller number of cells to various operations

Fine-grained: More objects each holding less data that's why services have more narrow scope in functionality. Example: An Account object holds balance, a Customer object holds name and address, a AccountOpenings object holds opening date, etc. Thus: Decreased design complexity , higher number of cells to various service operations. These are relationships defined between these objects.

PHP salt and hash SHA256 for login password

You can't do that because you can not know the salt at a precise time. Below, a code who works in theory (not tested for the syntaxe)

<?php
$password1 = $_POST['password'];
$salt      = 'hello_1m_@_SaLT';
$hashed    = hash('sha256', $password1 . $salt);
?>

When you insert :

$qry="INSERT INTO member VALUES('$username', '$hashed')";

And for retrieving user :

$qry="SELECT * FROM member WHERE username='$username' AND password='$hashed'";

What are the differences between .so and .dylib on osx?

Just an observation I just made while building naive code on OSX with cmake:

cmake ... -DBUILD_SHARED_LIBS=OFF ...

creates .so files

while

cmake ... -DBUILD_SHARED_LIBS=ON ...

creates .dynlib files.

Perhaps this helps anyone.

7-Zip command to create and extract a password-protected ZIP file on Windows?

From http://www.dotnetperls.com:

7z a secure.7z * -pSECRET

Where:

7z        : name and path of 7-Zip executable
a         : add to archive
secure.7z : name of destination archive
*         : add all files from current directory to destination archive
-pSECRET  : specify the password "SECRET"

To open :

7z x secure.7z

Then provide the SECRET password

Note: If the password contains spaces or special characters, then enclose it with single quotes

7z a secure.7z * -p"pa$$word @|"

ansible: lineinfile for several lines?

To add multiple lines you can use lineinfile module with with_items also including variable vars here to make it simple :)

---
- hosts: localhost  #change Host group as par inventory
  gather_facts: no
  become: yes
  vars:
    test_server: "10.168.1.1"
    test_server_name: "test-server"
    file_dest: "/etc/test/test_agentd.conf"

  - name: configuring test.conf
    lineinfile:
      dest: "{{ item.dest }}"
      regexp: "{{ item.regexp }}"
      line: "{{ item.line }}"
    with_items:
      - { dest: '"{{ file_dest }}"', regexp: 'Server=', line: 'Server="{{test_server}}"' }
      - { dest: '"{{ file_dest }}"', regexp: 'ServerActive=', line: 'ServerActive="{{test_server}}"' }
      - { dest: '"{{ file_dest }}"', regexp: 'Hostname=', line: 'Hostname="{{test_server_name}}"' }

How to define multiple CSS attributes in jQuery?

Better to just use .addClass() and .removeClass() even if you have 1 or more styles to change. It's more maintainable and readable.

If you really have the urge to do multiple CSS properties, then use the following:

.css({
   'font-size' : '10px',
   'width' : '30px',
   'height' : '10px'
});

NB!
Any CSS properties with a hyphen need to be quoted.
I've placed the quotes so no one will need to clarify that, and the code will be 100% functional.

NuGet auto package restore does not work with MSBuild

Nuget's Automatic Package Restore is a feature of the Visual Studio (starting in 2013), not MSBuild. You'll have to run nuget.exe restore if you want to restore packages from the command line.

You can also use the Enable Nuget Package Restore feature, but this is no longer recommended by the nuget folks because it makes intrusive changes to the project files and may cause problems if you build those projects in another solution.

Replace HTML page with contents retrieved via AJAX

Can't you just try to replace the body content with the document.body handler?

if your page is this:

<html>
<body>
blablabla
<script type="text/javascript">
document.body.innerHTML="hi!";
</script>
</body>
</html>

Just use the document.body to replace the body.

This works for me. All the content of the BODY tag is replaced by the innerHTML you specify. If you need to even change the html tag and all childs you should check out which tags of the 'document.' are capable of doing so.

An example with javascript scripting inside it:

<html>
<body>
blablabla
<script type="text/javascript">
var changeme = "<button onClick=\"document.bgColor = \'#000000\'\">click</button>";
document.body.innerHTML=changeme;
</script>
</body>

This way you can do javascript scripting inside the new content. Don't forget to escape all double and single quotes though, or it won't work. escaping in javascript can be done by traversing your code and putting a backslash in front of all singe and double quotes.

Bare in mind that server side scripting like php doesn't work this way. Since PHP is server-side scripting it has to be processed before a page is loaded. Javascript is a language which works on client-side and thus can not activate the re-processing of php code.

How to Correctly Use Lists in R?

Regarding your questions, let me address them in order and give some examples:

1) A list is returned if and when the return statement adds one. Consider

 R> retList <- function() return(list(1,2,3,4)); class(retList())
 [1] "list"
 R> notList <- function() return(c(1,2,3,4)); class(notList())
 [1] "numeric"
 R> 

2) Names are simply not set:

R> retList <- function() return(list(1,2,3,4)); names(retList())
NULL
R> 

3) They do not return the same thing. Your example gives

R> x <- list(1,2,3,4)
R> x[1]
[[1]]
[1] 1
R> x[[1]]
[1] 1

where x[1] returns the first element of x -- which is the same as x. Every scalar is a vector of length one. On the other hand x[[1]] returns the first element of the list.

4) Lastly, the two are different between they create, respectively, a list containing four scalars and a list with a single element (that happens to be a vector of four elements).

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

Display all post meta keys and meta values of the same post ID in wordpress

I use it in form of a meta box. Here is a function that dumps values of all the meta data for post.

    function dump_all_meta(){

        echo "<h3>All Post Meta</h3>";

        // Get all the data.
        $getPostCustom=get_post_custom();


        foreach( $getPostCustom as $name=>$value ) {

            echo "<strong>".$name."</strong>"."  =>  ";

            foreach($getPostCustom as $name=>$value) {

        echo "<strong>".$name."</strong>"."  =>  ";

        foreach($value as $nameAr=>$valueAr) {
                echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                echo $nameAr."  =>  ";
                echo var_dump($valueAr);
        }

        echo "<br /><br />";

        }
    } // Callback funtion ended.

Hope it helps. You can use it inside a meta box or at the front-end.

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

How to calculate UILabel height dynamically?

If you are using a UILabel with attributes, you can try the method textRect(forBounds:limitedToNumberOfLines).

This is my example:

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
label.numberOfLines = 0
label.text = "Learn how to use RxSwift and RxCocoa to write applications that can react to changes in your underlying data without you telling it to do so."

let rectOfLabel = label.textRect(forBounds: CGRect(x: 0, y: 0, width: 100, height: CGFloat.greatestFiniteMagnitude), limitedToNumberOfLines: 0)
let rectOfLabelOneLine = label.textRect(forBounds: CGRect(x: 0, y: 0, width: 100, height: CGFloat.greatestFiniteMagnitude), limitedToNumberOfLines: 1)
let heightOfLabel = rectOfLabel.height
let heightOfLine = rectOfLabelOneLine.height
let numberOfLines = Int(heightOfLabel / heightOfLine)

And my results on the Playground:

enter image description here

Output Django queryset as JSON

Try this:

class JSONListView(ListView):
    queryset = Users.objects.all()


    def get(self, request, *args, **kwargs):
        data = {}
        data["users"] = get_json_list(queryset)
        return JSONResponse(data)


def get_json_list(query_set):
    list_objects = []
    for obj in query_set:
        dict_obj = {}
        for field in obj._meta.get_fields():
            try:
                if field.many_to_many:
                    dict_obj[field.name] = get_json_list(getattr(obj, field.name).all())
                    continue
                dict_obj[field.name] = getattr(obj, field.name)
            except AttributeError:
                continue
        list_objects.append(dict_obj)
    return list_objects

How to print a string in C++

You need #include<string> to use string AND #include<iostream> to use cin and cout. (I didn't get it when I read the answers). Here's some code which works:

#include<string>
#include<iostream>
using namespace std;

int main()
{
    string name;
    cin >> name;
    string message("hi");
    cout << name << message;
    return 0;
}

Sorted array list in Java

I had the same problem. So I took the source code of java.util.TreeMap and wrote IndexedTreeMap. It implements my own IndexedNavigableMap:

public interface IndexedNavigableMap<K, V> extends NavigableMap<K, V> {
   K exactKey(int index);
   Entry<K, V> exactEntry(int index);
   int keyIndex(K k);
}

The implementation is based on updating node weights in the red-black tree when it is changed. Weight is the number of child nodes beneath a given node, plus one - self. For example when a tree is rotated to the left:

    private void rotateLeft(Entry<K, V> p) {
    if (p != null) {
        Entry<K, V> r = p.right;

        int delta = getWeight(r.left) - getWeight(p.right);
        p.right = r.left;
        p.updateWeight(delta);

        if (r.left != null) {
            r.left.parent = p;
        }

        r.parent = p.parent;


        if (p.parent == null) {
            root = r;
        } else if (p.parent.left == p) {
            delta = getWeight(r) - getWeight(p.parent.left);
            p.parent.left = r;
            p.parent.updateWeight(delta);
        } else {
            delta = getWeight(r) - getWeight(p.parent.right);
            p.parent.right = r;
            p.parent.updateWeight(delta);
        }

        delta = getWeight(p) - getWeight(r.left);
        r.left = p;
        r.updateWeight(delta);

        p.parent = r;
    }
  }

updateWeight simply updates weights up to the root:

   void updateWeight(int delta) {
        weight += delta;
        Entry<K, V> p = parent;
        while (p != null) {
            p.weight += delta;
            p = p.parent;
        }
    }

And when we need to find the element by index here is the implementation that uses weights:

public K exactKey(int index) {
    if (index < 0 || index > size() - 1) {
        throw new ArrayIndexOutOfBoundsException();
    }
    return getExactKey(root, index);
}

private K getExactKey(Entry<K, V> e, int index) {
    if (e.left == null && index == 0) {
        return e.key;
    }
    if (e.left == null && e.right == null) {
        return e.key;
    }
    if (e.left != null && e.left.weight > index) {
        return getExactKey(e.left, index);
    }
    if (e.left != null && e.left.weight == index) {
        return e.key;
    }
    return getExactKey(e.right, index - (e.left == null ? 0 : e.left.weight) - 1);
}

Also comes in very handy finding the index of a key:

    public int keyIndex(K key) {
    if (key == null) {
        throw new NullPointerException();
    }
    Entry<K, V> e = getEntry(key);
    if (e == null) {
        throw new NullPointerException();
    }
    if (e == root) {
        return getWeight(e) - getWeight(e.right) - 1;//index to return
    }
    int index = 0;
    int cmp;
    index += getWeight(e.left);

    Entry<K, V> p = e.parent;
    // split comparator and comparable paths
    Comparator<? super K> cpr = comparator;
    if (cpr != null) {
        while (p != null) {
            cmp = cpr.compare(key, p.key);
            if (cmp > 0) {
                index += getWeight(p.left) + 1;
            }
            p = p.parent;
        }
    } else {
        Comparable<? super K> k = (Comparable<? super K>) key;
        while (p != null) {
            if (k.compareTo(p.key) > 0) {
                index += getWeight(p.left) + 1;
            }
            p = p.parent;
        }
    }
    return index;
}

You can find the result of this work at http://code.google.com/p/indexed-tree-map/

TreeSet/TreeMap (as well as their indexed counterparts from the indexed-tree-map project) do not allow duplicate keys , you can use 1 key for an array of values. If you need a SortedSet with duplicates use TreeMap with values as arrays. I would do that.

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

Getting first value from map in C++

begin() returns the first pair, (precisely, an iterator to the first pair, and you can access the key/value as ->first and ->second of that iterator)

Given a filesystem path, is there a shorter way to extract the filename without its extension?

Firstly, the code in the question does not produce the described output. It extracts the file extension ("txt") and not the file base name ("hello"). To do that the last line should call First(), not Last(), like this...

static string GetFileBaseNameUsingSplit(string path)
{
    string[] pathArr = path.Split('\\');
    string[] fileArr = pathArr.Last().Split('.');
    string fileBaseName = fileArr.First().ToString();

    return fileBaseName;
}

Having made that change, one thing to think about as far as improving this code is the amount of garbage it creates:

  • A string[] containing one string for each path segment in path
  • A string[] containing at least one string for each . in the last path segment in path

Therefore, extracting the base file name from the sample path "C:\Program Files\hello.txt" should produce the (temporary) objects "C:", "Program Files", "hello.txt", "hello", "txt", a string[3], and a string[2]. This could be significant if the method is called on a large number of paths. To improve this, we can search path ourselves to locate the start and end points of the base name and use those to create one new string...

static string GetFileBaseNameUsingSubstringUnsafe(string path)
{
    // Fails on paths with no file extension - DO NOT USE!!
    int startIndex = path.LastIndexOf('\\') + 1;
    int endIndex = path.IndexOf('.', startIndex);
    string fileBaseName = path.Substring(startIndex, endIndex - startIndex);

    return fileBaseName;
}

This is using the index of the character after the last \ as the start of the base name, and from there looking for the first . to use as the index of the character after the end of the base name. Is this shorter than the original code? Not quite. Is it a "smarter" solution? I think so. At least, it would be if not for the fact that...

As you can see from the comment, the previous method is problematic. Though it works if you assume all paths end with a file name with an extension, it will throw an exception if the path ends with \ (i.e. a directory path) or otherwise contains no extension in the last segment. To fix this, we need to add an extra check to account for when endIndex is -1 (i.e. . is not found)...

static string GetFileBaseNameUsingSubstring(string path)
{
    int startIndex = path.LastIndexOf('\\') + 1;
    int endIndex = path.IndexOf('.', startIndex);
    int length = (endIndex >= 0 ? endIndex : path.Length) - startIndex;
    string fileBaseName = path.Substring(startIndex, length);

    return fileBaseName;
}

Now this version is nowhere near shorter than the original, but it is more efficient and (now) correct, too.

As far as .NET methods that implement this functionality, many other answers suggest using Path.GetFileNameWithoutExtension(), which is an obvious, easy solution but does not produce the same results as the code in the question. There is a subtle but important difference between GetFileBaseNameUsingSplit() and Path.GetFileNameWithoutExtension() (GetFileBaseNameUsingPath() below): the former extracts everything before the first . and the latter extracts everything before the last .. This doesn't make a difference for the sample path in the question, but take a look at this table comparing the results of the above four methods when called with various paths...

Description Method Path Result
Single extension GetFileBaseNameUsingSplit() "C:\Program Files\hello.txt" "hello"
Single extension GetFileBaseNameUsingPath() "C:\Program Files\hello.txt" "hello"
Single extension GetFileBaseNameUsingSubstringUnsafe() "C:\Program Files\hello.txt" "hello"
Single extension GetFileBaseNameUsingSubstring() "C:\Program Files\hello.txt" "hello"




Double extension GetFileBaseNameUsingSplit() "C:\Program Files\hello.txt.ext" "hello"
Double extension GetFileBaseNameUsingPath() "C:\Program Files\hello.txt.ext" "hello.txt"
Double extension GetFileBaseNameUsingSubstringUnsafe() "C:\Program Files\hello.txt.ext" "hello"
Double extension GetFileBaseNameUsingSubstring() "C:\Program Files\hello.txt.ext" "hello"




No extension GetFileBaseNameUsingSplit() "C:\Program Files\hello" "hello"
No extension GetFileBaseNameUsingPath() "C:\Program Files\hello" "hello"
No extension GetFileBaseNameUsingSubstringUnsafe() "C:\Program Files\hello" EXCEPTION: Length cannot be less than zero. (Parameter 'length')
No extension GetFileBaseNameUsingSubstring() "C:\Program Files\hello" "hello"




Leading period GetFileBaseNameUsingSplit() "C:\Program Files\.hello.txt" ""
Leading period GetFileBaseNameUsingPath() "C:\Program Files\.hello.txt" ".hello"
Leading period GetFileBaseNameUsingSubstringUnsafe() "C:\Program Files\.hello.txt" ""
Leading period GetFileBaseNameUsingSubstring() "C:\Program Files\.hello.txt" ""




Trailing period GetFileBaseNameUsingSplit() "C:\Program Files\hello.txt." "hello"
Trailing period GetFileBaseNameUsingPath() "C:\Program Files\hello.txt." "hello.txt"
Trailing period GetFileBaseNameUsingSubstringUnsafe() "C:\Program Files\hello.txt." "hello"
Trailing period GetFileBaseNameUsingSubstring() "C:\Program Files\hello.txt." "hello"




Directory path GetFileBaseNameUsingSplit() "C:\Program Files\" ""
Directory path GetFileBaseNameUsingPath() "C:\Program Files\" ""
Directory path GetFileBaseNameUsingSubstringUnsafe() "C:\Program Files\" EXCEPTION: Length cannot be less than zero. (Parameter 'length')
Directory path GetFileBaseNameUsingSubstring() "C:\Program Files\" ""




Current file path GetFileBaseNameUsingSplit() "hello.txt" "hello"
Current file path GetFileBaseNameUsingPath() "hello.txt" "hello"
Current file path GetFileBaseNameUsingSubstringUnsafe() "hello.txt" "hello"
Current file path GetFileBaseNameUsingSubstring() "hello.txt" "hello"




Parent file path GetFileBaseNameUsingSplit() "..\hello.txt" "hello"
Parent file path GetFileBaseNameUsingPath() "..\hello.txt" "hello"
Parent file path GetFileBaseNameUsingSubstringUnsafe() "..\hello.txt" "hello"
Parent file path GetFileBaseNameUsingSubstring() "..\hello.txt" "hello"




Parent directory path GetFileBaseNameUsingSplit() ".." ""
Parent directory path GetFileBaseNameUsingPath() ".." "."
Parent directory path GetFileBaseNameUsingSubstringUnsafe() ".." ""
Parent directory path GetFileBaseNameUsingSubstring() ".." ""

...and you'll see that Path.GetFileNameWithoutExtension() yields different results when passed a path where the file name has a double extension or a leading and/or trailing .. You can try it for yourself with the following code...

using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace SO6921105
{
    internal class PathExtractionResult
    {
        public string Description { get; set; }
        public string Method { get; set; }
        public string Path { get; set; }
        public string Result { get; set; }
    }

    public static class Program
    {
        private static string GetFileBaseNameUsingSplit(string path)
        {
            string[] pathArr = path.Split('\\');
            string[] fileArr = pathArr.Last().Split('.');
            string fileBaseName = fileArr.First().ToString();

            return fileBaseName;
        }

        private static string GetFileBaseNameUsingPath(string path)
        {
            return Path.GetFileNameWithoutExtension(path);
        }

        private static string GetFileBaseNameUsingSubstringUnsafe(string path)
        {
            // Fails on paths with no file extension - DO NOT USE!!
            int startIndex = path.LastIndexOf('\\') + 1;
            int endIndex = path.IndexOf('.', startIndex);
            string fileBaseName = path.Substring(startIndex, endIndex - startIndex);

            return fileBaseName;
        }

        private static string GetFileBaseNameUsingSubstring(string path)
        {
            int startIndex = path.LastIndexOf('\\') + 1;
            int endIndex = path.IndexOf('.', startIndex);
            int length = (endIndex >= 0 ? endIndex : path.Length) - startIndex;
            string fileBaseName = path.Substring(startIndex, length);

            return fileBaseName;
        }

        public static void Main()
        {
            MethodInfo[] testMethods = typeof(Program).GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
                .Where(method => method.Name.StartsWith("GetFileBaseName"))
                .ToArray();
            var inputs = new[] {
                new { Description = "Single extension",      Path = @"C:\Program Files\hello.txt"     },
                new { Description = "Double extension",      Path = @"C:\Program Files\hello.txt.ext" },
                new { Description = "No extension",          Path = @"C:\Program Files\hello"         },
                new { Description = "Leading period",        Path = @"C:\Program Files\.hello.txt"    },
                new { Description = "Trailing period",       Path = @"C:\Program Files\hello.txt."    },
                new { Description = "Directory path",        Path = @"C:\Program Files\"              },
                new { Description = "Current file path",     Path = "hello.txt"                       },
                new { Description = "Parent file path",      Path = @"..\hello.txt"                   },
                new { Description = "Parent directory path", Path = ".."                              }
            };
            PathExtractionResult[] results = inputs
                .SelectMany(
                    input => testMethods.Select(
                        method => {
                            string result;

                            try
                            {
                                string returnValue = (string) method.Invoke(null, new object[] { input.Path });

                                result = $"\"{returnValue}\"";
                            }
                            catch (Exception ex)
                            {
                                if (ex is TargetInvocationException)
                                    ex = ex.InnerException;
                                result = $"EXCEPTION: {ex.Message}";
                            }

                            return new PathExtractionResult() {
                                Description = input.Description,
                                Method = $"{method.Name}()",
                                Path = $"\"{input.Path}\"",
                                Result = result
                            };
                        }
                    )
                ).ToArray();
            const int ColumnPadding = 2;
            ResultWriter writer = new ResultWriter(Console.Out) {
                DescriptionColumnWidth = results.Max(output => output.Description.Length) + ColumnPadding,
                MethodColumnWidth = results.Max(output => output.Method.Length) + ColumnPadding,
                PathColumnWidth = results.Max(output => output.Path.Length) + ColumnPadding,
                ResultColumnWidth = results.Max(output => output.Result.Length) + ColumnPadding,
                ItemLeftPadding = " ",
                ItemRightPadding = " "
            };
            PathExtractionResult header = new PathExtractionResult() {
                Description = nameof(PathExtractionResult.Description),
                Method = nameof(PathExtractionResult.Method),
                Path = nameof(PathExtractionResult.Path),
                Result = nameof(PathExtractionResult.Result)
            };

            writer.WriteResult(header);
            writer.WriteDivider();
            foreach (IGrouping<string, PathExtractionResult> resultGroup in results.GroupBy(result => result.Description))
            {
                foreach (PathExtractionResult result in resultGroup)
                    writer.WriteResult(result);
                writer.WriteDivider();
            }
        }
    }

    internal class ResultWriter
    {
        private const char DividerChar = '-';
        private const char SeparatorChar = '|';

        private TextWriter Writer { get; }

        public ResultWriter(TextWriter writer)
        {
            Writer = writer ?? throw new ArgumentNullException(nameof(writer));
        }

        public int DescriptionColumnWidth { get; set; }

        public int MethodColumnWidth { get; set; }

        public int PathColumnWidth { get; set; }

        public int ResultColumnWidth { get; set; }

        public string ItemLeftPadding { get; set; }

        public string ItemRightPadding { get; set; }

        public void WriteResult(PathExtractionResult result)
        {
            WriteLine(
                $"{ItemLeftPadding}{result.Description}{ItemRightPadding}",
                $"{ItemLeftPadding}{result.Method}{ItemRightPadding}",
                $"{ItemLeftPadding}{result.Path}{ItemRightPadding}",
                $"{ItemLeftPadding}{result.Result}{ItemRightPadding}"
            );
        }

        public void WriteDivider()
        {
            WriteLine(
                new string(DividerChar, DescriptionColumnWidth),
                new string(DividerChar, MethodColumnWidth),
                new string(DividerChar, PathColumnWidth),
                new string(DividerChar, ResultColumnWidth)
            );
        }

        private void WriteLine(string description, string method, string path, string result)
        {
            Writer.Write(SeparatorChar);
            Writer.Write(description.PadRight(DescriptionColumnWidth));
            Writer.Write(SeparatorChar);
            Writer.Write(method.PadRight(MethodColumnWidth));
            Writer.Write(SeparatorChar);
            Writer.Write(path.PadRight(PathColumnWidth));
            Writer.Write(SeparatorChar);
            Writer.Write(result.PadRight(ResultColumnWidth));
            Writer.WriteLine(SeparatorChar);
        }
    }
}

TL;DR The code in the question does not behave as many seem to expect in some corner cases. If you're going to write your own path manipulation code, be sure to take into consideration...

  • ...how you define a "filename without extension" (is it everything before the first . or everything before the last .?)
  • ...files with multiple extensions
  • ...files with no extension
  • ...files with a leading .
  • ...files with a trailing . (probably not something you'll ever encounter on Windows, but they are possible)
  • ...directories with an "extension" or that otherwise contain a .
  • ...paths that end with a \
  • ...relative paths

Not all file paths follow the usual formula of X:\Directory\File.ext!

Random number generator only generating one random number

There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.

public String GenerateRandom(Random oRandom, int iLongitudPin)
{
    String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    int iLength = sCharacters.Length;
    char cCharacter;
    int iLongitudNuevaCadena = iLongitudPin; 
    String sRandomResult = "";
    for (int i = 0; i < iLongitudNuevaCadena; i++)
    {
        cCharacter = sCharacters[oRandom.Next(iLength)];
        sRandomResult += cCharacter.ToString();
    }
    return (sRandomResult);
}

Closing Excel Application using VBA

To avoid the Save prompt message, you have to insert those lines

Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True

After saving your work, you need to use this line to quit the Excel application

Application.Quit

Don't just simply put those line in Private Sub Workbook_Open() unless you got do a correct condition checking, else you may spoil your excel file.

For safety purpose, please create a module to run it. The following are the codes that i put:

Sub testSave()
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
Application.Quit
End Sub

Hope it help you solve the problem.

SQL select max(date) and corresponding value

You can use a subquery. The subquery will get the Max(CompletedDate). You then take this value and join on your table again to retrieve the note associate with that date:

select ET1.TrainingID,
  ET1.CompletedDate,
  ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
  select Max(CompletedDate) CompletedDate, TrainingID
  from HR_EmployeeTrainings
  --where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
  group by TrainingID
) ET2
  on ET1.TrainingID = ET2.TrainingID
  and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Rename the output.config produced by svcutil.exe to app.config. it worked for me.

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

The problem in my case is that the Gemfile.lock file had a BUNDLED_WITH version of 1.16.1 and gem install bundler installed version 2.0.1, so there was a version mismatch when looking to right the folder

gem install bundler -v 1.16.1 fixed it

Of course, you can also change your Gemfile.lock's BUNDLED_WITH with last bundler version and use recent software, as Sam3000 suggests

What and When to use Tuple?

The difference between a tuple and a class is that a tuple has no property names. This is almost never a good thing, and I would only use a tuple when the arguments are fairly meaningless like in an abstract math formula Eg. abstract calculus over 5,6,7 dimensions might take a tuple for the coordinates.

How to set the height and the width of a textfield in Java?

     f.setLayout(null);

add the above lines ( f is a JFrame or a Container where you have added the JTestField )

But try to learn 'LayoutManager' in java ; refer to other answers for the links of the tutorials .Or try This http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

How to make the corners of a button round?

You can also use the card layout like below

  <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:cardCornerRadius="30dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="Template"

                />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

How to compare two Carbon Timestamps?

This is how I am comparing 2 dates, now() and a date from the table

@if (\Carbon\Carbon::now()->lte($item->client->event_date_from))
    .....
    .....
@endif

Should work just right. I have used the comparison functions provided by Carbon.

Check if Cookie Exists

Response.Cookies contains the cookies that will be sent back to the browser. If you want to know whether a cookie exists, you should probably look into Request.Cookies.

Anyway, to see if a cookie exists, you can check Cookies.Get(string). However, if you use this method on the Response object and the cookie doesn't exist, then that cookie will be created.

See MSDN Reference for HttpCookieCollection.Get Method (String)

Nesting queries in SQL

You need to join the two tables and then filter the result in where clause:

SELECT country.name as country, country.headofstate 
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'

List of encodings that Node.js supports

The list of encodings that node supports natively is rather short:

  • ascii
  • base64
  • hex
  • ucs2/ucs-2/utf16le/utf-16le
  • utf8/utf-8
  • binary/latin1 (ISO8859-1, latin1 only in node 6.4.0+)

If you are using an older version than 6.4.0, or don't want to deal with non-Unicode encodings, you can recode the string:

Use iconv-lite to recode files:

var iconvlite = require('iconv-lite');
var fs = require('fs');

function readFileSync_encoding(filename, encoding) {
    var content = fs.readFileSync(filename);
    return iconvlite.decode(content, encoding);
}

Alternatively, use iconv:

var Iconv = require('iconv').Iconv;
var fs = require('fs');

function readFileSync_encoding(filename, encoding) {
    var content = fs.readFileSync(filename);
    var iconv = new Iconv(encoding, 'UTF-8');
    var buffer = iconv.convert(content);
    return buffer.toString('utf8');
}

UnsatisfiedDependencyException: Error creating bean with name

There is another instance still same error will shown after you doing everything above mentioned. When you change your codes accordingly mentioned solutions make sure to keep originals. So you can easily go back. So go and again check dispatcher-servelet configuration file's base package location. Is it scanning all relevant packages when you running application.

<context:component-scan base-package="your.pakage.path.here"/>

How to extract string following a pattern with grep, regex or perl

this could do it:

perl -ne 'if(m/name="(.*?)"/){ print $1 . "\n"; }'

javascript - Create Simple Dynamic Array

var arr = [];
for(var i=1; i<=mynumber; i++) {
   arr.push(i.toString());
}

How to test the `Mosquitto` server?

The OP has not defined the scope of testing, however, simple (gross) 'smoke testing' an install should be performed before any time is invested with functionality testing.

How to test if application is installed ('smoke-test')

Log into the mosquitto server's command line and type:

mosquitto

If mosquitto is installed the machine will return:

 mosquitto version 1.4.8 (build date Wed, date of installation) starting
 Using default config.
 Opening ipv4 listen socket on port 1883

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

Java and HTTPS url connection without downloading certificate

Java and HTTPS url connection without downloading certificate

If you really want to avoid downloading the server's certificate, then use an anonymous protocol like Anonymous Diffie-Hellman (ADH). The server's certificate is not sent with ADH and friends.

You select an anonymous protocol with setEnabledCipherSuites. You can see the list of cipher suites available with getEnabledCipherSuites.

Related: that's why you have to call SSL_get_peer_certificate in OpenSSL. You'll get a X509_V_OK with an anonymous protocol, and that's how you check to see if a certificate was used in the exchange.

But as Bruno and Stephed C stated, its a bad idea to avoid the checks or use an anonymous protocol.


Another option is to use TLS-PSK or TLS-SRP. They don't require server certificates either. (But I don't think you can use them).

The rub is, you need to be pre-provisioned in the system because TLS-PSK is Pres-shared Secret and TLS-SRP is Secure Remote Password. The authentication is mutual rather than server only.

In this case, the mutual authentication is provided by a property that both parties know the shared secret and arrive at the same premaster secret; or one (or both) does not and channel setup fails. Each party proves knowledge of the secret is the "mutual" part.

Finally, TLS-PSK or TLS-SRP don't do dumb things, like cough up the user's password like in a web app using HTTP (or over HTTPS). That's why I said each party proves knowledge of the secret...

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Often used with/as a part of OOAD and business modeling. The definition by Neil is correct, but it is basically identical to MVC, but just abstracted for the business. The "Good summary" is well done so I will not copy it here as it is not my work, more detailed but inline with Neil's bullet points.

Good summary - Conceito: Entity-Control-Boundary Pattern

OOAD

Subversion stuck due to "previous operation has not finished"?

I resolved this error today when it occurred trying to Commit to SVN. The error was genuine, TortoiseSVN could not access a file which I tried to Commit. This file had been saved while running a program "As Administrator" in Windows. This means the file has Administrator access but not access from my account (TortoiseSVN running as interactive user). I took ownership of the nominated file under my windows account and after that Cleanup was able to proceed.

Async always WaitingForActivation

For my answer, it is worth remembering that the TPL (Task-Parallel-Library), Task class and TaskStatus enumeration were introduced prior to the async-await keywords and the async-await keywords were not the original motivation of the TPL.

In the context of methods marked as async, the resulting Task is not a Task representing the execution of the method, but a Task for the continuation of the method.

This is only able to make use of a few possible states:

  • Canceled
  • Faulted
  • RanToCompletion
  • WaitingForActivation

I understand that Runningcould appear to have been a better default than WaitingForActivation, however this could be misleading, as the majority of the time, an async method being executed is not actually running (i.e. it may be await-ing something else). The other option may have been to add a new value to TaskStatus, however this could have been a breaking change for existing applications and libraries.

All of this is very different to when making use of Task.Run which is a part of the original TPL, this is able to make use of all the possible values of the TaskStatus enumeration.

If you wish to keep track of the status of an async method, take a look at the IProgress(T) interface, this will allow you to report the ongoing progress. This blog post, Async in 4.5: Enabling Progress and Cancellation in Async APIs will provide further information on the use of the IProgress(T) interface.

Clicking URLs opens default browser

The method boolean shouldOverrideUrlLoading(WebView view, String url) was deprecated in API 24. If you are supporting new devices you should use boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request).

You can use both by doing something like this:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    newsItem.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;
        }
    });
} else {
    newsItem.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
}

Convert output of MySQL query to utf8

SELECT CONVERT(CAST(column as BINARY) USING utf8) as column FROM table 

No plot window in matplotlib

If you encounter an issue in which pylab.show() freezes the IPython window (this may be Mac OS X specific; not sure), you can cmd-c in the IPython window, switch to the plot window, and it will break out.

Apparently, future calls to pylab.show() will not freeze the IPython window, only the first call. Unfortunately, I've found that the behavior of the plot window / interactions with show() changes every time I reinstall matplotlib, so this solution may not always hold.

Check existence of directory and create if doesn't exist

In terms of general architecture I would recommend the following structure with regard to directory creation. This will cover most potential issues and any other issues with directory creation will be detected by the dir.create call.

mainDir <- "~"
subDir <- "outputDirectory"

if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
    cat("subDir exists in mainDir and is a directory")
} else if (file.exists(paste(mainDir, subDir, sep = "/", collapse = "/"))) {
    cat("subDir exists in mainDir but is a file")
    # you will probably want to handle this separately
} else {
    cat("subDir does not exist in mainDir - creating")
    dir.create(file.path(mainDir, subDir))
}

if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
    # By this point, the directory either existed or has been successfully created
    setwd(file.path(mainDir, subDir))
} else {
    cat("subDir does not exist")
    # Handle this error as appropriate
}

Also be aware that if ~/foo doesn't exist then a call to dir.create('~/foo/bar') will fail unless you specify recursive = TRUE.

Android Studio: Can't start Git

If you are using Mac OS and have updated XCode you probably need to open XCode and accept the terms to avoid this error.

Problems with jQuery getJSON using local files in Chrome

Another way to do it is to start a local HTTP server on your directory. On Ubuntu and MacOs with Python installed, it's a one-liner.

Go to the directory containing your web files, and :

python -m SimpleHTTPServer

Then connect to http://localhost:8000/index.html with any web browser to test your page.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

If you transferred these files through disk or other means, it is likely they were not saved properly.