Programs & Examples On #Bssid

Basic Service Set Identification - MAC address of an Wireless Access Point.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Type

netsh wlan set hostednetwork mode=allow ssid=hotspotname key=123456789

perform all steps in proper order.. for more detail with image ,have a look..this might help to setup hotspot correctly.

http://www.infogeekers.com/turn-windows-8-into-wifi-hotspot/

Get SSID when WIFI is connected

Starting with Android 8.1 (API 27), apps must be granted the ACCESS_COARSE_LOCATION (or ACCESS_FINE_LOCATION) permission in order to obtain results from WifiInfo.getSSID() or WifiInfo.getBSSID(). Apps that target API 29 or higher (Android 10) must be granted ACCESS_FINE_LOCATION.

This permission is also needed to obtain results from WifiManager.getConnectionInfo() and WifiManager.getScanResults() although it is not clear if this is new in 8.1 or was required previously.

Source: "BSSID/SSID can be used to deduce location, so require the same location permissions for access to these WifiInfo fields requested using WifiManager.getConnectionInfo() as for WifiManager.getScanResults()."

How can I get Android Wifi Scan Results into a list?

Wrap an ArrayAdapter around your List<ScanResult>. Override getView() to populate your rows with the ScanResult data. Here is a free excerpt from one of my books that covers how to create custom ArrayAdapters like this.

Get response from PHP file using AJAX

in your PHP file, when you echo your data use json_encode (http://php.net/manual/en/function.json-encode.php)

e.g.

<?php
//plum or data...
$output = array("data","plum");

echo json_encode($output);

?>

in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this:

 $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                success function(json_data){
                    var data_array = $.parseJSON(json_data);

                    //access your data like this:
                    var plum_or_whatever = data_array['output'];.
                    //continue from here...
                }
            });

How do I get my page title to have an icon?

If you wanna use a URL just you can use this code.

<link rel="shortcut icon" type="image/x-icon" href="https://..." />

Android Material and appcompat Manifest merger failed

I had the same error when working with Groupie. implementation 'com.xwray:groupie:2.3.0'

I solved it by changing version to implementation 'com.xwray:groupie:2.1.0'

chrome undo the action of "prevent this page from creating additional dialogs"

Turning Hardware Acceleration OFF seems to be the setting that affects popups & dialogs.

Chrome was continually hiding Dialog Windows when I needed to respond Yes or No to things, also when I needed to Rename folders in my bookmarks panel. After weeks of doing this. I disabled all the Chrome helpers in Settings, Also In windows 10 I switched Window Snapping off. It has done something to put the popups and dialogs back in the Viewport.

When this bug is happening, I was able to shut a tab by first pressing Enter before clicking the tab close X button. The browser had an alert box, hidden which needed a response from the user.

Switching Hardware Accleration Off and back On, Killing the Chrome process and switching all the other Helpers Off and back has fixed it for me... It must be in chrome itself because Ive just gone into a Chrome window in the Mac and it has now stopped the problem, without any intervention. Im guessing flicking the chrome settings on/off/on has caused it to reposition the dialogs. I cant get the browser to repeat the fault now...

Is there a way to specify a max height or width for an image?

You can try this one

img{
    max-height:500px;
    max-width:500px;
    height:auto;
    width:auto;
}

This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px

You can check this post

Get column index from column name in python pandas

For returning multiple column indices, I recommend using the pandas.Index method get_indexer, if you have unique labels:

df = pd.DataFrame({"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]})
df.columns.get_indexer(['pear', 'apple'])
# Out: array([0, 1], dtype=int64)

If you have non-unique labels in the index (columns only support unique labels) get_indexer_for. It takes the same args as get_indeder:

df = pd.DataFrame(
    {"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]}, 
    index=[0, 1, 1])
df.index.get_indexer_for([0, 1])
# Out: array([0, 1, 2], dtype=int64)

Both methods also support non-exact indexing with, f.i. for float values taking the nearest value with a tolerance. If two indices have the same distance to the specified label or are duplicates, the index with the larger index value is selected:

df = pd.DataFrame(
    {"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]},
    index=[0, .9, 1.1])
df.index.get_indexer([0, 1])
# array([ 0, -1], dtype=int64)

Setting up Vim for Python

In general, vim is a very powerful regular language editor (macros extend this but we'll ignore that for now). This is because vim's a thin layer on top of ed, and ed isn't much more than a line editor that speaks regex. Emacs has the advantage of being built on top of ELisp; lending it the ability to easily parse complex grammars and perform indentation tricks like the one you shared above.

To be honest, I've never been able to dive into the depths of emacs because it is simply delightful meditating within my vim cave. With that said, let's jump in.

Getting Started

Janus

For beginners, I highly recommend installing the readymade Janus plugin (fwiw, the name hails from a Star Trek episode featuring Janus Vim). If you want a quick shortcut to a vim IDE it's your best bang for your buck.

I've never used it much, but I've seen others use it happily and my current setup is borrowed heavily from an old Janus build.

Vim Pathogen

Otherwise, do some exploring on your own! I'd highly recommend installing vim pathogen if you want to see the universe of vim plugins.

It's a package manager of sorts. Once you install it, you can git clone packages to your ~/.vim/bundle directory and they're auto-installed. No more plugin installation, maintenance, or uninstall headaches!

You can run the following script from the GitHub page to install pathogen:

mkdir -p ~/.vim/autoload ~/.vim/bundle; \
curl -so ~/.vim/autoload/pathogen.vim \
    https://raw.github.com/tpope/vim-pathogen/HEAD/autoload/pathogen.vim

Helpful Links

Here are some links on extending vim I've found and enjoyed:

How to convert any Object to String?

I am try to convert Object type variable into string using this line of code

try this to convert object value to string:

Java Code

 Object dataobject=value;
    //convert object into String  
     String convert= String.valueOf(dataobject);

WinForms DataGridView font size

The straight forward approach:

this.dataGridView1.DefaultCellStyle.Font = new Font("Tahoma", 15);

How to create a inner border for a box in html?

Html:

<div class="outerDiv">
    <div class="innerDiv">Content</div>
</div>

CSS:

.outerDiv{
    background: #000;
    padding: 10px;
 }

 .innerDiv{
     border: 2px dashed #fff;
     min-height: 200px; //adding min-height as there is no content inside

 }

What is trunk, branch and tag in Subversion?

A trunk is considered your main code base, a branch offshoot of the trunk. Like, you create a branch if you want to implement a new feature, but don't want to affect the main trunk.

TortoiseSVN has good documentation, and a great diff tool.

I use Visual studio, and I use VisualSVN and TortoiseSVN.

How do you run a SQL Server query from PowerShell?

To avoid SQL Injection with varchar parameters you could use

function sqlExecuteRead($connectionString, $sqlCommand, $pars) {

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $connection.Open()
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)

    if ($pars -and $pars.Keys) {
        foreach($key in $pars.keys) {
            # avoid injection in varchar parameters
            $par = $command.Parameters.Add("@$key", [system.data.SqlDbType]::VarChar, 512);
            $par.Value = $pars[$key];
        }
    }

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataset) | Out-Null
    $connection.Close()
    return $dataset.tables[0].rows

}

$connectionString = "connectionstringHere"
$sql = "select top 10 Message, TimeStamp, Level from dbo.log " +
    "where Message = @MSG and Level like @LEVEL"
$pars = @{
    MSG = 'this is a test from powershell'
    LEVEL = 'aaa%'
};
sqlExecuteRead $connectionString $sql $pars

Didn't Java once have a Pair class?

Many 3rd party libraries have their versions of Pair, but Java has never had such a class. The closest is the inner interface java.util.Map.Entry, which exposes an immutable key property and a possibly mutable value property.

node.js - how to write an array to file

To do what you want, using the fs.createWriteStream(path[, options]) function in a ES6 way:

const fs = require('fs');
const writeStream = fs.createWriteStream('file.txt');
const pathName = writeStream.path;
 
let array = ['1','2','3','4','5','6','7'];
  
// write each value of the array on the file breaking line
array.forEach(value => writeStream.write(`${value}\n`));

// the finish event is emitted when all data has been flushed from the stream
writeStream.on('finish', () => {
   console.log(`wrote all the array data to file ${pathName}`);
});

// handle the errors on the write process
writeStream.on('error', (err) => {
    console.error(`There is an error writing the file ${pathName} => ${err}`)
});

// close the stream
writeStream.end();

VARCHAR to DECIMAL

Implemented using Custom Function. This will check whether the string value can be converted to Decimal safely

CREATE FUNCTION [dbo].[TryParseAsDecimal]
(
    @Value      NVARCHAR(4000)
    ,@Precision INT
    ,@Scale     INT
)

RETURNS BIT
AS
BEGIN

    IF(ISNUMERIC(@Value) =0) BEGIN
        RETURN CAST(0 AS BIT)
    END
    SELECT @Value = REPLACE(@Value,',','') --Removes the comma

    --This function validates only the first part eg '1234567.8901111111'
    --It validates only the values before the '.' ie '1234567.'
    DECLARE @Index          INT
    DECLARE @Part1Length    INT 
    DECLARE @Part1          VARCHAR(4000)   

    SELECT @Index = CHARINDEX('.', @Value, 0)
    IF (@Index>0) BEGIN
        --If decimal places, extract the left part only and cast it to avoid leading zeros (eg.'0000000001' => '1')
        SELECT @Part1 =LEFT(@Value, @Index-1);
        SELECT @Part1=SUBSTRING(@Part1, PATINDEX('%[^0]%', @Part1+'.'), LEN(@Part1));
        SELECT @Part1Length = LEN(@Part1);
    END
    ELSE BEGIN
        SELECT @Part1 =CAST(@Value AS DECIMAL);
        SELECT @Part1Length= LEN(@Part1)
    END 

    IF (@Part1Length > (@Precision-@Scale)) BEGIN
        RETURN CAST(0 AS BIT)
    END

    RETURN CAST(1 AS BIT)

END

PHP order array by date?

He was considering having the date as a key, but worried that values will be written one above other, all I wanted to show (maybe not that obvious, that why I do edit) is that he can still have values intact, not written one above other, isn't this okay?!

<?php
 $data['may_1_2002']=
 Array(
 'title_id_32'=>'Good morning', 
 'title_id_21'=>'Blue sky',
 'title_id_3'=>'Summer',
 'date'=>'1 May 2002'
 );

 $data['may_2_2002']=
 Array(
 'title_id_34'=>'Leaves', 
 'title_id_20'=>'Old times',
  'date'=>'2 May   2002 '
 );


 echo '<pre>';
 print_r($data);
?>

Laravel Checking If a Record Exists

if (User::where('email', Input::get('email'))->exists()) {
    // exists
}

Write single CSV file using spark-csv

spark.sql("select * from df").coalesce(1).write.option("mode","append").option("header","true").csv("/your/hdfs/path/")

spark.sql("select * from df") --> this is dataframe

coalesce(1) or repartition(1) --> this will make your output file to 1 part file only

write --> writing data

option("mode","append") --> appending data to existing directory

option("header","true") --> enabling header

csv("") --> write as CSV file & its output location in HDFS

MySQL SELECT WHERE datetime matches day (and not necessarily time)

You can use %:

SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'

Should I use encodeURI or encodeURIComponent for encoding URLs?

As a general rule use encodeURIComponent. Don't be scared of the long name thinking it's more specific in it's use, to me it's the more commonly used method. Also don't be suckered into using encodeURI because you tested it and it appears to be encoding properly, it's probably not what you meant to use and even though your simple test using "Fred" in a first name field worked, you'll find later when you use more advanced text like adding an ampersand or a hashtag it will fail. You can look at the other answers for the reasons why this is.

It is more efficient to use if-return-return or if-else-return?

With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.

Controlling execution order of unit tests in Visual Studio

Here is a class that can be used to setup and run ordered tests independent of MS Ordered Tests framework for whatever reason--like not have to adjust mstest.exe arguments on a build machine, or mixing ordered with non-ordered in a class.

The original testing framework only sees the list of ordered tests as a single test so any init/cleanup like [TestInitalize()] Init() is only called before and after the entire set.

Usage:

        [TestMethod] // place only on the list--not the individuals
        public void OrderedStepsTest()
        {
            OrderedTest.Run(TestContext, new List<OrderedTest>
            {
                new OrderedTest ( T10_Reset_Database, false ),
                new OrderedTest ( T20_LoginUser1, false ),
                new OrderedTest ( T30_DoLoginUser1Task1, true ), // continue on failure
                new OrderedTest ( T40_DoLoginUser1Task2, true ), // continue on failure
                // ...
            });                
        }

Implementation:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace UnitTests.Utility
{    
    /// <summary>
    /// Define and Run a list of ordered tests. 
    /// 2016/08/25: Posted to SO by crokusek 
    /// </summary>    
    public class OrderedTest
    {
        /// <summary>Test Method to run</summary>
        public Action TestMethod { get; private set; }

        /// <summary>Flag indicating whether testing should continue with the next test if the current one fails</summary>
        public bool ContinueOnFailure { get; private set; }

        /// <summary>Any Exception thrown by the test</summary>
        public Exception ExceptionResult;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="testMethod"></param>
        /// <param name="continueOnFailure">True to continue with the next test if this test fails</param>
        public OrderedTest(Action testMethod, bool continueOnFailure = false)
        {
            TestMethod = testMethod;
            ContinueOnFailure = continueOnFailure;
        }

        /// <summary>
        /// Run the test saving any exception within ExceptionResult
        /// Throw to the caller only if ContinueOnFailure == false
        /// </summary>
        /// <param name="testContextOpt"></param>
        public void Run()
        {
            try
            {
                TestMethod();
            }
            catch (Exception ex)
            {
                ExceptionResult = ex;
                throw;
            }
        }

        /// <summary>
        /// Run a list of OrderedTest's
        /// </summary>
        static public void Run(TestContext testContext, List<OrderedTest> tests)
        {
            Stopwatch overallStopWatch = new Stopwatch();
            overallStopWatch.Start();

            List<Exception> exceptions = new List<Exception>();

            int testsAttempted = 0;
            for (int i = 0; i < tests.Count; i++)
            {
                OrderedTest test = tests[i];

                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();

                testContext.WriteLine("Starting ordered test step ({0} of {1}) '{2}' at {3}...\n",
                    i + 1,
                    tests.Count,
                    test.TestMethod.Method,
                    DateTime.Now.ToString("G"));

                try
                {
                    testsAttempted++;
                    test.Run();
                }
                catch
                {
                    if (!test.ContinueOnFailure)
                        break;
                }
                finally
                {
                    Exception testEx = test.ExceptionResult;

                    if (testEx != null)  // capture any "continue on fail" exception
                        exceptions.Add(testEx);

                    testContext.WriteLine("\n{0} ordered test step {1} of {2} '{3}' in {4} at {5}{6}\n",
                        testEx != null ? "Error:  Failed" : "Successfully completed",
                        i + 1,
                        tests.Count,
                        test.TestMethod.Method,
                        stopWatch.ElapsedMilliseconds > 1000
                            ? (stopWatch.ElapsedMilliseconds * .001) + "s"
                            : stopWatch.ElapsedMilliseconds + "ms",
                        DateTime.Now.ToString("G"),
                        testEx != null
                            ? "\nException:  " + testEx.Message +
                                "\nStackTrace:  " + testEx.StackTrace +
                                "\nContinueOnFailure:  " + test.ContinueOnFailure
                            : "");
                }
            }

            testContext.WriteLine("Completed running {0} of {1} ordered tests with a total of {2} error(s) at {3} in {4}",
                testsAttempted,
                tests.Count,
                exceptions.Count,
                DateTime.Now.ToString("G"),
                overallStopWatch.ElapsedMilliseconds > 1000
                    ? (overallStopWatch.ElapsedMilliseconds * .001) + "s"
                    : overallStopWatch.ElapsedMilliseconds + "ms");

            if (exceptions.Any())
            {
                // Test Explorer prints better msgs with this hierarchy rather than using 1 AggregateException().
                throw new Exception(String.Join("; ", exceptions.Select(e => e.Message), new AggregateException(exceptions)));
            }
        }
    }
}

Mockito - NullpointerException when stubbing Method

None of the above answers helped me. I was struggling to understand why code works in Java but not in Kotlin.

Then I figured it out from this thread.

You have to make class and member functions open, otherwise NPE was being thrown.

After making function open tests started to pass.

You might as well consider using compiler's "all-open" plugin:

Kotlin has classes and their members final by default, which makes it inconvenient to use frameworks and libraries such as Spring AOP that require classes to be open. The all-open compiler plugin adapts Kotlin to the requirements of those frameworks and makes classes annotated with a specific annotation and their members open without the explicit open keyword.

Undoing a git rebase

git reset --hard origin/{branchName}

is the correct solution to reset all your local changes done by rebase.

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

Seems like answered here: https://public-inbox.org/git/[email protected]/

So in a similar way, running

$ git diff --cc $M $M^1 $M^2 $(git merge-base $M^1 $M^2)

should show a combined patch that explains the state at $M relative to the states recorded in its parents and the merge base.

Octave/Matlab: Adding new elements to a vector

x(end+1) = newElem is a bit more robust.

x = [x newElem] will only work if x is a row-vector, if it is a column vector x = [x; newElem] should be used. x(end+1) = newElem, however, works for both row- and column-vectors.

In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)

How to check syslog in Bash on Linux?

If you like Vim, it has built-in syntax highlighting for the syslog file, e.g. it will highlight error messages in red.

vi +'syntax on' /var/log/syslog

How do I test if a string is empty in Objective-C?

You can have an empty string in two ways:

1) @"" // Does not contain space

2) @" " // Contain Space

Technically both the strings are empty. We can write both the things just by using ONE Condition

if ([firstNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""].length==0)
{
    NSLog(@"Empty String");
}
else
{
    NSLog(@"String contains some value");
}

How do I get the RootViewController from a pushed controller?

I encounter a strange condition.

self.viewControllers.first is not root viewController always.

Generally, self.viewControllers.first is root viewController indeed. But sometimes it's not.

class MyCustomMainNavigationController: UINavigationController {

    function configureForView(_ v: UIViewController, animated: Bool) {
        let root = self.viewControllers.first
        let isRoot = (v == root)
    
        // Update UI based on isRoot
        // ....
    }
}

extension MyCustomMainNavigationController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, 
        willShow viewController: UIViewController, 
        animated: Bool) {

        self.configureForView(viewController, animated: animated)
    }
}

My issue:

Generally, self.viewControllers.first is root viewController. But, when I call popToRootViewController(animated:), and then it triggers navigationController(_:willShow:animated:). At this moment, self.viewControllers.first is NOT root viewController, it's the last viewController which will disappear.

Summary

  • self.viewControllers.first is not always root viewController. Sometime, it will be the last viewController.

So, I suggest to keep rootViewController by property when self.viewControllers have ONLY one viewController. I get root viewController in viewDidLoad() of custom UINavigationController.

class MyCustomMainNavigationController: UINavigationController {
    fileprivate var myRoot: UIViewController!
    override func viewDidLoad() {

        super.viewDidLoad()

        // My UINavigationController is defined in storyboard. 
        // So at this moment, 
        // I can get root viewController by `self.topViewController!`
        let v = self.topViewController!
        self.myRoot = v
    }

}

Enviroments:

  • iPhone 7 with iOS 14.0.1
  • Xcode 12.0.1 (12A7300)

How to reference a method in javadoc?

you can use @see to do that:

sample:

interface View {
        /**
         * @return true: have read contact and call log permissions, else otherwise
         * @see #requestReadContactAndCallLogPermissions()
         */
        boolean haveReadContactAndCallLogPermissions();

        /**
         * if not have permissions, request to user for allow
         * @see #haveReadContactAndCallLogPermissions()
         */
        void requestReadContactAndCallLogPermissions();
    }

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

It's not a Git error message, it's the editor as git uses your default editor.

To solve this:

  1. press "i" (i for insert)
  2. write your merge message
  3. press "esc" (escape)
  4. write ":wq" (write & quit)
  5. then press enter

Initializing select with AngularJS and ng-repeat

As suggested you need to use ng-options and unfortunately I believe you need to reference the array element for a default (unless the array is an array of strings).

http://jsfiddle.net/FxM3B/3/

The JavaScript:

function AppCtrl($scope) {


    $scope.operators = [
        {value: 'eq', displayName: 'equals'},
        {value: 'neq', displayName: 'not equal'}
     ]

    $scope.filterCondition={
        operator: $scope.operators[0]
    }
}

The HTML:

<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator.value}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.displayName for operator in operators">
</select>
</body>

Java - Relative path of a file in a java web application

there is another way, if you are using a container like Tomcat :

String textPath = "http://localhost:8080/NameOfWebapp/resources/images/file.txt";

Read binary file as string in Ruby

First, you should open the file as a binary file. Then you can read the entire file in, in one command.

file = File.open("path-to-file.tar.gz", "rb")
contents = file.read

That will get you the entire file in a string.

After that, you probably want to file.close. If you don’t do that, file won’t be closed until it is garbage-collected, so it would be a slight waste of system resources while it is open.

Styling Password Fields in CSS

When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)

SCSS styles

@font-face {
  font-family: 'pass';
  font-style: normal;
  font-weight: 400;
  src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}

input.password {
  font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
  font-size: 18px;
  &::-webkit-input-placeholder {
    transform: scale(0.77);
    transform-origin: 0 50%;
  }
  &::-moz-placeholder {
    font-size: 14px;
    opacity: 1;
  }
  &:-ms-input-placeholder {
    font-size: 14px;
    font-family: 'Roboto', Helvetica, Arial, sans-serif;
  }

After that, I got identical display input[password]

How do I set vertical space between list items?

You can use margin. See the example:

http://jsfiddle.net/LthgY/

li{
  margin: 10px 0;
}

Is it possible to run CUDA on AMD GPUs?

You can run NVIDIA® CUDA™ code on Mac, and indeed on OpenCL 1.2 GPUs in general, using Coriander . Disclosure: I'm the author. Example usage:

cocl cuda_sample.cu
./cuda_sample

Result: enter image description here

System.Data.OracleClient requires Oracle client software version 8.1.7

When we first moved over to Vista with Oracle 10g, we experienced this issue when we installed the Oracle client on our Vista boxes, even when we were running with admin privileges during install.

Oracle brought out a new version of the 10g client (10.2.0.3) that was Vista compatible.

I do believe that this was after 11g was released, so it is possible that there is a 'Vista compatible' version for 11g also.

Best way to add Gradle support to IntelliJ Project

Another way, simpler.

Add your

build.gradle

file to the root of your project. Close the project. Manually remove *.iml file. Then choose "Import Project...", navigate to your project directory, select the build.gradle file and click OK.

PostgreSQL: days/months/years between two dates

SELECT
  AGE('2012-03-05', '2010-04-01'),
  DATE_PART('year', AGE('2012-03-05', '2010-04-01')) AS years,
  DATE_PART('month', AGE('2012-03-05', '2010-04-01')) AS months,
  DATE_PART('day', AGE('2012-03-05', '2010-04-01')) AS days;

This will give you full years, month, days ... between two dates:

          age          | years | months | days
-----------------------+-------+--------+------
 1 year 11 mons 4 days |     1 |     11 |    4

More detailed datediff information.

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

that is the right behavior.

if you set @item1 to a value the below expression will be true

IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)

Anyway in SQL Server there is not a such function but you can create your own:

CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
    RETURN 0
ELSE
    RETURN 1
END

jQuery return ajax result into outside variable

Using 'async': false to prevent asynchronous code is a bad practice,

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. https://xhr.spec.whatwg.org/

On the surface setting async to false fixes a lot of issues because, as the other answers show, you get your data into a variable. However, while waiting for the post data to return (which in some cases could take a few seconds because of database calls, slow connections, etc.) the rest of your Javascript functionality (like triggered events, Javascript handled buttons, JQuery transitions (like accordion, or autocomplete (JQuery UI)) will not be able to occur while the response is pending (which is really bad if the response never comes back as your site is now essentially frozen).

Try this instead,

var return_first;
function callback(response) {
  return_first = response;
  //use return_first variable here
}

$.ajax({
  'type': "POST",
  'global': false,
  'dataType': 'html',
  'url': "ajax.php?first",
  'data': { 'request': "", 'target': arrange_url, 'method': method_target },
  'success': function(data){
       callback(data);
  },
});

SSH to AWS Instance without key pairs

1) You should be able to change the ssh configuration (on Ubuntu this is typically in /etc/ssh or /etc/sshd) and re-enable password logins.

2) There's nothing really AWS specific about this - Apache can handle VHOSTS (virtual hosts) out-of-the-box - allowing you to specify that a certain domain is served from a certain directory. I'd Google that for more info on the specifics.

CMake does not find Visual C++ compiler

I looked in CMakeError.log file and found an error about cannot run 'rc.exe'

I searched and found this answer to copy RC.Exe and RcDll.Dll from the Microsoft SDKs bin to the VC bin, and then CMake worked.


Edit: The top answer to another question suggests that it's a PATH issue, so it could be enough to ensure the Microsoft SDK bin is in your PATH.

What port is used by Java RMI connection?

From the javadoc of java.rmi.registry.Registry

Therefore, a registry's remote object implementation is typically exported with a well-known address, such as with a well-known ObjID and TCP port number (default is 1099).

See more in the javadoc of java.rmi.registry.LocateRegistry.

SQL Server Convert Varchar to Datetime

You could do it this way but it leaves it as a varchar

declare @s varchar(50)

set @s = '2011-09-28 18:01:00'

select convert(varchar, cast(@s as datetime), 105) + RIGHT(@s, 9)

or

select convert(varchar(20), @s, 105)

Count number of 1's in binary representation

The best way in javascript to do so is

function getBinaryValue(num){
 return num.toString(2);
}

function checkOnces(binaryValue){
    return binaryValue.toString().replace(/0/g, "").length;
}

where binaryValue is the binary String eg: 1100

How to yum install Node.JS on Amazon Linux

I had Node.js 6.x installed and wanted to install Node.js 8.x.

Here's the commands I used (taken from Nodejs's site with a few extra steps to handle the yum cached data):

  1. sudo yum remove nodejs: Uninstall Node.js 6.x (I don't know if this was necessary or not)
  2. curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -
  3. sudo yum clean all
  4. sudo yum makecache: Regenerate metadata cache (this wasn't in the docs, but yum kept trying to install Node.jx 6.x, unsuccessfully, until I issued these last two commands)
  5. sudo yum install nodejs: Install Node.js 8.x

How to run a Maven project from Eclipse?

Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).

To enable this, the <packaging> element in your pom.xml should be jar (or similar).

Then, right-click the project and select Maven > Update Project Configuration

For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.

Adding click event listener to elements with the same class

A short and sweet solution, using ES6:

document.querySelectorAll('.input')
      .forEach(input => input.addEventListener('focus', this.onInputFocus));

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

Easiest way to toggle 2 classes in jQuery

Your onClick request:

<span class="A" onclick="var state = this.className.indexOf('A') > -1; $(this).toggleClass('A', !state).toggleClass('B', state);">Click Me</span>

Try it: https://jsfiddle.net/v15q6b5y/


Just the JS à la jQuery:

$('.selector').toggleClass('A', !state).toggleClass('B', state);

Javamail Could not convert socket to TLS GMail

Try using the smtpsend program that comes with JavaMail, as described here. If that fails in the same way, there's something wrong with your JDK configuration or your network configuration.

How do I get a TextBox to only accept numeric input in WPF?

Use:

Private Sub DetailTextBox_PreviewTextInput( _
  ByVal sender As Object, _
  ByVal e As System.Windows.Input.TextCompositionEventArgs) _
  Handles DetailTextBox.PreviewTextInput

    If _IsANumber Then
        If Not Char.IsNumber(e.Text) Then
            e.Handled = True
        End If
    End If
End Sub

Creating a singleton in Python

Here's a one-liner for you:

singleton = lambda c: c()

Here's how you use it:

@singleton
class wat(object):
    def __init__(self): self.x = 1
    def get_x(self): return self.x

assert wat.get_x() == 1

Your object gets instantiated eagerly. This may or may not be what you want.

jQuery select child element by class with unknown path

This should do the trick:

$('#thisElement').find('.classToSelect')

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

My answer is little late but simple; but may help someone in future; I did experiment with angular versions such as 4.4.3, 5.1+, 6.x, 7.x, 8.x, 9.x and 10.x using $event (latest at the moment)

Template:

<select (change)="onChange($event)">
    <option *ngFor="let v of values" [value]="v.id">{{v.name}}</option>
</select>

TS

export class MyComponent {
  public onChange(event): void {  // event will give you full breif of action
    const newVal = event.target.value;
    console.log(newVal);
  }
}

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

In my case none of the above solutions didn't help:

Root cause: incompatible version of gcc

Solution:

1. sudo apt install --reinstall gcc
2. sudo apt-get --purge -y remove 'nvidia*'
3  sudo apt install nvidia-driver-450 
4. sudo reboot

System: AWS EC2 18.04 instance

Solution source: https://forums.developer.nvidia.com/t/nvidia-smi-has-failed-in-ubuntu-18-04/68288/4

How to connect a Windows Mobile PDA to Windows 10

Install Windows Mobile Device Center for your architecture. (It will install older versions of .NET if needed.) In USB to PC settings on device uncheck Enable advanced network and tap OK. This worked for me on 2 different Windows 10 PCs.

Getting Class type from String

Class<?> cls = Class.forName(className);

But your className should be fully-qualified - i.e. com.mycompany.MyClass

%Like% Query in spring JpaRepository

I use this:

@Query("Select c from Registration c where lower(c.place) like lower(concat('%', concat(:place, '%')))")

lower() is like toLowerCase in String, so the result isn't case sensitive.

What are the default access modifiers in C#?

Short answer: minimum possible access (cf Jon Skeet's answer).

Long answer:

Non-nested types, enumeration and delegate accessibilities (may only have internal or public accessibility)

                     | Default   | Permitted declared accessibilities
------------------------------------------------------------------
namespace            | public    | none (always implicitly public)

enum                 | public    | public, internal

interface            | internal  | public, internal

class                | internal  | public, internal

struct               | internal  | public, internal

delegate             | internal  | public, internal

Nested type and member accessiblities

                     | Default   | Permitted declared accessibilities
------------------------------------------------------------------
namespace            | public    | none (always implicitly public)

enum                 | public    | All¹

interface            | public    | All¹

class                | private   | All¹

struct               | private   | public, internal, private²

delegate             | private   | All¹

constructor          | private   | All¹

enum member          | public    | none (always implicitly public)

interface member     | public    | none (always implicitly public)
     
method               | private   | All¹

field                | private   | All¹

user-defined operator| none      | public (must be declared public)

¹ All === public, protected, internal, private, protected internal

² structs cannot inherit from structs or classes (although they can, interfaces), hence protected is not a valid modifier

The accessibility of a nested type depends on its accessibility domain, which is determined by both the declared accessibility of the member and the accessibility domain of the immediately containing type. However, the accessibility domain of a nested type cannot exceed that of the containing type.

Note: CIL also has the provision for protected and internal (as opposed to the existing protected "or" internal), but to my knowledge this is not currently available for use in C#.


See:

http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx
http://msdn.microsoft.com/en-us/library/ms173121.aspx
http://msdn.microsoft.com/en-us/library/cx03xt0t.aspx
(Man I love Microsoft URLs...)

Iterating over and deleting from Hashtable in Java

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if key is null or equals 0.
  if (entry.getKey() == null || entry.getKey() == 0) {
    it.remove();
  }
}

When increasing the size of VARCHAR column on a large table could there be any problems?

Just wanted to add my 2 cents, since I googled this question b/c I found myself in a similar situation...

BE AWARE that while changing from varchar(xxx) to varchar(yyy) is a meta-data change indeed, but changing to varchar(max) is not. Because varchar(max) values (aka BLOB values - image/text etc) are stored differently on the disk, not within a table row, but "out of row". So the server will go nuts on a big table and become unresponsive for minutes (hours).

--no downtime
ALTER TABLE MyTable ALTER COLUMN [MyColumn] VARCHAR(1200)

--huge downtime
ALTER TABLE MyTable ALTER COLUMN [MyColumn] VARCHAR(max)

PS. same applies to nvarchar or course.

How to read the Stock CPU Usage data

More about "load average" showing CPU load over 1 minute, 5 minutes and 15 minutes

Linux, Mac, and other Unix-like systems display “load average” numbers. These numbers tell you how busy your system’s CPU, disk, and other resources are. They’re not self-explanatory at first, but it’s easy to become familiar with them.

WIKI: example, one can interpret a load average of "1.73 0.60 7.98" on a single-CPU system as:

during the last minute, the system was overloaded by 73% on average (1.73 runnable processes, so that 0.73 processes had to wait for a turn for a single CPU system on average).
during the last 5 minutes, the CPU was idling 40% of the time on average.
during the last 15 minutes, the system was overloaded 698% on average (7.98 runnable processes, so that 6.98 processes had to wait for a turn for a single CPU system on average) if dual core mean: 798% - 200% = 598%. 

You probably have a system with multiple CPUs or a multi-core CPU. The load average numbers work a bit differently on such a system. For example, if you have a load average of 2 on a single-CPU system, this means your system was overloaded by 100 percent — the entire period of time, one process was using the CPU while one other process was waiting. On a system with two CPUs, this would be complete usage — two different processes were using two different CPUs the entire time. On a system with four CPUs, this would be half usage — two processes were using two CPUs, while two CPUs were sitting idle.

To understand the load average number, you need to know how many CPUs your system has. A load average of 6.03 would indicate a system with a single CPU was massively overloaded, but it would be fine on a computer with 8 CPUs.

more info : Link

Initialize a vector array of strings

Sort of:

class some_class {
    static std::vector<std::string> v; // declaration
};

const char *vinit[] = {"one", "two", "three"};

std::vector<std::string> some_class::v(vinit, end(vinit)); // definition

end is just so I don't have to write vinit+3 and keep it up to date if the length changes later. Define it as:

template<typename T, size_t N>
T * end(T (&ra)[N]) {
    return ra + N;
}

Removing spaces from string

Try this:

String urle = HOST + url + value;

Then return the values from:

urle.replace(" ", "%20").trim();

PHP: date function to get month of the current date

See http://php.net/date

date('m') or date('n') or date('F') ...

Update

m Numeric representation of a month, with leading zeros 01 through 12

n Numeric representation of a month, without leading zeros 1 through 12

F Alphabetic representation of a month January through December

....see the docs link for even more options.

How to change the background color of the options menu?

This is how i solved mine. I just specified the background color and text color in styles. ie res > values > styles.xml file.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:itemBackground">#ffffff</item>
    <item name="android:textColor">#000000</item>
</style>

Calling a stored procedure in Oracle with IN and OUT parameters

If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!

The code is,

set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;

And then call the function as it is:

DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;

In what cases will HTTP_REFERER be empty

HTTP_REFERER - sent by the browser, stating the last page the browser viewed!

If you trusting [HTTP_REFERER] for any reason that is important, you should not, since it can be faked easily:

  1. Some browsers limit access to not allow HTTP_REFERER to be passed
  2. Type a address in the address bar will not pass the HTTP_REFERER
  3. open a new browser window will not pass the HTTP_REFERER, because HTTP_REFERER = NULL
  4. has some browser addon that blocks it for privacy reasons. Some firewalls and AVs do to.

Try this firefox extension, you'll be able to set any headers you want:

@Master of Celebration:

Firefox:

extensions: refspoof, refontrol, modify headers, no-referer

Completely disable: the option is available in about:config under "network.http.sendRefererHeader" and you want to set this to 0 to disable referer passing.

Google chrome / Chromium:

extensions: noref, spoofy, external noreferrer

Completely disable: Chnage ~/.config/google-chrome/Default/Preferences or ~/.config/chromium/Default/Preferences and set this:

{
   ...
   "enable_referrers": false,
   ...
}

Or simply add --no-referrers to shortcut or in cli:

google-chrome --no-referrers

Opera:

Completely disable: Settings > Preferences > Advanced > Network, and uncheck "Send referrer information"

Spoofing web service:

http://referer.us/

Standalone filtering proxy (spoof any header):

Privoxy

Spoofing http_referer when using wget

‘--referer=url’

Spoofing http_referer when using curl

-e, --referer

Spoofing http_referer wth telnet

telnet www.yoursite.com 80 (press return)
GET /index.html HTTP/1.0 (press return)
Referer: http://www.hah-hah.com (press return)
(press return again)

Graphviz's executables are not found (Python 3.4)

I'm using Windows 10, Python 3.6 on Anaconda 3 and have faced the same issue.

I've had it work by doing the following in sequence:

  1. From Anaconda Terminal: pip install pydotplus
  2. From Anaconda Terminal: conda install pydotplus
  3. From Anaconda Terminal: pip install graphviz
  4. From Anaconda Terminal: conda install graphviz
  5. Went to Windows Environment Varialbes, PATH, and added the location of my dot.exe file under graphviz directory in Anaconda.

worked fine after that.

htons() function in socket programing

the htons() function converts values between host and network byte orders. There is a difference between big-endian and little-endian and network byte order depending on your machine and network protocol in use.

How to fire an event when v-model changes?

You can actually simplify this by removing the v-on directives:

<input type="radio" name="optionsRadios" id="optionsRadios1" value="1" v-model="srStatus">

And use the watch method to listen for the change:

new Vue ({
    el: "#app",
    data: {
        cases: [
            { name: 'case A', status: '1' },
            { name: 'case B', status: '0' },
            { name: 'case C', status: '1' }
        ],
        activeCases: [],
        srStatus: ''
    },
    watch: {
        srStatus: function(val, oldVal) {
            for (var i = 0; i < this.cases.length; i++) {
                if (this.cases[i].status == val) {
                    this.activeCases.push(this.cases[i]);
                    alert("Fired! " + val);
                }
            }
        }
    }
});

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

Just putting in my 5 cents here. For me none of the above worked, so I was forced to stress down and actually look at every part of the process with fresh eyes.

In rushing this I forgot that I was trying to install my app on a totally new device.

So my error was that I hadn't updated my provisioning profile by ticking off my new device int the "Devices" section of the provisioning profile setup in the Provisioning Portal.

Apparently not including your device in the provisioning profile also generates this error message.

Convert List<T> to ObservableCollection<T> in WP7

Use this:

List<Class1> myList;
ObservableCollection<Class1> myOC = new ObservableCollection<Class1>(myList);

Can you have multiple $(document).ready(function(){ ... }); sections?

You can use multiple. But you can also use multiple functions inside one document.ready as well:

$(document).ready(function() {
    // Jquery
    $('.hide').hide();
    $('.test').each(function() {
       $(this).fadeIn();
    });

    // Reqular JS
    function test(word) {
       alert(word);
    }
    test('hello!');
});

Cloning an array in Javascript/Typescript

I have the same issue with primeNg DataTable. After trying and crying, I've fixed the issue by using this code.

private deepArrayCopy(arr: SelectItem[]): SelectItem[] {
    const result: SelectItem[] = [];
    if (!arr) {
      return result;
    }
    const arrayLength = arr.length;
    for (let i = 0; i <= arrayLength; i++) {
      const item = arr[i];
      if (item) {
        result.push({ label: item.label, value: item.value });
      }
    }
    return result;
  }

For initializing backup value

backupData = this.deepArrayCopy(genericItems);

For resetting changes

genericItems = this.deepArrayCopy(backupData);

The magic bullet is to recreate items by using {} instead of calling constructor. I've tried new SelectItem(item.label, item.value) which doesn't work.

Why doesn't RecyclerView have onItemClickListener()?

recyclerview animation has not been tested, the other is normal. I think it has been optimized to the maximum. Interface has other uses, you can temporarily ignore.

public abstract class BaseAdapterRV<VH extends BaseViewHolder> extends RecyclerView.Adapter<VH> implements AdapterInterface {
    public final String TAG = getClass().getSimpleName();

    protected final Activity mActivity;
    protected final LayoutInflater mInflater;
    protected ItemClickInterface<?, Integer> mListener;

    public BaseAdapterRV(Activity activity) {
        mActivity = activity;
        mInflater = LayoutInflater.from(mActivity);
    }

    @Override
    public final VH onCreateViewHolder(ViewGroup parent, int viewType) {
        return onCreateViewHolder(parent, viewType, mInflater);
    }

    @Override
    public final void onBindViewHolder(VH holder, int position) {
        holder.itemView.setTag(R.id.tag_view_click, position);
        //??????
        holder.itemView.setOnClickListener(mListener);
        holder.itemView.setOnLongClickListener(mListener);
        onBindVH(holder, position);
    }


    ///////////////////////////////////////////////////////////////////////////
    // ????????
    ///////////////////////////////////////////////////////////////////////////

    /**
     * ??!???notifyItemInserted???????position??????
     * ????onItemLongClick
     */
    public void setOnItemClickListener(ItemClickInterface<?, Integer> listener) {
        mListener = listener;
        notifyDataSetChanged();
    }

    @NonNull
    protected abstract VH onCreateViewHolder(ViewGroup parent, int viewType, LayoutInflater inflater);

    protected abstract void onBindVH(VH holder, int position);

}

This is Interface

/**
 * OnItemClickListener???
 * ?????{@link OnItemClickListener}{@link OnItemItemClickListener}
 */
public interface ItemClickInterface<DATA1, DATA2> extends View.OnClickListener, View.OnLongClickListener {

    void onItemClick(DATA1 data1, DATA2 data2);

    boolean onItemLongClick(DATA1 data1, DATA2 data2);
}

This is an abstract class

public abstract class OnItemClickListener<DATA> implements ItemClickInterface<View, DATA> {
    @Override
    public void onClick(View v) {
        onItemClick(v, (DATA) v.getTag(R.id.tag_view_click));
    }

    @Override
    public boolean onLongClick(View v) {
        return onItemLongClick(v, (DATA) v.getTag(R.id.tag_view_click));
    }

    @Override
    public boolean onItemLongClick(View view, DATA data) {
        return false;
    }
}

You only need it

    mAdapter.setOnItemClickListener(new OnItemClickListener<Integer>() {
        @Override
        public void onItemClick(View view, Integer integer) {

        }

        @Override
        public boolean onItemLongClick(View view, Integer integer) {
            return true;
        }
    });

Maven: How do I activate a profile from command line?

Just remove activation section, I don't know why -Pdev1 doesn't override default false activation. But if you omit this:

<activation> <activeByDefault>false</activeByDefault> </activation>

then your profile will be activated only after explicit declaration as -Pdev1

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

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

Can I give the col-md-1.5 in bootstrap?

Bootstrap has column offsets, so if you want columns with equal width without specifying size use this.

<div class="row">
  <div class="col">col</div>
  <div class="col">col</div>
  <div class="col">col</div>
  <div class="col">col</div>
</div>

Also check out this link https://getbootstrap.com/docs/4.0/layout/grid/#all-breakpoints

How to split a long array into smaller arrays, with JavaScript

More compact:

_x000D_
_x000D_
const chunk = (xs, size) =>_x000D_
  xs.map((_, i) =>_x000D_
    (i % size === 0 ? xs.slice(i, i + size) : null)).filter(Boolean);_x000D_
    _x000D_
// Usage:_x000D_
const sampleArray = new Array(33).fill(undefined).map((_, i) => i);_x000D_
_x000D_
console.log(chunk(sampleArray, 5));
_x000D_
_x000D_
_x000D_

Xcode stuck on Indexing

I have experienced this problem in some projects with Xcode 9.3.1 and in my case the problem is due to some swift code that for some reason Xcode doesn't like. This problem is hard to solve because is difficult to find what file is causing the problem.

When I have this problem, I removing some files from the Xcode project (removing references) and I try to test if indexing works. My process to do so

  1. Remove some files
  2. Close Xcode
  3. Open Xcode
  4. If indexing finish try to rename some method if works probably the files you have removed they have something strange for Xcode.

In my case I had a class definition with a reactive extension in the same file and for some reason Xcode doesn't like it, I moved the reactive extension to another file and now the indexing works fine.

Get a json via Http Request in NodeJS

Just tell request that you are using json:true and forget about header and parse

var options = {
    hostname: '127.0.0.1',
    port: app.get('port'),
    path: '/users',
    method: 'GET',
    json:true
}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);
});

and the same for post

var options = {
    hostname: '127.0.0.1',
    port: app.get('port'),
    path: '/users',
    method: 'POST',
    json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);
});

How to get row count using ResultSet in Java?

your sql Statement creating code may be like

statement = connection.createStatement();

To solve "com.microsoft.sqlserver.jdbc.SQLServerException: The requested operation is not supported on forward only result sets" exception change above code with

statement = connection.createStatement(
    ResultSet.TYPE_SCROLL_INSENSITIVE, 
    ResultSet.CONCUR_READ_ONLY);

After above change you can use

int size = 0;
try {
    resultSet.last();
    size = resultSet.getRow();
    resultSet.beforeFirst();
}
catch(Exception ex) {
    return 0;
}
return size;

to get row count

How to free memory in Java?

System.gc(); 

Runs the garbage collector.

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

Not recommended.

Edit: I wrote the original response in 2009. It's now 2015.

Garbage collectors have gotten steadily better in the ~20 years Java's been around. At this point, if you're manually calling the garbage collector, you may want to consider other approaches:

  • If you're forcing GC on a limited number of machines, it may be worth having a load balancer point away from the current machine, waiting for it to finish serving to connected clients, timeout after some period for hanging connections, and then just hard-restart the JVM. This is a terrible solution, but if you're looking at System.gc(), forced-restarts may be a possible stopgap.
  • Consider using a different garbage collector. For example, the (new in the last six years) G1 collector is a low-pause model; it uses more CPU overall, but does it's best to never force a hard-stop on execution. Since server CPUs now almost all have multiple cores, this is A Really Good Tradeoff to have available.
  • Look at your flags tuning memory use. Especially in newer versions of Java, if you don't have that many long-term running objects, consider bumping up the size of newgen in the heap. newgen (young) is where new objects are allocated. For a webserver, everything created for a request is put here, and if this space is too small, Java will spend extra time upgrading the objects to longer-lived memory, where they're more expensive to kill. (If newgen is slightly too small, you're going to pay for it.) For example, in G1:
    • XX:G1NewSizePercent (defaults to 5; probably doesn't matter.)
    • XX:G1MaxNewSizePercent (defaults to 60; probably raise this.)
  • Consider telling the garbage collector you're not okay with a longer pause. This will cause more-frequent GC runs, to allow the system to keep the rest of it's constraints. In G1:
    • XX:MaxGCPauseMillis (defaults to 200.)

How to set a fixed width column with CSS flexbox

In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

flex-basis: 25%;

This will be a lot smoother when testing.

// VARIABLES
$screen-xs:                                         480px;
$screen-sm:                                         768px;
$screen-md:                                         992px;
$screen-lg:                                         1200px;
$screen-xl:                                         1400px;
$screen-xxl:                                        1600px;

// QUERIES
@media screen (max-width: $screen-lg) {
    flex-basis: 25%;
}

@media screen (max-width: $screen-md) {
    flex-basis: 33.33%;
}

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

RegEx to match stuff between parentheses

You need to make your regex pattern 'non-greedy' by adding a '?' after the '.+'

By default, '*' and '+' are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.

Non-greedy makes the pattern only match the shortest possible match.

See Watch Out for The Greediness! for a better explanation.

Or alternately, change your regex to

\(([^\)]+)\)

which will match any grouping of parens that do not, themselves, contain parens.

PHP find difference between two datetimes

You can simply use datetime diff and format for calculating difference.

<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');
?>

For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.

Here is the working example

P.S. These features( diff() and format()) work with >=PHP 5.3.0 only

How to get hostname from IP (Linux)?

To find a hostname in your local network by IP address you can use:

nmblookup -A <ip>

To find a hostname on the internet you could use the host program:

host <ip>

Or you can install nbtscan by running:

sudo apt-get install nbtscan

And use:

nbtscan <ip>

*Taken from https://askubuntu.com/questions/205063/command-to-get-the-hostname-of-remote-server-using-ip-address/205067#205067

Update 2018-05-13

You can query a name server with nslookup. It works both ways!

nslookup <IP>
nslookup <hostname>

Where Sticky Notes are saved in Windows 10 1607

In windows 10 you can recover in this way, there is no .snt file

  1. Start Run
  2. Go to this %LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe
  3. Copy this folder Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe
  4. Replace it with new Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe
  5. Check your sticky notes now, you will get all your data

Disable Input fields in reactive form

I solved it by wrapping my input object with its label in a field set: The fieldset should have the disabled property binded to the boolean

 <fieldset [disabled]="isAnonymous">
    <label class="control-label" for="firstName">FirstName</label>
    <input class="form-control" id="firstName" type="text" formControlName="firstName" />
 </fieldset>

How to save/restore serializable object to/from file?

1. Restore Object From File

From Here you can deserialize an object from file in two way.

Solution-1: Read file into a string and deserialize JSON to a type

string json = File.ReadAllText(@"c:\myObj.json");
MyObject myObj = JsonConvert.DeserializeObject<MyObject>(json);

Solution-2: Deserialize JSON directly from a file

using (StreamReader file = File.OpenText(@"c:\myObj.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    MyObject myObj2 = (MyObject)serializer.Deserialize(file, typeof(MyObject));
}

2. Save Object To File

from here you can serialize an object to file in two way.

Solution-1: Serialize JSON to a string and then write string to a file

string json = JsonConvert.SerializeObject(myObj);
File.WriteAllText(@"c:\myObj.json", json);

Solution-2: Serialize JSON directly to a file

using (StreamWriter file = File.CreateText(@"c:\myObj.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(file, myObj);
}

3. Extra

You can download Newtonsoft.Json from NuGet by following command

Install-Package Newtonsoft.Json

how to modify an existing check constraint?

NO, you can't do it other way than so.

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The easiest way to convert a byte array to a stream is using the MemoryStream class:

Stream stream = new MemoryStream(byteArray);

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

How to find Port number of IP address?

The port is usually fixed, for DNS it's 53.

How do you get the cursor position in a textarea?

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal).

var cursorPosition = $('#myTextarea').prop("selectionStart");

Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.

I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.

Event detect when css property changed using Jquery

For properties for which css transition will affect, can use transitionend event, example for z-index:

_x000D_
_x000D_
$(".observed-element").on("webkitTransitionEnd transitionend", function(e) {_x000D_
  console.log("end", e);_x000D_
  alert("z-index changed");_x000D_
});_x000D_
_x000D_
$(".changeButton").on("click", function() {_x000D_
  console.log("click");_x000D_
  document.querySelector(".observed-element").style.zIndex = (Math.random() * 1000) | 0;_x000D_
});
_x000D_
.observed-element {_x000D_
  transition: z-index 1ms;_x000D_
  -webkit-transition: z-index 1ms;_x000D_
}_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 1px solid;_x000D_
  position: absolute;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button class="changeButton">change z-index</button>_x000D_
<div class="observed-element"></div>
_x000D_
_x000D_
_x000D_

Check if my SSL Certificate is SHA1 or SHA2

Update: The site below is no longer running because, as they say on the site:

As of January 1, 2016, no publicly trusted CA is allowed to issue a SHA-1 certificate. In addition, SHA-1 support was removed by most modern browsers and operating systems in early 2017. Any new certificate you get should automatically use a SHA-2 algorithm for its signature.

Legacy clients will continue to accept SHA-1 certificates, and it is possible to have requested a certificate on December 31, 2015 that is valid for 39 months. So, it is possible to see SHA-1 certificates in the wild that expire in early 2019.

Original answer:

You can also use https://shaaaaaaaaaaaaa.com/ - set up to make this particular task easy. The site has a text box - you type in your site domain name, click the Go button and it then tells you whether the site is using SHA1 or SHA2.

Background

Batch script to install MSI

This is how to install a normal MSI file silently:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"

Quick explanation:

 /L*V "C:\Temp\msilog.log"= verbose logging at indicated path
 /QN = run completely silently
 /i = run install sequence 

The msiexec.exe command line is extensive with support for a variety of options. Here is another overview of the same command line interface. Here is an annotated versions (was broken, resurrected via way back machine).

It is also possible to make a batch file a lot shorter with constructs such as for loops as illustrated here for Windows Updates.

If there are check boxes that must be checked during the setup, you must find the appropriate PUBLIC PROPERTIES attached to the check box and set it at the command line like this:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log" STARTAPP=1 SHOWHELP=Yes

These properties are different in each MSI. You can find them via the verbose log file or by opening the MSI in Orca, or another appropriate tool. You must look either in the dialog control section or in the Property table for what the property name is. Try running the setup and create a verbose log file first and then search the log for messages ala "Setting property..." and then see what the property name is there. Then add this property with the value from the log file to the command line.

Also have a look at how to use transforms to customize the MSI beyond setting command line parameters: How to make better use of MSI files

How to check if an integer is within a range of numbers in PHP?

You can use filter_var

filter_var(
    $yourInteger, 
    FILTER_VALIDATE_INT, 
    array(
        'options' => array(
            'min_range' => $min, 
            'max_range' => $max
        )
    )
);

This will also allow you to specify whether you want to allow octal and hex notation of integers. Note that the function is type-safe. 5.5 is not an integer but a float and will not validate.

Detailed tutorial about filtering data with PHP:

How can I change Eclipse theme?

Take a look at rogerdudler/eclipse-ui-themes . In the readme there is a link to a file that you need to extract into your eclipse/dropins folder.

When you have done that go to

Window -> Preferences -> General -> Appearance

And change the theme from GTK (or what ever it is currently) to Dark Juno (or Dark).

That will change the UI to a nice dark theme but to get the complete look and feel you can get the Eclipse Color Theme plugin from eclipsecolorthemes.org. The easiest way is to add this update URI to "Help -> Install New Software" and install it from there.

Eclipse Color Themes

This adds a "Color Theme" menu item under

Window -> Preferences -> Appearance

Where you can select from a large range of editor themes. My preferred one to use with PyDev is Wombat. For Java Solarized Dark

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

In my case:

sudo -E add-apt-repository ppa:linuxuprising/java

sudo apt-get update

sudo apt install  oracle-java12-installer

that works fine

500 internal server error at GetResponse()

looking at your error message first of all I would suggest you to recompile your whole application, make sure all the required dlls are there in bin folder when you recompile it.

Hive query output to file

I agree with tnguyen80's response. Please note that when there is a specific string value in query better to given entire query in double quotes.

For example:

$hive -e "select * from table where city = 'London' and id >=100" > /home/user/outputdirectory/city details.csv

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

You have to use the iterator's remove() method, which means no enhanced for loop:

for (final Iterator iterator = myArrayList.iterator(); iterator.hasNext(); ) {
    iterator.next();
    if (someCondition) {
        iterator.remove();
    }
}

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

Copy all order entries of home folder .iml file into your /src/main/main.iml file. This will solve the problem.

Difference between Git and GitHub

In simple:

Git - is local repository.

GitHub - is central repository.

Hope below image will help to understand: Git and GitHub Difference

Git and GitHub Difference more details

Converting Python dict to kwargs?

** operator would be helpful here.

** operator will unpack the dict elements and thus **{'type':'Event'} would be treated as type='Event'

func(**{'type':'Event'}) is same as func(type='Event') i.e the dict elements would be converted to the keyword arguments.

FYI

* will unpack the list elements and they would be treated as positional arguments.

func(*['one', 'two']) is same as func('one', 'two')

Get Insert Statement for existing row in MySQL

Based on your comments, your goal is to migrate database changes from a development environment to a production environment.

The best way to do this is to keep your database changes in your source code and consequently track them in your source control system such as git or svn.

you can get up and running quickly with something like this: https://github.com/davejkiger/mysql-php-migrations

as a very basic custom solution in PHP, you can use a function like this:

function store_once($table, $unique_fields, $other_fields=array()) {
    $where = "";
    $values = array();
    foreach ($unique_fields as $k => $v) {
        if (!empty($where)) $where .= " && ";
        $where .= "$k=?";
        $values[] = $v;
    }
    $records = query("SELECT * FROM $table WHERE $where", $values);
    if (false == $records) {
        store($table, array_merge($unique_fields, $other_fields));
    }
}

then you can create a migration script which will update any environment to your specifications.

How can I disable a button in a jQuery dialog from a function?

This did the job for me:

$find("<%= btnPrint.ClientID %>").set_enabled(true);

No visible cause for "Unexpected token ILLEGAL"

Here is my reason:

before:

var path = "D:\xxx\util.s"

which \u is a escape, I figured it out by using Codepen's analyze JS.

after:

var path = "D:\\xxx\\util.s"

and the error fixed

How to declare a type as nullable in TypeScript?

Nullable type can invoke runtime error. So I think it's good to use a compiler option --strictNullChecks and declare number | null as type. also in case of nested function, although input type is null, compiler can not know what it could break, so I recommend use !(exclamination mark).

function broken(name: string | null): string {
  function postfix(epithet: string) {
    return name.charAt(0) + '.  the ' + epithet; // error, 'name' is possibly null
  }
  name = name || "Bob";
  return postfix("great");
}

function fixed(name: string | null): string {
  function postfix(epithet: string) {
    return name!.charAt(0) + '.  the ' + epithet; // ok
  }
  name = name || "Bob";
  return postfix("great");
}

Reference. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

inside OnCreate method :-

{

    Button b = (Button)findViewById(R.id.button1);
    b.setOnClickListener((View.OnClickListener)this);

    b = (Button)findViewById(R.id.button2);
    b.setOnClickListener((View.OnClickListener)this);
} 

@Override
public void OnClick(View v){

    switch(v.getId()){
         case R.id.button1:
             //whatever
             break;

         case R.id.button2:
             //whatever
             break;
}

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

What is the difference between decodeURIComponent and decodeURI?

js> s = "http://www.example.com/string with + and ? and & and spaces";
http://www.example.com/string with + and ? and & and spaces
js> encodeURI(s)
http://www.example.com/string%20with%20+%20and%20?%20and%20&%20and%20spaces
js> encodeURIComponent(s)
http%3A%2F%2Fwww.example.com%2Fstring%20with%20%2B%20and%20%3F%20and%20%26%20and%20spaces

Looks like encodeURI produces a "safe" URI by encoding spaces and some other (e.g. nonprintable) characters, whereas encodeURIComponent additionally encodes the colon and slash and plus characters, and is meant to be used in query strings. The encoding of + and ? and & is of particular importance here, as these are special chars in query strings.

React ignores 'for' attribute of the label element

For React you must use it's per-define keywords to define html attributes.

class -> className

is used and

for -> htmlFor

is used, as react is case sensitive make sure you must follow small and capital as required.

TypeError: $.browser is undefined

Replace your jquery files with followings :

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

jQuery Get Selected Option From Dropdown

For get value of tag selected:

 $('#id_Of_Parent_Selected_Tag').find(":selected").val();

And if you want to get text use this code:

 $('#id_Of_Parent_Selected_Tag').find(":selected").text();

For Example:

<div id="i_am_parent_of_select_tag">
<select>
        <option value="1">CR7</option>
        <option value="2">MESSI</option>
</select>
</div>


<script>
 $('#i_am_parent_of_select_tag').find(":selected").val();//OUTPUT:1 OR 2
 $('#i_am_parent_of_select_tag').find(":selected").text();//OUTPUT:CR7 OR MESSI
</script>

What is __init__.py for?

It facilitates importing other python files. When you placed this file in a directory (say stuff)containing other py files, then you can do something like import stuff.other.

root\
    stuff\
         other.py

    morestuff\
         another.py

Without this __init__.py inside the directory stuff, you couldn't import other.py, because Python doesn't know where the source code for stuff is and unable to recognize it as a package.

How to convert SQL Server's timestamp column to datetime format

"You keep using that word. I do not think it means what you think it means." — Inigo Montoya

The timestamp has absolutely no relationship to time as marc_s originally said.

declare @Test table (
     TestId int identity(1,1) primary key clustered
    ,Ts     timestamp
    ,CurrentDt datetime default getdate()
    ,Something varchar(max)
)

insert into @Test (Something)
    select name from sys.tables
waitfor delay '00:00:10'

insert into @Test (Something)
    select name from sys.tables

select * from @Test

Notice in the output that Ts (hex) increments by one for each record, but the actual time has a gap of 10 seconds. If it were related to time then there would be a gap in the timestamp to correspond with the difference in the time.

How to escape double quotes in JSON

When and where to use \\\" instead. OK if you are like me you will feel just as silly as I did when I realized what I was doing after I found this thread.

If you're making a .json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes:\" is the one you're looking for.

However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\". This is because you're building your text string within an HTML <script> block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \" from the standard answer and the JSON parser will parse this as just the double quotes.

<script>
  var text="{";
  text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
  text += "}";
  var obj=JSON.parse(text);
</script>

+1: since it's a JavaScript text string, a double backslash double quote \\" would work too; because the double quote does not need escaped within a single quoted string eg '\"' and '"' result in the same JS string.

How do I put text on ProgressBar?

I have created a InfoProgressBar control which uses a TransparentLabel control. Testing on a form with a Timer, I get some slight glitches displaying the text every 30-40 value changes if using a timer interval of less than 250 milliseconds (probably because of the time required to update the screen is greater than the timer interval).

It would be possible to modify UpdateText method to insert all the calculated values into CustomText but it isn't something that I have needed yet. This would remove the need for the DisplayType property and enumerate.

The TransparentLabel class was created by adding a new UserControl and changing it to inheriting from Label with the following implementation:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace Utils.GUI
{
    public partial class TransparentLabel : Label
    {
        // hide the BackColor attribute as much as possible.
        // setting the base value has no effect as drawing the
        // background is disabled
        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override Color BackColor
        {
            get
            {
                return Color.Transparent;
            }
            set
            {
            }
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x20; //  WS_EX_TRANSPARENT
                return cp;
            }
        }

        public override string Text
        {
            get
            {
                return base.Text;
            }
            set
            {
                base.Text = value;
                if(Parent != null) Parent.Invalidate(Bounds, false);
            }
        }

        public override ContentAlignment TextAlign
        {
            get
            {
                return base.TextAlign;
            }
            set
            {
                base.TextAlign = value;
                if(Parent != null) Parent.Invalidate(Bounds, false);
            }
        }

        public TransparentLabel()
        {
            InitializeComponent();

            SetStyle(ControlStyles.Opaque, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, false);

            base.BackColor = Color.Transparent;
        }

        protected override void OnMove(EventArgs e)
        {
            base.OnMove(e);
            RecreateHandle();
        }

        protected override void OnPaintBackground(PaintEventArgs pevent)
        {
            // do nothing
        }
    }
}

I did not make any changes to the related designer code but here it is for completeness.

namespace Utils.GUI
{
    partial class TransparentLabel
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if(disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
        }

        #endregion
    }
}

I then created another new UserControl and changed it to derive from ProgressBar with the following implementation:

using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Windows.Forms.Design.Behavior;

namespace Utils.GUI
{
    [Designer(typeof(InfoProgressBarDesigner))]
    public partial class InfoProgressBar : ProgressBar
    {
        // designer class to add font baseline snapline by copying it from the label
        private class InfoProgressBarDesigner : ControlDesigner
        {
            public override IList SnapLines
            {
                get
                {
                    IList snapLines = base.SnapLines;

                    InfoProgressBar control = Control as InfoProgressBar;

                    if(control != null)
                    {
                        using(IDesigner designer = TypeDescriptor.CreateDesigner(control.lblText, typeof(IDesigner)))
                        {
                            if(designer != null)
                            {
                                designer.Initialize(control.lblText);

                                ControlDesigner boxDesigner = designer as ControlDesigner;

                                if(boxDesigner != null)
                                {
                                    foreach(SnapLine line in boxDesigner.SnapLines)
                                    {
                                        if(line.SnapLineType == SnapLineType.Baseline)
                                        {
                                            snapLines.Add(new SnapLine(SnapLineType.Baseline, line.Offset, line.Filter, line.Priority));
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    return snapLines;
                }
            }
        }

        // enum to select the type of displayed value
        public enum ProgressBarDisplayType
        {
            Custom = 0,
            Percent = 1,
            Progress = 2,
            Remain = 3,
            Value = 4,
        }

        private string _customText;
        private ProgressBarDisplayType _displayType;
        private int _range;

        [Bindable(false)]
        [Browsable(true)]
        [DefaultValue("{0}")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        // {0} is replaced with the result of the selected calculation
        public string CustomText
        {
            get
            {
                return _customText;
            }
            set
            {
                _customText = value;
                UpdateText();
            }
        }

        [Bindable(false)]
        [Browsable(true)]
        [DefaultValue(ProgressBarDisplayType.Percent)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        public ProgressBarDisplayType DisplayType
        {
            get
            {
                return _displayType;
            }
            set
            {
                _displayType = value;
                UpdateText();
            }
        }

        [Bindable(false)]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        // don't use the lblText font as if it is null, it checks the parent font (i.e. this property) and gives an infinite loop
        public override Font Font
        {
            get
            {
                return base.Font;
            }
            set
            {
                base.Font = value; 
            }
        }

        [Bindable(false)]
        [Browsable(true)]
        [DefaultValue(100)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        public new int Maximum
        {
            get
            {
                return base.Maximum;
            }
            set
            {
                base.Maximum = value;
                _range = base.Maximum - base.Minimum;
                UpdateText();
            }
        }

        [Bindable(false)]
        [Browsable(true)]
        [DefaultValue(0)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        public new int Minimum
        {
            get
            {
                return base.Minimum;
            }
            set
            {
                base.Minimum = value;
                _range = base.Maximum - base.Minimum;
                UpdateText();
            }
        }

        [Bindable(false)]
        [Browsable(true)]
        [DefaultValue(ContentAlignment.MiddleLeft)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        public ContentAlignment TextAlign 
        {
            get
            {
                return lblText.TextAlign;
            }
            set
            {
                lblText.TextAlign = value;
            }
        }

        [Bindable(false)]
        [Browsable(true)]
        [DefaultValue(typeof(Color), "0x000000")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        public Color TextColor
        {
            get
            {
                return lblText.ForeColor;
            }
            set
            {
                lblText.ForeColor = value;
            }
        }

        [Bindable(false)]
        [Browsable(true)]
        [DefaultValue(0)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        public new int Value
        {
            get
            {
                return base.Value;
            }
            set
            {
                base.Value = value;
                UpdateText();
            }
        }

        public InfoProgressBar()
        {
            InitializeComponent();

            CustomText = "{0}";
            DisplayType = ProgressBarDisplayType.Percent;
            Maximum = 100;
            Minimum = 0;
            TextAlign = ContentAlignment.MiddleLeft;
            TextColor = Color.Black;
            Value = 0;

            // means the label gets drawn in front of the progress bar
            lblText.Parent = this;

            _range = base.Maximum - base.Minimum;
        }

        protected void UpdateText()
        {
            switch(DisplayType)
            {
                case ProgressBarDisplayType.Custom:
                {
                    lblText.Text = _customText;
                    break;
                }
                case ProgressBarDisplayType.Percent:
                {
                    if(_range > 0)
                    {
                        lblText.Text = string.Format(_customText, string.Format("{0}%", (int)((Value * 100) / _range)));
                    }
                    else
                    {
                        lblText.Text = "100%";
                    }
                    break;
                }
                case ProgressBarDisplayType.Progress:
                {
                    lblText.Text = string.Format(_customText, (Value - Minimum));
                    break;
                }
                case ProgressBarDisplayType.Remain:
                {
                    lblText.Text = string.Format(_customText, (Maximum - Value));
                    break;
                }
                case ProgressBarDisplayType.Value:
                {
                    lblText.Text = string.Format(_customText, Value);
                    break;
                }
            }
        }

        public new void Increment(int value)
        {
            base.Increment(value);
            UpdateText();
        }

        public new void PerformStep()
        {
            base.PerformStep();
            UpdateText();
        }
    }
}

And the designer code:

namespace Utils.GUI
{
    partial class InfoProgressBar
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if(disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.lblText = new Utils.GUI.TransparentLabel();
            this.SuspendLayout();
            // 
            // lblText
            // 
            this.lblText.BackColor = System.Drawing.Color.Transparent;
            this.lblText.Dock = System.Windows.Forms.DockStyle.Fill;
            this.lblText.Location = new System.Drawing.Point(0, 0);
            this.lblText.Name = "lblText";
            this.lblText.Padding = new System.Windows.Forms.Padding(3, 0, 3, 0);
            this.lblText.Size = new System.Drawing.Size(100, 23);
            this.lblText.TabIndex = 0;
            this.lblText.Text = "transparentLabel1";
            this.ResumeLayout(false);

        }

        #endregion

        private TransparentLabel lblText;

    }
}

position fixed is not working

You forgot to add the width of the two divs.

.header {
    position: fixed;
    top:0;
    background-color: #f00;
    height: 100px; width: 100%;
}
.footer {
    position: fixed;
    bottom: 0;
    background-color: #f0f;
    height: 120px; width:100%;
}

demo

numpy: most efficient frequency counts for unique values in an array

I was also interested in this, so I did a little performance comparison (using perfplot, a pet project of mine). Result:

y = np.bincount(a)
ii = np.nonzero(y)[0]
out = np.vstack((ii, y[ii])).T

is by far the fastest. (Note the log-scaling.)

enter image description here


Code to generate the plot:

import numpy as np
import pandas as pd
import perfplot
from scipy.stats import itemfreq


def bincount(a):
    y = np.bincount(a)
    ii = np.nonzero(y)[0]
    return np.vstack((ii, y[ii])).T


def unique(a):
    unique, counts = np.unique(a, return_counts=True)
    return np.asarray((unique, counts)).T


def unique_count(a):
    unique, inverse = np.unique(a, return_inverse=True)
    count = np.zeros(len(unique), np.int)
    np.add.at(count, inverse, 1)
    return np.vstack((unique, count)).T


def pandas_value_counts(a):
    out = pd.value_counts(pd.Series(a))
    out.sort_index(inplace=True)
    out = np.stack([out.keys().values, out.values]).T
    return out


perfplot.show(
    setup=lambda n: np.random.randint(0, 1000, n),
    kernels=[bincount, unique, itemfreq, unique_count, pandas_value_counts],
    n_range=[2 ** k for k in range(26)],
    logx=True,
    logy=True,
    xlabel="len(a)",
)

Regular expression to stop at first match

Use non-greedy matching, if your engine supports it. Add the ? inside the capture.

/location="(.*?)"/

When adding a Javascript library, Chrome complains about a missing source map, why?

While, the fix as per Valeri works, but its only for tfjs.

If you're expecting for body-pix or any other tensor-flow/models, you would be facing the same. It is an open issue too and the team is working on the fix!

https://github.com/dequelabs/axe-core/issues/1977

But, if you don't have problem in degrading the version (if anyone wants to use body-pix) from latest docs, below both links works fine as I've tested the same:

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/[email protected]"></script> 

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

First prevent default actions on your entire document as usual:

$(document).bind('touchmove', function(e){
  e.preventDefault();           
});

Then stop your class of elements from propagating to the document level. This stops it from reaching the function above and thus e.preventDefault() is not initiated:

$('.scrollable').bind('touchmove', function(e){
  e.stopPropagation();
});

This system seems to be more natural and less intensive than calculating the class on all touch moves. Use .on() rather than .bind() for dynamically generated elements.

Also consider these meta tags to prevent unfortunate things from happening while using your scrollable div:

<meta content='True' name='HandheldFriendly' />
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />

How to delete columns in numpy.array

Removing Matrix columns that contain NaN. This is a lengthy answer, but hopefully easy to follow.

def column_to_vector(matrix, i):
    return [row[i] for row in matrix]
import numpy
def remove_NaN_columns(matrix):
    import scipy
    import math
    from numpy import column_stack, vstack

    columns = A.shape[1]
    #print("columns", columns)
    result = []
    skip_column = True
    for column in range(0, columns):
        vector = column_to_vector(A, column)
        skip_column = False
        for value in vector:
            # print(column, vector, value, math.isnan(value) )
            if math.isnan(value):
                skip_column = True
        if skip_column == False:
            result.append(vector)
    return column_stack(result)

### test it
A = vstack(([ float('NaN'), 2., 3., float('NaN')], [ 1., 2., 3., 9]))
print("A shape", A.shape, "\n", A)
B = remove_NaN_columns(A)
print("B shape", B.shape, "\n", B)

A shape (2, 4) 
 [[ nan   2.   3.  nan]
 [  1.   2.   3.   9.]]
B shape (2, 2) 
 [[ 2.  3.]
 [ 2.  3.]]

Escaping a forward slash in a regular expression

If you are using C#, you do not need to escape it.

Easiest way to ignore blank lines when reading a file in Python

Why are you all going the hard way?

with open("myfile") as myfile:
    nonempty = filter(str.rstrip, myfile)

Convert nonempty into a list if you have the urge to do so, although I highly suggest keeping nonempty a generator as it is in Python 3.x

In Python 2.x you may use itertools.ifilter to do your bidding instead.

How to easily resize/optimize an image size with iOS?

To resize an image I have better (graphical) results by using this function in stead of DrawInRect:

- (UIImage*) reduceImageSize:(UIImage*) pImage newwidth:(float) pWidth
{
    float lScale = pWidth / pImage.size.width;
    CGImageRef cgImage = pImage.CGImage;
    UIImage   *lResult = [UIImage imageWithCGImage:cgImage scale:lScale
                            orientation:UIImageOrientationRight];
    return lResult;
}

Aspect ratio is taken care for automatically

What is a reasonable length limit on person "Name" fields?

depending on who is going to be using your database, for example African names will do with varchar(20) for last name and first name separated. however it is different from nation to nation but for the sake saving your database resources and memory, separate last name and first name fields and use varchar(30) think that will work.

Java ArrayList of Doubles

Using guava

Doubles.asList(1.2, 5.6, 10.1);

or immutable list

ImmutableList.of(1.2, 5.6, 10.1);

How to convert Seconds to HH:MM:SS using T-SQL

DECLARE @TimeinSecond INT
SET @TimeinSecond = 340 -- Change the seconds
SELECT RIGHT('0' + CAST(@TimeinSecond / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((@TimeinSecond / 60) % 60 AS VARCHAR),2)  + ':' +
RIGHT('0' + CAST(@TimeinSecond % 60 AS VARCHAR),2)

Is there way to use two PHP versions in XAMPP?

Follow this easy steps. I am currently running XAMPP on PHP 7.2 but needs PHP 5.6 to work on old projects

STEP 1

Download Thread Safe version of PHP on https://windows.php.net/download

Put files on your [Drive]:\xampp\php5.6

  • Rename the folder depending on Php version

STEP 2

Copy [Drive]:\xampp\apache\conf\extra\httpd-xampp.conf

Rename it to [Drive]:\xampp\apache\conf\extra\httpd-xampp5.6.confRename the file depending on Php version

STEP 3

Edit the newly created 'httpd-xampp5.6.conf'

basically you need to change All the PHP source and .dll

Before

LoadFile "C:/xampp/php/php7ts.dll"
LoadFile "C:/xampp/php/libpq.dll"
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

After

LoadFile "C:/xampp/php5.6/php5ts.dll"
LoadFile "C:/xampp/php5.6/libpq.dll"
LoadModule php5_module "C:/xampp/php5.6/php5apache2_4.dll"

Here is my file: https://gist.github.com/mpalencia/f8a20c31bffb02fe20d371218c23d1ec

STEP 4

Edit the file [Drive]:\xampp\apache\conf\httpd.conf

Before

# XAMPP settings
Include "conf/extra/httpd-xampp.conf"

After

# XAMPP settings
Include "conf/extra/httpd-xampp5.6.conf"
  • You can just edit this line when switching to diffent version

STEP 5

Edit your PHP 5.6 configuration - php.ini

Add you extension directory: extension_dir = "C:\xampp\php5.6\ext"

STEP 6

Start Apache

STEP 7

Edit PHP environment variable path on Windows

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

The R Language Definition is handy for answering these types of questions:

R has three basic indexing operators, with syntax displayed by the following examples

    x[i]
    x[i, j]
    x[[i]]
    x[[i, j]]
    x$a
    x$"a"

For vectors and matrices the [[ forms are rarely used, although they have some slight semantic differences from the [ form (e.g. it drops any names or dimnames attribute, and that partial matching is used for character indices). When indexing multi-dimensional structures with a single index, x[[i]] or x[i] will return the ith sequential element of x.

For lists, one generally uses [[ to select any single element, whereas [ returns a list of the selected elements.

The [[ form allows only a single element to be selected using integer or character indices, whereas [ allows indexing by vectors. Note though that for a list, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element.

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

How to pass the -D System properties while testing on Eclipse?

run configuration -> arguments -> vm arguments

(can also be placed in the debug configuration under Debug Configuration->Arguments->VM Arguments)

How do I format a number in Java?

Try this:

String.format("%.2f", 32.302342342342343);

Simple and efficient.

What is the Oracle equivalent of SQL Server's IsNull() function?

You can use the condition if x is not null then.... It's not a function. There's also the NVL() function, a good example of usage here: NVL function ref.

Using Jquery AJAX function with datatype HTML

Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.

Ajax call:

$.ajax({
  type : 'POST',
  url : 'post.php',
  dataType : 'html',
  data: {
      email : $('#email').val()
  },
  success : function(data){
      $('#waiting').hide(500);
      $('#message').removeClass().addClass((data == '') ? 'error' : 'success')
     .html(data).show(500);
      if (data == '') {
          $('#message').html("Format your email correcly");
          $('#demoForm').show(500);
      }
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
      $('#waiting').hide(500);
      $('#message').removeClass().addClass('error')
      .text('There was an error.').show(500);
      $('#demoForm').show(500);
  }

});

post.php

<?php
sleep(1);

function processEmail($email) {
    if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
        // your logic here (ex: add into database)
        return true;
    }
    return false;
}

if (processEmail($_POST['email'])) {
    echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Below solution worked for me, Just added

u "String"

(representing the string as unicode) before my string.

result_html = result.to_html(col_space=1, index=False, justify={'right'})

text = u"""
<html>
<body>
<p>
Hello all, <br>
<br>
Here's weekly summary report.  Let me know if you have any questions. <br>
<br>
Data Summary <br>
<br>
<br>
{0}
</p>
<p>Thanks,</p>
<p>Data Team</p>
</body></html>
""".format(result_html)

Confirmation dialog on ng-click - AngularJS

In today's date this solution works for me:

/**
 * A generic confirmation for risky actions.
 * Usage: Add attributes: ng-really-message="Are you sure"? ng-really-click="takeAction()" function
 */
angular.module('app').directive('ngReallyClick', [function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                var message = attrs.ngReallyMessage;
                if (message && confirm(message)) {
                    scope.$apply(attrs.ngReallyClick);
                }
            });
        }
    }
}]);

Credits:https://gist.github.com/asafge/7430497#file-ng-really-js

Notepad++ Multi editing

Yes: simply press and hold the Alt key, click and drag to select the lines whose columns you wish to edit, and begin typing.

You can also go to Settings > Preferences..., and in the Editing tab, turn on multi-editing, to enable selection of multiple separate regions or columns of text to edit at once.

It's much more intuitive, as you can see your edits live as you type.

Android Layout Animations from bottom to top and top to bottom on ImageView click

create directory in /res/anim and create bottom_to_original.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="1500"
        android:fromYDelta="100%"
        android:toYDelta="1%" />
</set>

JAVA:

    LinearLayout ll = findViewById(R.id.ll);

    Animation animation;
    animation = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.sample_animation);
    ll .setAnimation(animation);

Programmatically go back to previous ViewController in Swift

Try this: for the previous view use this:

navigationController?.popViewController(animated: true)  

pop to root use this code:

navigationController?.popToRootViewController(animated: true) 

Compare a string using sh shell

-eq is used to compare integers. Use = instead.

How do I return to an older version of our code in Subversion?

There are a lot of dangerous answers on this page. Note that since SVN version 1.6, doing an update -r can cause tree conflicts, which rapidly escalates into a potentially data losing kafkeresque nightmare where you're googling for information on tree conflicts.

The correct way to revert to a version is:

svn merge -r HEAD:12345 .

Where 12345 is the version number. Don't forget the dot.

Could not autowire field in spring. why?

I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml

<dependency> 
            <groupId> org.springframework.boot </groupId> 
            <artifactId> spring-boot-starter-web </artifactId> 
            <version> 1.2.0.RELEASE </version> 
</dependency>

How to extract public key using OpenSSL?

For AWS importing an existing public key,

  1. Export from the .pem doing this... (on linux)

    openssl rsa -in ./AWSGeneratedKey.pem -pubout -out PublicKey.pub
    

This will produce a file which if you open in a text editor looking something like this...

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn/8y3uYCQxSXZ58OYceG
A4uPdGHZXDYOQR11xcHTrH13jJEzdkYZG8irtyG+m3Jb6f9F8WkmTZxl+4YtkJdN
9WyrKhxq4Vbt42BthadX3Ty/pKkJ81Qn8KjxWoL+SMaCGFzRlfWsFju9Q5C7+aTj
eEKyFujH5bUTGX87nULRfg67tmtxBlT8WWWtFe2O/wedBTGGQxXMpwh4ObjLl3Qh
bfwxlBbh2N4471TyrErv04lbNecGaQqYxGrY8Ot3l2V2fXCzghAQg26Hc4dR2wyA
PPgWq78db+gU3QsePeo2Ki5sonkcyQQQlCkL35Asbv8khvk90gist4kijPnVBCuv
cwIDAQAB
-----END PUBLIC KEY-----
  1. However AWS will NOT accept this file.

    You have to strip off the -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- from the file. Save it and import and it should work in AWS.

OnclientClick and OnClick is not working at the same time?

What if you don't immediately set the button to disabled, but delay that through setTimeout? Your 'disable' function would return and the submit would continue.

Convert String to equivalent Enum value

Use static method valueOf(String) defined for each enum.

For example if you have enum MyEnum you can say MyEnum.valueOf("foo")

How to empty a Heroku database

Now it's diffrent with heroku. Try: heroku pg:reset DATABASE --confirm

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Installing Google Protocol Buffers on mac

I used macports

sudo port install protobuf-cpp

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

How to find difference between two columns data?

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

or

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

Android button with different background colors

You have to put the selector.xml file in the drwable folder. Then write: android:background="@drawable/selector". This takes care of the pressed and focussed states.

Check if list<t> contains any of another list

Here is a sample to find if there are match elements in another list

List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};

if (nums1.Any(x => nums2.Any(y => y == x)))
{
    Console.WriteLine("There are equal elements");
}
else
{
    Console.WriteLine("No Match Found!");
}

Android Studio doesn't see device

Switching to PTP USP Option instead of MTP is the solution.

How to use `@ts-ignore` for a block

You can't.

As a workaround you can use a // @ts-nocheck comment at the top of a file to disable type-checking for that file: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/

So to disable checking for a block (function, class, etc.), you can move it into its own file, then use the comment/flag above. (This isn't as flexible as block-based disabling of course, but it's the best option available at the moment.)

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

As of JDK 8u102, the posted solutions relying on reflection will no longer work: the field that these solutions set is now final (https://bugs.openjdk.java.net/browse/JDK-8149417).

Looks like it's back to either (a) using Bouncy Castle, or (b) installing the JCE policy files.

Unable to generate an explicit migration in entity framework

I had the same problems and was only able to resolve it running Add-Migration 'MigrationName' -Force

With -Force being the important part.

Bash function to find newest file matching pattern

You can use stat with a file glob and a decorate-sort-undecorate with the file time added on the front:

$ stat -f "%m%t%N" b2* | sort -rn | head -1 | cut -f2-

Check if the number is integer

If you prefer not to write your own function, try check.integer from package installr. Currently it uses VitoshKa's answer.

Also try check.numeric(v, only.integer=TRUE) from package varhandle, which has the benefit of being vectorized.

How to stop a function

A simple return statement will 'stop' or return the function; in precise terms, it 'returns' function execution to the point at which the function was called - the function is terminated without further action.

That means you could have a number of places throughout your function where it might return. Like this:

def player():
    # do something here
    check_winner_variable = check_winner()  # check something 
    if check_winner_variable == '1': 
        return
    second_test_variable = second_test()
    if second_test_variable == '1': 
        return
       
    # let the computer do something
    computer()

How can I get the username of the logged-in user in Django?

request.user.get_username() will return a string of the users email.

request.user.username will return a method.

What is the hamburger menu icon called and the three vertical dots icon called?

At eBay it’s the kabob.

Also heard it called the snowman or sushi roll.

Can I stop 100% Width Text Boxes from extending beyond their containers?

Just style the input to offset for the extra padding. In the following example the padding on the input would be 10px on the left and right for a total padding offset of 20px:

input[type=text]{
   width: calc(100% - 20px);
}

What is web.xml file and what are all things can I do with it?

If using Struts, we disable direct access to the JSP files by using this tag in web.xml

 <security-constraint>
<web-resource-collection>
  <web-resource-name>no_access</web-resource-name>
  <url-pattern>*.jsp</url-pattern>
</web-resource-collection>
<auth-constraint/>

jQuery check if it is clicked or not

<script>
    var listh = document.getElementById( 'list-home-list' );
    var hb = document.getElementsByTagName('hb');
    $("#list-home-list").click(function(){
    $(this).style.color = '#2C2E33';
    hb.style.color = 'white';
    });
</script>

How to check if an array element exists?

array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.

It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)

if (isset($a['element']) || array_key_exists('element', $a)) {
       //the element exists in the array. write your code here.
}

The benchmarking comparison: (extracted from below blog posts).

array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms

See http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/ and http://thinkofdev.com/php-isset-and-multi-dimentional-array/

for detailed discussion.

How can I concatenate strings in VBA?

There is the concatenate function. For example

=CONCATENATE(E2,"-",F2)
But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won't work as expected.

How to create a template function within a class? (C++)

See here: Templates, template methods,Member Templates, Member Function Templates

class   Vector
{
  int     array[3];

  template <class TVECTOR2> 
  void  eqAdd(TVECTOR2 v2);
};

template <class TVECTOR2>
void    Vector::eqAdd(TVECTOR2 a2)
{
  for (int i(0); i < 3; ++i) array[i] += a2[i];
}

How to calculate difference in hours (decimal) between two dates in SQL Server?

Declare @date1 datetime
Declare @date2 datetime

Set @date1 = '11/20/2009 11:00:00 AM'
Set @date2 = '11/20/2009 12:00:00 PM'

Select Cast(DateDiff(hh, @date1, @date2) as decimal(3,2)) as HoursApart

Result = 1.00

font-weight is not working properly?

Its because the font size (9px) is too small to display bold. Try 11px or more and it works fine.

Fastest way to serialize and deserialize .NET objects

I took the liberty of feeding your classes into the CGbR generator. Because it is in an early stage it doesn't support DateTime yet, so I simply replaced it with long. The generated serialization code looks like this:

public int Size
{
    get 
    { 
        var size = 24;
        // Add size for collections and strings
        size += Cts == null ? 0 : Cts.Count * 4;
        size += Tes == null ? 0 : Tes.Count * 4;
        size += Code == null ? 0 : Code.Length;
        size += Message == null ? 0 : Message.Length;

        return size;              
    }
}

public byte[] ToBytes(byte[] bytes, ref int index)
{
    if (index + Size > bytes.Length)
        throw new ArgumentOutOfRangeException("index", "Object does not fit in array");

    // Convert Cts
    // Two bytes length information for each dimension
    GeneratorByteConverter.Include((ushort)(Cts == null ? 0 : Cts.Count), bytes, ref index);
    if (Cts != null)
    {
        for(var i = 0; i < Cts.Count; i++)
        {
            var value = Cts[i];
            value.ToBytes(bytes, ref index);
        }
    }
    // Convert Tes
    // Two bytes length information for each dimension
    GeneratorByteConverter.Include((ushort)(Tes == null ? 0 : Tes.Count), bytes, ref index);
    if (Tes != null)
    {
        for(var i = 0; i < Tes.Count; i++)
        {
            var value = Tes[i];
            value.ToBytes(bytes, ref index);
        }
    }
    // Convert Code
    GeneratorByteConverter.Include(Code, bytes, ref index);
    // Convert Message
    GeneratorByteConverter.Include(Message, bytes, ref index);
    // Convert StartDate
    GeneratorByteConverter.Include(StartDate.ToBinary(), bytes, ref index);
    // Convert EndDate
    GeneratorByteConverter.Include(EndDate.ToBinary(), bytes, ref index);
    return bytes;
}

public Td FromBytes(byte[] bytes, ref int index)
{
    // Read Cts
    var ctsLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
    var tempCts = new List<Ct>(ctsLength);
    for (var i = 0; i < ctsLength; i++)
    {
        var value = new Ct().FromBytes(bytes, ref index);
        tempCts.Add(value);
    }
    Cts = tempCts;
    // Read Tes
    var tesLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
    var tempTes = new List<Te>(tesLength);
    for (var i = 0; i < tesLength; i++)
    {
        var value = new Te().FromBytes(bytes, ref index);
        tempTes.Add(value);
    }
    Tes = tempTes;
    // Read Code
    Code = GeneratorByteConverter.GetString(bytes, ref index);
    // Read Message
    Message = GeneratorByteConverter.GetString(bytes, ref index);
    // Read StartDate
    StartDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));
    // Read EndDate
    EndDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));

    return this;
}

I created a list of sample objects like this:

var objects = new List<Td>();
for (int i = 0; i < 1000; i++)
{
    var obj = new Td
    {
        Message = "Hello my friend",
        Code = "Some code that can be put here",
        StartDate = DateTime.Now.AddDays(-7),
        EndDate = DateTime.Now.AddDays(2),
        Cts = new List<Ct>(),
        Tes = new List<Te>()
    };
    for (int j = 0; j < 10; j++)
    {
        obj.Cts.Add(new Ct { Foo = i * j });
        obj.Tes.Add(new Te { Bar = i + j });
    }
    objects.Add(obj);
}

Results on my machine in Release build:

var watch = new Stopwatch();
watch.Start();
var bytes = BinarySerializer.SerializeMany(objects);
watch.Stop();

Size: 149000 bytes

Time: 2.059ms 3.13ms

Edit: Starting with CGbR 0.4.3 the binary serializer supports DateTime. Unfortunately the DateTime.ToBinary method is insanely slow. I will replace it with somehting faster soon.

Edit2: When using UTC DateTime by invoking ToUniversalTime() the performance is restored and clocks in at 1.669ms.

How to redirect to another page using AngularJS?

If you want to use a link then: in the html have:

<button type="button" id="btnOpenLine" class="btn btn-default btn-sm" ng-click="orderMaster.openLineItems()">Order Line Items</button>

in the typescript file

public openLineItems() {
if (this.$stateParams.id == 0) {
    this.Flash.create('warning', "Need to save order!", 3000);
    return
}
this.$window.open('#/orderLineitems/' + this.$stateParams.id);

}

I hope you see this example helpful as it was for me along with the other answers.

Compiling/Executing a C# Source File in Command Prompt

Here is how to install MSBuild with standalone C# 7.0 compiler which is no longer bundled in the latest .Net Framework 4.7:

Is it possible to install a C# compiler without Visual Studio?

Then just run

"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\Roslyn\csc.exe" MyApplication.cs

to compile single source file to executable.

Also note that .Net Core doesn't support compiling single source file without preconfigured project.

WPF ListView - detect when selected item is clicked

These are all great suggestions, but if I were you, I would do this in your view model. Within your view model, you can create a relay command that you can then bind to the click event in your item template. To determine if the same item was selected, you can store a reference to your selected item in your view model. I like to use MVVM Light to handle the binding. This makes your project much easier to modify in the future, and allows you to set the binding in Blend.

When all is said and done, your XAML will look like what Sergey suggested. I would avoid using the code behind in your view. I'm going to avoid writing code in this answer, because there is a ton of examples out there.

Here is one: How to use RelayCommand with the MVVM Light framework

If you require an example, please comment, and I will add one.

~Cheers

I said I wasn't going to do an example, but I am. Here you go.

1) In your project, add MVVM Light Libraries Only.

2) Create a class for your view. Generally speaking, you have a view model for each view (view: MainWindow.xaml && viewModel: MainWindowViewModel.cs)

3) Here is the code for the very, very, very basic view model:

All included namespace (if they show up here, I am assuming you already added the reference to them. MVVM Light is in Nuget)

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

Now add a basic public class:

/// <summary>
/// Very basic model for example
/// </summary>
public class BasicModel 
{
    public string Id { get; set; }
    public string Text { get; set; }

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="text"></param>
    public BasicModel(string text)
    {
        this.Id = Guid.NewGuid().ToString();
        this.Text = text;
    }
}

Now create your viewmodel:

public class MainWindowViewModel : ViewModelBase
{
    public MainWindowViewModel()
    {
        ModelsCollection = new ObservableCollection<BasicModel>(new List<BasicModel>() {
            new BasicModel("Model one")
            , new BasicModel("Model two")
            , new BasicModel("Model three")
        });
    }

    private BasicModel _selectedBasicModel;

    /// <summary>
    /// Stores the selected mode.
    /// </summary>
    /// <remarks>This is just an example, may be different.</remarks>
    public BasicModel SelectedBasicModel 
    {
        get { return _selectedBasicModel; }
        set { Set(() => SelectedBasicModel, ref _selectedBasicModel, value); }
    }

    private ObservableCollection<BasicModel> _modelsCollection;

    /// <summary>
    /// List to bind to
    /// </summary>
    public ObservableCollection<BasicModel> ModelsCollection
    {
        get { return _modelsCollection; }
        set { Set(() => ModelsCollection, ref _modelsCollection, value); }
    }        
}

In your viewmodel, add a relaycommand. Please note, I made this async and had it pass a parameter.

    private RelayCommand<string> _selectItemRelayCommand;
    /// <summary>
    /// Relay command associated with the selection of an item in the observablecollection
    /// </summary>
    public RelayCommand<string> SelectItemRelayCommand
    {
        get
        {
            if (_selectItemRelayCommand == null)
            {
                _selectItemRelayCommand = new RelayCommand<string>(async (id) =>
                {
                    await selectItem(id);
                });
            }

            return _selectItemRelayCommand;
        }
        set { _selectItemRelayCommand = value; }
    }

    /// <summary>
    /// I went with async in case you sub is a long task, and you don't want to lock you UI
    /// </summary>
    /// <returns></returns>
    private async Task<int> selectItem(string id)
    {
        this.SelectedBasicModel = ModelsCollection.FirstOrDefault(x => x.Id == id);
        Console.WriteLine(String.Concat("You just clicked:", SelectedBasicModel.Text));
        //Do async work

        return await Task.FromResult(1);
    }

In the code behind for you view, create a property for you viewmodel and set the datacontext for your view to the viewmodel (please note, there are other ways to do this, but I am trying to make this a simple example.)

public partial class MainWindow : Window
{
    public MainWindowViewModel MyViewModel { get; set; }
    public MainWindow()
    {
        InitializeComponent();

        MyViewModel = new MainWindowViewModel();
        this.DataContext = MyViewModel;
    }
}

In your XAML, you need to add some namespaces to the top of your code

<Window x:Class="Basic_Binding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:Custom="clr-namespace:GalaSoft.MvvmLight;assembly=GalaSoft.MvvmLight"
    Title="MainWindow" Height="350" Width="525">

I added "i" and "Custom."

Here is the ListView:

<ListView 
        Grid.Row="0" 
        Grid.Column="0" 
        HorizontalContentAlignment="Stretch"
        ItemsSource="{Binding ModelsCollection}"
        ItemTemplate="{DynamicResource BasicModelDataTemplate}">
    </ListView>

Here is the ItemTemplate for the ListView:

<DataTemplate x:Key="BasicModelDataTemplate">
        <Grid>
            <TextBlock Text="{Binding Text}">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="MouseLeftButtonUp">
                        <i:InvokeCommandAction 
                            Command="{Binding DataContext.SelectItemRelayCommand, 
                                RelativeSource={RelativeSource FindAncestor, 
                                        AncestorType={x:Type ItemsControl}}}"
                            CommandParameter="{Binding Id}">                                
                        </i:InvokeCommandAction>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </TextBlock>
        </Grid>
    </DataTemplate>

Run your application, and check out the output window. You can use a converter to handle the styling of the selected item.

This may seem really complicated, but it makes life a lot easier down the road when you need to separate your view from your ViewModel (e.g. develop a ViewModel for multiple platforms.) Additionally, it makes working in Blend 10x easier. Once you develop your ViewModel, you can hand it over to a designer who can make it look very artsy :). MVVM Light adds some functionality to make Blend recognize your ViewModel. For the most part, you can do just about everything you want to in the ViewModel to affect the view.

If anyone reads this, I hope you find this helpful. If you have questions, please let me know. I used MVVM Light in this example, but you could do this without MVVM Light.

~Cheers

Is there any native DLL export functions viewer?

If you don't have the source code and API documentation, the machine code is all there is, you need to disassemble the dll library using something like IDA Pro , another option is use the trial version of PE Explorer.

PE Explorer provides a Disassembler. There is only one way to figure out the parameters: run the disassembler and read the disassembly output. Unfortunately, this task of reverse engineering the interface cannot be automated.

PE Explorer comes bundled with descriptions for 39 various libraries, including the core Windows® operating system libraries (eg. KERNEL32, GDI32, USER32, SHELL32, WSOCK32), key graphics libraries (DDRAW, OPENGL32) and more.

alt text
(source: heaventools.com)

Best way to do a split pane in HTML

You can do it with jQuery UI without another JavaScript library. Just add a function to the .resizable resize event to adjust the width of the other div.

$("#left_pane").resizable({
  handles: 'e', // 'East' side of div draggable
  resize: function() {
    $("#right_pane").outerWidth( $("#container").innerWidth() - $("#left_pane").outerWidth() );
  }
});

Here's the complete JSFiddle.

What is the right way to treat argparse.Namespace() as a dictionary?

Is it proper to "reach into" an object and use its dict property?

In general, I would say "no". However Namespace has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.

On the other hand, Namespace does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__, but the limits of my imagination are not the same as yours.

Running Jupyter via command line on Windows

In Python 3.7.6 for Windows 10. After installation, I use these commands.

1. pip install notebook
2. python -m notebook

OR

C:\Users\Hamza\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts .

For my pc python-scripts are located in the above path. You can add this path in environment variables. Then run command.

1. jupyter notebook

Using JQuery hover with HTML image map

This question is old but I wanted to add an alternative to the accepted answer which didn't exist at the time.

Image Mapster is a jQuery plugin that I wrote to solve some of the shortcomings of Map Hilight (and it was initially an extension of that plugin, though it's since been almost completely rewritten). Initially, this was just the ability to maintain selection state for areas, fix browser compatibility problems. Since its initial release a few months ago, though, I have added a lot of features including the ability to use an alternate image as the source for the highlights.

It also has the ability to identify areas as "masks," meaning you can create areas with "holes", and additionally create complex groupings of areas. For example, area A could cause another area B to be highlighted, but area B itself would not respond to mouse events.

There are a few examples on the web site that show most of the features. The github repository also has more examples and complete documentation.

Eclipse: How do I add the javax.servlet package to a project?

  1. Download the file from http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadjavaxservletjar.htm

  2. Make a folder ("lib") inside the project folder and move that jar file to there.

  3. In Eclipse, right click on project > BuildPath > Configure BuildPath > Libraries > Add External Jar

Thats all

CSS3 opacity gradient?

We can do it by css like.

body {
  background: #000;
  background-image: linear-gradient(90deg, rgba(255, 255, 255, .3) 0%, rgba(231, 231, 231, .3) 22.39%, rgba(209, 209, 209,  .3) 42.6%, rgba(182, 182, 182, .3) 79.19%, rgba(156, 156, 156, .3) 104.86%);
  
}

JSON response parsing in Javascript to get key/value pair

var yourobj={
"c":{
    "a":[{"name":"cable - black","value":2},{"name":"case","value":2}]
    },
"o":{
    "v":[{"name":"over the ear headphones - white/purple","value":1}]
},
"l":{
    "e":[{"name":"lens cleaner","value":1}]
},
"h":{
    "d":[{"name":"hdmi cable","value":1},
         {"name":"hdtv essentials (hdtv cable setup)","value":1},
         {"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]
}}
  • first of all it's a good idea to get organized
  • top level reference must be a more convenient name other that a..v... etc
  • in o.v,o.i.e no need for the array [] because it is one json entry

my solution

var obj = [];
for(n1 in yourjson)
    for(n1_1 in yourjson[n])
        for(n1_2 in yourjson[n][n1_1])
            obj[n1_2[name]] = n1_2[value];

Approved code

for(n1 in yourobj){
    for(n1_1 in yourobj[n1]){
    for(n1_2 in yourobj[n1][n1_1]){
            for(n1_3 in yourobj[n1][n1_1][n1_2]){
      obj[yourobj[n1][n1_1][n1_2].name]=yourobj[n1][n1_1][n1_2].value;
            }
    }
 }
}
console.log(obj);

result

*You should use distinguish accessorizes when using [] method or dot notation

proove

How do I clear a C++ array?

Assuming a C-style array a of size N, with elements of a type implicitly convertible from 0, the following sets all the elements to values constructed from 0.

std::fill(a, a+N, 0);

Note that this is not the same as "emptying" or "clearing".

Edit: Following james Kanze's suggestion, in C++11 you could use the more idiomatic alternative

std::fill( std::begin( a ), std::end( a ), 0 );

In the absence of C++11, you could roll out your own solution along these lines:

template <typename T, std::size_t N> T* end_(T(&arr)[N]) { return arr + N; }

template <typename T, std::size_t N> T* begin_(T(&arr)[N]) { return arr; }

std::fill( begin_( a ), end_( a ), 0 );

Entity framework left join

It might be a bit of an overkill, but I wrote an extension method, so you can do a LeftJoin using the Join syntax (at least in method call notation):

persons.LeftJoin(
    phoneNumbers,
    person => person.Id,
    phoneNumber => phoneNumber.PersonId,
    (person, phoneNumber) => new
        {
            Person = person,
            PhoneNumber = phoneNumber?.Number
        }
);

My code does nothing more than adding a GroupJoin and a SelectMany call to the current expression tree. Nevertheless, it looks pretty complicated because I have to build the expressions myself and modify the expression tree specified by the user in the resultSelector parameter to keep the whole tree translatable by LINQ-to-Entities.

public static class LeftJoinExtension
{
    public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
        this IQueryable<TOuter> outer,
        IQueryable<TInner> inner,
        Expression<Func<TOuter, TKey>> outerKeySelector,
        Expression<Func<TInner, TKey>> innerKeySelector,
        Expression<Func<TOuter, TInner, TResult>> resultSelector)
    {
        MethodInfo groupJoin = typeof (Queryable).GetMethods()
                                                 .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
                                                 .MakeGenericMethod(typeof (TOuter), typeof (TInner), typeof (TKey), typeof (LeftJoinIntermediate<TOuter, TInner>));
        MethodInfo selectMany = typeof (Queryable).GetMethods()
                                                  .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
                                                  .MakeGenericMethod(typeof (LeftJoinIntermediate<TOuter, TInner>), typeof (TInner), typeof (TResult));

        var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
                                      ((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> {OneOuter = oneOuter, ManyInners = manyInners});

        MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);

        var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
                                           (t => t.ManyInners.DefaultIfEmpty());

        ParameterExpression paramUser = resultSelector.Parameters.First();

        ParameterExpression paramNew = Expression.Parameter(typeof (LeftJoinIntermediate<TOuter, TInner>), "t");
        MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");

        LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body), paramNew, resultSelector.Parameters.Skip(1).First());

        MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);

        return outer.Provider.CreateQuery<TResult>(exprSelectMany);
    }

    private class LeftJoinIntermediate<TOuter, TInner>
    {
        public TOuter OneOuter { get; set; }
        public IEnumerable<TInner> ManyInners { get; set; }
    }

    private class Replacer : ExpressionVisitor
    {
        private readonly ParameterExpression _oldParam;
        private readonly Expression _replacement;

        public Replacer(ParameterExpression oldParam, Expression replacement)
        {
            _oldParam = oldParam;
            _replacement = replacement;
        }

        public override Expression Visit(Expression exp)
        {
            if (exp == _oldParam)
            {
                return _replacement;
            }

            return base.Visit(exp);
        }
    }
}

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

how to display progress while loading a url to webview in android?

Check out the sample code. It help you.

 private ProgressBar progressBar;
 progressBar=(ProgressBar)findViewById(R.id.webloadProgressBar);
 WebView urlWebView= new WebView(Context);
    urlWebView.setWebViewClient(new AppWebViewClients(progressBar));
                        urlWebView.getSettings().setJavaScriptEnabled(true);
                        urlWebView.loadUrl(detailView.getUrl());

public class AppWebViewClients extends WebViewClient {
     private ProgressBar progressBar;

    public AppWebViewClients(ProgressBar progressBar) {
        this.progressBar=progressBar;
        progressBar.setVisibility(View.VISIBLE);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
    }
}

Thanks.

Insert results of a stored procedure into a temporary table

In SQL Server 2005 you can use INSERT INTO ... EXEC to insert the result of a stored procedure into a table. From MSDN's INSERT documentation (for SQL Server 2000, in fact):

--INSERT...EXECUTE procedure example
INSERT author_sales EXECUTE get_author_sales