Programs & Examples On #Partial specialization

Partial template specialization is a particular form of class template specialization. Usually used in reference to the C++ programming language, it allows the programmer to specialize only some arguments of a class template, as opposed to explicit specialization, where all the template arguments are provided.

What is com.sun.proxy.$Proxy

  1. Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler, which defines a method that is invoked when a proxy method is invoked.

  2. You create them by using the call

    Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
    

    The arguments are:

    1. classLoader. Once the class is generated, it is loaded with this class loader.
    2. interfaces. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.
    3. invocationHandler. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler. When a method from any of the supported interfaces, or hashCode, equals, or toString, is invoked, the method invoke is invoked on the handler, passing the Method object for the method to be invoked and the arguments passed.

    For more on this, see the documentation for the Proxy class.

  3. Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.

JavaScript: set dropdown selected item based on option text

You can loop through the select_obj.options. There's a #text method in each of the option object, which you can use to compare to what you want and set the selectedIndex of the select_obj.

Failed to resolve: com.android.support:appcompat-v7:26.0.0

File -> Project Structure -> Modules (app) -> Open Dependencies Tab -> Remove all then use + to add from the proposed list.

Default value in an asp.net mvc view model

Use specific value:

[Display(Name = "Date")]
public DateTime EntryDate {get; set;} = DateTime.Now;//by C# v6

Passing properties by reference in C#

Just a little expansion to Nathan's Linq Expression solution. Use multi generic param so that the property doesn't limited to string.

void GetString<TClass, TProperty>(string input, TClass outObj, Expression<Func<TClass, TProperty>> outExpr)
{
    if (!string.IsNullOrEmpty(input))
    {
        var expr = (MemberExpression) outExpr.Body;
        var prop = (PropertyInfo) expr.Member;
        if (!prop.GetValue(outObj).Equals(input))
        {
            prop.SetValue(outObj, input, null);
        }
    }
}

Set initial value in datepicker with jquery?

I'm not entirely sure if I understood your question, but it seems that you're trying to set value for an input type Date.

If you want to set a value for an input type 'Date', then it has to be formatted as "yyyy-MM-dd" (Note: capital MM for Month, lower case mm for minutes). Otherwise, it will clear the value and leave the datepicker empty.

Let's say you have a button called "DateChanger" and you want to set your datepicker to "22 Dec 2012" when you click it.

<script>
    $(document).ready(function () {
        $('#DateChanger').click(function() {
             $('#dtFrom').val("2012-12-22");
        });
    });
</script>
<input type="date" id="dtFrom" name="dtFrom" />
<button id="DateChanger">Click</button>

Remember to include JQuery reference.

Vue template or render function not defined yet I am using neither?

My previous code was

Vue.component('message', require('./components/message.vue'));

when i got such errors then i just add .default to it and it worked..

Vue.component('message', require('./components/message.vue').default);

Current Subversion revision command

REV=svn info svn://svn.code.sf.net/p/retroshare/code/trunk | grep 'Revision:' | cut -d\ -f2

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

How to replace text of a cell based on condition in excel

You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM. Then simply type where it says TYPE: what you want to say in QUOTES.

Example.. "OTHER"

Find a string by searching all tables in SQL Server Management Studio 2008

Improving the amazing answer from @Brandon, I added type to ntext and xml using castings:

BEGIN TRAN

DECLARE @SearchStr nvarchar(100) = 'SEARCH_TEXT'
DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL

BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal', 'ntext', 'xml')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL

        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT((cast(' + @ColumnName + ' as nvarchar(max))), 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE (cast(' + @ColumnName + ' as nvarchar(max))) LIKE ' + @SearchStr2
            )
        END
    END    
END

SELECT ColumnName, ColumnValue FROM @Results

ROLLBACK

Inverse of matrix in R

Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 

jquery AJAX and json format

I never had any luck with that approach. I always do this (hope this helps):

var obj = {};

obj.first_name = $("#namec").val();
obj.last_name = $("#surnamec").val();
obj.email = $("#emailc").val();
obj.mobile = $("#numberc").val();
obj.password = $("#passwordc").val();

Then in your ajax:

$.ajax({
        type: "POST",
        url: hb_base_url + "consumer",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(obj),
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
    });

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

Override method authenticationManagerBean in WebSecurityConfigurerAdapter to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder) as a Spring bean:

For example:

   @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
   }

How to use comparison and ' if not' in python?

Operator precedence in python
You can see that not X has higher precedence than and. Which means that the not only apply to the first part (u0 <= u). Write:

if not (u0 <= u and u < u0+step):  

or even

if not (u0 <= u < u0+step):  

Bash: Syntax error: redirection unexpected

Before running the script, you should check first line of the shell script for the interpreter.

Eg: if scripts starts with /bin/bash , run the script using the below command "bash script_name.sh"

if script starts with /bin/sh, run the script using the below command "sh script_name.sh"

./sample.sh - This will detect the interpreter from the first line of the script and run.

Different Linux distributions having different shells as default.

Making heatmap from pandas DataFrame

For people looking at this today, I would recommend the Seaborn heatmap() as documented here.

The example above would be done as follows:

import numpy as np 
from pandas import DataFrame
import seaborn as sns
%matplotlib inline

Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)

sns.heatmap(df, annot=True)

Where %matplotlib is an IPython magic function for those unfamiliar.

versionCode vs versionName in Android Manifest

I'm going to give you my interpretation of the only documentation I can find on the subject.

"for example to check an upgrade or downgrade relationship." <- You can downgrade an app.

"you should make sure that each successive release of your application uses a greater value. The system does not enforce this behavior" <- The number really should increase, but you can still downgrade an app.

android:versionCode — An integer value that represents the version of the application code, relative to other versions. The value is an integer so that other applications can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any integer you want, however you should make sure that each successive release of your application uses a greater value. The system does not enforce this behavior, but increasing the value with successive releases is normative. Typically, you would release the first version of your application with versionCode set to 1, then monotonically increase the value with each release, regardless whether the release constitutes a major or minor release. This means that the android:versionCode value does not necessarily have a strong resemblance to the application release version that is visible to the user (see android:versionName, below). Applications and publishing services should not display this version value to users.

How do I extract data from JSON with PHP?

// Using json as php array 

$json = '[{"user_id":"1","user_name":"Sayeed Amin","time":"2019-11-06 13:21:26"}]';

//or use from file
//$json = file_get_contents('results.json');

$someArray = json_decode($json, true);

foreach ($someArray as $key => $value) {
    echo $value["user_id"] . ", " . $value["user_name"] . ", " . $value["time"] . "<br>";
}

Can you overload controller methods in ASP.NET MVC?

Yes. I've been able to do this by setting the HttpGet/HttpPost (or equivalent AcceptVerbs attribute) for each controller method to something distinct, i.e., HttpGet or HttpPost, but not both. That way it can tell based on the type of request which method to use.

[HttpGet]
public ActionResult Show()
{
   ...
}

[HttpPost]
public ActionResult Show( string userName )
{
   ...
}

One suggestion I have is that, for a case like this, would be to have a private implementation that both of your public Action methods rely on to avoid duplicating code.

How to find the location of the Scheduled Tasks folder

Tasks are saved in filesystem AND registry

Tasks are stored in 3 locations: 1 file system location and 2 registry locations.

File system:

C:\Windows\System32\Tasks

Registry:

HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree

So, you need to delete a corrupted task in these 3 locations.

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

SELECT  
   T.NAME AS [TABLE NAME]
   ,C.NAME AS [COLUMN NAME]
   ,P.NAME AS [DATA TYPE]
   ,P.MAX_LENGTH AS [Max_SIZE]
   ,C.[max_length] AS [ActualSizeUsed]
   ,CAST(P.PRECISION AS VARCHAR) +'/'+ CAST(P.SCALE AS VARCHAR) AS [PRECISION/SCALE]
FROM SYS.OBJECTS AS T
JOIN SYS.COLUMNS AS C
    ON T.OBJECT_ID = C.OBJECT_ID
JOIN SYS.TYPES AS P
    ON C.SYSTEM_TYPE_ID = P.SYSTEM_TYPE_ID
    AND C.[user_type_id] = P.[user_type_id]
WHERE T.TYPE_DESC='USER_TABLE'
  AND T.name = 'InventoryStatus'
ORDER BY 2

Concatenating date with a string in Excel

Thanks for the solution !

It works, but in a french Excel environment, you should apply something like

TEXTE(F2;"jj/mm/aaaa")

to get the date preserved as it is displayed in F2 cell, after concatenation. Best Regards

How to extract closed caption transcript from YouTube video?

There is a free python tool called YouTube transcript API

You can use it in scripts or as a command line tool:

pip install youtube_transcript_api

How to get the selected value from RadioButtonList?

radiobuttonlist.selected <value> to process with your code.

How to compile C++ under Ubuntu Linux?

You should use g++, not gcc, to compile C++ programs.

For this particular program, I just typed

make avishay

and let make figure out the rest. Gives your executable a decent name, too, instead of a.out.

Internet Access in Ubuntu on VirtualBox

it could be a problem with your specific network adapter. I have a Dell 15R and there are no working drivers for ubuntu or ubuntu server; I even tried compiling wireless drivers myself, but to no avail.

However, in virtualbox, I was able to get wireless working by using the default configuration. It automatically bridged my internal wireless adapter and hence used my native OS's wireless connection for wireless.

If you are trying to get a separate wireless connection from within ubuntu in virtualbox, then it would take more configuring. If so, let me know, if not, I will not bother typing up instructions to something you are not looking to do, as it is quite complicated in some instances.

p.s. you should be using Windows 7 if you have any technical inclination. Do you live under a rock? No offense intended.

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

Create views on two first "selects" and "union" them.

Only allow specific characters in textbox

    private void txtuser_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar) && !char.IsControl(e.KeyChar))
        {
            e.Handled = true;
        }
    }

Python: Is there an equivalent of mid, right, and left from BASIC?

You can use this method also it will act like that

thadari=[1,2,3,4,5,6]

#Front Two(Left)
print(thadari[:2])
[1,2]

#Last Two(Right)# edited
print(thadari[-2:])
[5,6]

#mid
mid = len(thadari) //2

lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]

Hope it will help

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

AlexRobbins' answer worked for me, except that the first two lines need to be in the model (perhaps this was assumed?), and should reference self:

def book_author(self):
  return self.book.author

Then the admin part works nicely.

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Edit 2: See @flodel's answer. Much better.

Try:

# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))  

Edit: or as @ CarlWitthoft suggested in the comments:

matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))

Regex match digits, comma and semicolon?

word.matches("^[0-9,;]+$"); you were almost there

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

Console.WriteLine and generic List

If there is a piece of code that you repeat all the time according to Don't Repeat Yourself you should put it in your own library and call that. With that in mind there are 2 aspects to getting the right answer here. The first is clarity and brevity in the code that calls the library function. The second is the performance implications of foreach.

First let's think about the clarity and brevity in the calling code.

You can do foreach in a number of ways:

  1. for loop
  2. foreach loop
  3. Collection.ForEach

Out of all the ways to do a foreach List.ForEach with a lamba is the clearest and briefest.

list.ForEach(i => Console.Write("{0}\t", i));

So at this stage it may look like the List.ForEach is the way to go. However what's the performance of this? It's true that in this case the time to write to the console will govern the performance of the code. When we know something about performance of a particular language feature we should certainly at least consider it.

According to Duston Campbell's performance measurements of foreach the fastest way of iterating the list under optimised code is using a for loop without a call to List.Count.

The for loop however is a verbose construct. It's also seen as a very iterative way of doing things which doesn't match with the current trend towards functional idioms.

So can we get brevity, clarity and performance? We can by using an extension method. In an ideal world we would create an extension method on Console that takes a list and writes it with a delimiter. We can't do this because Console is a static class and extension methods only work on instances of classes. Instead we need to put the extension method on the list itself (as per David B's suggestion):

public static void WriteLine(this List<int> theList)
{
  foreach (int i in list)
  {
    Console.Write("{0}\t", t.ToString());
  }
  Console.WriteLine();
}

This code is going to used in many places so we should carry out the following improvements:

  • Instead of using foreach we should use the fastest way of iterating the collection which is a for loop with a cached count.
  • Currently only List can be passed as an argument. As a library function we can generalise it through a small amount of effort.
  • Using List limits us to just Lists, Using IList allows this code to work with Arrays too.
  • Since the extension method will be on an IList we need to change the name to make it clearer what we are writing to:

Here's how the code for the function would look:

public static void WriteToConsole<T>(this IList<T> collection)
{
    int count = collection.Count();
    for(int i = 0;  i < count; ++i)
    {
        Console.Write("{0}\t", collection[i].ToString(), delimiter);
    }
    Console.WriteLine();
}

We can improve this even further by allowing the client to pass in the delimiter. We could then provide a second function that writes to console with the standard delimiter like this:

public static void WriteToConsole<T>(this IList<T> collection)
{
    WriteToConsole<T>(collection, "\t");
}

public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
    int count = collection.Count();
    for(int i = 0;  i < count; ++i)
    {
         Console.Write("{0}{1}", collection[i].ToString(), delimiter);
    }
    Console.WriteLine();
}

So now, given that we want a brief, clear performant way of writing lists to the console we have one. Here is entire source code including a demonstration of using the the library function:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleWritelineTest
{
    public static class Extensions
    {
        public static void WriteToConsole<T>(this IList<T> collection)
        {
            WriteToConsole<T>(collection, "\t");
        }

        public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
        {
            int count = collection.Count();
            for(int i = 0;  i < count; ++i)
            {
                Console.Write("{0}{1}", collection[i].ToString(), delimiter);
            }
            Console.WriteLine();
        }
    }

    internal class Foo
    {
        override public string ToString()
        {
            return "FooClass";
        }
    }

    internal class Program
    {

        static void Main(string[] args)
        {
            var myIntList = new List<int> {1, 2, 3, 4, 5};
            var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};
            var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};
            var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};
            // Using the standard delimiter /t
            myIntList.WriteToConsole();
            myDoubleList.WriteToConsole();
            myDoubleArray.WriteToConsole();
            myFooList.WriteToConsole();
            // Using our own delimiter ~
            myIntList.WriteToConsole("~");
            Console.Read();
        }
    }
}

=======================================================

You might think that this should be the end of the answer. However there is a further piece of generalisation that can be done. It's not clear from fatcat's question if he is always writing to the console. Perhaps something else is to be done in the foreach. In that case Jason Bunting's answer is going to give that generality. Here is his answer again:

list.ForEach(i => Console.Write("{0}\t", i));

That is unless we make one more refinement to our extension methods and add FastForEach as below:

public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)
    {
        int count = collection.Count();
        for (int i = 0; i < count; ++i)
        {
            actionToPerform(collection[i]);    
        }
        Console.WriteLine();
    }

This allows us to execute any arbitrary code against every element in the collection using the fastest possible iteration method.

We can even change the WriteToConsole function to use FastForEach

public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
     collection.FastForEach(item => Console.Write("{0}{1}", item.ToString(), delimiter));
}

So now the entire source code, including an example usage of FastForEach is:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleWritelineTest
{
    public static class Extensions
    {
        public static void WriteToConsole<T>(this IList<T> collection)
        {
            WriteToConsole<T>(collection, "\t");
        }

        public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
        {
             collection.FastForEach(item => Console.Write("{0}{1}", item.ToString(), delimiter));
        }

        public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)
        {
            int count = collection.Count();
            for (int i = 0; i < count; ++i)
            {
                actionToPerform(collection[i]);    
            }
            Console.WriteLine();
        }
    }

    internal class Foo
    {
        override public string ToString()
        {
            return "FooClass";
        }
    }

    internal class Program
    {

        static void Main(string[] args)
        {
            var myIntList = new List<int> {1, 2, 3, 4, 5};
            var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};
            var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};
            var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};

            // Using the standard delimiter /t
            myIntList.WriteToConsole();
            myDoubleList.WriteToConsole();
            myDoubleArray.WriteToConsole();
            myFooList.WriteToConsole();

            // Using our own delimiter ~
            myIntList.WriteToConsole("~");

            // What if we want to write them to separate lines?
            myIntList.FastForEach(item => Console.WriteLine(item.ToString()));
            Console.Read();
        }
    }
}

Hbase quickly count number of rows

Two ways Worked for me to get count of rows from hbase table with Speed

Scenario #1

If hbase table size is small then login to hbase shell with valid user and execute

>count '<tablename>'

Example

>count 'employee'

6 row(s) in 0.1110 seconds

Scenario #2

If hbase table size is large,then execute inbuilt RowCounter map reduce job: Login to hadoop machine with valid user and execute:

/$HBASE_HOME/bin/hbase org.apache.hadoop.hbase.mapreduce.RowCounter '<tablename>'

Example:

 /$HBASE_HOME/bin/hbase org.apache.hadoop.hbase.mapreduce.RowCounter 'employee'

     ....
     ....
     ....
     Virtual memory (bytes) snapshot=22594633728
                Total committed heap usage (bytes)=5093457920
        org.apache.hadoop.hbase.mapreduce.RowCounter$RowCounterMapper$Counters
                ROWS=6
        File Input Format Counters
                Bytes Read=0
        File Output Format Counters
                Bytes Written=0

What is the difference between fastcgi and fpm?

Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable

whereas

PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments

However, there are pros and cons to both and one should choose as per their specific use case.

I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.

Overriding interface property type defined in Typescript d.ts file

I have created this type that allows me to easily override nested interfaces:

export type DeepPartialAny<T> = {
  [P in keyof T]?: T[P] extends Obj ? DeepPartialAny<T[P]> : any;
};

export type Override<A extends Obj, AOverride extends DeepPartialAny<A>> = { [K in keyof A]:
  AOverride[K] extends never
    ? A[K]
    : AOverride[K] extends Obj
    ? Override<A[K], AOverride[K]>
    : AOverride[K]
};

And then you can use it like that:

interface Foo {
  Bar: {
    Baz: string;
  };
}
type Foo2 = Override<Foo, { Bar: { Baz: number } }>;

const bar: Foo2['Bar']['Baz'] = 1; // number;

Difference between $(document.body) and $('body')

I have found a pretty big difference in timing when testing in my browser.

I used the following script:

WARNING: running this will freeze your browser a bit, might even crash it.

_x000D_
_x000D_
var n = 10000000, i;_x000D_
i = n;_x000D_
console.time('selector');_x000D_
while (i --> 0){_x000D_
    $("body");_x000D_
}_x000D_
_x000D_
console.timeEnd('selector');_x000D_
_x000D_
i = n;_x000D_
console.time('element');_x000D_
while (i --> 0){_x000D_
    $(document.body);_x000D_
}_x000D_
_x000D_
console.timeEnd('element');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

I did 10 million interactions, and those were the results (Chrome 65):

selector: 19591.97509765625ms
element: 4947.8759765625ms

Passing the element directly is around 4 times faster than passing the selector.

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:

services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
    {
        options.YourProperty = yourValue;
    })

PHP Include for HTML?

Try to get some debugging information, could be that the file path is wrong, for example.

Try these two things:- Add this line to the top of your sample page:

<?php error_reporting(E_ALL);?>

This will print all errors/warnings/notices in the page so if there is any problem you get a text message describing it instead of a blank page

Additionally you can change include() to require()

<?php require ('headings.php'); ?>
<?php require ('navbar.php'); ?>
<?php require ('image.php'); ?>

This will throw a FATAL error PHP is unable to load required pages, and should help you in getting better tracing what is going wrong..

You can post the error descriptions here, if you get any, and you are unable to figure out what it means..

Remove from the beginning of std::vector

Two suggestions:

  1. Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
  2. Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;

Copy folder structure (without files) from one location to another

cd /path/to/directories &&
find . -type d -exec mkdir -p -- /path/to/backup/{} \;

Any free WPF themes?

There are some Microsoft Themes in the WPF page on CodePlex:

CodePlex - Windows Presentation Foundation

Pretty-Print JSON Data to a File using Python

If you already have existing JSON files which you want to pretty format you could use this:

    with open('twitterdata.json', 'r+') as f:
        data = json.load(f)
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()

How to change a css class style through Javascript?

If you want to manipulate the actual CSS class instead of modifying the DOM elements or using modifier CSS classes, see https://stackoverflow.com/a/50036923/482916.

VueJs get url query

You can also get them with pure javascript.

For example:

new URL(location.href).searchParams.get('page')

For this url: websitename.com/user/?page=1, it would return a value of 1

How to run a bash script from C++ program

Since this is a pretty old question, and this method hasn't been added (aside from the system() call function) I guess it would be useful to include creating the shell script with the C binary itself. The shell code will be housed inside the file.c source file. Here is an example of code:

#include <stdio.h>
#include <stdlib.h>

#define SHELLSCRIPT "\
#/bin/bash \n\
echo -e \"\" \n\
echo -e \"This is a test shell script inside C code!!\" \n\
read -p \"press <enter> to continue\" \n\
clear\
"

int main() {

system(SHELLSCRIPT);
return 0;
}

Basically, in a nutshell (pun intended), we are defining the script name, fleshing out the script, enclosing them in double quotes (while inserting proper escapes to ignore double quotes in the shell code), and then calling that script's name, which in this example is SHELLSCRIPT using the system() function in main().

Using CSS to affect div style inside iframe

probably not the way you are thinking. the iframe would have to <link> in the css file too. AND you can't do it even with javascript if it's on a different domain.

.attr('checked','checked') does not work

$('.checkbox').prop('checked',true); 
$('.checkbox').prop('checked',false);

... works perfectly with jquery1.9.1

Java: Clear the console

You can use following code to clear command line console:

public static void clearScreen() {  
    System.out.print("\033[H\033[2J");  
    System.out.flush();  
}  

For further references visit: http://techno-terminal.blogspot.in/2014/12/clear-command-line-console-and-bold.html

Regular expression for extracting tag attributes

If you want to be general, you have to look at the precise specification of the a tag, like here. But even with that, if you do your perfect regexp, what if you have malformed html?

I would suggest to go for a library to parse html, depending on the language you work with: e.g. like python's Beautiful Soup.

PHP is not recognized as an internal or external command in command prompt

Extra info:

If you are using PhpStorm as IDE, after updating the path variable you need to restart PhpStorm so that it takes effect.

Restarting terminal window was not enough for me. (PhpStorm 2020.3.2)

Java String import

String is present in package java.lang which is imported by default in all java programs.

Python: SyntaxError: keyword can't be an expression

sum.up is not a valid keyword argument name. Keyword arguments must be valid identifiers. You should look in the documentation of the library you are using how this argument really is called – maybe sum_up?

Why does find -exec mv {} ./target/ + not work?

I encountered the same issue on Mac OSX, using a ZSH shell: in this case there is no -t option for mv, so I had to find another solution. However the following command succeeded:

find .* * -maxdepth 0 -not -path '.git' -not -path '.backup' -exec mv '{}' .backup \;

The secret was to quote the braces. No need for the braces to be at the end of the exec command.

I tested under Ubuntu 14.04 (with BASH and ZSH shells), it works the same.

However, when using the + sign, it seems indeed that it has to be at the end of the exec command.

Get sum of MySQL column in PHP

MySQL 5.6 (LAMP) . column_value is the column you want to add up. table_name is the table.

Method #1

$qry = "SELECT column_value AS count
        FROM table_name ";

$res = $db->query($qry);

$total = 0;
while ($rec = $db->fetchAssoc($res)) {
    $total += $rec['count'];
}
echo "Total: " . $total . "\n";

Method #2

$qry = "SELECT SUM(column_value) AS count 
        FROM table_name ";

$res = $db->query($qry);

$total = 0;
$rec = $db->fetchAssoc($res);
$total = $rec['count'];

echo "Total: " . $total . "\n";

Method #3 -SQLi

$qry = "SELECT SUM(column_value) AS count 
        FROM table_name ";

$res = $conn->query($sql);

$total = 0;
$rec = row = $res->fetch_assoc();
$total = $rec['count'];

echo "Total: " . $total . "\n";

Method #4: Depreciated (don't use)

$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name'); 
$row = mysql_fetch_assoc($res); 
$sum = $row['count'];

android asynctask sending callbacks to ui

IN completion to above answers, you can also customize your fallbacks for each async call you do, so that each call to the generic ASYNC method will populate different data, depending on the onTaskDone stuff you put there.

  Main.FragmentCallback FC= new  Main.FragmentCallback(){
            @Override
            public void onTaskDone(String results) {

                localText.setText(results); //example TextView
            }
        };

new API_CALL(this.getApplicationContext(), "GET",FC).execute("&Books=" + Main.Books + "&args=" + profile_id);

Remind: I used interface on the main activity thats where "Main" comes, like this:

public interface FragmentCallback {
    public void onTaskDone(String results);


}

My API post execute looks like this:

  @Override
    protected void onPostExecute(String results) {

        Log.i("TASK Result", results);
        mFragmentCallback.onTaskDone(results);

    }

The API constructor looks like this:

 class  API_CALL extends AsyncTask<String,Void,String>  {

    private Main.FragmentCallback mFragmentCallback;
    private Context act;
    private String method;


    public API_CALL(Context ctx, String api_method,Main.FragmentCallback fragmentCallback) {
        act=ctx;
        method=api_method;
        mFragmentCallback = fragmentCallback;


    }

List all column except for one in R

In addition to tcash21's numeric indexing if OP may have been looking for negative indexing by name. Here's a few ways I know, some are risky than others to use:

mtcars[, -which(names(mtcars) == "carb")]  #only works on a single column
mtcars[, names(mtcars) != "carb"]          #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")] 
mtcars[, -match(c("carb", "mpg"), names(mtcars))] 
mtcars2 <- mtcars; mtcars2$hp <- NULL         #lost column (risky)


library(gdata) 
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE) 

Generally I use:

mtcars[, !names(mtcars) %in% c("carb", "mpg")] 

because I feel it's safe and efficient.

How to convert a PNG image to a SVG?

There is a website where you can upload your image, and see the result.

http://vectormagic.com/home

But if you want to download your svg-image, you need to register. (If you register, you get 2 images for free)

Installing SciPy and NumPy using pip

in my case, upgrading pip did the trick. Also, I've installed scipy with -U parameter (upgrade all packages to the last available version)

Replace multiple whitespaces with single whitespace in JavaScript string

using a regular expression with the replace function does the trick:

string.replace(/\s/g, "")

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

Parse an URL in JavaScript

function parse_url(str, component) {
  //       discuss at: http://phpjs.org/functions/parse_url/
  //      original by: Steven Levithan (http://blog.stevenlevithan.com)
  // reimplemented by: Brett Zamir (http://brett-zamir.me)
  //         input by: Lorenzo Pisani
  //         input by: Tony
  //      improved by: Brett Zamir (http://brett-zamir.me)
  //             note: original by http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  //             note: blog post at http://blog.stevenlevithan.com/archives/parseuri
  //             note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  //             note: Does not replace invalid characters with '_' as in PHP, nor does it return false with
  //             note: a seriously malformed URL.
  //             note: Besides function name, is essentially the same as parseUri as well as our allowing
  //             note: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
  //        example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
  //        returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}

  var query, key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port',
      'relative', 'path', 'directory', 'file', 'query', 'fragment'
    ],
    ini = (this.php_js && this.php_js.ini) || {},
    mode = (ini['phpjs.parse_url.mode'] &&
      ini['phpjs.parse_url.mode'].local_value) || 'php',
    parser = {
      php: /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-scheme to catch file:/// (should restrict this)
    };

  var m = parser[mode].exec(str),
    uri = {},
    i = 14;
  while (i--) {
    if (m[i]) {
      uri[key[i]] = m[i];
    }
  }

  if (component) {
    return uri[component.replace('PHP_URL_', '')
      .toLowerCase()];
  }
  if (mode !== 'php') {
    var name = (ini['phpjs.parse_url.queryKey'] &&
      ini['phpjs.parse_url.queryKey'].local_value) || 'queryKey';
    parser = /(?:^|&)([^&=]*)=?([^&]*)/g;
    uri[name] = {};
    query = uri[key[12]] || '';
    query.replace(parser, function($0, $1, $2) {
      if ($1) {
        uri[name][$1] = $2;
      }
    });
  }
  delete uri.source;
  return uri;
}

reference

#1071 - Specified key was too long; max key length is 1000 bytes

I had this issue, and solved by following:

Cause

There is a known bug with MySQL related to MyISAM, the UTF8 character set and indexes that you can check here.

Resolution

  • Make sure MySQL is configured with the InnoDB storage engine.

  • Change the storage engine used by default so that new tables will always be created appropriately:

    set GLOBAL storage_engine='InnoDb';

  • For MySQL 5.6 and later, use the following:

    SET GLOBAL default_storage_engine = 'InnoDB';

  • And finally make sure that you're following the instructions provided in Migrating to MySQL.

Reference

Select specific row from mysql table

You can use LIMIT 2,1 instead of WHERE row_number() = 3.

As the documentation explains, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return.

Keep in mind that it's an 0-based index. So, if you want the line number n, the first argument should be n-1. The second argument will always be 1, because you just want one row. For example, if you want the line number 56 of a table customer:

SELECT * FROM customer LIMIT 55,1

docker cannot start on windows

Error Code:

error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.29/version: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect . This error may also indicate that the docker daemon is not running.

Solutions:

1) For Windows 7 Command Window(cmd.exe), open cmd.exe with run as administrator and execute following command:

docker-machine env --shell cmd default

You will receive following output:

SET DOCKER_TLS_VERIFY=1
SET DOCKER_HOST=tcp://192.168.99.100:2376
SET DOCKER_CERT_PATH=C:\Users\USER_NAME\.docker\machine\machines\default
SET DOCKER_MACHINE_NAME=default
SET COMPOSE_CONVERT_WINDOWS_PATHS=true
REM Run this command to configure your shell:
REM @FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i

Copy the command below and execute on cmd:

@FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i

And then execute following command to control:

docker version

2) For Windows 7 Powershell, open powershell.exe with run as administrator and execute following command:

docker-machine env --shell=powershell | Invoke-Expression

And then execute following command to control:

docker version

3) If you reopen cmd or powershell, you should repeat the related steps again.

Get HTML source of WebElement in Selenium WebDriver using Python

I hope this could help: http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html

Here is described Java method:

java.lang.String    getText() 

But unfortunately it's not available in Python. So you can translate the method names to Python from Java and try another logic using present methods without getting the whole page source...

E.g.

 my_id = elem[0].get_attribute('my-id')

eclipse won't start - no java virtual machine was found

I came across same issue y'day, with PATH etc configured correctly. It can be opened from command line, just now working by a double click.

And it was working now, by just "Run as administrator" :)

ModelState.AddModelError - How can I add an error that isn't for a property?

Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

This simple method solved the problem for me: Copy the content of your dataset, open an empty Excel sheet, choose "Paste Special" -> "Values", and save. Import the new file instead.

(I tried all the existing solutions, and none worked for me. My old dataset appeared to have no missing values, space, special characters, or embedded formulas.)

disable editing default value of text input

You can either use the readonly or the disabled attribute. Note that when disabled, the input's value will not be submitted when submitting the form.

<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">

How can I generate a random number in a certain range?

To extend what Rahul Gupta said:

You can use Java function int random = Random.nextInt(n).
This returns a random int in the range [0, n-1].

I.e., to get the range [20, 80] use:

final int random = new Random().nextInt(61) + 20; // [0, 60] + 20 => [20, 80]

To generalize more:

final int min = 20;
final int max = 80;
final int random = new Random().nextInt((max - min) + 1) + min;

Assigning out/ref parameters in Moq

For 'out', the following seems to work for me.

public interface IService
{
    void DoSomething(out string a);
}

[TestMethod]
public void Test()
{
    var service = new Mock<IService>();
    var expectedValue = "value";
    service.Setup(s => s.DoSomething(out expectedValue));

    string actualValue;
    service.Object.DoSomething(out actualValue);
    Assert.AreEqual(expectedValue, actualValue);
}

I'm guessing that Moq looks at the value of 'expectedValue' when you call Setup and remembers it.

For ref, I'm looking for an answer also.

I found the following QuickStart guide useful: https://github.com/Moq/moq4/wiki/Quickstart

redistributable offline .NET Framework 3.5 installer for Windows 8

After several month without real solution for this problem, I suppose that the best solution is to upgrade the application to .NET framework 4.0, which is supported by Windows 8, Windows 10 and Windows 2012 Server by default and it is still available as offline installation for Windows XP.

Get a list of all the files in a directory (recursive)

This is what I came up with for a gradle build script:

task doLast {
    ext.FindFile = { list, curPath ->
        def files = file(curPath).listFiles().sort()

        files.each {  File file ->

            if (file.isFile()) {
                list << file
            }
            else {
                list << file  // If you want the directories in the list

                list = FindFile( list, file.path) 
            }
        }
        return list
    }

    def list = []
    def theFile = FindFile(list, "${project.projectDir}")

    list.each {
        println it.path
    }
}

Log all requests from the python-requests module

Having a script or even a subsystem of an application for a network protocol debugging, it's desired to see what request-response pairs are exactly, including effective URLs, headers, payloads and the status. And it's typically impractical to instrument individual requests all over the place. At the same time there are performance considerations that suggest using single (or few specialised) requests.Session, so the following assumes that the suggestion is followed.

requests supports so called event hooks (as of 2.23 there's actually only response hook). It's basically an event listener, and the event is emitted before returning control from requests.request. At this moment both request and response are fully defined, hence can be logged.

import logging

import requests


logger = logging.getLogger('httplogger')

def logRoundtrip(response, *args, **kwargs):
    extra = {'req': response.request, 'res': response}
    logger.debug('HTTP roundtrip', extra=extra)

session = requests.Session()
session.hooks['response'].append(logRoundtrip)

That's basically how to log all HTTP round-trips of a session.

Formatting HTTP round-trip log records

For the logging above to be useful there can be specialised logging formatter that understands req and res extras on logging records. It can look like this:

import textwrap

class HttpFormatter(logging.Formatter):   

    def _formatHeaders(self, d):
        return '\n'.join(f'{k}: {v}' for k, v in d.items())

    def formatMessage(self, record):
        result = super().formatMessage(record)
        if record.name == 'httplogger':
            result += textwrap.dedent('''
                ---------------- request ----------------
                {req.method} {req.url}
                {reqhdrs}

                {req.body}
                ---------------- response ----------------
                {res.status_code} {res.reason} {res.url}
                {reshdrs}

                {res.text}
            ''').format(
                req=record.req,
                res=record.res,
                reqhdrs=self._formatHeaders(record.req.headers),
                reshdrs=self._formatHeaders(record.res.headers),
            )

        return result

formatter = HttpFormatter('{asctime} {levelname} {name} {message}', style='{')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logging.basicConfig(level=logging.DEBUG, handlers=[handler])

Now if you do some requests using the session, like:

session.get('https://httpbin.org/user-agent')
session.get('https://httpbin.org/status/200')

The output to stderr will look as follows.

2020-05-14 22:10:13,224 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): httpbin.org:443
2020-05-14 22:10:13,695 DEBUG urllib3.connectionpool https://httpbin.org:443 "GET /user-agent HTTP/1.1" 200 45
2020-05-14 22:10:13,698 DEBUG httplogger HTTP roundtrip
---------------- request ----------------
GET https://httpbin.org/user-agent
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive

None
---------------- response ----------------
200 OK https://httpbin.org/user-agent
Date: Thu, 14 May 2020 20:10:13 GMT
Content-Type: application/json
Content-Length: 45
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

{
  "user-agent": "python-requests/2.23.0"
}


2020-05-14 22:10:13,814 DEBUG urllib3.connectionpool https://httpbin.org:443 "GET /status/200 HTTP/1.1" 200 0
2020-05-14 22:10:13,818 DEBUG httplogger HTTP roundtrip
---------------- request ----------------
GET https://httpbin.org/status/200
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive

None
---------------- response ----------------
200 OK https://httpbin.org/status/200
Date: Thu, 14 May 2020 20:10:13 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

A GUI way

When you have a lot of queries, having a simple UI and a way to filter records comes at handy. I'll show to use Chronologer for that (which I'm the author of).

First, the hook has be rewritten to produce records that logging can serialise when sending over the wire. It can look like this:

def logRoundtrip(response, *args, **kwargs): 
    extra = {
        'req': {
            'method': response.request.method,
            'url': response.request.url,
            'headers': response.request.headers,
            'body': response.request.body,
        }, 
        'res': {
            'code': response.status_code,
            'reason': response.reason,
            'url': response.url,
            'headers': response.headers,
            'body': response.text
        },
    }
    logger.debug('HTTP roundtrip', extra=extra)

session = requests.Session()
session.hooks['response'].append(logRoundtrip)

Second, logging configuration has to be adapted to use logging.handlers.HTTPHandler (which Chronologer understands).

import logging.handlers

chrono = logging.handlers.HTTPHandler(
  'localhost:8080', '/api/v1/record', 'POST', credentials=('logger', ''))
handlers = [logging.StreamHandler(), chrono]
logging.basicConfig(level=logging.DEBUG, handlers=handlers)

Finally, run Chronologer instance. e.g. using Docker:

docker run --rm -it -p 8080:8080 -v /tmp/db \
    -e CHRONOLOGER_STORAGE_DSN=sqlite:////tmp/db/chrono.sqlite \
    -e CHRONOLOGER_SECRET=example \
    -e CHRONOLOGER_ROLES="basic-reader query-reader writer" \
    saaj/chronologer \
    python -m chronologer -e production serve -u www-data -g www-data -m

And run the requests again:

session.get('https://httpbin.org/user-agent')
session.get('https://httpbin.org/status/200')

The stream handler will produce:

DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org:443
DEBUG:urllib3.connectionpool:https://httpbin.org:443 "GET /user-agent HTTP/1.1" 200 45
DEBUG:httplogger:HTTP roundtrip
DEBUG:urllib3.connectionpool:https://httpbin.org:443 "GET /status/200 HTTP/1.1" 200 0
DEBUG:httplogger:HTTP roundtrip

Now if you open http://localhost:8080/ (use "logger" for username and empty password for the basic auth popup) and click "Open" button, you should see something like:

Screenshot of Chronologer

How to generate a random number in C++?

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    srand(time(NULL));
    int random_number = std::rand(); // rand() return a number between ?0? and RAND_MAX
    std::cout << random_number;
    return 0;
}

http://en.cppreference.com/w/cpp/numeric/random/rand

chai test array equality doesn't work as expected

Try to use deep Equal. It will compare nested arrays as well as nested Json.

expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });

Please refer to main documentation site.

How to get a Static property with Reflection

This is C#, but should give you the idea:

public static void Main() {
    typeof(Program).GetProperty("GetMe", BindingFlags.NonPublic | BindingFlags.Static);
}

private static int GetMe {
    get { return 0; }
}

(you need to OR NonPublic and Static only)

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

I fixed my problem with the solution below:

In Gradle build file, add dependency:

implementation 'com.android.support:multidex:1.0.3'

And then in the "defaultConfig" section, add:

multiDexEnabled true

Setting public class variables

You're "setting" the value of that variable/attribute. Not overriding or overloading it. Your code is very, very common and normal.

All of these terms ("set", "override", "overload") have specific meanings. Override and Overload are about polymorphism (subclassing).

From http://en.wikipedia.org/wiki/Object-oriented_programming :

Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the addition operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism.

Debugging iframes with Chrome developer tools

Currently evaluation in the console is performed in the context of the main frame in the page and it adheres to the same cross-origin policy as the main frame itself. This means that you cannot access elements in the iframe unless the main frame can. You can still set breakpoints in and debug your code using Scripts panel though.

Update: This is no longer true. See Metagrapher's answer.

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

if you are using visual studio , enable the build property "Prefer 32-bit". see image below.

enter image description here

Submit two forms with one button

The currently chosen best answer is too fuzzy to be reliable.

This feels to me like a fairly safe way to do it:

(Javascript: using jQuery to write it simpler)

$('#form1').submit(doubleSubmit);

function doubleSubmit(e1) {
    e1.preventDefault();
    e1.stopPropagation();
    var post_form1 = $.post($(this).action, $(this).serialize());

    post_form1.done(function(result) {
            // would be nice to show some feedback about the first result here
            $('#form2').submit();
        });
};

Post the first form without changing page, wait for the process to complete. Then post the second form. The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).

I didn't test the code, though.

How to Use Content-disposition for force a file to download to the hard drive?

With recent browsers you can use the HTML5 download attribute as well:

<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>

It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):

(function (){

    addEvent(window, "load", function (){
        if (isInternetExplorer())
            polyfillDataUriDownload();
    });

    function polyfillDataUriDownload(){
        var links = document.querySelectorAll('a[download], area[download]');
        for (var index = 0, length = links.length; index<length; ++index) {
            (function (link){
                var dataUri = link.getAttribute("href");
                var fileName = link.getAttribute("download");
                if (dataUri.slice(0,5) != "data:")
                    throw new Error("The XHR part is not implemented here.");
                addEvent(link, "click", function (event){
                    cancelEvent(event);
                    try {
                        var dataBlob = dataUriToBlob(dataUri);
                        forceBlobDownload(dataBlob, fileName);
                    } catch (e) {
                        alert(e)
                    }
                });
            })(links[index]);
        }
    }

    function forceBlobDownload(dataBlob, fileName){
        window.navigator.msSaveBlob(dataBlob, fileName);
    }

    function dataUriToBlob(dataUri) {
        if  (!(/base64/).test(dataUri))
            throw new Error("Supports only base64 encoding.");
        var parts = dataUri.split(/[:;,]/),
            type = parts[1],
            binData = atob(parts.pop()),
            mx = binData.length,
            uiArr = new Uint8Array(mx);
        for(var i = 0; i<mx; ++i)
            uiArr[i] = binData.charCodeAt(i);
        return new Blob([uiArr], {type: type});
    }

    function addEvent(subject, type, listener){
        if (window.addEventListener)
            subject.addEventListener(type, listener, false);
        else if (window.attachEvent)
            subject.attachEvent("on" + type, listener);
    }

    function cancelEvent(event){
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    }

    function isInternetExplorer(){
        return /*@cc_on!@*/false || !!document.documentMode;
    }
    
})();

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

The best way to do this is by a simple check and assess. I usually do something like this:

#ifndef _DEPRECATION_DISABLE   /* One time only */
#define _DEPRECATION_DISABLE   /* Disable deprecation true */
#if (_MSC_VER >= 1400)         /* Check version */
#pragma warning(disable: 4996) /* Disable deprecation */
#endif /* #if defined(NMEA_WIN) && (_MSC_VER >= 1400) */
#endif /* #ifndef _DEPRECATION_DISABLE */

All that is really required is the following:

#pragma warning(disable: 4996)

Hasn't failed me yet; Hope this helps

ASP.NET Temporary files cleanup

Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.

For background, see the Understanding ASP.NET dynamic compilation article on MSDN.

How can I change image tintColor in iOS and WatchKit

Now i use this method based in Duncan Babbage response:

+ (UIImageView *) tintImageView: (UIImageView *)imageView withColor: (UIColor*) color{
    imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [imageView setTintColor:color];
    return imageView;
}

How can I reference a dll in the GAC from Visual Studio?

Assuming you alredy tried to "Add Reference..." as explained above and did not succeed, you can have a look here. They say you have to meet some prerequisites: - .NET 3.5 SP1 - Windows Installer 4.5

EDIT: According to this post it is a known issue.

And this could be the solution you're looking for :)

Count unique values using pandas groupby

I think you can use SeriesGroupBy.nunique:

print (df.groupby('param')['group'].nunique())
param
a    2
b    1
Name: group, dtype: int64

Another solution with unique, then create new df by DataFrame.from_records, reshape to Series by stack and last value_counts:

a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a    2
b    1
dtype: int64

Can you issue pull requests from the command line on GitHub?

I ended up making my own, I find that it works better the other solutions that were around.

https://npmjs.org/package/pullr

QR Code encoding and decoding using zxing

this is my working example Java code to encode QR code using ZXing with UTF-8 encoding, please note: you will need to change the path and utf8 data to your path and language characters

package com.mypackage.qr;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;

import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.*;

public class CreateQR {

public static void main(String[] args)
{
    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] b = null;
    try {
        // Convert a string to UTF-8 bytes in a ByteBuffer
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("utf 8 characters - i used hebrew, but you should write some of your own language characters"));
        b = bbuf.array();
    } catch (CharacterCodingException e) {
        System.out.println(e.getMessage());
    }

    String data;
    try {
        data = new String(b, "UTF-8");
        // get a byte matrix for the data
        BitMatrix matrix = null;
        int h = 100;
        int w = 100;
        com.google.zxing.Writer writer = new MultiFormatWriter();
        try {
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            matrix = writer.encode(data,
            com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints);
        } catch (com.google.zxing.WriterException e) {
            System.out.println(e.getMessage());
        }

        // change this path to match yours (this is my mac home folder, you can use: c:\\qr_png.png if you are on windows)
                String filePath = "/Users/shaybc/Desktop/OutlookQR/qr_png.png";
        File file = new File(filePath);
        try {
            MatrixToImageWriter.writeToFile(matrix, "PNG", file);
            System.out.println("printing to " + file.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    } catch (UnsupportedEncodingException e) {
        System.out.println(e.getMessage());
    }
}

}

How to change line color in EditText

The best approach is to use an AppCompatEditText with backgroundTint attribute of app namespace. i.e.

    <android.support.v7.widget.AppCompatEditText
    android:layout_width="match_parent"      
    app:backgroundTint="YOUR COLOR"
    android:layout_height="wrap_content" />

when we use android:backgroundTint it will only work in API21 or more but app:backgroundTint works on all API levels your app does.

Bulk Record Update with SQL

Or you can simply update without using join like this:

Update t1 set  t1.Description = t2.Description from @tbl2 t2,tbl1 t1
where t1.ID= t2.ID

Delete file from internal storage

This works for me:

Java

File file = new File(photoPath);
file.delete();

MediaScannerConnection.scanFile(context,
                new String[]{file.toString()},
                new String[]{file.getName()},null);

Kotlin

val file = File(photoPath) 
file.delete()

MediaScannerConnection.scanFile(context, arrayOf(file.toString()),
      arrayOf(file.getName()), null)

Pass variables between two PHP pages without using a form or the URL of page

Sessions would be good choice for you. Take a look at these two examples from PHP Manual:

Code of page1.php

<?php
// page1.php

session_start();

echo 'Welcome to page #1';

$_SESSION['favcolor'] = 'green';
$_SESSION['animal']   = 'cat';
$_SESSION['time']     = time();

// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';

// Or pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>

Code of page2.php

<?php
// page2.php

session_start();

echo 'Welcome to page #2<br />';

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal'];   // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>

To clear up things - SID is PHP's predefined constant which contains session name and its id. Example SID value:

PHPSESSID=d78d0851898450eb6aa1e6b1d2a484f1

Android: No Activity found to handle Intent error? How it will resolve

Intent intent=new Intent(String) is defined for parameter task, whereas you are passing parameter componentname into this, use instead:

Intent i = new Intent(Settings.this, com.scytec.datamobile.vd.gui.android.AppPreferenceActivity.class);
                    startActivity(i);

In this statement replace ActivityName by Name of Class of Activity, this code resides in.

Reading images in python

If you just want to read an image in Python using the specified libraries only, I will go with matplotlib

In matplotlib :

import matplotlib.image
read_img = matplotlib.image.imread('your_image.png')

How can I find the maximum value and its index in array in MATLAB?

3D case

Modifying Mohsen's answer for 3D array:

[M,I] = max (A(:));
[ind1, ind2, ind3] = ind2sub(size(A),I)

How to obtain values of request variables using Python and Flask

You can get posted form data from request.form and query string data from request.args.

myvar =  request.form["myvar"]
myvar = request.args["myvar"]

Find the day of a week

start = as.POSIXct("2017-09-01")
end = as.POSIXct("2017-09-06")

dat = data.frame(Date = seq.POSIXt(from = start,
                                   to = end,
                                   by = "DSTday"))

# see ?strptime for details of formats you can extract

# day of the week as numeric (Monday is 1)
dat$weekday1 = as.numeric(format(dat$Date, format = "%u"))

# abbreviated weekday name
dat$weekday2 = format(dat$Date, format = "%a")

# full weekday name
dat$weekday3 = format(dat$Date, format = "%A")

dat
# returns
    Date       weekday1 weekday2  weekday3
1 2017-09-01        5      Fri    Friday
2 2017-09-02        6      Sat    Saturday
3 2017-09-03        7      Sun    Sunday
4 2017-09-04        1      Mon    Monday
5 2017-09-05        2      Tue    Tuesday
6 2017-09-06        3      Wed    Wednesday

Getting an option text/value with JavaScript

You can use:

var option_user_selection = element.options[ element.selectedIndex ].text

Regex for numbers only

Use the beginning and end anchors.

Regex regex = new Regex(@"^\d$");

Use "^\d+$" if you need to match more than one digit.


Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ??????????. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.


If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.

How to determine if one array contains all elements of another array

a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]

a - b
# => [5, 1, 14, 8]

b - a
# => [15]

(b - a).empty?
# => false

Javascript loop through object array?

for (let key in data) {
    let value = data[key];
    for (i = 0; i < value.length; i++) {
      console.log(value[i].msgFrom);
      console.log(value[i].msgBody);
    }
  }

How do I link to Google Maps with a particular longitude and latitude?

As of today (1st November, 2020), Google provided a provision of Universal URL which works quite efficiently on cross-platforms and thus, Google recommends this method.

Syntax: https://www.google.com/maps/search/?api=1&query=<lat>,<lng>

Example : https://www.google.com/maps/search/?api=1&query=28.6139,77.2090 (New Delhi, India)

Documentation/Source.

How to run a cron job on every Monday, Wednesday and Friday?

Use this command to add job

crontab -e

In this format:

0 19 * * 1,3,5 /path to your file/file.php

How to convert time milliseconds to hours, min, sec format in JavaScript?

Worked for me

msToTime(milliseconds) {
    //Get hours from milliseconds
    var hours = milliseconds / (1000*60*60);
    var absoluteHours = Math.floor(hours);
    var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;

    //Get remainder from hours and convert to minutes
    var minutes = (hours - absoluteHours) * 60;
    var absoluteMinutes = Math.floor(minutes);
    var m = absoluteMinutes > 9 ? absoluteMinutes : '0' +  absoluteMinutes;

    //Get remainder from minutes and convert to seconds
    var seconds = (minutes - absoluteMinutes) * 60;
    var absoluteSeconds = Math.floor(seconds);
    var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;

    return h == "00" ? m + ':' + s : h + ':' + m + ':' + s;
}

.htaccess mod_rewrite - how to exclude directory from rewrite rule

If you want to remove a particular directory from the rule (meaning, you want to remove the directory foo) ,you can use :

RewriteEngine on

RewriteCond %{REQUEST_URI} !^/foo/$
RewriteRule !index\.php$ /index.php [L]

The rewriteRule above will rewrite all requestes to /index.php excluding requests for /foo/ .

To exclude all existent directries, you will need to use the following condition above your rule :

RewriteCond %{REQUEST_FILENAME} !-d

the following rule

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !index\.php$ /index.php [L]

rewrites everything (except directries) to /index.php .

How to tell which row number is clicked in a table?

In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:

<table id="elitable" border="1" cellspacing="0" width="100%">
  <tr>
 <td>100</td><td>AAA</td><td>aaa</td>
  </tr>
  <tr>
<td>200</td><td>BBB</td><td>bbb</td>
   </tr>
   <tr>
<td>300</td><td>CCC</td><td>ccc</td>
  </tr>
</table>


    <script>
    $(function(){
        $("#elitable tr").click(function(){
        alert (this.rowIndex);
        });
    });
    </script>

DEMO

Is there a way to disable initial sorting for jquery DataTables?

In datatable options put this:

$(document).ready( function() {
  $('#example').dataTable({
    "aaSorting": [[ 2, 'asc' ]], 
    //More options ...

   });
})

Here is the solution: "aaSorting": [[ 2, 'asc' ]],

2 means table will be sorted by third column,
asc in ascending order.

Print empty line?

You will always only get an indent error if there is actually an indent error. Double check that your final line is indented the same was as the other lines -- either with spaces or with tabs. Most likely, some of the lines had spaces (or tabs) and the other line had tabs (or spaces).

Trust in the error message -- if it says something specific, assume it to be true and figure out why.

How to Determine the Screen Height and Width in Flutter

Hey you can use this class to get Screen Width and Height in percentage

import 'package:flutter/material.dart';
class Responsive{
  static width(double p,BuildContext context)
  {
    return MediaQuery.of(context).size.width*(p/100);
  }
  static height(double p,BuildContext context)
  {
    return MediaQuery.of(context).size.height*(p/100);
  }
}

and to Use like this

Container(height: Responsive.width(100, context), width: Responsive.width(50, context),);

Remove columns from dataframe where ALL values are NA

You can use Janitor package remove_empty

library(janitor)

df %>%
  remove_empty(c("rows", "cols")) #select either row or cols or both

Also, Another dplyr approach

 library(dplyr) 
 df %>% select_if(~all(!is.na(.)))

OR

df %>% select_if(colSums(!is.na(.)) == nrow(df))

this is also useful if you want to only exclude / keep column with certain number of missing values e.g.

 df %>% select_if(colSums(!is.na(.))>500)

Add a CSS class to <%= f.submit %>

<%= f.submit 'name of button here', :class => 'submit_class_name_here' %>

This should do. If you're getting an error, chances are that you're not supplying the name.

Alternatively, you can style the button without a class:

form#form_id_here input[type=submit]

Try that, as well.

Adding padding to a tkinter widget only on one side

The padding options padx and pady of the grid and pack methods can take a 2-tuple that represent the left/right and top/bottom padding.

Here's an example:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

Choose folders to be ignored during search in VS Code

I'm an idiot so it took me a while to realize this, but make sure that the Gear icon is clicked on the global search so your settings can be applied.

Visual Studio Code Gear Icon on Search clicked

Class Not Found: Empty Test Suite in IntelliJ

Interestingly, I've faced this issue many times due to different reasons. For e.g. Invalidating cache and restarting has helped as well.

Last I fixed it by correcting my output path in File -> Project Structure -> Project -> Project Compiler Output to : absolute_path_of_package/out

for e.g. : /Users/random-guy/myWorkspace/src/DummyProject/out

Regex how to match an optional character

Use

[A-Z]?

to make the letter optional. {1} is redundant. (Of course you could also write [A-Z]{0,1} which would mean the same, but that's what the ? is there for.)

You could improve your regex to

^([0-9]{5})+\s+([A-Z]?)\s+([A-Z])([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})

And, since in most regex dialects, \d is the same as [0-9]:

^(\d{5})+\s+([A-Z]?)\s+([A-Z])(\d{3})(\d{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])\d{3}(\d{4})(\d{2})(\d{2})

But: do you really need 11 separate capturing groups? And if so, why don't you capture the fourth-to-last group of digits?

Hide text within HTML?

You said that you can’t use HTML comments because the CMS filters them out. So I assume that you really want to hide this content and you don’t need to display it ever.

In that case, you shouldn’t use CSS (only), as you’d only play on the presentation level, not affecting the content level. Your content should also be hidden for user-agents ignoring the CSS (people using text browsers, feed readers, screen readers; bots; etc.).

In HTML5 there is the global hidden attribute:

When specified on an element, it indicates that the element is not yet, or is no longer, directly relevant to the page's current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user. User agents should not render elements that have the hidden attribute specified.

Example (using the small element here, because it’s an "attribution"):

<small hidden>Thanks to John Doe for this idea.</small>

As a fallback (for user-agents that don’t know the hidden attribute), you can specify in your CSS:

[hidden] {display:none;}

An general element for plain text could be the script element used as "data block":

<script type="text/plain" hidden>
Thanks to John Doe for this idea.
</script>

Alternatively, you could also use data-* attributes on existing elements (resp. on new div elements if you want to group some elements for the attribution):

<p data-attribution="Thanks to John Doe for this idea!">This is some visible example content …</p>

How to populate options of h:selectOneMenu from database?

Roll-your-own generic converter for complex objects as selected item

The Balusc gives a very useful overview answer on this subject. But there is one alternative he does not present: The Roll-your-own generic converter that handles complex objects as the selected item. This is very complex to do if you want to handle all cases, but pretty simple for simple cases.

The code below contains an example of such a converter. It works in the same spirit as the OmniFaces SelectItemsConverter as it looks through the children of a component for UISelectItem(s) containing objects. The difference is that it only handles bindings to either simple collections of entity objects, or to strings. It does not handle item groups, collections of SelectItems, arrays and probably a lot of other things.

The entities that the component binds to must implement the IdObject interface. (This could be solved in other way, such as using toString.)

Note that the entities must implement equals in such a way that two entities with the same ID compares equal.

The only thing that you need to do to use it is to specify it as converter on the select component, bind to an entity property and a list of possible entities:

<h:selectOneMenu value="#{bean.user}" converter="selectListConverter">
  <f:selectItem itemValue="unselected" itemLabel="Select user..."/>
  <f:selectItem itemValue="empty" itemLabel="No user"/>
  <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

Converter:

/**
 * A converter for select components (those that have select items as children).
 * 
 * It convertes the selected value string into one of its element entities, thus allowing
 * binding to complex objects.
 * 
 * It only handles simple uses of select components, in which the value is a simple list of
 * entities. No ItemGroups, arrays or other kinds of values.
 * 
 * Items it binds to can be strings or implementations of the {@link IdObject} interface.
 */
@FacesConverter("selectListConverter")
public class SelectListConverter implements Converter {

  public static interface IdObject {
    public String getDisplayId();
  }

  @Override
  public Object getAsObject(FacesContext context, UIComponent component, String value) {
    if (value == null || value.isEmpty()) {
      return null;
    }

    return component.getChildren().stream()
      .flatMap(child -> getEntriesOfItem(child))
      .filter(o -> value.equals(o instanceof IdObject ? ((IdObject) o).getDisplayId() : o))
      .findAny().orElse(null);
  }

  /**
   * Gets the values stored in a {@link UISelectItem} or a {@link UISelectItems}.
   * For other components returns an empty stream.
   */
  private Stream<?> getEntriesOfItem(UIComponent child) {
    if (child instanceof UISelectItem) {
      UISelectItem item = (UISelectItem) child;
      if (!item.isNoSelectionOption()) {
        return Stream.of(item.getValue());
      }

    } else if (child instanceof UISelectItems) {
      Object value = ((UISelectItems) child).getValue();

      if (value instanceof Collection) {
        return ((Collection<?>) value).stream();
      } else {
        throw new IllegalStateException("Unsupported value of UISelectItems: " + value);
      }
    }

    return Stream.empty();
  }

  @Override
  public String getAsString(FacesContext context, UIComponent component, Object value) {
    if (value == null) return null;
    if (value instanceof String) return (String) value;
    if (value instanceof IdObject) return ((IdObject) value).getDisplayId();

    throw new IllegalArgumentException("Unexpected value type");
  }

}

PowerShell equivalent to grep -f

Maybe?

[regex]$regex = (get-content <regex file> |
foreach {
          '(?:{0})' -f $_
        }) -join '|'

Get-Content <filespec> -ReadCount 10000 |
 foreach {
           if ($_ -match $regex)
             {
              $true
              break
             }
         }

How to add Button over image using CSS?

I like TryingToImprove's answer. I've essentially taken his answer and simplified it down to the barebones css to accomplish the same thing. I think it's a lot easier to chew on.

HTML:

<div class="content">
    <img src="http://placehold.it/182x121"/> 
    <a href="#">Counter-Strike 1.6 Steam</a>
</div>        

CSS:

.content{    
    display:inline-block;
    position:relative;
}

.content a {
    position:absolute;
    bottom:5px;
    right:5px;
}

Working fiddle here.

How can I delay a method call for 1 second?

Use in Swift 3

perform(<Selector>, with: <object>, afterDelay: <Time in Seconds>)

How to submit a form with JavaScript by clicking a link?

document.getElementById("theForm").submit();

It works perfect in my case.

you can use it in function also like,

function submitForm()
{
     document.getElementById("theForm").submit();
} 

Set "theForm" as your form ID. It's done.

Declare a Range relative to the Active Cell with VBA

There is an .Offset property on a Range class which allows you to do just what you need

ActiveCell.Offset(numRows, numCols)

follow up on a comment:

Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))

and you can verify by MsgBox newRange.Address

and here's how to assign this range to an array

POST request with a simple string in body with Alamofire

You can do this:

  1. I created a separated request Alamofire object.
  2. Convert string to Data
  3. Put in httpBody the data

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = HTTPMethod.post.rawValue
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    let pjson = attendences.toJSONString(prettyPrint: false)
    let data = (pjson?.data(using: .utf8))! as Data
    
    request.httpBody = data
    
    Alamofire.request(request).responseJSON { (response) in
    
    
        print(response)
    
    }
    

Using :: in C++

The :: is called scope resolution operator. Can be used like this:

:: identifier
class-name :: identifier
namespace :: identifier

You can read about it here
https://docs.microsoft.com/en-us/cpp/cpp/scope-resolution-operator?view=vs-2017

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

I encountered similar issue when uploading a file returned 409.

Besides issues mentioned above it can also happen due to file size restrictions for POST on the server side. For example, tomcat (java web server) have POST size limit of 2MB by default.

Run JavaScript code on window close or page refresh?

Sometimes you may want to let the server know that the user is leaving the page. This is useful, for example, to clean up unsaved images stored temporarily on the server, to mark that user as "offline", or to log when they are done their session.

Historically, you would send an AJAX request in the beforeunload function, however this has two problems. If you send an asynchronous request, there is no guarantee that the request would be executed correctly. If you send a synchronous request, it is more reliable, but the browser would hang until the request has finished. If this is a slow request, this would be a huge inconvenience to the user.

Later came navigator.sendBeacon(). By using the sendBeacon() method, the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. This solves all of the problems with submission of analytics data: the data is sent reliably, it's sent asynchronously, and it doesn't impact the loading of the next page.

Unless you are targeting only desktop users, sendBeacon() should not be used with unload or beforeunload since these do not reliably fire on mobile devices. Instead you can listen to the visibilitychange event. This event will fire every time your page is visible and the user switches tabs, switches apps, goes to the home screen, answers a phone call, navigates away from the page, closes the tab, refreshes, etc.

Here is an example of its usage:

document.addEventListener('visibilitychange', function() {
    if (document.visibilityState == 'hidden') { 
        navigator.sendBeacon("/log.php", analyticsData);
    }
});

When the user returns to the page, document.visibilityState will change to 'visible', so you can also handle that event as well.

sendBeacon() is supported in:

  • Edge 14
  • Firefox 31
  • Chrome 39
  • Safari 11.1
  • Opera 26
  • iOS Safari 11.4

It is NOT currently supported in:

  • Internet Explorer
  • Opera Mini

Here is a polyfill for sendBeacon() in case you need to add support for unsupported browsers. If the method is not available in the browser, it will send a synchronous AJAX request instead.

Update:

It might be worth mentioning that sendBeacon() only sends POST requests. If you need to send a request using any other method, an alternative would be to use the fetch API with the keepalive flag set to true, which causes it to behave the same way as sendBeacon(). Browser support for the fetch API is about the same.

fetch(url, {
   method: ..., 
   body: ...,            
   headers: ...,       
   credentials: 'include',
   mode: 'no-cors',
   keepalive: true,
})

Only variables should be passed by reference

Since it raise a flag for over 10 years, but works just fine and return the expected value, a little stfu operator is the goodiest bad practice you are all looking for:

$file_extension = @end(explode('.', $file_name));

But warning, don't use in loops due to a performance hit. Newest version of php 7.3+ offer the method array_key_last() and array_key_first().

https://www.php.net/manual/en/function.array-key-last.php

Base64 encoding in SQL Server 2005 T-SQL

I loved @Slai's answer. I only had to make very minor modifications into the one-liners I was looking for. I thought I'd share what I ended up with in case it helps anyone else stumbling onto this page like I did:

DECLARE @Source VARCHAR(50) = '12345'
DECLARE @Encoded VARCHAR(500) = CONVERT(VARCHAR(500), (SELECT CONVERT(VARBINARY, @Source) FOR XML PATH(''), BINARY BASE64))
DECLARE @Decoded VARCHAR(500) = CONVERT(VARCHAR(500), CONVERT(XML, @Encoded).value('.','varbinary(max)'))
SELECT @Source AS [Source], @Encoded AS [Encoded], @Decoded AS [Decoded]

Get all dates between two dates in SQL Server

This can be considered as bit tricky way as in my situation, I can't use a CTE table, so decided to join with sys.all_objects and then created row numbers and added that to start date till it reached the end date.

See the code below where I generated all dates in Jul 2018. Replace hard coded dates with your own variables (tested in SQL Server 2016):

select top (datediff(dd, '2018-06-30', '2018-07-31')) ROW_NUMBER() 
over(order by a.name) as SiNo, 
Dateadd(dd, ROW_NUMBER() over(order by a.name) , '2018-06-30') as Dt from sys.all_objects a

How to generate class diagram from project in Visual Studio 2013?

Because one moderator deleted my detailed image-supported answer on this question, just because I copied and pasted from another question, I am forced to put a less detailed answer and I will link the original answer if you want a more visual way to see the solution.


For Visual Studio 2019 and Visual Studio 2017 Users
For People who are missing this old feature in VS2019 (or maybe VS2017) from the old versions of Visual Studio


This feature still available, but it is NOT available by default, you have to install it separately.

  1. Open VS 2019 go to Tools -> Get Tools and Features
  2. Select the Individual components tab and search for Class Designer
  3. Select this Component and Install it, After finish installing this component (you may need to restart visual studio)
  4. Right-click on the project and select Add -> Add New Item
  5. Search for 'class' word and NOW you can see Class Diagram component

see this answer also to see an image associated

https://stackoverflow.com/a/66289543/4390133

(whish that the moderator realized this is the same question and instead of deleting my answer, he could mark one of the questions as duplicated to the other)


Update to create a class-diagram for the whole project
I received a downvote because I did not mention how to generate a diagram for the whole project, here is how to do it (after applying the previous steps)

  1. Add class diagram to the project
  2. if the option Preview Selected Items is enabled in the solution explorer, disabled it temporarily, you can re-enable it later

enter image description here

  1. open the class diagram that you created in step 2 (by double-clicking on it)
  2. drag-and-drop the project from the solution explorer to the class diagram

you could be shocked by the results to the point that you can change your mind and remove your downvote (please do NOT upvote, it is enough to remove your downvote)

Hadoop: «ERROR : JAVA_HOME is not set»

You can add in your .bashrc file:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

and it will dynamically change when you update your packages.

How can I iterate through a string and also know the index (current position)?

You can use standard STL function distance as mentioned before

index = std::distance(s.begin(), it);

Also, you can access string and some other containers with the c-like interface:

for (i=0;i<string1.length();i++) string1[i];

How to force link from iframe to be opened in the parent window

Use target-attribute:

<a target="_parent" href="http://url.org">link</a>

Kill detached screen session

Alternatively, while in your screen session all you have to do is type exit

This will kill the shell session initiated by the screen, which effectively terminates the screen session you are on.

No need to bother with screen session id, etc.

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

python 2.7: cannot pip on windows "bash: pip: command not found"

  1. press [win] + Pause
  2. Advanced settings
  3. System variables
  4. Append ;C:\python27\Scripts to the end of Path variable
  5. Restart console

How to check if a particular service is running on Ubuntu

For centos, below command worked for me (:

locate postgres | grep service

Output:

/usr/lib/firewalld/services/postgresql.xml

/usr/lib/systemd/system/postgresql-9.3.service

sudo systemctl status postgresql-9.3.service

Using 'starts with' selector on individual class names

Classes that start with "apple-" plus classes that contain " apple-"

$("div[class^='apple-'],div[class*=' apple-']")

How to get text of an element in Selenium WebDriver, without including child element text?

def get_true_text(tag):
    children = tag.find_elements_by_xpath('*')
    original_text = tag.text
    for child in children:
        original_text = original_text.replace(child.text, '', 1)
    return original_text

How merge two objects array in angularjs?

You can use angular.extend(dest, src1, src2,...);

In your case it would be :

angular.extend($scope.actions.data, data);

See documentation here :

https://docs.angularjs.org/api/ng/function/angular.extend

Otherwise, if you only get new values from the server, you can do the following

for (var i=0; i<data.length; i++){
    $scope.actions.data.push(data[i]);
}

How to know which is running in Jupyter notebook?

Assuming you have the wrong backend system you can change the backend kernel by creating a new or editing the existing kernel.json in the kernels folder of your jupyter data path jupyter --paths. You can have multiple kernels (R, Python2, Python3 (+virtualenvs), Haskell), e.g. you can create an Anaconda specific kernel:

$ <anaconda-path>/bin/python3 -m ipykernel install --user --name anaconda --display-name "Anaconda"

Should create a new kernel:

<jupyter-data-dir>/kernels/anaconda/kernel.json

{
    "argv": [ "<anaconda-path>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
    "display_name": "Anaconda",
    "language": "python"
}

You need to ensure ipykernel package is installed in the anaconda distribution.

This way you can just switch between kernels and have different notebooks using different kernels.

C++ templates that accept only certain types

Executive summary: Don't do that.

j_random_hacker's answer tells you how to do this. However, I would also like to point out that you should not do this. The whole point of templates is that they can accept any compatible type, and Java style type constraints break that.

Java's type constraints are a bug not a feature. They are there because Java does type erasure on generics, so Java can't figure out how to call methods based on the value of type parameters alone.

C++ on the other hand has no such restriction. Template parameter types can be any type compatible with the operations they are used with. There doesn't have to be a common base class. This is similar to Python's "Duck Typing," but done at compile time.

A simple example showing the power of templates:

// Sum a vector of some type.
// Example:
// int total = sum({1,2,3,4,5});
template <typename T>
T sum(const vector<T>& vec) {
    T total = T();
    for (const T& x : vec) {
        total += x;
    }
    return total;
}

This sum function can sum a vector of any type that support the correct operations. It works with both primitives like int/long/float/double, and user defined numeric types that overload the += operator. Heck, you can even use this function to join strings, since they support +=.

No boxing/unboxing of primitives is necessary.

Note that it also constructs new instances of T using T(). This is trivial in C++ using implicit interfaces, but not really possible in Java with type constraints.

While C++ templates don't have explicit type constraints, they are still type safe, and will not compile with code that does not support the correct operations.

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

Java integer to byte array

byte[] conv = new byte[4];
conv[3] = (byte) input & 0xff;
input >>= 8;
conv[2] = (byte) input & 0xff;
input >>= 8;
conv[1] = (byte) input & 0xff;
input >>= 8;
conv[0] = (byte) input;

How to concatenate multiple lines of output to one line?

Probably the best way to do it is using 'awk' tool which will generate output into one line

$ awk ' /pattern/ {print}' ORS=' ' /path/to/file

It will merge all lines into one with space delimiter

Formatting floats in a numpy array

[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]

What is the difference between "INNER JOIN" and "OUTER JOIN"?

There are major mainly 2 types of JOINs in SQL: [INNER and OUTER]


Examples

Suppose you have two tables, with a single column each, and data as follows:

A    B
-    -
1    3
2    4
3    5
4    6
7
8

Note that (1,2,7,8) are unique to A, (3,4) are common, and (5,6) are unique to B.



  • (INNER) JOIN:

The INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be the same.

INNER JOIN

select * from a INNER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a = b.b;

Result:

a | b
--+--
3 | 3
4 | 4


  • LEFT (OUTER) JOIN:

This join returns all the rows of the table on the left side of the join and matching rows for the table on the right side of the join. The rows for which there is no matching row on the right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.

LEFT JOIN / LEFT OUTER JOIN

select * from a LEFT OUTER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a = b.b(+);

Result:

a |  b
--+-----
1 | null
2 | null
3 |    3
4 |    4
7 | null
8 | null


  • RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table

RIGHT JOIN / RIGHT OUTER JOIN

select * from a RIGHT OUTER JOIN b on a.a = b.b;
select a.*, b.*  from a,b where a.a(+) = b.b;

Result:

a    |  b
-----+----
3    |  3
4    |  4
null |  5
null |  6


  • FULL (OUTER) JOIN:

    FULL JOIN creates the result-set by combining the result of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from both the tables. The rows for which there is no matching, the result-set will contain NULL values.

FULL JOIN / FULL OUTER JOIN

select * from a FULL OUTER JOIN b on a.a = b.b;

Result:

 a   |  b
-----+-----
   1 | null
   2 | null
   3 |    3
   4 |    4
null |    6
null |    5
   7 | null
   8 | null

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

jQuery DataTables Getting selected row values

More a comment than an answer - but I cannot add comments yet: Thanks for your help, the count was the easy part. Just for others that might come here. I hope that it will save you some time.

It took me a while to get the attributes from the rows and to understand how to access them from the data() Object (that the data() is an Array and the Attributes can be read by adding them with a dot and not with brackets:

$('#button').click( function () {
    for (var i = 0; i < table.rows('.selected').data().length; i++) { 
       console.log( table.rows('.selected').data()[i].attributeNameFromYourself);
    }
} );

(by the way: I get the data for my table using AJAX and JSON)

Set selected item of spinner programmatically

Some explanation (at least for Fragments - never tried with pure Activity). Hope it helps someone to understand Android better.

Most popular answer by Arun George is correct but don't work in some cases.
The answer by Marco HC uses Runnable wich is a last resort due to additional CPU load.

The answer is - you should simply choose correct place to call to setSelection(), for example it works for me:

@Override
public void onResume() {
    super.onResume();

    yourSpinner.setSelection(pos);
 }

But it won't work in onCreateView(). I suspect that is the reason for the interest to this topic.

The secret is that with Android you can't do anything you want in any method - oops:( - components may just not be ready. As another example - you can't scroll ScrollView neither in onCreateView() nor in onResume() (see the answer here)

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

Is there a good jQuery Drag-and-drop file upload plugin?

If you are still looking for one, I just released mine: http://github.com/weixiyen/jquery-filedrop

Works for Firefox 3.6 right now. I decided not to do the Chrome hack for now and let Webkit catch up with FileReader() in the next versions of Safari and Chrome.

This plugin is future compatible.

FileReader() is the official standard over something like XHR.getAsBinary() which is deprecated according to mozilla.

It's also the only HTML5 desktop drag+drop plugin out there that I know of which allows you to send extra data along with the file, including data that can be calculated at the time of upload with a callback function.

Extract elements of list at odd positions

You can make use of bitwise AND operator &. Let's see below:

x = [1, 2, 3, 4, 5, 6, 7]
y = [i for i in x if i&1]
>>> 
[1, 3, 5, 7]

Bitwise AND operator is used with 1, and the reason it works because, odd number when written in binary must have its first digit as 1. Let's check

23 = 1 * (2**4) + 0 * (2**3) + 1 * (2**2) + 1 * (2**1) + 1 * (2**0) = 10111
14 = 1 * (2**3) + 1 * (2**2) + 1 * (2**1) + 0 * (2**0) = 1110

AND operation with 1 will only return 1 (1 in binary will also have last digit 1), iff the value is odd.

Check the Python Bitwise Operator page for more.

P.S: You can tactically use this method if you want to select odd and even columns in a dataframe. Let's say x and y coordinates of facial key-points are given as columns x1, y1, x2, etc... To normalize the x and y coordinates with width and height values of each image you can simply perform

for i in range(df.shape[1]):
    if i&1:
        df.iloc[:, i] /= heights
    else:
        df.iloc[:, i] /= widths

This is not exactly related to the question but for data scientists and computer vision engineers this method could be useful.

Cheers!

Assign output of os.system to a variable and prevent it from being displayed on the screen

From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is popen:

os.popen('cat /etc/services').read()

From the docs for Python 3.6,

This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.


Here's the corresponding code for subprocess:

import subprocess

proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out

How do I find out if a column exists in a VB.Net DataRow

You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".

Exclude subpackages from Spring autowiring?

I am using @ComponentScan as follows for the same use case. This is the same as BenSchro10's XML answer but this uses annotations. Both use a filter with type=AspectJ

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration;
import org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration;
import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = { "com.example" },
    excludeFilters = @ComponentScan.Filter(type = FilterType.ASPECTJ, pattern = "com.example.ignore.*"))
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Change div height on button click

Look at to vwphillips' post from 03-06-2010, 03:35 PM in http://www.codingforums.com/archive/index.php/t-190887.html

<html>
   <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

      <script type="text/javascript">

        function Div(id,ud) {
           var div=document.getElementById(id);
           var h=parseInt(div.style.height)+ud;
           if (h>=1){
              div.style.height = h + "em"; // I'm using "em" instead of "px", but you can use px like measure...
           }
        }
      </script>

   </head>
   <body>
      <div>
         <input type="button" value="+" onclick="Div('my_div', 1);">&nbsp;&nbsp; 
         <input type="button" value="-" onclick="Div('my_div', -1);"></div>
      </div>

      <div id="my_div" style="height: 1em; width: 1em; overflow: auto;"></div>

   </body>
</html>

This worked for me :)

Best regards!

Disable a Button

Swift 5 / SwiftUI

Nowadays it's done like this.

Button(action: action) {
  Text(buttonLabel)
}
  .disabled(!isEnabled)

Match linebreaks - \n or \r\n?

You have different line endings in the example texts in Debuggex. What is especially interesting is that Debuggex seems to have identified which line ending style you used first, and it converts all additional line endings entered to that style.

I used Notepad++ to paste sample text in Unix and Windows format into Debuggex, and whichever I pasted first is what that session of Debuggex stuck with.

So, you should wash your text through your text editor before pasting it into Debuggex. Ensure that you're pasting the style you want. Debuggex defaults to Unix style (\n).

Also, NEL (\u0085) is something different entirely: https://en.wikipedia.org/wiki/Newline#Unicode

(\r?\n) will cover Unix and Windows. You'll need something more complex, like (\r\n|\r|\n), if you want to match old Mac too.

An existing connection was forcibly closed by the remote host

This is not a bug in your code. It is coming from .Net's Socket implementation. If you use the overloaded implementation of EndReceive as below you will not get this exception.

    SocketError errorCode;
    int nBytesRec = socket.EndReceive(ar, out errorCode);
    if (errorCode != SocketError.Success)
    {
        nBytesRec = 0;
    }

NameError: name 'reduce' is not defined in Python

You can add

from functools import reduce

before you use the reduce.

Base table or view not found: 1146 Table Laravel 5

I faced this problem too in laravel 5.2 and if declaring the table name doesn't work,it is probably because you have some wrong declaration or mistake in validation code in Request (If you are using one)

how to redirect to home page

Can you do this on the server, using Apache's mod_rewrite for example? If not, you can use the window.location.replace method to erase the current URL from the back/forward history (to not break the back button) and go to the root of the web site:

window.location.replace('/');

Android studio: emulator is running but not showing up in Run App "choose a running device"

I am using Idea based Android Studio (some people are talking about eclipse one here)

When I launch the app in the emulator (using the Run App button of Android Studio) AVD shows up but the app does not launch or run.

However when I connect my mobile and launch the app on my mobile the App works (this itself took some time, enabling developer options on mobile and doing the right configuration)

  • Because My app is launching on connected mobile, I can say nothing wrong with App.
  • There is some problem with AVD integration which I could not figure out so As of now I am working around my problem following way.

1 - I installed the app manually by dragging the APK file on AVD. (APK file is app\build\outputs\apk\debug folder)

2 - Then my AVD was not showing the installed APP list. 3 - I searched my APP using Google bar on AVD and dragged the APP icon on the home screen of AVD.

4 - I can now launch the APP using my APP icon on the home screen of AVD.

That's how I am working around my problem. I will try to debug more on why it does not get installed and launched directly.

I have verified that Run App Icon does install the Application. Installation, not launching, appears to be the problem for me.

Why dividing two integers doesn't get a float?

"a" is an integer, when divided with integer it gives you an integer. Then it is assigned to "b" as an integer and becomes a float.

You should do it like this

b = a / 350.0;

MacOSX homebrew mysql root password

In case you have inadvertently set and forgot the root password, and you don't want to wipe all your databases and start over because you are lazy and forgot to have a back up solution in place, and you are using a fairly recent Homebrew install (Winter 2013), here are steps to reset your password for MySQL.

Stop the currently running MySQL instance

launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

Now start mysql by hand skipping the grant tables and networking

$(brew --prefix mysql)/bin/mysqld_safe --skip-grant-tables --skip-networking

Note that if when you run echo $(brew --prefix mysql) and it does not respond as "/usr/local/opt/mysql" in bash, you will need to adjust the path accordingly.

Once you have done this, you now should have a running, unprotected MySQL instance up.

Log in and set the password

mysql -u root

At the prompt, enter the following MySQL command to set a new password for the effected user.

mysql> update mysql.user set password=PASSWORD('new_password_here') WHERE user='root';

If all went to plan it should say:

Query OK, 1 row affected (0.02 sec)
Rows matched: 4  Changed: 1  Warnings: 0

Exit out of the MySQL prompt.

mysql> exit
Bye

Stop server:

mysqladmin -u root shutdown

Now, lets put back the launch daemon so we have our MySQL at the ready again:

launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

Congratulations. You've just reset your mysql root password. Pour yourself a coffee and get a backup solution in place!

Why does GitHub recommend HTTPS over SSH?

Either you are quoting wrong or github has different recommendation on different pages or they may learned with time and updated their reco.

We strongly recommend using an SSH connection when interacting with GitHub. SSH keys are a way to identify trusted computers, without involving passwords. The steps below will walk you through generating an SSH key and then adding the public key to your GitHub account.

https://help.github.com/articles/generating-ssh-keys

What is the intended use-case for git stash?

I will break answer on three paragraphs.

Part 1:

git stash (To save your un-committed changes in a "stash". Note: this removes changes from working tree!)

git checkout some_branch (change to intended branch -- in this case some_branch)

git stash list (list stashes)

You can see:
stash@{0}: WIP on {branch_name}: {SHA-1 of last commit} {last commit of you branch}
stash@{0}: WIP on master: 085b095c6 modification for test

git stash apply (to apply stash to working tree in current branch)

git stash apply stash@{12} (if you will have many stashes you can choose what stash will apply -- in this case we apply stash 12)

git stash drop stash@{0} (to remove from stash list -- in this case stash 0)

git stash pop stash@{1} (to apply selected stash and drop it from stash list)

Part 2:
You can hide your changes with this command but it is not necessary.
You can continue on the next day without stash.
This commands for hide your changes and work on different branches or for implementation some realisation of your code and save in stashes without branches and commitsor your custom case!
And later you can use some of stashes and check wich is better.

Part 3:
Stash command for local hide your changes.
If you want work remotely you must commit and push.

Simple URL GET/POST function in Python

You could use this to wrap urllib2:

def URLRequest(url, params, method="GET"):
    if method == "POST":
        return urllib2.Request(url, data=urllib.urlencode(params))
    else:
        return urllib2.Request(url + "?" + urllib.urlencode(params))

That will return a Request object that has result data and response codes.

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

If you are running on a 64 bit system and trying to load a 32 bit dll you need to compile your application as 32 bit instead of any cpu. If you are not doing this it behaves exactly as you describe.

If that isn't the case use Dependency Walker to verify that the dll has its required dependencies.

Select count(*) from multiple tables

My experience is with SQL Server, but could you do:

select (select count(*) from table1) as count1,
  (select count(*) from table2) as count2

In SQL Server I get the result you are after.

how to refresh page in angular 2

If you want to reload the page , you can easily go to your component then do :

location.reload();

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

Below Solution worked for me :

Type About:Config in the Address Bar and press Enter.

“This Might void your warranty!” warning will be displayed, click on I’ll be careful, I Promise button.

Type security.ssl.enable_ocsp_stapling in search box.

The value field is true, double click on it to make it false.

Now try to connect your website again.

Why "no projects found to import"?

In new updated eclipse the option "create project from existing source" is found here, File>New>Project>Android>Android Project from Existing Code. Then browse to root directory.

enter image description here

calling a function from class in python - different way

you have to use self as the first parameters of a method

in the second case you should use

class MathOperations:
    def testAddition (self,x, y):
        return x + y

    def testMultiplication (self,a, b):
        return a * b

and in your code you could do the following

tmp = MathOperations
print tmp.testAddition(2,3)

if you use the class without instantiating a variable first

print MathOperation.testAddtion(2,3)

it gives you an error "TypeError: unbound method"

if you want to do that you will need the @staticmethod decorator

For example:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

then in your code you could use

print MathsOperations.testAddition(2,3)

ImportError: No module named 'bottle' - PyCharm

in your PyCharm project:

  • press Ctrl+Alt+s to open the settings
  • on the left column, select Project Interpreter
  • on the top right there is a list of python binaries found on your system, pick the right one
  • eventually click the + button to install additional python modules
  • validate

enter image description here

Git push failed, "Non-fast forward updates were rejected"

This is what worked for me. It can be found in git documentation here

If you are on your desired branch you can do this:

git fetch origin
# Fetches updates made to an online repository
git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work

Count if two criteria match - EXCEL formula

Add the sheet name infront of the cell, e.g.:

=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")

Assumes the sheet name is "stock"

How to wait for 2 seconds?

Try this example:

exec DBMS_LOCK.sleep(5);

This is the whole script:

SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Start Date / Time" FROM DUAL;

exec DBMS_LOCK.sleep(5);

SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "End Date / Time" FROM DUAL;

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two possible reasons 1. If you are using HttpClient in your service you need to import HttpClientModule in your module file and mention it in the imports array.

import { HttpClientModule } from '@angular/common/http';
  1. If you are using normal Http in your services you need to import HttpModule in your module file and mention it in the imports array.

    import { HttpModule } from '@angular/http'

By default, this is not available in the angular then you need to install @angular/http

If you wish you can use both HttpClientModule and HttpModule in your project.

How to change screen resolution of Raspberry Pi

As other comments here pointed out, you'll need to uncomment disable_overscan=1 in /boot/config.txt

if you are using NOOBS (this is what im using), you'll find in the end of the file a set of default settings that has disable_overscan=0 attribute. you'll need to change its value to 1, and re-boot.

How do I use Safe Area Layout programmatically?

You can use view.safeAreaInsets as explained here https://www.raywenderlich.com/174078/auto-layout-visual-format-language-tutorial-2

code sample (taken from raywenderlich.com):

override func viewSafeAreaInsetsDidChange() {
  super.viewSafeAreaInsetsDidChange()

  if !allConstraints.isEmpty {
    NSLayoutConstraint.deactivate(allConstraints)
    allConstraints.removeAll()
  }

  let newInsets = view.safeAreaInsets
  let leftMargin = newInsets.left > 0 ? newInsets.left : Metrics.padding
  let rightMargin = newInsets.right > 0 ? newInsets.right : Metrics.padding
  let topMargin = newInsets.top > 0 ? newInsets.top : Metrics.padding
  let bottomMargin = newInsets.bottom > 0 ? newInsets.bottom : Metrics.padding

  let metrics = [
    "horizontalPadding": Metrics.padding,
    "iconImageViewWidth": Metrics.iconImageViewWidth,
    "topMargin": topMargin,
    "bottomMargin": bottomMargin,
    "leftMargin": leftMargin,
    "rightMargin": rightMargin]
}


let views: [String: Any] = [
  "iconImageView": iconImageView,
  "appNameLabel": appNameLabel,
  "skipButton": skipButton,
  "appImageView": appImageView,
  "welcomeLabel": welcomeLabel,
  "summaryLabel": summaryLabel,
  "pageControl": pageControl]

let iconVerticalConstraints = NSLayoutConstraint.constraints(
  withVisualFormat: "V:|-topMargin-[iconImageView(30)]",
  metrics: metrics,
  views: views)
allConstraints += iconVerticalConstraints

let topRowHorizontalFormat = """
  H:|-leftMargin-[iconImageView(iconImageViewWidth)]-[appNameLabel]-[skipButton]-rightMargin-|
  """
...

Android Studio: Where is the Compiler Error Output Window?

Are you on Windows? Launch cmd, find your project folder and run "gradlew build". This should already give you more output than the IDE, you can also use --info, --stacktrace and --debug there.

How to validate Google reCAPTCHA v3 on server side?

I liked Levit's answer and ended up using it. But I just wanted to point out, just in case, that there is an official Google PHP library for new reCAPTCHA: https://github.com/google/recaptcha

The latest version (right now 1.1.2) supports Composer and contains an example that you can run to see if you have configured everything correctly.

Below you can see part of the example that comes with this official library (with my minor modifications for clarity):

// Make the call to verify the response and also pass the user's IP address
    $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

    if ($resp->isSuccess()) {
// If the response is a success, that's it!
        ?>
        <h2>Success!</h2>
        <p>That's it. Everything is working. Go integrate this into your real project.</p>
        <p><a href="/">Try again</a></p>
        <?php
    } else {
// If it's not successful, then one or more error codes will be returned.
        ?>
        <h2>Something went wrong</h2>
        <p>The following error was returned: <?php
            foreach ($resp->getErrorCodes() as $code) {
                echo '<tt>' , $code , '</tt> ';
            }
            ?></p>
        <p>Check the error code reference at <tt><a href="https://developers.google.com/recaptcha/docs/verify#error-code-reference">https://developers.google.com/recaptcha/docs/verify#error-code-reference</a></tt>.
        <p><strong>Note:</strong> Error code <tt>missing-input-response</tt> may mean the user just didn't complete the reCAPTCHA.</p>
        <p><a href="/">Try again</a></p>
    <?php
    }

Hope it helps someone.

new DateTime() vs default(DateTime)

The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min

Therefore there is no difference between default(DateTime) and new DateTime() and DateTime.Min

Java: How to set Precision for double value?

Here's an efficient way of achieving the result with two caveats.

  1. Limits precision to 'maximum' N digits (not fixed to N digits).
  2. Rounds down the number (not round to nearest).

See sample test cases here.

123.12345678 ==> 123.123
1.230000 ==> 1.23
1.1 ==> 1.1
1 ==> 1.0
0.000 ==> 0.0
0.00 ==> 0.0
0.4 ==> 0.4
0 ==> 0.0
1.4999 ==> 1.499
1.4995 ==> 1.499
1.4994 ==> 1.499

Here's the code. The two caveats I mentioned above can be addressed pretty easily, however, speed mattered more to me than accuracy, so i left it here. String manipulations like System.out.printf("%.2f",123.234); are computationally costly compared to mathematical operations. In my tests, the below code (without the sysout) took 1/30th the time compared to String manipulations.

public double limitPrecision(String dblAsString, int maxDigitsAfterDecimal) {
    int multiplier = (int) Math.pow(10, maxDigitsAfterDecimal);
    double truncated = (double) ((long) ((Double.parseDouble(dblAsString)) * multiplier)) / multiplier;
    System.out.println(dblAsString + " ==> " + truncated);
    return truncated;
}

How do I mock a REST template exchange?

If your intention is test the service without care about the rest call, I will suggest to not use any annotation in your unit test to simplify the test.

So, my suggestion is refactor your service to receive the resttemplate using injection constructor. This will facilitate the test. Example:

@Service
class SomeService {
    @AutoWired
    SomeService(TestTemplateObjects restTemplateObjects) {
        this.restTemplateObjects = restTemplateObjects;
    }
}

The RestTemplate as component, to be injected and mocked after:

@Component
public class RestTemplateObjects {

    private final RestTemplate restTemplate;

    public RestTemplateObjects () {
        this.restTemplate = new RestTemplate();
        // you can add extra setup the restTemplate here, like errorHandler or converters
    }

    public RestTemplate getRestTemplate() {
        return restTemplate;
    }
}

And the test:

public void test() {

    when(mockedRestTemplateObject.get).thenReturn(mockRestTemplate);

    //mock restTemplate.exchange
    when(mockRestTemplate.exchange(...)).thenReturn(mockedResponseEntity);

    SomeService someService = new SomeService(mockedRestTemplateObject);
    someService.getListofObjectsA();
}

In this way, you have direct access to mock the rest template by the SomeService constructor.

Change arrow colors in Bootstraps carousel

If you are using bootstrap.min.css for carousel-

<a class="left carousel-control" href="#carouselExample" data-slide="prev">
  <span class="glyphicon glyphicon-chevron-left"></span>
  <span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carouselExample" data-slide="next">
  <span class="glyphicon glyphicon-chevron-right"></span>
  <span class="sr-only">Next</span>
</a>

Open the bootstrap.min.css file and find the property "glyphicon-chevron-right" and add the property "color:red"

CSS Change List Item Background Color with Class

Scenario: I have a navigation menu like this. Note: Link <a> is child of list item <li>. I wanted to change the background of the selected list item and remove the background color of unselected list item.

<nav>
        <ul>
            <li><a href="#">Intro</a></li>
            <li><a href="#">Size</a></li>
            <li><a href="#">Play</a></li>
            <li><a href="#">Food</a></li>
        </ul>
        <div class="clear"></div>

       </nav>

I tried to add a class .active into the list item using jQuery but it was not working

.active
{
    background-color: #480048;
}

$("nav li a").click(function () {
        $(this).parent().addClass("active");
        $(this).parent().siblings().removeClass("active");
    });

Solution: Basically, using .active class changing the background-color of list item does not work. So I changed the css class name from .active to "nav li.active a" so using the same javascript it will add the .active class into the selected list item. Now if the list item <li> has .active class then css will change the background color of the child of that list item <a>.

nav li.active a
{
    background-color: #480048;
}

What is the difference between a hash join and a merge join (Oracle RDBMS )?

A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.

A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.

(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).

The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:

  1. The size of each hash table is reduced, hence reducing the maximum amount of memory required and potentially removing the need for the operation to require temporary disk space.
  2. For parallel query operations the amount of inter-process messaging is vastly reduced, reducing CPU usage and improving performance, as each hash join can be performed by one pair of PQ processes.
  3. For non-parallel query operations the memory requirement is reduced by a factor of n, and the first rows are projected from the query earlier.

You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.

In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.

This topic is very well covered in the documentation.

http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523

12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm

Tool for comparing 2 binary files in Windows

Total Commander also has a binary compare option: go to: File \\Compare by content

ps. I guess some people may alredy be using this tool and may not be aware of the built-in feature.