Programs & Examples On #Clear cache

How do you clear your Visual Studio cache on Windows Vista?

The accepted answer gave two locations:

here

C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache

and possibly here

C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache

Did you try those?

Edited to add

On my Windows Vista machine, it's located in

%Temp%\VWDWebCache

and in

%LocalAppData%\Microsoft\WebsiteCache

From your additional information (regarding team edition) this comes from Clear Client TFS Cache:

Clear Client TFS Cache

Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.

To solve it..

For Windows Vista delete contents of this folder

%LocalAppData%\Microsoft\Team Foundation\1.0\Cache

Selecting empty text input using jQuery

As mentioned in the top ranked post, the following works with the Sizzle engine.

$('input:text[value=""]');

In the comments, it was noted that removing the :text portion of the selector causes the selector to fail. I believe what's happening is that Sizzle actually relies on the browser's built in selector engine when possible. When :text is added to the selector, it becomes a non-standard CSS selector and thereby must needs be handled by Sizzle itself. This means that Sizzle checks the current value of the INPUT, instead of the "value" attribute specified in the source HTML.

So it's a clever way to check for empty text fields, but I think it relies on a behavior specific to the Sizzle engine (that of using the current value of the INPUT instead of the attribute defined in the source code). While Sizzle might return elements that match this selector, document.querySelectorAll will only return elements that have value="" in the HTML. Caveat emptor.

How do I output text without a newline in PowerShell?

The problem that I hit was that Write-Output actually linebreaks the output when using using PowerShell v2, at least to stdout. I was trying to write an XML text to stdout without success, because it would be hard wrapped at character 80.

The workaround was to use

[Console]::Out.Write($myVeryLongXMLTextBlobLine)

This was not an issue in PowerShell v3. Write-Output seems to be working properly there.

Depending on how the PowerShell script is invoked, you may need to use

[Console]::BufferWidth =< length of string, e.g. 10000)

before you write to stdout.

JOptionPane YES/No Options Confirm Dialog Box Issue

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

How to override and extend basic Django admin templates?

I couldn't find a single answer or a section in the official Django docs that had all the information I needed to override/extend the default admin templates, so I'm writing this answer as a complete guide, hoping that it would be helpful for others in the future.

Assuming the standard Django project structure:

mysite-container/         # project container directory
    manage.py
    mysite/               # project package
        __init__.py
        admin.py
        apps.py
        settings.py
        urls.py
        wsgi.py
    app1/
    app2/
    ...
    static/
    templates/

Here's what you need to do:

  1. In mysite/admin.py, create a sub-class of AdminSite:

    from django.contrib.admin import AdminSite
    
    
    class CustomAdminSite(AdminSite):
        # set values for `site_header`, `site_title`, `index_title` etc.
        site_header = 'Custom Admin Site'
        ...
    
        # extend / override admin views, such as `index()`
        def index(self, request, extra_context=None):
            extra_context = extra_context or {}
    
            # do whatever you want to do and save the values in `extra_context`
            extra_context['world'] = 'Earth'
    
            return super(CustomAdminSite, self).index(request, extra_context)
    
    
    custom_admin_site = CustomAdminSite()
    

    Make sure to import custom_admin_site in the admin.py of your apps and register your models on it to display them on your customized admin site (if you want to).

  2. In mysite/apps.py, create a sub-class of AdminConfig and set default_site to admin.CustomAdminSite from the previous step:

    from django.contrib.admin.apps import AdminConfig
    
    
    class CustomAdminConfig(AdminConfig):
        default_site = 'admin.CustomAdminSite'
    
  3. In mysite/settings.py, replace django.admin.site in INSTALLED_APPS with apps.CustomAdminConfig (your custom admin app config from the previous step).

  4. In mysite/urls.py, replace admin.site.urls from the admin URL to custom_admin_site.urls

    from .admin import custom_admin_site
    
    
    urlpatterns = [
        ...
        path('admin/', custom_admin_site.urls),
        # for Django 1.x versions: url(r'^admin/', include(custom_admin_site.urls)),
        ...
    ]
    
  5. Create the template you want to modify in your templates directory, maintaining the default Django admin templates directory structure as specified in the docs. For example, if you were modifying admin/index.html, create the file templates/admin/index.html.

    All of the existing templates can be modified this way, and their names and structures can be found in Django's source code.

  6. Now you can either override the template by writing it from scratch or extend it and then override/extend specific blocks.

    For example, if you wanted to keep everything as-is but wanted to override the content block (which on the index page lists the apps and their models that you registered), add the following to templates/admin/index.html:

    {% extends 'admin/index.html' %}
    
    {% block content %}
      <h1>
        Hello, {{ world }}!
      </h1>
    {% endblock %}
    

    To preserve the original contents of a block, add {{ block.super }} wherever you want the original contents to be displayed:

    {% extends 'admin/index.html' %}
    
    {% block content %}
      <h1>
        Hello, {{ world }}!
      </h1>
      {{ block.super }}
    {% endblock %}
    

    You can also add custom styles and scripts by modifying the extrastyle and extrahead blocks.

Iterating C++ vector from the end to the beginning

I like the backwards iterator at the end of Yakk - Adam Nevraumont's answer, but it seemed complicated for what I needed, so I wrote this:

template <class T>
class backwards {
    T& _obj;
public:
    backwards(T &obj) : _obj(obj) {}
    auto begin() {return _obj.rbegin();}
    auto end() {return _obj.rend();}
};

I'm able to take a normal iterator like this:

for (auto &elem : vec) {
    // ... my useful code
}

and change it to this to iterate in reverse:

for (auto &elem : backwards(vec)) {
    // ... my useful code
}

Why doesn't importing java.util.* include Arrays and Lists?

I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.

Have you tried compiling from the command line?

I have the exact same version:

here it is

Probably you're thinking the warning is an error.

UPDATE

It looks like you have a Arrays.class file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class

Embed image in a <button> element

You could use input type image.

<input type="image" src="http://example.com/path/to/image.png" />

It works as a button and can have the event handlers attached to it.

Alternatively, you can use css to style your button with a background image, and set the borders, margins and the like appropriately.

<button style="background: url(myimage.png)" ... />

Sleep Command in T-SQL?

Here is a very simple piece of C# code to test the CommandTimeout with. It creates a new command which will wait for 2 seconds. Set the CommandTimeout to 1 second and you will see an exception when running it. Setting the CommandTimeout to either 0 or something higher than 2 will run fine. By the way, the default CommandTimeout is 30 seconds.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data.SqlClient;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var builder = new SqlConnectionStringBuilder();
      builder.DataSource = "localhost";
      builder.IntegratedSecurity = true;
      builder.InitialCatalog = "master";

      var connectionString = builder.ConnectionString;

      using (var connection = new SqlConnection(connectionString))
      {
        connection.Open();

        using (var command = connection.CreateCommand())
        {
          command.CommandText = "WAITFOR DELAY '00:00:02'";
          command.CommandTimeout = 1;

          command.ExecuteNonQuery();
        }
      }
    }
  }
}

Multiple Java versions running concurrently under Windows

We can install multiple versions of Java Development kits on the same machine using SDKMan.

Some points about SDKMan are as following:

  1. SDKMan is free to use and it is developed by the open source community.
  2. SDKMan is written in bash and it only requires curl and zip/unzip programs to be present on your system.
  3. SDKMan can install around 29 Software Development Kits for the JVM such as Java, Groovy, Scala, Kotlin and Ceylon. Ant, Gradle, Grails, Maven, SBT, Spark, Spring Boot, Vert.x.
  4. We do not need to worry about setting the _HOME and PATH environment variables because SDKMan handles it automatically.

SDKMan can run on any UNIX based platforms such as Mac OSX, Linux, Cygwin, Solaris and FreeBSD and we can install it using following commands:

$ curl -s "https://get.sdkman.io" | bash  
$ source "$HOME/.sdkman/bin/sdkman-init.sh" 

Because SDKMan is written in bash and only requires curl and zip/unzip to be present on your system. You can install SDKMan on windows as well either by first installing Cygwin or Git Bash for Windows environment and then running above commands.

Command sdk list java will give us a list of java versions which we can install using SDKMan.

Installing Java 8

$ sdk install java 8.0.201-oracle

Installing Java 9

$ sdk install java 9.0.4-open 

Installing Java 11

$ sdk install java 11.0.2-open

Uninstalling a Java version

In case you want to uninstall any JDK version e.g., 11.0.2-open you can do that as follows:

$ sdk uninstall java 11.0.2-open

Switching current Java version

If you want to activate one version of JDK for all terminals and applications, you can use the command

sdk default java <your-java_version>

Above commands will also update the PATH and JAVA_HOME variables automatically. You can read more on my article How to Install Multiple Versions of Java on the Same Machine.

TypeError: $(...).DataTable is not a function

I got this error because I found out that I referenced jQuery twice.

The first time: on the master page (_Layout.cshtml) in ASP.NET MVC, and then again on one current page so I commented out the one on the master page.

If you are using ASP.NET MVC this snippet could help you

@*@Scripts.Render("~/bundles/jquery")*@//comment this line 
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

and in the current page I added these lines

<script src="~/scripts/jquery-1.10.2.js"></script>

<!-- #region datatables files -->
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<!-- #endregion -->

Hope this help you even if don't use ASP.NET MVC

Replace forward slash "/ " character in JavaScript string?

Just use the split - join approach:

my_string.split('/').join('replace_with_this')

Difference between SurfaceView and View?

Why use SurfaceView and not the classic View class...

One main reason is that SurfaceView can rapidly render the screen.

In simple words a SV is more capable of managing the timing and render animations.

To have a better understanding what is a SurfaceView we must compare it with the View class.

What is the difference... check this simple explanation in the video

https://m.youtube.com/watch?feature=youtu.be&v=eltlqsHSG30

Well with the View we have one major problem....the timing of rendering animations.

Normally the onDraw() is called from the Android run-time system.

So, when Android run-time system calls onDraw() then the application cant control

the timing of display, and this is important for animation. We have a gap of timing

between the application (our game) and the Android run-time system.

The SV it can call the onDraw() by a dedicated Thread.

Thus: the application controls the timing. So we can display the next bitmap image of the animation.

CSS :selected pseudo class similar to :checked, but for <select> elements

This worked for me :

select option {
   color: black;
}
select:not(:checked) {
   color: gray;
}

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

Alternatively, style the tbody with a predetermined size (via height:20em, for example) and use overflow-y:scroll;

Then, you can have a huge tbody, which will scroll independently of the rest of the page.

How to alter a column's data type in a PostgreSQL table?

If data already exists in the column you should do:

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;

As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.

Chrome Dev Tools - Modify javascript and reload

This is a bit of a work around, but one way you can achieve this is by adding a breakpoint at the start of the javascript file or block you want to manipulate.

Then when you reload, the debugger will pause on that breakpoint, and you can make any changes you want to the source, save the file and then run the debugger through the modified code.

But as everyone has said, next reload the changes will be gone - at least it let's you run some slightly modified JS client side.

Visual Studio debugger error: Unable to start program Specified file cannot be found

Guessing from the information I have, you're not actually compiling the program, but trying to run it. That is, ALL_BUILD is set as your startup project. (It should be in a bold font, unlike the other projects in your solution) If you then try to run/debug, you will get the error you describe, because there is simply nothing to run.

The project is most likely generated via CMAKE and included in your Visual Studio solution. Set any of the projects that do generate a .exe as the startup project (by right-clicking on the project and selecting "set as startup project") and you will most likely will be able to start those from within Visual Studio.

Android ListView with Checkbox and all clickable

Set the listview adapter to "simple_list_item_multiple_choice"

ArrayAdapter<String> adapter;

List<String> values; // put values in this

//Put in listview
adapter = new ArrayAdapter<UserProfile>(
this,
android.R.layout.simple_list_item_multiple_choice, 
values);
setListAdapter(adapter);    

Automatically create an Enum based on values in a database lookup table?

enum builder class

public class XEnum
{
    private EnumBuilder enumBuilder;
    private int index;
    private AssemblyBuilder _ab;
    private AssemblyName _name;
    public XEnum(string enumname)
    {
        AppDomain currentDomain = AppDomain.CurrentDomain;
        _name = new AssemblyName("MyAssembly");
        _ab = currentDomain.DefineDynamicAssembly(
            _name, AssemblyBuilderAccess.RunAndSave);

        ModuleBuilder mb = _ab.DefineDynamicModule("MyModule");

        enumBuilder = mb.DefineEnum(enumname, TypeAttributes.Public, typeof(int));


    }
    /// <summary>
    /// adding one string to enum
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public FieldBuilder add(string s)
    {
        FieldBuilder f = enumBuilder.DefineLiteral(s, index);
        index++;
        return f;
    }
    /// <summary>
    /// adding array to enum
    /// </summary>
    /// <param name="s"></param>
    public void addRange(string[] s)
    {
        for (int i = 0; i < s.Length; i++)
        {
            enumBuilder.DefineLiteral(s[i], i);
        }
    }
    /// <summary>
    /// getting index 0
    /// </summary>
    /// <returns></returns>
    public object getEnum()
    {
        Type finished = enumBuilder.CreateType();
        _ab.Save(_name.Name + ".dll");
        Object o1 = Enum.Parse(finished, "0");
        return o1;
    }
    /// <summary>
    /// getting with index
    /// </summary>
    /// <param name="i"></param>
    /// <returns></returns>
    public object getEnum(int i)
    {
        Type finished = enumBuilder.CreateType();
        _ab.Save(_name.Name + ".dll");
        Object o1 = Enum.Parse(finished, i.ToString());
        return o1;
    }
}

create an object

string[] types = { "String", "Boolean", "Int32", "Enum", "Point", "Thickness", "long", "float" };
XEnum xe = new XEnum("Enum");
        xe.addRange(types);
        return xe.getEnum();

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

If you are wanting to reference the cell progmatically then you will get much more readable code if you use the Cells method of a sheet. It takes a row and column index instead of a traditonal cell reference. It is very similar to the Offset method.

adding multiple event listeners to one element

Unless your do_something function actually does something with any given arguments, you can just pass it as the event handler.

var first = document.getElementById('first');
first.addEventListener('touchstart', do_something, false);
first.addEventListener('click', do_something, false);

How do I change the font color in an html table?

<table>
<tbody>
<tr>
<td>
<select name="test" style="color: red;">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>

What is the difference between a .cpp file and a .h file?

A header (.h, .hpp, ...) file contains

  • Class definitions ( class X { ... }; )
  • Inline function definitions ( inline int get_cpus() { ... } )
  • Function declarations ( void help(); )
  • Object declarations ( extern int debug_enabled; )

A source file (.c, .cpp, .cxx) contains

  • Function definitions ( void help() { ... } or void X::f() { ... } )
  • Object definitions ( int debug_enabled = 1; )

However, the convention that headers are named with a .h suffix and source files are named with a .cpp suffix is not really required. One can always tell a good compiler how to treat some file, irrespective of its file-name suffix ( -x <file-type> for gcc. Like -x c++ ).

Source files will contain definitions that must be present only once in the whole program. So if you include a source file somewhere and then link the result of compilation of that file and then the one of the source file itself together, then of course you will get linker errors, because you have those definitions now appear twice: Once in the included source file, and then in the file that included it. That's why you had problems with including the .cpp file.

Select2 open dropdown on focus

Probably after the selection is made a select2-focus event is triggered.

The only way I found is a combination of select2-focus and select2-blur event and the jQuery one event handler.

So the first time the element get the focus, the select2 is opened for one time (because of one), when the element is blurred the one event handler is attached again and so on.

Code:

$('#test').select2({
    data: [{
        id: 0,
        text: "enhancement"
    }, {
        id: 1,
        text: "bug"
    }, {
        id: 2,
        text: "duplicate"
    }, {
        id: 3,
        text: "invalid"
    }, {
        id: 4,
        text: "wontfix"
    }],
    width: "300px"
}).one('select2-focus', select2Focus).on("select2-blur", function () {
    $(this).one('select2-focus', select2Focus)
})

function select2Focus() {
    $(this).select2('open');
}

Demo: http://jsfiddle.net/IrvinDominin/fnjNb/

UPDATE

To let the mouse click work you must check the event that fires the handler, it must fire the open method only if the event is focus

Code:

function select2Focus() {
    if (/^focus/.test(event.type)) {
        $(this).select2('open');
    }
}

Demo: http://jsfiddle.net/IrvinDominin/fnjNb/4/

UPDATE FOR SELECT2 V 4.0

select2 v 4.0 has changed its API's and dropped the custom events (see https://github.com/select2/select2/issues/1908). So it's necessary change the way to detect the focus on it.

Code:

$('.js-select').select2({
    placeholder: "Select",
    width: "100%"
})

$('.js-select').next('.select2').find('.select2-selection').one('focus', select2Focus).on('blur', function () {
    $(this).one('focus', select2Focus)
})

function select2Focus() {
    $(this).closest('.select2').prev('select').select2('open');
}

Demo: http://jsfiddle.net/IrvinDominin/xfmgte70/

How to update Ruby with Homebrew?

I would use ruby-build with rbenv. The following lines install Ruby 3.0.0 and set it as your default Ruby version:

$ brew update
$ brew install ruby-build
$ brew install rbenv

$ rbenv install 3.0.0
$ rbenv global 3.0.0

How to open VMDK File of the Google-Chrome-OS bundle 2012?

For me my vmdk file was accompanied by a vmx file. Opening the vmx file worked for vmware player.

How to detect running app using ADB command

No need to use grep. ps in Android can filter by COMM value (last 15 characters of the package name in case of java app)

Let's say we want to check if com.android.phone is running:

adb shell ps m.android.phone
USER     PID   PPID  VSIZE  RSS     WCHAN    PC         NAME
radio     1389  277   515960 33964 ffffffff 4024c270 S com.android.phone

Filtering by COMM value option has been removed from ps in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof command:

adb shell pidof com.android.phone

It returns the PID if such process was found or an empty string otherwise.

How do I detect whether a Python variable is a function?

If you want to detect everything that syntactically looks like a function: a function, method, built-in fun/meth, lambda ... but exclude callable objects (objects with __call__ method defined), then try this one:

import types
isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType, types.UnboundMethodType))

I compared this with the code of is*() checks in inspect module and the expression above is much more complete, especially if your goal is filtering out any functions or detecting regular properties of an object.

Using a scanner to accept String input and storing in a String Array

There is no use of pointers in java so far. You can create an object from the class and use different classes which are linked with each other and use the functions of every class in main class.

How do you remove an array element in a foreach loop?

A better solution is to use the array_filter function:

$display_related_tags =
    array_filter($display_related_tags, function($e) use($found_tag){
        return $e != $found_tag['name'];
    });

As the php documentation reads:

As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.

In PHP 7, foreach does not use the internal array pointer.

Can I access variables from another file?

I may be doing this a little differently. I'm not sure why I use this syntax, copied it from some book a long time ago. But each of my js files defines a variable. The first file, for no reason at all, is called R:

    var R = 
    { 
        somevar: 0,
        othervar: -1,

        init: function() {
          ...
        } // end init function

        somefunction: function(somearg) {
          ...
        }  // end somefunction

        ...

    }; // end variable R definition


    $( window ).load(function() {
       R.init();
    })

And then if I have a big piece of code that I want to segregate, I put it in a separate file and a different variable name, but I can still reference the R variables and functions. I called the new one TD for no good reason at all:

    var TD = 
    { 
        xvar: 0,
        yvar: -1,

        init: function() {
           ...
        } // end init function

        sepfunction: function() {
           ...
           R.somefunction(xvar);
           ...
        }  // end somefunction

        ...

    }; // end variable TD definition


    $( window ).load(function() {
       TD.init();
    })

You can see that where in the TD 'sepfunction' I call the R.somefunction. I realize this doesn't give any runtime efficiencies because both scripts to need to load, but it does help me keep my code organized.

How to read an http input stream

try this code

String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";

while ((line = br.readLine()) != null) {
    sb.append(line);
}

data = sb.toString();
System.out.println(data);

How to convert string into float in JavaScript?

Try

_x000D_
_x000D_
let str ="554,20";_x000D_
let float = +str.replace(',','.');_x000D_
let int = str.split(',').map(x=>+x);_x000D_
_x000D_
console.log({float,int});
_x000D_
_x000D_
_x000D_

Log to the base 2 in python

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

def lg(x, tol=1e-13):
  res = 0.0

  # Integer part
  while x<1:
    res -= 1
    x *= 2
  while x>=2:
    res += 1
    x /= 2

  # Fractional part
  fp = 1.0
  while fp>=tol:
    fp /= 2
    x *= x
    if x >= 2:
        x /= 2
        res += fp

  return res

How to group pandas DataFrame entries by date in a non-unique column

I'm using pandas 0.16.2. This has better performance on my large dataset:

data.groupby(data.date.dt.year)

Using the dt option and playing around with weekofyear, dayofweek etc. becomes far easier.

Add new line in text file with Windows batch file

Suppose you want to insert a particular line of text (not an empty line):

@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1

@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /p L=
  IF %%i==%insertat% ECHO(!TL!
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%

COPY /Y %tempfile% %origfile% >NUL

DEL %tempfile%

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

you have to customize security for your browser or allow permission through customizing security. (it is impractical for your local testing) to know more about please go through the link.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Disabled href tag

I have one:

<a href="#">This is a disabled tag.</a>

Hope it will help you ;)

How to get week number of the month from the date in sql server 2008

Code is below:

set datefirst 7
declare @dt datetime='29/04/2016 00:00:00'
select (day(@dt)+datepart(WEEKDAY,dateadd(d,-day(@dt),@dt+1)))/7

How to set time zone in codeigniter?

add it in your index.php file, and it will work on all over your site

if ( function_exists( 'date_default_timezone_set' ) ) {
    date_default_timezone_set('Asia/Kolkata');
}

How do I check if a PowerShell module is installed?

  • First test if the module is loaded
  • Then import

```

if (Get-Module -ListAvailable -Name <<MODULE_NAME>>) {
    Write-Verbose -Message "<<MODULE_NAME>> Module does not exist." -Verbose
}
if (!(Get-Module -Name <<MODULE_NAME>>)) {
    Get-Module -ListAvailable <<MODULE_NAME>> | Import-Module | Out-Null
}

```

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

Get all rows from SQLite

I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:

String name;
if (cursor.moveToFirst()) {

        while (cursor.isAfterLast() == false) {
            name = cursor.getString(cursor
                    .getColumnIndex(countyname));

            list.add(name);
            cursor.moveToNext();
        }
}

Getting error "No such module" using Xcode, but the framework is there

I was getting the same error as i added couple of frameworks using Cocoapods. If we are using Pods in our project, we should use xcodeworkspace instead of xcodeproject. To run the project through xcodebuild, i added -workspace <workspacename> parameter in xcodebuild command and it worked perfectly.

Get width/height of SVG element

This is the consistent cross-browser way I found:

var heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'],
    widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];

var svgCalculateSize = function (el) {

    var gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
        bounds = {
            width: 0,
            height: 0
        };

    heightComponents.forEach(function (css) { 
        bounds.height += parseFloat(gCS[css]);
    });
    widthComponents.forEach(function (css) {
        bounds.width += parseFloat(gCS[css]);
    });
    return bounds;
};

jQuery to remove an option from drop down list, given option's text/value

$("option[value='foo']").remove();

or better (if you have few selects in the page):

$("#select_id option[value='foo']").remove();

Get class name of object as string in Swift

You can try this way:

self.classForCoder.description()

Find out if string ends with another string in C++

Let a be a string and b the string you look for. Use a.substr to get the last n characters of a and compare them to b (where n is the length of b)

Or use std::equal (include <algorithm>)

Ex:

bool EndsWith(const string& a, const string& b) {
    if (b.size() > a.size()) return false;
    return std::equal(a.begin() + a.size() - b.size(), a.end(), b.begin());
}

Get a pixel from HTML Canvas?

You can use i << 2.

const data = context.getImageData(x, y, width, height).data;
const pixels = [];

for (let i = 0, dx = 0; dx < data.length; i++, dx = i << 2) {
    pixels.push({
        r: data[dx  ],
        g: data[dx+1],
        b: data[dx+2],
        a: data[dx+3]
    });
}

SELECT FOR UPDATE with SQL Server

How about trying to do a simple update on this row first (without really changing any data)? After that you can proceed with the row like in was selected for update.

UPDATE dbo.Customer SET FieldForLock = FieldForLock WHERE CustomerID = @CustomerID
/* do whatever you want */

Edit: you should wrap it in a transaction of course

Edit 2: another solution is to use SERIALIZABLE isolation level

Suppress console output in PowerShell

Try redirecting the output like this:

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1

Warning about SSL connection when connecting to MySQL database

I found this warning too then I fixed it by using SSL=false suffix to the connection string like this example code.

Example:

connectionString = "jdbc:mysql://{server-name}:3306/%s?useUnicode=yes&characterEncoding=UTF-8&useSSL=false"

How to Find And Replace Text In A File With C#

Read all file content. Make a replacement with String.Replace. Write content back to file.

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);

Objective-C: Calling selectors with multiple arguments

@Shane Arney

performSelector:withObject:withObject:

You might also want to mention that this method is only for passing maximum 2 arguments, and it cannot be delayed. (such as performSelector:withObject:afterDelay:).

kinda weird that apple only supports 2 objects to be send and didnt make it more generic.

Django database query: How to get object by id?

I got here for the same problem, but for a different reason:

Class.objects.get(id=1)

This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected:

Class.objects.all()

Tail of the traceback for the get() method:

File "django/db/models/loading.py", line 197, in get_models
    self._populate()
File "django/db/models/loading.py", line 72, in _populate
    self.load_app(app_name, True)
File "django/db/models/loading.py", line 94, in load_app
    app_module = import_module(app_name)
File "django/utils/importlib.py", line 35, in import_module
    __import__(name)
ImportError: No module named myapp

Reading the code inside Django's loading.py, I came to the conclusion that my settings.py had a bad path to my app which contains my Class model definition. All I had to do was correct the path to the app and the get() method executed fine.

Here is my settings.py with the corrected path:

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    # ...
    'mywebproject.myapp',

)

All the confusion was caused because I am using Django's ORM as a standalone, so the namespace had to reflect that.

Dynamic array in C#

Sometimes plain arrays are preferred to Generic Lists, since they are more convenient (Better performance for costly computation -Numerical Algebra Applications for example, or for exchanging Data with Statistics software like R or Matlab)

In this case you may use the ToArray() method after initiating your List dynamically

List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");

string[] array = list.ToArray();

Of course, this has sense only if the size of the array is never known nor fixed ex-ante. if you already know the size of your array at some point of the program it is better to initiate it as a fixed length array. (If you retrieve data from a ResultSet for example, you could count its size and initiate an array of that size, dynamically)

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

Here's another way using Visual Studio: If you do New Item in Visual Studio and you select Web Form, it will create a standalone *.aspx web form, which is what you have for your current web form (is this what you did?). You need to select Web Content Form and then select the master page you want attached to it.

Android, How to limit width of TextView (and add three dots at the end of text)?

eg. you can use

android:maxLength="13"

this will restrict texview length to 13 but problem is if you try to add 3 dots(...), it wont display it, as it will be part of textview length.

     String userName;
     if (data.length() >= 13) {
            userName = data.substring(0, 13)+ "...";

     } else {

            userName = data;

    }
        textView.setText(userName);

apart from this you have to use

 android:maxLines="1"

How to use "Share image using" sharing Intent to share images in android?

SuperM answer worked for me but with Uri.fromFile() instead of Uri.parse().

With Uri.parse(), it worked only with Whatsapp.

This is my code:

sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFile));

Output of Uri.parse():
/storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg

Output of Uri.fromFile:
file:///storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg

How do I get a python program to do nothing?

You could use a pass statement:

if condition:
    pass

Python 2.x documentation

Python 3.x documentation

However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if statement.

If you have something like this:

if condition:        # condition in your case being `num2 == num5`
    pass
else:
    do_something()

You can in general change it to this:

if not condition:
    do_something()

But in this specific case you could (and should) do this:

if num2 != num5:        # != is the not-equal-to operator
    do_something()

How do I make an auto increment integer field in Django?

In Django

1 : we have default field with name "id" which is auto increment.
2 : You can define a auto increment field using AutoField field.

class Order(models.Model):
    auto_increment_id = models.AutoField(primary_key=True)
    #you use primary_key = True if you do not want to use default field "id" given by django to your model

db design

+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                  |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE `core_order` (
  `auto_increment_id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`auto_increment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)

If you want to use django's default id as increment field .

class Order(models.Model):
    dd_date = models.DateTimeField(auto_now_add=True)

db design

+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE `core_order` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dd_date` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+

Change navbar text color Bootstrap

Try this

.nav.navbar-nav.navbar-right li a span{
    color: blue;
}

If it doesn't work try this

.nav.navbar-nav.navbar-right li a {
    color: blue;
}

How to compare two strings are equal in value, what is the best method?

string1.equals(string2) is right way to do it.

String s = "something", t = "maybe something else";
 if (s == t)      // Legal, but usually results WRONG.
 if (s.equals(t)) // RIGHT way to check the two strings
  /* == will fail in following case:*/
 String s1 = new String("abc");
 String s2 = new String("abc");

 if(s1==s2) //it will return false

SVN: Folder already under version control but not comitting?

Copy problematic folder into some backup directory and remove it from your SVN working directory. Remember to delete all .svn hidden directories from the copied folder.

Now update your project, clean-up and commit what has left. Now move your folder back to working directory, add it and commit. Most of the time this workaround works, it seems that basically SVN got confused...

Update: quoting comment by @Mark:

Didn't need to move the folder around, just deleting the .svn folder and then svn-adding it worked.

Formatting a Date String in React Native

Easily accomplished using a package.

Others have mentioned Moment. Moment is great but very large for a simple use like this, and unfortunately not modular so you have to import the whole package to use any of it.

I recommend using date-fns (https://date-fns.org/) (https://github.com/date-fns/date-fns). It is light-weight and modular, so you can import only the functions that you need.

In your case:

Install it: npm install date-fns --save

In your component:

import { format } from "date-fns";

var date = new Date("2016-01-04 10:34:23");

var formattedDate = format(date, "MMMM do, yyyy H:mma");

console.log(formattedDate);

Substitute the format string above "MMMM do, yyyy H:mma" with whatever format you require.

Update: v1 vs v2 format differences

v1 used Y for year and D for day, while v2 uses y and d. Format strings above have been updated for v2; the equivalent for v1 would be "MMMM Do, YYYY H:mma" (source: https://blog.date-fns.org/post/unicode-tokens-in-date-fns-v2-sreatyki91jg/). Thanks @Red

Best practices for circular shift (rotate) operations in C++

See also an earlier version of this answer on another rotate question with some more details about what asm gcc/clang produce for x86.

The most compiler-friendly way to express a rotate in C and C++ that avoids any Undefined Behaviour seems to be John Regehr's implementation. I've adapted it to rotate by the width of the type (using fixed-width types like uint32_t).

#include <stdint.h>   // for uint32_t
#include <limits.h>   // for CHAR_BIT
// #define NDEBUG
#include <assert.h>

static inline uint32_t rotl32 (uint32_t n, unsigned int c)
{
  const unsigned int mask = (CHAR_BIT*sizeof(n) - 1);  // assumes width is a power of 2.

  // assert ( (c<=mask) &&"rotate by type width or more");
  c &= mask;
  return (n<<c) | (n>>( (-c)&mask ));
}

static inline uint32_t rotr32 (uint32_t n, unsigned int c)
{
  const unsigned int mask = (CHAR_BIT*sizeof(n) - 1);

  // assert ( (c<=mask) &&"rotate by type width or more");
  c &= mask;
  return (n>>c) | (n<<( (-c)&mask ));
}

Works for any unsigned integer type, not just uint32_t, so you could make versions for other sizes.

See also a C++11 template version with lots of safety checks (including a static_assert that the type width is a power of 2), which isn't the case on some 24-bit DSPs or 36-bit mainframes, for example.

I'd recommend only using the template as a back-end for wrappers with names that include the rotate width explicitly. Integer-promotion rules mean that rotl_template(u16 & 0x11UL, 7) would do a 32 or 64-bit rotate, not 16 (depending on the width of unsigned long). Even uint16_t & uint16_t is promoted to signed int by C++'s integer-promotion rules, except on platforms where int is no wider than uint16_t.


On x86, this version inlines to a single rol r32, cl (or rol r32, imm8) with compilers that grok it, because the compiler knows that x86 rotate and shift instructions mask the shift-count the same way the C source does.

Compiler support for this UB-avoiding idiom on x86, for uint32_t x and unsigned int n for variable-count shifts:

  • clang: recognized for variable-count rotates since clang3.5, multiple shifts+or insns before that.
  • gcc: recognized for variable-count rotates since gcc4.9, multiple shifts+or insns before that. gcc5 and later optimize away the branch and mask in the wikipedia version, too, using just a ror or rol instruction for variable counts.
  • icc: supported for variable-count rotates since ICC13 or earlier. Constant-count rotates use shld edi,edi,7 which is slower and takes more bytes than rol edi,7 on some CPUs (especially AMD, but also some Intel), when BMI2 isn't available for rorx eax,edi,25 to save a MOV.
  • MSVC: x86-64 CL19: Only recognized for constant-count rotates. (The wikipedia idiom is recognized, but the branch and AND aren't optimized away). Use the _rotl / _rotr intrinsics from <intrin.h> on x86 (including x86-64).

gcc for ARM uses an and r1, r1, #31 for variable-count rotates, but still does the actual rotate with a single instruction: ror r0, r0, r1. So gcc doesn't realize that rotate-counts are inherently modular. As the ARM docs say, "ROR with shift length, n, more than 32 is the same as ROR with shift length n-32". I think gcc gets confused here because left/right shifts on ARM saturate the count, so a shift by 32 or more will clear the register. (Unlike x86, where shifts mask the count the same as rotates). It probably decides it needs an AND instruction before recognizing the rotate idiom, because of how non-circular shifts work on that target.

Current x86 compilers still use an extra instruction to mask a variable count for 8 and 16-bit rotates, probably for the same reason they don't avoid the AND on ARM. This is a missed optimization, because performance doesn't depend on the rotate count on any x86-64 CPU. (Masking of counts was introduced with 286 for performance reasons because it handled shifts iteratively, not with constant-latency like modern CPUs.)

BTW, prefer rotate-right for variable-count rotates, to avoid making the compiler do 32-n to implement a left rotate on architectures like ARM and MIPS that only provide a rotate-right. (This optimizes away with compile-time-constant counts.)

Fun fact: ARM doesn't really have dedicated shift/rotate instructions, it's just MOV with the source operand going through the barrel-shifter in ROR mode: mov r0, r0, ror r1. So a rotate can fold into a register-source operand for an EOR instruction or something.


Make sure you use unsigned types for n and the return value, or else it won't be a rotate. (gcc for x86 targets does arithmetic right shifts, shifting in copies of the sign-bit rather than zeroes, leading to a problem when you OR the two shifted values together. Right-shifts of negative signed integers is implementation-defined behaviour in C.)

Also, make sure the shift count is an unsigned type, because (-n)&31 with a signed type could be one's complement or sign/magnitude, and not the same as the modular 2^n you get with unsigned or two's complement. (See comments on Regehr's blog post). unsigned int does well on every compiler I've looked at, for every width of x. Some other types actually defeat the idiom-recognition for some compilers, so don't just use the same type as x.


Some compilers provide intrinsics for rotates, which is far better than inline-asm if the portable version doesn't generate good code on the compiler you're targeting. There aren't cross-platform intrinsics for any compilers that I know of. These are some of the x86 options:

  • Intel documents that <immintrin.h> provides _rotl and _rotl64 intrinsics, and same for right shift. MSVC requires <intrin.h>, while gcc require <x86intrin.h>. An #ifdef takes care of gcc vs. icc, but clang doesn't seem to provide them anywhere, except in MSVC compatibility mode with -fms-extensions -fms-compatibility -fms-compatibility-version=17.00. And the asm it emits for them sucks (extra masking and a CMOV).
  • MSVC: _rotr8 and _rotr16.
  • gcc and icc (not clang): <x86intrin.h> also provides __rolb/__rorb for 8-bit rotate left/right, __rolw/__rorw (16-bit), __rold/__rord (32-bit), __rolq/__rorq (64-bit, only defined for 64-bit targets). For narrow rotates, the implementation uses __builtin_ia32_rolhi or ...qi, but the 32 and 64-bit rotates are defined using shift/or (with no protection against UB, because the code in ia32intrin.h only has to work on gcc for x86). GNU C appears not to have any cross-platform __builtin_rotate functions the way it does for __builtin_popcount (which expands to whatever's optimal on the target platform, even if it's not a single instruction). Most of the time you get good code from idiom-recognition.

// For real use, probably use a rotate intrinsic for MSVC, or this idiom for other compilers.  This pattern of #ifdefs may be helpful
#if defined(__x86_64__) || defined(__i386__)

#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>  // Not just <immintrin.h> for compilers other than icc
#endif

uint32_t rotl32_x86_intrinsic(rotwidth_t x, unsigned n) {
  //return __builtin_ia32_rorhi(x, 7);  // 16-bit rotate, GNU C
  return _rotl(x, n);  // gcc, icc, msvc.  Intel-defined.
  //return __rold(x, n);  // gcc, icc.
  // can't find anything for clang
}
#endif

Presumably some non-x86 compilers have intrinsics, too, but let's not expand this community-wiki answer to include them all. (Maybe do that in the existing answer about intrinsics).


(The old version of this answer suggested MSVC-specific inline asm (which only works for 32bit x86 code), or http://www.devx.com/tips/Tip/14043 for a C version. The comments are replying to that.)

Inline asm defeats many optimizations, especially MSVC-style because it forces inputs to be stored/reloaded. A carefully-written GNU C inline-asm rotate would allow the count to be an immediate operand for compile-time-constant shift counts, but it still couldn't optimize away entirely if the value to be shifted is also a compile-time constant after inlining. https://gcc.gnu.org/wiki/DontUseInlineAsm.

Writing Python lists to columns in csv

I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:

import csv
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j','k']
with open('C:/test/numbers.csv', 'wb+') as myfile:
    wr = csv.writer(myfile)
    wr.writerow(("list1", "list2"))
    rcount = 0
    for row in list1:
        wr.writerow((list1[rcount], list2[rcount]))
        rcount = rcount + 1
    myfile.close()

Plot smooth line with PyPlot

You could use scipy.interpolate.spline to smooth out your data yourself:

from scipy.interpolate import spline

# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)  

power_smooth = spline(T, power, xnew)

plt.plot(xnew,power_smooth)
plt.show()

spline is deprecated in scipy 0.19.0, use BSpline class instead.

Switching from spline to BSpline isn't a straightforward copy/paste and requires a little tweaking:

from scipy.interpolate import make_interp_spline, BSpline

# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300) 

spl = make_interp_spline(T, power, k=3)  # type: BSpline
power_smooth = spl(xnew)

plt.plot(xnew, power_smooth)
plt.show()

Before: screenshot 1

After: screenshot 2

How can I make the browser wait to display the page until it's fully loaded?

Here's a solution using jQuery:

<script type="text/javascript">
$('#container').css('opacity', 0);
$(window).load(function() {
  $('#container').css('opacity', 1);
});
</script>

I put this script just after my </body> tag. Just replace "#container" with a selector for the DOM element(s) you want to hide. I tried several variations of this (including .hide()/.show(), and .fadeOut()/.fadeIn()), and just setting the opacity seems to have the fewest ill effects (flicker, changing page height, etc.). You can also replace css('opacity', 0) with fadeTo(100, 1) for a smoother transition. (No, fadeIn() won't work, at least not under jQuery 1.3.2.)

Now the caveats: I implemented the above because I'm using TypeKit and there's an annoying flicker when you refresh the page and the fonts take a few hundred milliseconds to load. So I don't want any text to appear on the screen until TypeKit has loaded. But obviously you're in big trouble if you use the code above and something on your page fails to load. There are two obvious ways that it could be improved:

  1. A maximum time limit (say, 1 second) after which everything appears whether the page is loaded or not
  2. Some kind of loading indicator (say, something from http://www.ajaxload.info/)

I won't bother implementing the loading indicator here, but the time limit is easy. Just add this to the script above:

$(document).ready(function() {
  setTimeout('$("#container").css("opacity", 1)', 1000);
});

So now, worst-case scenario, your page will take an extra second to appear.

Regex to replace multiple spaces with a single space

Here is an alternate solution if you do not want to use replace (replace spaces in a string without using replace javascript)

_x000D_
_x000D_
var str="The dog      has a long   tail, and it     is RED!";
var rule=/\s{1,}/g;

str = str.split(rule).join(" "); 

document.write(str);
_x000D_
_x000D_
_x000D_

How do I compile a .c file on my Mac?

In 2017, this will do it:

cc myfile.c

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I had a similar problem, not exactly the same conditions and then i saw this post. Hope it helps someone. Apparently i was using one of my EF entity models a base class for a type that was not specified as a db set in my dbcontext. To fix this issue i had to create a base class that had all the properties common to the two types and inherit from the new base class among the two types.

Example:

//Bad Flow
    //class defined in dbcontext as a dbset
    public class Customer{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //class not defined in dbcontext as a dbset
    public class DuplicateCustomer:Customer{ 
       public object DuplicateId {get; set;}
    }


    //Good/Correct flow*
    //Common base class
    public class CustomerBase{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //entity model referenced in dbcontext as a dbset
    public class Customer: CustomerBase{

    }

    //entity model not referenced in dbcontext as a dbset
    public class DuplicateCustomer:CustomerBase{

       public object DuplicateId {get; set;}

    }

WooCommerce - get category for product page

$product->get_categories() is deprecated since version 3.0! Use wc_get_product_category_list instead.

https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html

Combining multiple commits before pushing in Git

What you want to do is referred to as "squashing" in git. There are lots of options when you're doing this (too many?) but if you just want to merge all of your unpushed commits into a single commit, do this:

git rebase -i origin/master

This will bring up your text editor (-i is for "interactive") with a file that looks like this:

pick 16b5fcc Code in, tests not passing
pick c964dea Getting closer
pick 06cf8ee Something changed
pick 396b4a3 Tests pass
pick 9be7fdb Better comments
pick 7dba9cb All done

Change all the pick to squash (or s) except the first one:

pick 16b5fcc Code in, tests not passing
squash c964dea Getting closer
squash 06cf8ee Something changed
squash 396b4a3 Tests pass
squash 9be7fdb Better comments
squash 7dba9cb All done

Save your file and exit your editor. Then another text editor will open to let you combine the commit messages from all of the commits into one big commit message.

Voila! Googling "git squashing" will give you explanations of all the other options available.

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

One options is: disabled this extension_dir = "ext"

and the other is:

go to wamp icon and see php and the click on php error logs then from error log u can find exact error.

this error occurs only if paths are not properly set.

Set default option in mat-select

Working StackBlitz

No need to use ngModel or Forms

In your html:

 <mat-form-field>
  <mat-select [(value)]="selected" placeholder="Mode">
    <mat-option value="domain">Domain</mat-option>
    <mat-option value="exact">Exact</mat-option>
  </mat-select>
</mat-form-field>

and in your component just set your public property selected to the default:

selected = 'domain';

How to draw rounded rectangle in Android UI?

Use CardView for Round Rectangle. CardView give more functionality like cardCornerRadius, cardBackgroundColor, cardElevation & many more. CardView make UI more suitable then Custom Round Rectangle drawable.

How to call a .NET Webservice from Android using KSOAP2?

Typecast the envelope to SoapPrimitive:

SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
String strRes = result.toString();

and it will work.

How do I remove the space between inline/inline-block elements?

So a lot of complicated answers. The easiest way I can think of is to just give one of the elements a negative margin (either margin-left or margin-right depending on the position of the element).

Why is <deny users="?" /> included in the following example?

"At run time, the authorization module iterates through the allow and deny elements, starting at the most local configuration file, until the authorization module finds the first access rule that fits a particular user account. Then, the authorization module grants or denies access to a URL resource depending on whether the first access rule found is an allow or a deny rule. The default authorization rule is . Thus, by default, access is allowed unless configured otherwise."

Article at MSDN

deny = * means deny everyone
deny = ? means deny unauthenticated users

In your 1st example deny * will not affect dan, matthew since they were already allowed by the preceding rule.

According to the docs, here is no difference in your 2 rule sets.

Bootstrap 3 panel header with buttons wrong position

You should apply a "clearfix" to clear the parent element. Next thing, the h4 for the header title, extend all the way across the header, so after you apply clearfix, it will push down the child element causing the header div to have a larger height.

Here is a fix, just replace it with your code.

  <div class="panel-heading clearfix">
     <b>Panel header</b>
       <div class="btn-group pull-right">
        <a href="#" class="btn btn-default btn-sm">## Lock</a>
        <a href="#" class="btn btn-default btn-sm">## Delete</a>
        <a href="#" class="btn btn-default btn-sm">## Move</a>
      </div>
   </div>

Editted on 12/22/2015 - added .clearfix to heading div

How to reset settings in Visual Studio Code?

This may be overkill, but it seemed to work for me:

#!/bin/sh

rm -rfv "$HOME/.vscode"
rm -rfv "$HOME/Library/Application Support/Code"
rm -rfv "$HOME/Library/Caches/com.microsoft.VSCode"
rm -rfv "$HOME/Library/Saved Application State/com.microsoft.VSCode.savedState"

After I ran that, and restarted VSC, it showed the the "Welcome" screen, which I took to mean that it was starting from scratch.

Can I use Objective-C blocks as properties?

For Swift, just use closures: example.


In Objective-C:

@property (copy)void

@property (copy)void (^doStuff)(void);

It's that simple.

Here is the actual Apple documentation, which states precisely what to use:

Apple doco.

In your .h file:

// Here is a block as a property:
//
// Someone passes you a block. You "hold on to it",
// while you do other stuff. Later, you use the block.
//
// The property 'doStuff' will hold the incoming block.

@property (copy)void (^doStuff)(void);

// Here's a method in your class.
// When someone CALLS this method, they PASS IN a block of code,
// which they want to be performed after the method is finished.

-(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater;

// We will hold on to that block of code in "doStuff".

Here's your .m file:

 -(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater
    {
    // Regarding the incoming block of code, save it for later:
    self.doStuff = pleaseDoMeLater;

    // Now do other processing, which could follow various paths,
    // involve delays, and so on. Then after everything:
    [self _alldone];
    }

-(void)_alldone
    {
    NSLog(@"Processing finished, running the completion block.");
    // Here's how to run the block:
    if ( self.doStuff != nil )
       self.doStuff();
    }

Beware of out-of-date example code.

With modern (2014+) systems, do what is shown here. It is that simple.

Check if a specific value exists at a specific key in any subarray of a multidimensional array

The simplest way is this:

$my_array = array(    
    0 =>  array(  
        "name"   => "john",  
        "id"    =>  4  
    ),  
    1   =>  array(  
        "name" =>  "mark",  
        "id" => 152  
    ), 
    2   =>  array(  
        "name" =>  "Eduard",  
        "id" => 152  
    )
);

if (array_search(152, array_column($my_array, 'id')) !== FALSE)
  echo 'FOUND!';
else
  echo 'NOT FOUND!';

When to use CouchDB over MongoDB and vice versa

The answers above all over complicate the story.

  1. If you plan to have a mobile component, or need desktop users to work offline and then sync their work to a server you need CouchDB.
  2. If your code will run only on the server then go with MongoDB

That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.

jquery $(window).height() is returning the document height

I think your document must be having enough space in the window to display its contents. That means there is no need to scroll down to see any more part of the document. In that case, document height would be equal to the window height.

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

If System.IO.File.Exists(FilePath) Then
    MsgBox("The file exists")
Else
    MsgBox("the file doesn't exist")
End If

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

The livereload plugin fails to serve cordova.js file and serves // mock cordova file during development.

FIX: You need go to node_modules/@ionic/app-scripts/dist/dev-server/serve-config.js

and replace

exports.ANDROID_PLATFORM_PATH = path.join('platforms', 'android', 'assets', 'www');

to

exports.ANDROID_PLATFORM_PATH = path.join('platforms', 'android', 'app', 'src', 'main', 'assets', 'www');

SQL Server: Invalid Column Name

Following procedure helped me solve this issue but i don't know why.

  1. Cut the code in question given by the lines in the message
  2. Save the query (e.g. to file)
  3. Paste the code to where it was before
  4. Again save the query

Even if it seems to be the same query executing it did not throw this error

Use HTML5 to resize an image before upload

Here is what I ended up doing and it worked great.

First I moved the file input outside of the form so that it is not submitted:

<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
    <input id="name" value="#{name}" />
    ... a few more inputs ... 
</form>

Then I changed the uploadPhotos function to handle only the resizing:

window.uploadPhotos = function(url){
    // Read in file
    var file = event.target.files[0];

    // Ensure it's an image
    if(file.type.match(/image.*/)) {
        console.log('An image has been loaded');

        // Load the image
        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            var image = new Image();
            image.onload = function (imageEvent) {

                // Resize the image
                var canvas = document.createElement('canvas'),
                    max_size = 544,// TODO : pull max size from a site config
                    width = image.width,
                    height = image.height;
                if (width > height) {
                    if (width > max_size) {
                        height *= max_size / width;
                        width = max_size;
                    }
                } else {
                    if (height > max_size) {
                        width *= max_size / height;
                        height = max_size;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                var dataUrl = canvas.toDataURL('image/jpeg');
                var resizedImage = dataURLToBlob(dataUrl);
                $.event.trigger({
                    type: "imageResized",
                    blob: resizedImage,
                    url: dataUrl
                });
            }
            image.src = readerEvent.target.result;
        }
        reader.readAsDataURL(file);
    }
};

As you can see I'm using canvas.toDataURL('image/jpeg'); to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl); to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:

/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = parts[1];

        return new Blob([raw], {type: contentType});
    }

    var parts = dataURL.split(BASE64_MARKER);
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;

    var uInt8Array = new Uint8Array(rawLength);

    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }

    return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB      */

Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.

/* Handle image resized events */
$(document).on("imageResized", function (event) {
    var data = new FormData($("form[id*='uploadImageForm']")[0]);
    if (event.blob && event.url) {
        data.append('image_data', event.blob);

        $.ajax({
            url: event.url,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(data){
               //handle errors...
            }
        });
    }
});

How do I get the current mouse screen coordinates in WPF?

Or in pure WPF use PointToScreen.

Sample helper method:

// Gets the absolute mouse position, relative to screen
Point GetMousePos() => _window.PointToScreen(Mouse.GetPosition(_window));

How can I resize an image using Java?

If you are dealing with large images or want a nice looking result it's not a trivial task in java. Simply doing it via a rescale op via Graphics2D will not create a high quality thumbnail. You can do it using JAI, but it requires more work than you would imagine to get something that looks good and JAI has a nasty habit of blowing our your JVM with OutOfMemory errors.

I suggest using ImageMagick as an external executable if you can get away with it. Its simple to use and it does the job right so that you don't have to.

Converting Select results into Insert script - SQL Server

Native method:

for example if you have table

Users(Id, name)

You can do this:

select 'insert into Table values(Id=' + Id + ', name=' + name + ')' from Users

C#: List All Classes in Assembly

Use Assembly.GetTypes. For example:

Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
    Console.WriteLine(type.FullName);
}

Getting the name of a variable as a string

Many of the answers return just one variable name. But that won't work well if more than one variable have the same value. Here's a variation of Amr Sharaki's answer which returns multiple results if more variables have the same value.

def getVariableNames(variable):
    results = []
    globalVariables=globals().copy()
    for globalVariable in globalVariables:
        if id(variable) == id(globalVariables[globalVariable]):
            results.append(globalVariable)
    return results

a = 1
b = 1
getVariableNames(a)
# ['a', 'b']

Removing object from array in Swift 3

This is official answer to find index of specific object, then you can easily remove any object using that index :

var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
     // students[i] = "Max"
     students.remove(at: i)
}
print(students)
// Prints ["Ben", "Ivy", "Jordell"]

Here is the link: https://developer.apple.com/documentation/swift/array/2994720-firstindex

Display a RecyclerView in Fragment

Make sure that you have the correct layout, and that the RecyclerView id is inside the layout. Otherwise, you will be getting this error. I had the same problem, then I noticed the layout was wrong.

    public class ColorsFragment extends Fragment {

         public ColorsFragment() {}

         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {

==> make sure you are getting the correct layout here. R.layout...

             View rootView = inflater.inflate(R.layout.fragment_colors, container, false); 

Get element by id - Angular2

if you want to set value than you can do the same in some function on click or on some event fire.

also you can get value using ViewChild using local variable like this

<input type='text' id='loginInput' #abc/>

and get value like this

this.abc.nativeElement.value

here is working example

Update

okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this

ngAfterViewInit(){
    document.getElementById('loginInput').value = '123344565';
  }

ngAfterViewInit will not throw any error because it will render after template loading

bootstrap 3 navbar collapse button not working

You need to change in this markup

 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar collapse">

change the

data-target=".navbar collapse"

to

data-target=".navbar-collapse"

Reason : The value of data-target is a any class name of the associated nav div. In this case it is

<div class="collapse navbar-collapse">  <-- Look at here
     <ul class="nav navbar-nav navbar-right">
     .....
</div>

Js Fiddle Demo

What are Makefile.am and Makefile.in?

DEVELOPER runs autoconf and automake:

  1. autoconf -- creates shippable configure script
    (which the installer will later run to make the Makefile)
  1. automake - creates shippable Makefile.in data file
    (which configure will later read to make the Makefile)

INSTALLER runs configure, make and sudo make install:

./configure       # Creates  Makefile        (from     Makefile.in).  
make              # Creates  the application (from the Makefile just created).  

sudo make install # Installs the application 
                  #   Often, by default its files are installed into /usr/local


INPUT/OUTPUT MAP

Notation below is roughly: inputs --> programs --> outputs

DEVELOPER runs these:

configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in depreciated. Use configure.ac)

Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)

INSTALLER runs these:

Makefile.in -> configure -> Makefile (*.in = input file)

Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)


"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."

"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."

Manuals:

Free online tutorials:


Example:

The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)

From this my generated configure is over 41k lines of code.

And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)

What is the difference between a Docker image and a container?

As in the programming aspect,

Image is source code.

When source code is compiled and build, it is called an application.

Similar to that "when an instance is created for the image", it is called a "container".

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Office 365 use two servers, smtp server and protect extended sever.

First server is smtp.office365.com (property Host of smtp client) and second server is STARTTLS/smtp.office365.com (property TargetName of smtp client). Another thing is must put Usedefaultcredential =false before set networkcredentials.

    client.UseDefaultCredentials = False
    client.Credentials = New NetworkCredential("[email protected]", "Password")
    client.Host = "smtp.office365.com"
    client.EnableSsl = true
    client.TargetName = "STARTTLS/smtp.office365.com"
    client.Port = 587

    client.Send(mail)

Close virtual keyboard on button press

Use Below Code

your_button_id.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try  {
            InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {

        }
    }
});

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

public class RemoveExtraSpacesEfficient {

    public static void main(String[] args) {

        String s = "my    name is    mr    space ";

        char[] charArray = s.toCharArray();

        char prev = s.charAt(0);

        for (int i = 0; i < charArray.length; i++) {
            char cur = charArray[i];
            if (cur == ' ' && prev == ' ') {

            } else {
                System.out.print(cur);
            }
            prev = cur;
        }
    }
}

The above solution is the algorithm with the complexity of O(n) without using any java function.

Does MS SQL Server's "between" include the range boundaries?

It does includes boundaries.

declare @startDate date = cast('15-NOV-2016' as date) 
declare @endDate date = cast('30-NOV-2016' as date)
create table #test (c1 date)
insert into #test values(cast('15-NOV-2016' as date))
insert into #test values(cast('20-NOV-2016' as date))
insert into #test values(cast('30-NOV-2016' as date))
select * from #test where c1 between @startDate and @endDate
drop table #test
RESULT    c1
2016-11-15
2016-11-20
2016-11-30


declare @r1 int  = 10
declare @r2 int  = 15
create table #test1 (c1 int)
insert into #test1 values(10)
insert into #test1 values(15)
insert into #test1 values(11)
select * from #test1 where c1 between @r1 and @r2
drop table #test1
RESULT c1
10
11
15

Override and reset CSS style: auto or none don't work

I ended up using Javascript to perfect everything.

My JS fiddle: https://jsfiddle.net/QEpJH/612/

HTML:

<div class="container">
    <img src="http://placekitten.com/240/300">
</div>

<h3 style="clear: both;">Full Size Image - For Reference</h3>
<img src="http://placekitten.com/240/300">

CSS:

.container {
    background-color:#000;
    width:100px;
    height:200px;

    display:flex;
    justify-content:center;
    align-items:center;
    overflow:hidden;

}

JS:

$(".container").each(function(){
    var divH = $(this).height()
    var divW = $(this).width()
    var imgH = $(this).children("img").height();
    var imgW = $(this).children("img").width();

    if ( (imgW/imgH) < (divW/divH)) { 
        $(this).addClass("1");
        var newW = $(this).width();
        var newH = (newW/imgW) * imgH;
        $(this).children("img").width(newW); 
        $(this).children("img").height(newH); 
    } else {
        $(this).addClass("2");
        var newH = $(this).height();
        var newW = (newH/imgH) * imgW;
        $(this).children("img").width(newW); 
        $(this).children("img").height(newH); 
    }
})

Beautiful way to remove GET-variables with PHP?

Another solution... I find this function more elegant, it will also remove the trailing '?' if the key to remove is the only one in the query string.

/**
 * Remove a query string parameter from an URL.
 *
 * @param string $url
 * @param string $varname
 *
 * @return string
 */
function removeQueryStringParameter($url, $varname)
{
    $parsedUrl = parse_url($url);
    $query = array();

    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $query);
        unset($query[$varname]);
    }

    $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
    $query = !empty($query) ? '?'. http_build_query($query) : '';

    return $parsedUrl['scheme']. '://'. $parsedUrl['host']. $path. $query;
}

Tests:

$urls = array(
    'http://www.example.com?test=test',
    'http://www.example.com?bar=foo&test=test2&foo2=dooh',
    'http://www.example.com',
    'http://www.example.com?foo=bar',
    'http://www.example.com/test/no-empty-path/?foo=bar&test=test5',
    'https://www.example.com/test/test.test?test=test6',
);

foreach ($urls as $url) {
    echo $url. '<br/>';
    echo removeQueryStringParameter($url, 'test'). '<br/><br/>';
}

Will output:

http://www.example.com?test=test
http://www.example.com

http://www.example.com?bar=foo&test=test2&foo2=dooh
http://www.example.com?bar=foo&foo2=dooh

http://www.example.com
http://www.example.com

http://www.example.com?foo=bar
http://www.example.com?foo=bar

http://www.example.com/test/no-empty-path/?foo=bar&test=test5
http://www.example.com/test/no-empty-path/?foo=bar

https://www.example.com/test/test.test?test=test6
https://www.example.com/test/test.test

» Run these tests on 3v4l

Get a list of URLs from a site

Here is a list of sitemap generators (from which obviously you can get the list of URLs from a site): http://code.google.com/p/sitemap-generators/wiki/SitemapGenerators

Web Sitemap Generators

The following are links to tools that generate or maintain files in the XML Sitemaps format, an open standard defined on sitemaps.org and supported by the search engines such as Ask, Google, Microsoft Live Search and Yahoo!. Sitemap files generally contain a collection of URLs on a website along with some meta-data for these URLs. The following tools generally generate "web-type" XML Sitemap and URL-list files (some may also support other formats).

Please Note: Google has not tested or verified the features or security of the third party software listed on this site. Please direct any questions regarding the software to the software's author. We hope you enjoy these tools!

Server-side Programs

  • Enarion phpSitemapsNG (PHP)
  • Google Sitemap Generator (Linux/Windows, 32/64bit, open-source)
  • Outil en PHP (French, PHP)
  • Perl Sitemap Generator (Perl)
  • Python Sitemap Generator (Python)
  • Simple Sitemaps (PHP)
  • SiteMap XML Dynamic Sitemap Generator (PHP) $
  • Sitemap generator for OS/2 (REXX-script)
  • XML Sitemap Generator (PHP) $

CMS and Other Plugins:

  • ASP.NET - Sitemaps.Net
  • DotClear (Spanish)
  • DotClear (2)
  • Drupal
  • ECommerce Templates (PHP) $
  • Ecommerce Templates (PHP or ASP) $
  • LifeType
  • MediaWiki Sitemap generator
  • mnoGoSearch
  • OS Commerce
  • phpWebSite
  • Plone
  • RapidWeaver
  • Textpattern
  • vBulletin
  • Wikka Wiki (PHP)
  • WordPress

Downloadable Tools

  • GSiteCrawler (Windows)
  • GWebCrawler & Sitemap Creator (Windows)
  • G-Mapper (Windows)
  • Inspyder Sitemap Creator (Windows) $
  • IntelliMapper (Windows) $
  • Microsys A1 Sitemap Generator (Windows) $
  • Rage Google Sitemap Automator $ (OS-X)
  • Screaming Frog SEO Spider and Sitemap generator (Windows/Mac) $
  • Site Map Pro (Windows) $
  • Sitemap Writer (Windows) $
  • Sitemap Generator by DevIntelligence (Windows)
  • Sorrowmans Sitemap Tools (Windows)
  • TheSiteMapper (Windows) $
  • Vigos Gsitemap (Windows)
  • Visual SEO Studio (Windows)
  • WebDesignPros Sitemap Generator (Java Webstart Application)
  • Weblight (Windows/Mac) $
  • WonderWebWare Sitemap Generator (Windows)

Online Generators/Services

  • AuditMyPc.com Sitemap Generator
  • AutoMapIt
  • Autositemap $
  • Enarion phpSitemapsNG
  • Free Sitemap Generator
  • Neuroticweb.com Sitemap Generator
  • ROR Sitemap Generator
  • ScriptSocket Sitemap Generator
  • SeoUtility Sitemap Generator (Italian)
  • SitemapDoc
  • Sitemapspal
  • SitemapSubmit
  • Smart-IT-Consulting Google Sitemaps XML Validator
  • XML Sitemap Generator
  • XML-Sitemaps Generator

CMS with integrated Sitemap generators

  • Concrete5

Google News Sitemap Generators The following plugins allow publishers to update Google News Sitemap files, a variant of the sitemaps.org protocol that we describe in our Help Center. In addition to the normal properties of Sitemap files, Google News Sitemaps allow publishers to describe the types of content they publish, along with specifying levels of access for individual articles. More information about Google News can be found in our Help Center and Help Forums.

  • WordPress Google News plugin

Code Snippets / Libraries

  • ASP script
  • Emacs Lisp script
  • Java library
  • Perl script
  • PHP class
  • PHP generator script

If you believe that a tool should be added or removed for a legitimate reason, please leave a comment in the Webmaster Help Forum.

The network path was not found

I recently had the same issue. It's more likely that your application can not connect to database server due to the network issues.

In my case I was connected to wrong WiFi.

Check array position for null/empty

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

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

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

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

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

Check if argparse optional argument is set or not

I think that optional arguments (specified with --) are initialized to None if they are not supplied. So you can test with is not None. Try the example below:

import argparse as ap

def main():
    parser = ap.ArgumentParser(description="My Script")
    parser.add_argument("--myArg")
    args, leftovers = parser.parse_known_args()

    if args.myArg is not None:
        print "myArg has been set (value is %s)" % args.myArg

jQuery: Check if button is clicked

jQuery(':button').click(function () {
    if (this.id == 'button1') {
        alert('Button 1 was clicked');
    }
    else if (this.id == 'button2') {
        alert('Button 2 was clicked');
    }
});

EDIT:- This will work for all buttons.

Submit form with Enter key without submit button?

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

Find TODO tags in Eclipse

Go TO Window>Show View >Markers

than you will get java task .

java task have all TODOs of your project

PHP, MySQL error: Column count doesn't match value count at row 1

You have 9 fields listed, but only 8 values. Try adding the method.

"Correct" way to specifiy optional arguments in R functions

To be honest I like the OP's first way of actually starting it with a NULL value and then checking it with is.null (primarily because it is very simply and easy to understand). It maybe depends on the way people are used to coding but the Hadley seems to support the is.null way too:

From Hadley's book "Advanced-R" Chapter 6, Functions, p.84 (for the online version check here):

You can determine if an argument was supplied or not with the missing() function.

i <- function(a, b) {
  c(missing(a), missing(b))
}
i()
#> [1] TRUE TRUE
i(a = 1)
#> [1] FALSE  TRUE
i(b = 2)
#> [1]  TRUE FALSE
i(1, 2)
#> [1] FALSE FALSE

Sometimes you want to add a non-trivial default value, which might take several lines of code to compute. Instead of inserting that code in the function definition, you could use missing() to conditionally compute it if needed. However, this makes it hard to know which arguments are required and which are optional without carefully reading the documentation. Instead, I usually set the default value to NULL and use is.null() to check if the argument was supplied.

Find distance between two points on map using Google Map API V2

simple util function to calculate distance between two geopoints:

public static long getDistanceMeters(double lat1, double lng1, double lat2, double lng2) {

    double l1 = toRadians(lat1);
    double l2 = toRadians(lat2);
    double g1 = toRadians(lng1);
    double g2 = toRadians(lng2);

    double dist = acos(sin(l1) * sin(l2) + cos(l1) * cos(l2) * cos(g1 - g2));
    if(dist < 0) {
        dist = dist + Math.PI;
    }

    return Math.round(dist * 6378100);
}

How do I convert an enum to a list in C#?

Here for usefulness... some code for getting the values into a list, which converts the enum into readable form for the text

public class KeyValuePair
  {
    public string Key { get; set; }

    public string Name { get; set; }

    public int Value { get; set; }

    public static List<KeyValuePair> ListFrom<T>()
    {
      var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>());
      return array
        .Select(a => new KeyValuePair
          {
            Key = a.ToString(),
            Name = a.ToString().SplitCapitalizedWords(),
            Value = Convert.ToInt32(a)
          })
          .OrderBy(kvp => kvp.Name)
         .ToList();
    }
  }

.. and the supporting System.String extension method:

/// <summary>
/// Split a string on each occurrence of a capital (assumed to be a word)
/// e.g. MyBigToe returns "My Big Toe"
/// </summary>
public static string SplitCapitalizedWords(this string source)
{
  if (String.IsNullOrEmpty(source)) return String.Empty;
  var newText = new StringBuilder(source.Length * 2);
  newText.Append(source[0]);
  for (int i = 1; i < source.Length; i++)
  {
    if (char.IsUpper(source[i]))
      newText.Append(' ');
    newText.Append(source[i]);
  }
  return newText.ToString();
}

How to set an image as a background for Frame in Swing GUI of java?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
  JButton b1;
  JLabel l1;
public BackgroundImageJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
 One way
-----------------*/
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);

// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads  \\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
add(l1);
add(b1);
// Just for refresh :) Not optional!
  setSize(399,399);
   setSize(400,400);
   }
   public static void main(String args[])
  {
   new BackgroundImageJFrame();
 }
 }

List append() in for loop

The list.append function does not return any value(but None), it just adds the value to the list you are using to call that method.

In the first loop round you will assign None (because the no-return of append) to a, then in the second round it will try to call a.append, as a is None it will raise the Exception you are seeing

You just need to change it to:

a=[]
for i in range(5):    
    a.append(i)
print(a)
# [0, 1, 2, 3, 4]

list.append is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).

If you would like to create a new list based in one list without destroying or mutating it you can do something like this:

a=['a', 'b', 'c']
result = a + ['d']

print result
# ['a', 'b', 'c', 'd']

print a
# ['a', 'b', 'c']

As a corollary only, you can mimic the append method by doing the following:

a=['a', 'b', 'c']
a = a + ['d']

print a
# ['a', 'b', 'c', 'd']

Run Java Code Online

rextester runs java snippets

Also accessible as runjavaonline.com

Evenly space multiple views within a container view

I just solved my problem using the multiplier feature. I'm not sure it works for all cases, but for me it worked perfectly. I'm on Xcode 6.3 FYI.

What I ended up doing was:

1) First getting my buttons positioned on a 320px width screen distributed the way I wanted it to look on a 320px device.

step 1: getting buttons positioned

2) Then I added a leading Space constraint to superview on all of my buttons.

step 2: add leading space constraints

3) Then I modified the properties of the leading space so that the constant was 0 and the multiplier is the x offset divided by width of the screen (e.g. my first button was 8px from left edge so I set my multiplier to 8/320)

4) Then the important step here is to change the second Item in the constraint relation to be the superview.Trailing instead of superview.leading. This is key because superview.Leading is 0 and trailing in my case is 320, so 8/320 is 8 px on a 320px device, then when the superview's width changes to 640 or whatever, the views all move at a ratio relative to width of the 320px screen size. The math here is much simpler to understand.

step 3 & 4: change multiplier to xPos/screenWidth and set second item to .Trailing

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

Is it possible to use an input value attribute as a CSS selector?

As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:

<style>
input:not([value=""]){
border:2px solid red;
}
</style>

<input type="text" onkeyup="this.setAttribute('value', this.value);"/>

open read and close a file in 1 line of code

You don't really have to close it - Python will do it automatically either during garbage collection or at program exit. But as @delnan noted, it's better practice to explicitly close it for various reasons.

So, what you can do to keep it short, simple and explicit:

with open('pagehead.section.htm','r') as f:
    output = f.read()

Now it's just two lines and pretty readable, I think.

Limiting Powershell Get-ChildItem by File Creation Date Range

Use Where-Object and test the $_.CreationTime:

Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") | 
    Where-Object { $_.CreationTime -ge "03/01/2013" -and $_.CreationTime -le "03/31/2013" }

How to update a plot in matplotlib?

All of the above might be true, however for me "online-updating" of figures only works with some backends, specifically wx. You just might try to change to this, e.g. by starting ipython/pylab by ipython --pylab=wx! Good luck!

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

Convert audio files to mp3 using ffmpeg

Never mind,

I am converting my audio files to mp2 by using the command:

ffmpeg -i input.wav -f mp2 output.mp3

This command works perfectly.

I know that this actually converts the files to mp2 format, but then the resulting file sizes are the same..

Java RegEx meta character (.) and ordinary dot?

If you want to end check whether your sentence ends with "." then you have to add [\.\]$ to the end of your pattern.

Select all occurrences of selected word in VSCode

In my MacOS case for some reason Cmd+Shift+L is not working while pressing the short cut on the keyboard (although it work just fine while clicking on this option in menu: Selection -> Select All Occurences). So for me pressing Cmd+FN+F2 did the trick (FN is for enabling "F2" obviously).

Btw, if you forget this shortcut just do right-click on the selection and see "Change All Occurrences" option

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

Beginning with MySQL 8.0.19 you can use an alias for that row (see reference).

INSERT INTO beautiful (name, age)
    VALUES
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
    AS new
ON DUPLICATE KEY UPDATE
    age = new.age
    ...

For earlier versions use the keyword VALUES (see reference, deprecated with MySQL 8.0.20).

INSERT INTO beautiful (name, age)
    VALUES
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
ON DUPLICATE KEY UPDATE
    age = VALUES(age),
     ...

How can VBA connect to MySQL database in Excel?

Enable Microsoft ActiveX Data Objects 2.8 Library

Dim oConn As ADODB.Connection 
Private Sub ConnectDB()     
Set oConn = New ADODB.Connection    
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _        
"SERVER=localhost;" & _         
"DATABASE=yourdatabase;" & _        
"USER=yourdbusername;" & _      
"PASSWORD=yourdbpassword;" & _      
"Option=3" 
End Sub

There rest is here: http://www.heritage-tech.net/908/inserting-data-into-mysql-from-excel-using-vba/

Is Java's assertEquals method reliable?

Yes, it is used all the time for testing. It is very likely that the testing framework uses .equals() for comparisons such as these.

Below is a link explaining the "string equality mistake". Essentially, strings in Java are objects, and when you compare object equality, typically they are compared based on memory address, and not by content. Because of this, two strings won't occupy the same address, even if their content is identical, so they won't match correctly, even though they look the same when printed.

http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

How to find difference between two columns data?

select previous, Present, previous-Present as Difference from tablename

or

select previous, Present, previous-Present as Difference from #TEMP1

Removing viewcontrollers from navigation stack

Swift 5:

navigationController?.viewControllers.removeAll(where: { (vc) -> Bool in
    if vc.isKind(of: MyViewController.self) || vc.isKind(of: MyViewController2.self) {
        return false
    } else {
        return true
    }
})

Solving Quadratic Equation

# syntaxis:2.7
# solution for quadratic equation
# a*x**2 + b*x + c = 0

d = b**2-4*a*c # discriminant

if d < 0:
    print 'No solutions'
elif d == 0:
    x1 = -b / (2*a)
    print 'The sole solution is',x1
else: # if d > 0
    x1 = (-b + math.sqrt(d)) / (2*a)
    x2 = (-b - math.sqrt(d)) / (2*a)
    print 'Solutions are',x1,'and',x2

YouTube Autoplay not working

You can use embed player with opacity over on a cover photo with a right positioned play icon. After this you can check the activeElement of your document.

Of course I know this is not an optimal solution, but works on mobile devices too.

<div style="position: relative;">
   <img src="http://s3.amazonaws.com/content.newsok.com/newsok/images/mobile/play_button.png" style="position:absolute;top:0;left:0;opacity:1;" id="cover">
   <iframe width="560" height="315" src="https://www.youtube.com/embed/2qhCjgMKoN4?controls=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in- picture" allowfullscreen style="position: absolute;top:0;left:0;opacity:0;" id="player"></iframe>
 </div>
 <script>
   setInterval(function(){
      if(document.activeElement instanceof HTMLIFrameElement){
         document.getElementById('cover').style.opacity=0;
         document.getElementById('player').style.opacity=1;
       }
    } , 50);
  </script>

Try it on codepen: https://codepen.io/sarkiroka/pen/OryxGP

Bootstrap 3 offset on right not left

_x000D_
_x000D_
<div class="row col-xs-12">            _x000D_
            <nav class="col-xs-12 col-xs-offset-7" aria-label="Page navigation">_x000D_
                <ul class="pagination mt-0">                   _x000D_
                    <li class="page-item">                        _x000D_
                        <div class="form-group">_x000D_
                            <div class="input-group">_x000D_
                                <input type="text" asp-for="search" class="form-control" placeholder="Search" aria-controls="order-listing" />_x000D_
_x000D_
                                <div class="input-group-prepend bg-info">_x000D_
                                    <input type="submit" value="Search" class="input-group-text bg-transparent">                                   _x000D_
                                </div>_x000D_
                            </div>_x000D_
                        </div>_x000D_
                    </li>_x000D_
                   _x000D_
                </ul>_x000D_
            </nav>_x000D_
        </div>
_x000D_
_x000D_
_x000D_

Android textview outline text

So, little late, but MagicTextView will do text outlines, amongst other things.

enter image description here

<com.qwerjk.better_text.MagicTextView
    xmlns:qwerjk="http://schemas.android.com/apk/res/com.qwerjk.better_text"
    android:textSize="78dp"
    android:textColor="#ff333333"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    qwerjk:strokeColor="#FFff0000"
    qwerjk:strokeJoinStyle="miter"
    qwerjk:strokeWidth="5"
    android:text="Magic" />

Note: I made this, and am posting more for the sake of future travelers than the OP. It's borderline spam, but being on-topic, perhaps acceptable?

Comparing strings by their alphabetical order

import java.io.*;
import java.util.*;
public class CandidateCode {
    public static void main(String args[] ) throws Exception {
       Scanner sc = new Scanner(System.in);
           int n =Integer.parseInt(sc.nextLine());
           String arr[] = new String[n];
        for (int i = 0; i < arr.length; i++) {
                arr[i] = sc.nextLine();
                }


         for(int i = 0; i <arr.length; ++i) {
            for (int j = i + 1; j <arr.length; ++j) {
                if (arr[i].compareTo(arr[j]) > 0) {
                    String temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        for(int i = 0; i <arr.length; i++) {
            System.out.println(arr[i]);
        }
   }
}

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

Windows Forms - Enter keypress activates submit button?

Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key. On detection call whatever code you would have for the "submit" button.

Why should we typedef a struct so often in C?

Let's start with the basics and work our way up.

Here is an example of Structure definition:

struct point
  {
    int x, y;
  };

Here the name point is optional.

A Structure can be declared during its definition or after.

Declaring during definition

struct point
  {
    int x, y;
  } first_point, second_point;

Declaring after definition

struct point
  {
    int x, y;
  };
struct point first_point, second_point;

Now, carefully note the last case above; you need to write struct point to declare Structures of that type if you decide to create that type at a later point in your code.

Enter typedef. If you intend to create new Structure ( Structure is a custom data-type) at a later time in your program using the same blueprint, using typedef during its definition might be a good idea since you can save some typing moving forward.

typedef struct point
  {
    int x, y;
  } Points;

Points first_point, second_point;

A word of caution while naming your custom type

Nothing prevents you from using _t suffix at the end of your custom type name but POSIX standard reserves the use of suffix _t to denote standard library type names.

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

  1. running code before Compilation : use controller
  2. running code after Compilation : use Link

Angular convention : write business logic in controller and DOM manipulation in link.

Apart from this you can call one controller function from link function of another directive.For example you have 3 custom directives

<animal>
<panther>
<leopard></leopard>
</panther> 
</animal>

and you want to access animal from inside of "leopard" directive.

http://egghead.io/lessons/angularjs-directive-communication will be helpful to know about inter-directive communication

Wait until ActiveWorkbook.RefreshAll finishes - VBA

DISCLAIMER: The code below reportedly casued some crashes! Use with care.

according to THIS answer in Excel 2010 and above CalculateUntilAsyncQueriesDone halts macros until refresh is done
ThisWorkbook.RefreshAll
Application.CalculateUntilAsyncQueriesDone

Convert integer to string Jinja

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

Input button target="_blank" isn't causing the link to load in a new window/tab

In a similar use case, this worked for me...

<button onclick="window.open('https://www.w3.org/', '_blank');">  My Button </button>

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

The JPA @Column Annotation

The nullable attribute of the @Column annotation has two purposes:

  • it's used by the schema generation tool
  • it's used by Hibernate during flushing the Persistence Context

Schema Generation Tool

The HBM2DDL schema generation tool translates the @Column(nullable = false) entity attribute to a NOT NULL constraint for the associated table column when generating the CREATE TABLE statement.

As I explained in the Hibernate User Guide, it's better to use a tool like Flyway instead of relying on the HBM2DDL mechanism for generating the database schema.

Persistence Context Flush

When flushing the Persistence Context, Hibernate ORM also uses the @Column(nullable = false) entity attribute:

new Nullability( session ).checkNullability( values, persister, true );

If the validation fails, Hibernate will throw a PropertyValueException, and prevents the INSERT or UPDATE statement to be executed needesly:

if ( !nullability[i] && value == null ) {
    //check basic level one nullablilty
    throw new PropertyValueException(
            "not-null property references a null or transient value",
            persister.getEntityName(),
            persister.getPropertyNames()[i]
        );    
}

The Bean Validation @NotNull Annotation

The @NotNull annotation is defined by Bean Validation and, just like Hibernate ORM is the most popular JPA implementation, the most popular Bean Validation implementation is the Hibernate Validator framework.

When using Hibernate Validator along with Hibernate ORM, Hibernate Validator will throw a ConstraintViolation when validating the entity.

The name 'model' does not exist in current context in MVC3

I've got the same issue after updating packages. I did the whole stuff You've written above in this topic, but the red underlying of the model keyword has not disappeared. Later, found solution: just deleted 'package' folder from my project's dir and rebuilded, in the meantime allowed NuGet to restore missing packages. Refreshed, and it's done!

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

In my case, upgraded from spring-securiy-web 3.1.3 to 4.2.12, the defaultHttpFirewall was changed from DefaultHttpFirewall to StrictHttpFirewall by default. So just define it in XML configuration like below:

<bean id="defaultHttpFirewall" class="org.springframework.security.web.firewall.DefaultHttpFirewall"/>
<sec:http-firewall ref="defaultHttpFirewall"/>

set HTTPFirewall as DefaultHttpFirewall

How to change the height of a div dynamically based on another div using css?

The simplest way to get equal height columns, without the ugly side effects that come along with absolute positioning, is to use the display: table properties:

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  display: table;
}

.div2, .div3 {
  display: table-cell;
}
.div2 {
  width:150px;
  height:auto;
  background-color: #F4A460;  

}
.div3 {
  width:150px;
  height:auto;
  background-color: #FFFFE0;  
}

http://jsfiddle.net/E4Zgj/21/


Now, if your goal is to have .div2 so that it is only as tall as it needs to be to contain its content while .div3 is at least as tall as .div2 but still able to expand if its content makes it taller than .div2, then you need to use flexbox. Flexbox support isn't quite there yet (IE10, Opera, Chrome. Firefox follows an old spec, but is following the current spec soon).

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  display: flex;
  align-items: flex-start;
}

.div2 {
  width:150px;
  background-color: #F4A460;
}

.div3 {
  width:150px;
  background-color: #FFFFE0;
  align-self: stretch;
}

http://jsfiddle.net/E4Zgj/22/

How to override the path of PHP to use the MAMP path?

Everytime you save MAMP config (PHP section), it saves the current version of PHP on ~/.profile file and creates the alias for php, pear and pecl, to point to the current configured version. (Note: you need to check "Make this version available on the command line" option in MAMP)

However, you need to refresh your terminal (open another session) to get this file refreshed. You can also type source ~/.profile to refesh the aliases manually.

If you want to extract this curerent version in a PHP_VERSION variable - as commented above - for further use, you can do:

export PHP_VERSION=`grep "alias php" ~/.profile | cut -d"/" -f6 | cut -c4-`

And then you'll have $PHP_VERSION available with the current version of MAMP.

Finally, if you want to run your php using the current configured version on mamp, you just need to add to your ~/.bash_profile the following:

export PHP_VERSION=`grep "alias php" ~/.profile | cut -d"/" -f6 | cut -c4-`
export PHPRC="/Library/Application Support/appsolute/MAMP PRO/conf/" #point to your php.ini folder to use the same php settings
export PATH=/Applications/MAMP/bin/php/php$PHP_VERSION/bin:$PATH

Now, even script that relies on /usr/bin/env php will read the correct version from Mamp config.

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

Maven artifact and groupId naming

Your convention seems to be reasonable. If I were searching for your framework in the Maven repo, I would look for awesome-inhouse-framework-x.y.jar in com.mycompany.awesomeinhouseframework group directory. And I would find it there according to your convention.

Two simple rules work for me:

  • reverse-domain-packages for groupId (since such are quite unique) with all the constrains regarding Java packages names
  • project name as artifactId (keeping in mind that it should be jar-name friendly i.e. not contain characters that maybe invalid for a file name or just look weird)

JS map return object

Use .map without return in simple way. Also start using let and const instead of var because let and const is more recommended

_x000D_
_x000D_
const rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
const launchOptimistic = rockets.map(elem => (_x000D_
  {_x000D_
    country: elem.country,_x000D_
    launches: elem.launches+10_x000D_
  } _x000D_
));_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
_x000D_
_x000D_

Offline Speech Recognition In Android (JellyBean)

In short, I don't have the implementation, but the explanation.

Google did not make offline speech recognition available to third party apps. Offline recognition is only accessable via the keyboard. Ben Randall (the developer of utter!) explains his workaround in an article at Android Police:

I had implemented my own keyboard and was switching between Google Voice Typing and the users default keyboard with an invisible edit text field and transparent Activity to get the input. Dirty hack!

This was the only way to do it, as offline Voice Typing could only be triggered by an IME or a system application (that was my root hack) . The other type of recognition API … didn't trigger it and just failed with a server error. … A lot of work wasted for me on the workaround! But at least I was ready for the implementation...

From Utter! Claims To Be The First Non-IME App To Utilize Offline Voice Recognition In Jelly Bean

How to override equals method in Java

Item 10: Obey the general contract when overriding equals

According to Effective Java, Overriding the equals method seems simple, but there are many ways to get it wrong, and consequences can be dire. The easiest way to avoid problems is not to override the equals method, in which case each instance of the class is equal only to itself. This is the right thing to do if any of the following conditions apply:

  • Each instance of the class is inherently unique. This is true for classes such as Thread that represent active entities rather than values. The equals implementation provided by Object has exactly the right behavior for these classes.

  • There is no need for the class to provide a “logical equality” test. For example, java.util.regex.Pattern could have overridden equals to check whether two Pattern instances represented exactly the same regular expression, but the designers didn’t think that clients would need or want this functionality. Under these circumstances, the equals implementation inherited from Object is ideal.

  • A superclass has already overridden equals, and the superclass behavior is appropriate for this class. For example, most Set implementations inherit their equals implementation from AbstractSet, List implementations from AbstractList, and Map implementations from AbstractMap.

  • The class is private or package-private, and you are certain that its equals method will never be invoked. If you are extremely risk-averse, you can override the equals method to ensure that it isn’t invoked accidentally:

The equals method implements an equivalence relation. It has these properties:

  • Reflexive: For any non-null reference value x, x.equals(x) must return true.

  • Symmetric: For any non-null reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns true.

  • Transitive: For any non-null reference values x, y, z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.

  • Consistent: For any non-null reference values x and y, multiple invocations of x.equals(y) must consistently return true or consistently return false, provided no information used in equals comparisons is modified.

  • For any non-null reference value x, x.equals(null) must return false.

Here’s a recipe for a high-quality equals method:

  1. Use the == operator to check if the argument is a reference to this object. If so, return true. This is just a performance optimization but one that is worth doing if the comparison is potentially expensive.

  2. Use the instanceof operator to check if the argument has the correct type. If not, return false. Typically, the correct type is the class in which the method occurs. Occasionally, it is some interface implemented by this class. Use an interface if the class implements an interface that refines the equals contract to permit comparisons across classes that implement the interface. Collection interfaces such as Set, List, Map, and Map.Entry have this property.

  3. Cast the argument to the correct type. Because this cast was preceded by an instanceof test, it is guaranteed to succeed.

  4. For each “significant” field in the class, check if that field of the argument matches the corresponding field of this object. If all these tests succeed, return true; otherwise, return false. If the type in Step 2 is an interface, you must access the argument’s fields via interface methods; if the type is a class, you may be able to access the fields directly, depending on their accessibility.

  5. For primitive fields whose type is not float or double, use the == operator for comparisons; for object reference fields, call the equals method recursively; for float fields, use the static Float.compare(float, float) method; and for double fields, use Double.compare(double, double). The special treatment of float and double fields is made necessary by the existence of Float.NaN, -0.0f and the analogous double values; While you could compare float and double fields with the static methods Float.equals and Double.equals, this would entail autoboxing on every comparison, which would have poor performance. For array fields, apply these guidelines to each element. If every element in an array field is significant, use one of the Arrays.equals methods.

  6. Some object reference fields may legitimately contain null. To avoid the possibility of a NullPointerException, check such fields for equality using the static method Objects.equals(Object, Object).

    // Class with a typical equals method
    
    public final class PhoneNumber {
    
        private final short areaCode, prefix, lineNum;
    
        public PhoneNumber(int areaCode, int prefix, int lineNum) {
    
            this.areaCode = rangeCheck(areaCode,  999, "area code");
    
            this.prefix   = rangeCheck(prefix,    999, "prefix");
    
            this.lineNum  = rangeCheck(lineNum,  9999, "line num");
    
        }
    
        private static short rangeCheck(int val, int max, String arg) {
    
            if (val < 0 || val > max)
    
               throw new IllegalArgumentException(arg + ": " + val);
    
            return (short) val;
    
        }
    
        @Override public boolean equals(Object o) {
            if (o == this)
                return true;
            if (!(o instanceof PhoneNumber))
                return false;
            PhoneNumber pn = (PhoneNumber)o;
            return pn.lineNum == lineNum && pn.prefix == prefix
                    && pn.areaCode == areaCode;
        }
        ... // Remainder omitted
    
    }
    

How to copy marked text in notepad++

I had the same problem. You can list the regex matches in a new tab, every match in new line in PSPad Editor, which is very similar as Notepad++.

Hit Ctrl + F to search, check the regexp opion, put the regexp and click on List.

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

You could add it:

public static IEnumerable<T> OrderBy( this IEnumerable<T> input, string queryString) {
    //parse the string into property names
    //Use reflection to get and sort by properties
    //something like

    foreach( string propname in queryString.Split(','))
        input.OrderBy( x => GetPropertyValue( x, propname ) );

    // I used Kjetil Watnedal's reflection example
}

The GetPropertyValue function is from Kjetil Watnedal's answer

The issue would be why? Any such sort would throw exceptions at run-time, rather than compile time (like D2VIANT's answer).

If you're dealing with Linq to Sql and the orderby is an expression tree it will be converted into SQL for execution anyway.

Cannot implicitly convert type 'int' to 'short'

The result of summing two Int16 variables is an Int32:

Int16 i1 = 1;
Int16 i2 = 2;
var result = i1 + i2;
Console.WriteLine(result.GetType().Name);

It outputs Int32.

Python Pandas Error tokenizing data

Simple resolution: Open the csv file in excel & save it with different name file of csv format. Again try importing it spyder, Your problem will be resolved!

How generate unique Integers based on GUIDs

If you are looking to break through the 2^32 barrier then try this method:

/// <summary>
/// Generate a BigInteger given a Guid. Returns a number from 0 to 2^128
/// 0 to 340,282,366,920,938,463,463,374,607,431,768,211,456
/// </summary>
    public BigInteger GuidToBigInteger(Guid guid)
    {
        BigInteger l_retval = 0;
        byte[] ba = guid.ToByteArray();
        int i = ba.Count();
        foreach (byte b in ba)
        {
            l_retval += b * BigInteger.Pow(256, --i);
        }
        return l_retval;
    }

The universe will decay to a cold and dark expanse before you experience a collision.

How to use subList()

I've implemented and tested this one; it should cover most bases:

public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
    int size = list.size();
    if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
        return Collections.emptyList();
    }

    fromIndex = Math.max(0, fromIndex);
    toIndex = Math.min(size, toIndex);

    return list.subList(fromIndex, toIndex);
}

Python multiprocessing PicklingError: Can't pickle <type 'function'>

I'd use pathos.multiprocesssing, instead of multiprocessing. pathos.multiprocessing is a fork of multiprocessing that uses dill. dill can serialize almost anything in python, so you are able to send a lot more around in parallel. The pathos fork also has the ability to work directly with multiple argument functions, as you need for class methods.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> p = Pool(4)
>>> class Test(object):
...   def plus(self, x, y): 
...     return x+y
... 
>>> t = Test()
>>> p.map(t.plus, x, y)
[4, 6, 8, 10]
>>> 
>>> class Foo(object):
...   @staticmethod
...   def work(self, x):
...     return x+1
... 
>>> f = Foo()
>>> p.apipe(f.work, f, 100)
<processing.pool.ApplyResult object at 0x10504f8d0>
>>> res = _
>>> res.get()
101

Get pathos (and if you like, dill) here: https://github.com/uqfoundation

Choosing line type and color in Gnuplot 4.0

I've ran into this topic, because i was struggling with dashed lines too (gnuplot 4.6 patchlevel 0)

If you use:

set termoption dashed

Your posted code will work accordingly.

Related question:
However, if I want to export a png with: set terminal png, this isn't working anymore. Anyone got a clue why?

Turns out, out, gnuplots png export library doesnt support this.
Possbile solutions:

  • one can simply export to ps, then convert it with pstopng
  • according to @christoph, if you use pngcairo as your terminal (set terminal pngcairo) it will work

html form - make inputs appear on the same line

You can make a class for each label and inside it put:

display: inline-block;

And width the value that you need.

MATLAB - multiple return values from a function?

Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed

Returning value from Thread

Using Future described in above answers does the job, but a bit less significantly as f.get(), blocks the thread until it gets the result, which violates concurrency.

Best solution is to use Guava's ListenableFuture. An example :

    ListenableFuture<Void> future = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1, new NamedThreadFactory).submit(new Callable<Void>()
    {
        @Override
        public Void call() throws Exception
        {
            someBackgroundTask();
        }
    });
    Futures.addCallback(future, new FutureCallback<Long>()
    {
        @Override
        public void onSuccess(Long result)
        {
            doSomething();
        }

        @Override
        public void onFailure(Throwable t)
        {

        }
    };

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Select the values of one property on all objects of an array in PowerShell

To complement the preexisting, helpful answers with guidance of when to use which approach and a performance comparison.

  • Outside of a pipeline[1], use (PSv3+):

    $objects.Name
    as demonstrated in rageandqq's answer, which is both syntactically simpler and much faster.

    • Accessing a property at the collection level to get its members' values as an array is called member enumeration and is a PSv3+ feature.

    • Alternatively, in PSv2, use the foreach statement, whose output you can also assign directly to a variable:

      $results = foreach ($obj in $objects) { $obj.Name }

    • If collecting all output from a (pipeline) command in memory first is feasible, you can also combine pipelines with member enumeration; e.g.:

       (Get-ChildItem -File | Where-Object Length -lt 1gb).Name
      
    • Tradeoffs:

      • Both the input collection and output array must fit into memory as a whole.
      • If the input collection is itself the result of a command (pipeline) (e.g., (Get-ChildItem).Name), that command must first run to completion before the resulting array's elements can be accessed.
  • In a pipeline, in case you must pass the results to another command, notably if the original input doesn't fit into memory as a whole, use:

    $objects | Select-Object -ExpandProperty Name

    • The need for -ExpandProperty is explained in Scott Saad's answer (you need it to get only the property value).
    • You get the usual pipeline benefits of the pipeline's streaming behavior, i.e. one-by-one object processing, which typically produces output right away and keeps memory use constant (unless you ultimately collect the results in memory anyway).
    • Tradeoff:
      • Use of the pipeline is comparatively slow.

For small input collections (arrays), you probably won't notice the difference, and, especially on the command line, sometimes being able to type the command easily is more important.


Here is an easy-to-type alternative, which, however is the slowest approach; it uses simplified ForEach-Object syntax called an operation statement (again, PSv3+): ; e.g., the following PSv3+ solution is easy to append to an existing command:

$objects | % Name      # short for: $objects | ForEach-Object -Process { $_.Name }

The PSv4+ .ForEach() array method, more comprehensively discussed in this article, is yet another, well-performing alternative, but note that it requires collecting all input in memory first, just like member enumeration:

# By property name (string):
$objects.ForEach('Name')

# By script block (more flexibility; like ForEach-Object)
$objects.ForEach({ $_.Name })
  • This approach is similar to member enumeration, with the same tradeoffs, except that pipeline logic is not applied; it is marginally slower than member enumeration, though still noticeably faster than the pipeline.

  • For extracting a single property value by name (string argument), this solution is on par with member enumeration (though the latter is syntactically simpler).

  • The script-block variant ({ ... }) allows arbitrary transformations; it is a faster - all-in-memory-at-once - alternative to the pipeline-based ForEach-Object cmdlet (%).

Note: The .ForEach() array method, like its .Where() sibling (the in-memory equivalent of Where-Object), always returns a collection (an instance of [System.Collections.ObjectModel.Collection[psobject]]), even if only one output object is produced.
By contrast, member enumeration, Select-Object, ForEach-Object and Where-Object return a single output object as-is, without wrapping it in a collection (array).


Comparing the performance of the various approaches

Here are sample timings for the various approaches, based on an input collection of 10,000 objects, averaged across 10 runs; the absolute numbers aren't important and vary based on many factors, but it should give you a sense of relative performance (the timings come from a single-core Windows 10 VM:

Important

  • The relative performance varies based on whether the input objects are instances of regular .NET Types (e.g., as output by Get-ChildItem) or [pscustomobject] instances (e.g., as output by Convert-FromCsv).
    The reason is that [pscustomobject] properties are dynamically managed by PowerShell, and it can access them more quickly than the regular properties of a (statically defined) regular .NET type. Both scenarios are covered below.

  • The tests use already-in-memory-in-full collections as input, so as to focus on the pure property extraction performance. With a streaming cmdlet / function call as the input, performance differences will generally be much less pronounced, as the time spent inside that call may account for the majority of the time spent.

  • For brevity, alias % is used for the ForEach-Object cmdlet.

General conclusions, applicable to both regular .NET type and [pscustomobject] input:

  • The member-enumeration ($collection.Name) and foreach ($obj in $collection) solutions are by far the fastest, by a factor of 10 or more faster than the fastest pipeline-based solution.

  • Surprisingly, % Name performs much worse than % { $_.Name } - see this GitHub issue.

  • PowerShell Core consistently outperforms Windows Powershell here.

Timings with regular .NET types:

  • PowerShell Core v7.0.0-preview.3
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.005
1.06   foreach($o in $objects) { $o.Name }           0.005
6.25   $objects.ForEach('Name')                      0.028
10.22  $objects.ForEach({ $_.Name })                 0.046
17.52  $objects | % { $_.Name }                      0.079
30.97  $objects | Select-Object -ExpandProperty Name 0.140
32.76  $objects | % Name                             0.148
  • Windows PowerShell v5.1.18362.145
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.012
1.32   foreach($o in $objects) { $o.Name }           0.015
9.07   $objects.ForEach({ $_.Name })                 0.105
10.30  $objects.ForEach('Name')                      0.119
12.70  $objects | % { $_.Name }                      0.147
27.04  $objects | % Name                             0.312
29.70  $objects | Select-Object -ExpandProperty Name 0.343

Conclusions:

  • In PowerShell Core, .ForEach('Name') clearly outperforms .ForEach({ $_.Name }). In Windows PowerShell, curiously, the latter is faster, albeit only marginally so.

Timings with [pscustomobject] instances:

  • PowerShell Core v7.0.0-preview.3
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.006
1.11   foreach($o in $objects) { $o.Name }           0.007
1.52   $objects.ForEach('Name')                      0.009
6.11   $objects.ForEach({ $_.Name })                 0.038
9.47   $objects | Select-Object -ExpandProperty Name 0.058
10.29  $objects | % { $_.Name }                      0.063
29.77  $objects | % Name                             0.184
  • Windows PowerShell v5.1.18362.145
Factor Command                                       Secs (10-run avg.)
------ -------                                       ------------------
1.00   $objects.Name                                 0.008
1.14   foreach($o in $objects) { $o.Name }           0.009
1.76   $objects.ForEach('Name')                      0.015
10.36  $objects | Select-Object -ExpandProperty Name 0.085
11.18  $objects.ForEach({ $_.Name })                 0.092
16.79  $objects | % { $_.Name }                      0.138
61.14  $objects | % Name                             0.503

Conclusions:

  • Note how with [pscustomobject] input .ForEach('Name') by far outperforms the script-block based variant, .ForEach({ $_.Name }).

  • Similarly, [pscustomobject] input makes the pipeline-based Select-Object -ExpandProperty Name faster, in Windows PowerShell virtually on par with .ForEach({ $_.Name }), but in PowerShell Core still about 50% slower.

  • In short: With the odd exception of % Name, with [pscustomobject] the string-based methods of referencing the properties outperform the scriptblock-based ones.


Source code for the tests:

Note:

  • Download function Time-Command from this Gist to run these tests.

    • Assuming you have looked at the linked code to ensure that it is safe (which I can personally assure you of, but you should always check), you can install it directly as follows:

      irm https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1 | iex
      
  • Set $useCustomObjectInput to $true to measure with [pscustomobject] instances instead.

$count = 1e4 # max. input object count == 10,000
$runs  = 10  # number of runs to average 

# Note: Using [pscustomobject] instances rather than instances of 
#       regular .NET types changes the performance characteristics.
# Set this to $true to test with [pscustomobject] instances below.
$useCustomObjectInput = $false

# Create sample input objects.
if ($useCustomObjectInput) {
  # Use [pscustomobject] instances.
  $objects = 1..$count | % { [pscustomobject] @{ Name = "$foobar_$_"; Other1 = 1; Other2 = 2; Other3 = 3; Other4 = 4 } }
} else {
  # Use instances of a regular .NET type.
  # Note: The actual count of files and folders in your file-system
  #       may be less than $count
  $objects = Get-ChildItem / -Recurse -ErrorAction Ignore | Select-Object -First $count
}

Write-Host "Comparing property-value extraction methods with $($objects.Count) input objects, averaged over $runs runs..."

# An array of script blocks with the various approaches.
$approaches = { $objects | Select-Object -ExpandProperty Name },
              { $objects | % Name },
              { $objects | % { $_.Name } },
              { $objects.ForEach('Name') },
              { $objects.ForEach({ $_.Name }) },
              { $objects.Name },
              { foreach($o in $objects) { $o.Name } }

# Time the approaches and sort them by execution time (fastest first):
Time-Command $approaches -Count $runs | Select Factor, Command, Secs*

[1] Technically, even a command without |, the pipeline operator, uses a pipeline behind the scenes, but for the purpose of this discussion using the pipeline refers only to commands that do use | and therefore involve multiple commands connected by a pipeline.

How to refresh Android listview?

I was the same when, in a fragment, I wanted to populate a ListView (in a single TextView) with the mac address of BLE devices scanned over some time.

What I did was this:

public class Fragment01 extends android.support.v4.app.Fragment implements ...
{
    private ListView                listView;
    private ArrayAdapter<String>    arrayAdapter_string;

...

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    ...
    this.listView= (ListView) super.getActivity().findViewById(R.id.fragment01_listView);
    ...
    this.arrayAdapter_string= new ArrayAdapter<String>(super.getActivity(), R.layout.dispositivo_ble_item, R.id.fragment01_item_textView_titulo);
    this.listView.setAdapter(this.arrayAdapter_string);
}


@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
    ...
    super.getActivity().runOnUiThread(new RefreshListView(device));
}


private class RefreshListView implements Runnable
{
    private BluetoothDevice bluetoothDevice;

    public RefreshListView(BluetoothDevice bluetoothDevice)
    {
        this.bluetoothDevice= bluetoothDevice;
    }

    @Override
    public void run()
    {
        Fragment01.this.arrayAdapter_string.add(new String(bluetoothDevice.toString()));
        Fragment01.this.arrayAdapter_string.notifyDataSetChanged();
    }
}

Then the ListView began to dynamically populate with the mac address of the devices found.

Get Android Phone Model programmatically

The following strings are all of use when you want to retrieve manufacturer, name of the device, and/or the model:

String manufacturer = Build.MANUFACTURER;
String brand        = Build.BRAND;
String product      = Build.PRODUCT;
String model        = Build.MODEL;

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

html cellpadding the left side of a cell

I recently had to do this to create half decent looking emails for an email client that did not support the CSS necessary. For an HTML only solution I use a wrapping table to provide the padding.

_x000D_
_x000D_
<table border="1" cellspacing="0" cellpadding="0">_x000D_
    <tr><td height="5" colspan="3"></td></tr>_x000D_
    <tr>_x000D_
        <td width="5"></td>_x000D_
        <td>_x000D_
            This cells padding matches what you want._x000D_
            <ul>_x000D_
                <li>5px Left, Top, Bottom padding</li>_x000D_
                <li>10px on the right</li>_x000D_
            </ul>    _x000D_
            You can then put your table inside this_x000D_
            cell with no spacing or padding set.                    _x000D_
        </td>_x000D_
        <td width="10"></td>_x000D_
    </tr>_x000D_
    <tr><td height="5" colspan="3"></td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

As of 2017 you would only do this for old email client support, it's pretty overkill.

Difference between `Optional.orElse()` and `Optional.orElseGet()`

I reached here for the problem Kudo mentioned.

I'm sharing my experience for others.

orElse, or orElseGet, that is the question:

static String B() {
    System.out.println("B()...");
    return "B";
}

public static void main(final String... args) {
    System.out.println(Optional.of("A").orElse(B()));
    System.out.println(Optional.of("A").orElseGet(() -> B()));
}

prints

B()...
A
A

orElse evaluates the value of B() interdependently of the value of the optional. Thus, orElseGet is lazy.

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

How to see full absolute path of a symlink

Another way to see information is stat command that will show more information. Command stat ~/.ssh on my machine display

File: ‘/home/sumon/.ssh’ -> ‘/home/sumon/ssh-keys/.ssh.personal’
  Size: 34          Blocks: 0          IO Block: 4096   symbolic link
Device: 801h/2049d  Inode: 25297409    Links: 1
Access: (0777/lrwxrwxrwx)  Uid: ( 1000/   sumon)   Gid: ( 1000/   sumon)
Access: 2017-09-26 16:41:18.985423932 +0600
Modify: 2017-09-25 15:48:07.880104043 +0600
Change: 2017-09-25 15:48:07.880104043 +0600
 Birth: -

Hope this may help someone.

How to set JAVA_HOME path on Ubuntu?

add JAVA_HOME to the file:

/etc/environment

for it to be available to the entire system (you would need to restart Ubuntu though)

Click outside menu to close in jquery

2 options that you can investigate:

  • On showing of the menu, place a large empty DIV behind it covering up the rest of the page and give that an on-click event to close the menu (and itself). This is akin to the methods used with lightboxes where clicking on the background closes the lightbox
  • On showing of the menu, attach a one-time click event handler on the body that closes the menu. You use jQuery's '.one()' for this.

tr:hover not working

Your best bet is to use

table.YourClass tr:hover td {
background-color: #FEFEFE;
}

Rows aren't fully support for background color but cells are, using the combination of :hover and the child element will yield the results you need.

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Unfortunately, modules aren't supported by many browsers right now.

This feature is only just beginning to be implemented in browsers natively at this time. It is implemented in many transpilers, such as TypeScript and Babel, and bundlers such as Rollup and Webpack.

Found on MDN

Print empty line?

You can just do

print()

to get an empty line.

How to use new PasswordEncoder from Spring Security

Here is the implementation of BCrypt which is working for me.

in spring-security.xml

<authentication-manager >
    <authentication-provider ref="authProvider"></authentication-provider>  
    </authentication-manager>
<beans:bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
  <beans:property name="userDetailsService" ref="userDetailsServiceImpl" />
  <beans:property name="passwordEncoder" ref="encoder" />
</beans:bean>
<!-- For hashing and salting user passwords -->
    <beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

In java class

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(yourpassword);

For more detailed example of spring security Click Here

Hope this will help.

Thanks

Calling jQuery method from onClick attribute in HTML

this works....

<script language="javascript">
    (function($) {
     $.fn.MessageBox = function(msg) {
       return this.each(function(){
         alert(msg);
       })
     };
    })(jQuery);? 
</script>

.

   <body>
      <div class="Title">Welcome!</div>
     <input type="button" value="ahaha"  onclick="$(this).MessageBox('msg');" />
    </body>

edit

you are using a failsafe jQuery code using the $ alias... it should be written like:

(function($) {
  // plugin code here, use $ as much as you like
})(jQuery); 

or

jQuery(function($) {
   // your code using $ alias here
 });

note that it has a 'jQuery' word in each of it....

How to get text with Selenium WebDriver in Python

This is the correct answer. It worked!!

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome("E:\\Python\\selenium\\webdriver\\chromedriver.exe")
driver.get("https://www.tatacliq.com/global-desi-navy-embroidered-kurta/p-mp000000000876745")
driver.set_page_load_timeout(45)
driver.maximize_window()
driver.implicitly_wait(2)
driver.get_screenshot_as_file("E:\\Python\\Tatacliq.png")
print ("Executed Successfully")
driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").click()
SpecialPrice = driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").text
print(SpecialPrice)

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

Redirect to Action in another controller

Use this:

return RedirectToAction("LogIn", "Account", new { area = "" });

This will redirect to the LogIn action in the Account controller in the "global" area.

It's using this RedirectToAction overload:

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    Object routeValues
)

MSDN

Beginner Python Practice?

I found python in 1988 and fell in love with it. Our group at work had been dissolved and we were looking for other jobs on site, so I had a couple of months to play around doing whatever I wanted to. I spent the time profitably learning and using python. I suggest you spend time thinking up and writing utilities and various useful tools. I've got 200-300 in my python tools library now (can't even remember them all). I learned python from Guido's tutorial, which is a good place to start (a C programmer will feel right at home).

python is also a great tool for making models -- physical, math, stochastic, etc. Use numpy and scipy. It also wouldn't hurt to learn some GUI stuff -- I picked up wxPython and learned it, as I had some experience using wxWidgets in C++. wxPython has some impressive demo stuff!

Xcode 10, Command CodeSign failed with a nonzero exit code

This issue can also occur when upgrade from XCODE 11.x to 12.0. After installation of new version of XCODE, restart system to overcome this issue.

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

Python basics printing 1 to 100

x=1 while x<=100: print(x) x=x+3

How can I select records ONLY from yesterday?

This comment is for readers who have found this entry but are using mysql instead of oracle! on mysql you can do the following: Today

SELECT  * 
FROM 
WHERE date(tran_date) = CURRENT_DATE()

Yesterday

SELECT  * 
FROM yourtable 
WHERE date(tran_date) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)

How to Make A Chevron Arrow Using CSS?

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

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

Here Fiddle