Programs & Examples On #Svcutil.exe

The ServiceModel Metadata Utility tool (SVCUTIL.EXE) is used to generate service model code from metadata documents and metadata documents from service model code.

Where is svcutil.exe in Windows 7?

Try to generate the proxy class via SvcUtil.exe with command

Syntax:

svcutil.exe /language:<type> /out:<name>.cs /config:<name>.config http://<host address>:<port>

Example:

svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceSamples/myService1

To check if service is available try in your IE URL from example upon without myService1 postfix

Service Reference Error: Failed to generate code for the service reference

http://uliasz.com/2011/06/wcf-custom-tool-error-failed-to-generate-code-for-the-service-reference/#comment-1647

Thanks to the article above.

In my case, i have this issue with my WPF project in VS.Net 2008. After going through this article, i was realizing that the assembly used in the web service is different version of assembly used on client.

It works just fine after updating the assembly on the client.

WCF gives an unsecured or incorrectly secured fault error

Same this problem i am facing my client application is WinForms application C# 4.0

When i read the solution here, i checked Date & Time of client computer, but that was right and current time was showing, but still i was facing these problem.

After some work-around i found that wrong time zone has selected, i am in India and time zone was of Canada, the host server is located in Kuwait.

I found that system converts time to universal time.

When i changed the time zone to India's time zone, the problem was soled.

Bat file to run a .exe at the command prompt

Just put that line in the bat file...

Alternatively you can even make a shortcut for svcutil.exe, then add the arguments in the 'target' window.

URL encoding the space character: + or %20?

From Wikipedia (emphasis and link added):

When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.

So, the real percent encoding uses %20 while form data in URLs is in a modified form that uses +. So you're most likely to only see + in URLs in the query string after an ?.

Recommended way to insert elements into map

  1. insert is not a recommended way - it is one of the ways to insert into map. The difference with operator[] is that the insert can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert.
  2. operator[] needs the default constructor because the map checks if the element exists. If it doesn't then it creates one using default constructor and returns a reference (or const reference to it).

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

Error installing mysql2: Failed to build gem native extension

This solved my problem once in Windows:

subst X: "C:\Program files\MySQL\MySQL Server 5.5" 
gem install mysql2 -v 0.x.x --platform=ruby -- --with-mysql-dir=X: --with-mysql-lib=X:\lib\opt 
subst X: /D

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

Short answer:

In common use, space " ", Tab "\t" and newline "\n" are the difference:

string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false

string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false

string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false

https://dotnetfiddle.net/4hkpKM

also see this answer about: whitespace characters


Long answer:

There are also a few other white space characters, you probably never used before

https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

replace now.getTime() with your long value.

//GET UTC time for current date
        Date now= new Date();
        //LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
        LocalDate localDate = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDate();
        DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));

jQuery Ajax POST example with PHP

I am using this simple one line code for years without a problem (it requires jQuery):

<script src="http://malsup.github.com/jquery.form.js"></script> 
<script type="text/javascript">
    function ap(x,y) {$("#" + y).load(x);};
    function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>

Here ap() means an Ajax page and af() means an Ajax form. In a form, simply calling af() function will post the form to the URL and load the response on the desired HTML element.

<form id="form_id">
    ...
    <input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>

Visual Studio Code cannot detect installed git

I found that i had git: false in settings.json. Changed it to true and works now.

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT [UserID] FROM [User] u LEFT JOIN (
SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) t on t.TailUser=u.USerID

Change auto increment starting number?

If you need this procedure for variable fieldnames instead of id this might be helpful:

DROP PROCEDURE IF EXISTS update_auto_increment;
DELIMITER //
CREATE PROCEDURE update_auto_increment (_table VARCHAR(128), _fieldname VARCHAR(128))
BEGIN
    DECLARE _max_stmt VARCHAR(1024);
    DECLARE _stmt VARCHAR(1024);    
    SET @inc := 0;

    SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(',_fieldname,'), 0) + 1 INTO @inc FROM ', _table);
    PREPARE _max_stmt FROM @MAX_SQL;
    EXECUTE _max_stmt;
    DEALLOCATE PREPARE _max_stmt;

    SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT =  ', @inc);
    PREPARE _stmt FROM @SQL;
    EXECUTE _stmt;
    DEALLOCATE PREPARE _stmt;
END //
DELIMITER ;

CALL update_auto_increment('your_table_name', 'autoincrement_fieldname');

How in node to split string by newline ('\n')?

The first one should work:

> "a\nb".split("\n");
[ 'a', 'b' ]
> var a = "test.js\nagain.js"
undefined
> a.split("\n");
[ 'test.js', 'again.js' ]

Fixing slow initial load for IIS

Writing a ping service/script to hit your idle website is rather a best way to go because you will have a complete control. Other options that you have mentioned would be available if you have leased a dedicated hosting box.

In a shared hosting space, warmup scripts are the best first level defense (self help is the best help). Here is an article which shares an idea on how to do it from your own web application.

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

Work for me in CentOS:

$ service mysql stop
$ mysqld --skip-grant-tables &
$ mysql -u root mysql

mysql> FLUSH PRIVILEGES;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

$ service mysql restart

What is 'Currying'?

An example of currying would be when having functions you only know one of the parameters at the moment:

For example:

func aFunction(str: String) {
    let callback = callback(str) // signature now is `NSData -> ()`
    performAsyncRequest(callback)
}

func callback(str: String, data: NSData) {
    // Callback code
}

func performAsyncRequest(callback: NSData -> ()) {
    // Async code that will call callback with NSData as parameter
}

Here, since you don't know the second parameter for callback when sending it to performAsyncRequest(_:) you would have to create another lambda / closure to send that one to the function.

Javascript Print iframe contents only

Use this code for IE9 and above:

window.frames["printf"].focus();
window.frames["printf"].print();

For IE8:

window.frames[0].focus();
window.frames[0].print();

What is the maximum characters for the NVARCHAR(MAX)?

By default, nvarchar(MAX) values are stored exactly the same as nvarchar(4000) values would be, unless the actual length exceed 4000 characters; in that case, the in-row data is replaced by a pointer to one or more seperate pages where the data is stored.

If you anticipate data possibly exceeding 4000 character, nvarchar(MAX) is definitely the recommended choice.

Source: https://social.msdn.microsoft.com/Forums/en-US/databasedesign/thread/d5e0c6e5-8e44-4ad5-9591-20dc0ac7a870/

How to randomize (shuffle) a JavaScript array?

Shuffle Array In place

    function shuffleArr (array){
        for (var i = array.length - 1; i > 0; i--) {
            var rand = Math.floor(Math.random() * (i + 1));
            [array[i], array[rand]] = [array[rand], array[i]]
        }
    }

ES6 Pure, Iterative

    const getShuffledArr = arr => {
        const newArr = arr.slice()
        for (let i = newArr.length - 1; i > 0; i--) {
            const rand = Math.floor(Math.random() * (i + 1));
            [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
        }
        return newArr
    };

Reliability and Performance Test

Some solutions on this page aren't reliable (they only partially randomise the array). Other solutions are significantly less efficient. With testShuffleArrayFun (see below) we can test array shuffling functions for reliability and performance.

    function testShuffleArrayFun(getShuffledArrayFun){
        const arr = [0,1,2,3,4,5,6,7,8,9]

        var countArr = arr.map(el=>{
            return arr.map(
                el=> 0
            )
        }) //   For each possible position in the shuffledArr and for 
           //   each possible value, we'll create a counter. 
        const t0 = performance.now()
        const n = 1000000
        for (var i=0 ; i<n ; i++){
            //   We'll call getShuffledArrayFun n times. 
            //   And for each iteration, we'll increment the counter. 
            var shuffledArr = getShuffledArrayFun(arr)
            shuffledArr.forEach(
                (value,key)=>{countArr[key][value]++}
            )
        }
        const t1 = performance.now()
        console.log(`Count Values in position`)
        console.table(countArr)

        const frequencyArr = countArr.map( positionArr => (
            positionArr.map(  
                count => count/n
            )
        )) 

        console.log("Frequency of value in position")
        console.table(frequencyArr)
        console.log(`total time: ${t1-t0}`)
    }

Other Solutions

Other solutions just for fun.

ES6 Pure, Recursive

    const getShuffledArr = arr => {
        if (arr.length === 1) {return arr};
        const rand = Math.floor(Math.random() * arr.length);
        return [arr[rand], ...getShuffledArr(arr.filter((_, i) => i != rand))];
    };

ES6 Pure using array.map

    function getShuffledArr (arr){
        return [...arr].map( (_, i, arrCopy) => {
            var rand = i + ( Math.floor( Math.random() * (arrCopy.length - i) ) );
            [arrCopy[rand], arrCopy[i]] = [arrCopy[i], arrCopy[rand]]
            return arrCopy[i]
        })
    }

ES6 Pure using array.reduce

    function getShuffledArr (arr){
        return arr.reduce( 
            (newArr, _, i) => {
                var rand = i + ( Math.floor( Math.random() * (newArr.length - i) ) );
                [newArr[rand], newArr[i]] = [newArr[i], newArr[rand]]
                return newArr
            }, [...arr]
        )
    }

Best way to verify string is empty or null

You can make use of Optional and Apache commons Stringutils library

Optional.ofNullable(StringUtils.noEmpty(string1)).orElse(string2);

here it will check if the string1 is not null and not empty else it will return string2

Using intents to pass data between activities

Try this from your AndroidTabRestaurantDescSearchListView activity

Intent intent  = new Intent(this,RatingDescriptionSearchActivity.class );
intent.putExtras( getIntent().getExtras() );
startActivity( intent );  

And then from RatingDescriptionSearchActivity activity just call

getIntent().getStringExtra("key")

How to disable horizontal scrolling of UIScrollView?

I had the tableview contentInset set in viewDidLoad (as below) that what causing the horizontal scrolling

self.tableView.contentInset = UIEdgeInsetsMake(0, 30, 0, 0);

Check if there are any tableview contentInset set for different reasons and disable it

Powershell 2 copy-item which creates a folder if doesn't exist

Here's an example that worked for me. I had a list of about 500 specific files in a text file, contained in about 100 different folders, that I was supposed to copy over to a backup location in case those files were needed later. The text file contained full path and file name, one per line. In my case, I wanted to strip off the Drive letter and first sub-folder name from each file name. I wanted to copy all these files to a similar folder structure under another root destination folder I specified. I hope other users find this helpful.

# Copy list of files (full path + file name) in a txt file to a new destination, creating folder structure for each file before copy
$rootDestFolder = "F:\DestinationFolderName"
$sourceFiles = Get-Content C:\temp\filelist.txt
foreach($sourceFile in $sourceFiles){
    $filesplit = $sourceFile.split("\")
    $splitcount = $filesplit.count
    # This example strips the drive letter & first folder ( ex: E:\Subfolder\ ) but appends the rest of the path to the rootDestFolder
    $destFile = $rootDestFolder + "\" + $($($sourceFile.split("\")[2..$splitcount]) -join "\")
    # Output List of source and dest 
    Write-Host ""
    Write-Host "===$sourceFile===" -ForegroundColor Green
    Write-Host "+++$destFile+++"
    # Create path and file, if they do not already exist
    $destPath = Split-Path $destFile
    If(!(Test-Path $destPath)) { New-Item $destPath -Type Directory }
    If(!(Test-Path $destFile)) { Copy-Item $sourceFile $destFile }
}

Export specific rows from a PostgreSQL table as INSERT SQL script

You can make view of the table with specifit records and then dump sql file

CREATE VIEW foo AS
SELECT id,name,city FROM nyummy.cimory WHERE city = 'tokyo'

Android: How to stretch an image to the screen width while maintaining aspect ratio?

I did it with these values within a LinearLayout:

Scale type: fitStart
Layout gravity: fill_horizontal
Layout height: wrap_content
Layout weight: 1
Layout width: fill_parent

How to compare two floating point numbers in Bash?

Of course, if you don't need really floating-point arithmetic, just arithmetic on e.g. dollar values where there are always exactly two decimal digits, you might just drop the dot (effectively multiplying by 100) and compare the resulting integers.

if [[ $((10#${num1/.})) < $((10#${num2/.})) ]]; then
    ...

This obviously requires you to be sure that both values have the same number of decimal places.

Asus Zenfone 5 not detected by computer

driver Asus for Windows: http://www.asus.com/sa-en/support/Download/39/1/0/2/32/

Choose target device: USB device

enter image description here (open image in new tab for bigger)

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I'd like to get back to Fiddler. After having played with that for a while, it is clearly the best way to edit any web requests on-the-fly. Being JavaScript, POST, GET, HTML, XML whatever and anything. It's free, but a little tricky to implement. Here's my HOW-TO:

To use Fiddler to manipulate JavaScript (on-the-fly) with Firefox, do the following:

1) Download and install Fiddler

2) Download and install the Fiddler extension: "3 Syntax-Highlighting add-ons"

3) Restart Firefox and enable the "FiddlerHook" extension

4) Open Firefox and enable the FiddlerHook toolbar button: View > Toolbars > Customize...

5) Click the Fiddler tool button and wait for fiddler to start.

6) Point your browser to Fiddler's test URLs:

Echo Service:  http://127.0.0.1:8888/
DNS Lookup:    http://www.localhost.fiddler:8888/

7) Add Fiddler Rules in order to intercept and edit JavaScript before reaching the browser/server. In Fiddler click: Rules > Customize Rules.... [CTRL-R] This will start the ScriptEditor.

8) Edit and Add the following rules:


a) To pause JavaScript to allow editing, add under the function "OnBeforeResponse":

if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "javascript")){
  oSession["x-breakresponse"]="reason is JScript"; 
}

b) To pause HTTP POSTs to allow editing when using the POST verb, edit "OnBeforeRequest":

if (oSession.HTTPMethodIs("POST")){
  oSession["x-breakrequest"]="breaking for POST";
}

c) To pause a request for an XML file to allow editing, edit "OnBeforeRequest":

if (oSession.url.toLowerCase().indexOf(".xml")>-1){
  oSession["x-breakrequest"]="reason_XML"; 
}

[9] TODO: Edit the above CustomRules.js to allow for disabling (a-c).

10) The browser loading will now stop on every JavaScript found and display a red pause mark for every script. In order to continue loading the page you need to click the green "Run to Completion" button for every script. (Which is why we'd like to implement [9].)

Window.open as modal popup?

You can try open a modal dialog with html5 and css3, try this code:

_x000D_
_x000D_
.windowModal {_x000D_
    position: fixed;_x000D_
    font-family: Arial, Helvetica, sans-serif;_x000D_
    top: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    background: rgba(0,0,0,0.8);_x000D_
    z-index: 99999;_x000D_
    opacity:0;_x000D_
    -webkit-transition: opacity 400ms ease-in;_x000D_
    -moz-transition: opacity 400ms ease-in;_x000D_
    transition: opacity 400ms ease-in;_x000D_
    pointer-events: none;_x000D_
}_x000D_
.windowModal:target {_x000D_
    opacity:1;_x000D_
    pointer-events: auto;_x000D_
}_x000D_
_x000D_
.windowModal > div {_x000D_
    width: 400px;_x000D_
    position: relative;_x000D_
    margin: 10% auto;_x000D_
    padding: 5px 20px 13px 20px;_x000D_
    border-radius: 10px;_x000D_
    background: #fff;_x000D_
    background: -moz-linear-gradient(#fff, #999);_x000D_
    background: -webkit-linear-gradient(#fff, #999);_x000D_
    background: -o-linear-gradient(#fff, #999);_x000D_
}_x000D_
.close {_x000D_
    background: #606061;_x000D_
    color: #FFFFFF;_x000D_
    line-height: 25px;_x000D_
    position: absolute;_x000D_
    right: -12px;_x000D_
    text-align: center;_x000D_
    top: -10px;_x000D_
    width: 24px;_x000D_
    text-decoration: none;_x000D_
    font-weight: bold;_x000D_
    -webkit-border-radius: 12px;_x000D_
    -moz-border-radius: 12px;_x000D_
    border-radius: 12px;_x000D_
    -moz-box-shadow: 1px 1px 3px #000;_x000D_
    -webkit-box-shadow: 1px 1px 3px #000;_x000D_
    box-shadow: 1px 1px 3px #000;_x000D_
}_x000D_
_x000D_
.close:hover { background: #00d9ff; }
_x000D_
<a href="#divModal">Open Modal Window</a>_x000D_
_x000D_
<div id="divModal" class="windowModal">_x000D_
    <div>_x000D_
        <a href="#close" title="Close" class="close">X</a>_x000D_
        <h2>Modal Dialog</h2>_x000D_
        <p>This example shows a modal window without using javascript only using html5 and css3, I try it it¡</p>_x000D_
        <p>Using javascript, with new versions of html5 and css3 is not necessary can do whatever we want without using js libraries.</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

Get the name of a pandas DataFrame

Here is a sample function: 'df.name = file` : Sixth line in the code below

def df_list(): filename_list = current_stage_files(PATH) df_list = [] for file in filename_list: df = pd.read_csv(PATH+file) df.name = file df_list.append(df) return df_list

What is the difference between a definition and a declaration?

Stages of an executable generation:

(1) pre-processor -> (2) translator/compiler -> (3) linker

In stage 2 (translator/compiler), declaration statements in our code tell to the compiler that these things we are going to use in future and you can find definition later, meaning is :

translator make sure that : what is what ? means declaration

and (3) stage (linker) needs definition to bind the things

Linker make sure that : where is what ? means definition

Oracle SQL Developer: Unable to find a JVM

The solution that worked for me: If you have Sqldeveloper with java incorporated, you can use the \sqldeveloper\bin\sqldeveloper.bat to launch sqldeveloper as told here.

Is nested function a good approach when required by only one function?

It's actually fine to declare one function inside another one. This is specially useful creating decorators.

However, as a rule of thumb, if the function is complex (more than 10 lines) it might be a better idea to declare it on the module level.

How to get to a particular element in a List in java?

The List interface supports random access via the get method - to get line 0, use list.get(0). You'll need to use array access on that, ie, lines.get(0)[0] is the first element of the first line.

See the javadoc here.

how to find all indexes and their columns for tables, views and synonyms in oracle

Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

C++ JSON Serialization

Using ThorsSerializer

Dog *d1 = new Dog();
d1->name = "myDog";

std::stringstream  stream << ThorsAnvil::Serialize::jsonExport(d1);
string serialized = stream.str();

Dog *d2 = nullptr;
stream >> ThorsAnvil::Serialize::jsonImport(d2);
std::cout << d2->name; // This will print "myDog"

I think that is pretty close to your original.
There is a tiny bit of set up. You need to declare your class is Serializable.

#include "ThorSerialize/Traits.h"
#include "ThorSerialize/JsonThor.h"

struct Dog
{
    std::string  name;
};

// Declare the "Dog" class is Serializable; Serialize the member "name"
ThorsAnvil_MakeTrait(Dog, name);

No other coding is required.

Complete Examples can be found:

What is the default root pasword for MySQL 5.7

In my case the data directory was automatically initialized with the --initialize-insecure option. So /var/log/mysql/error.log does not contain a temporary password but:

[Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.

What worked was:

shell> mysql -u root --skip-password
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

Details: MySQL 5.7 Reference Manual > 2.10.4 Securing the Initial MySQL Account

ALTER TABLE add constraint

alter table User 
    add constraint userProperties
    foreign key (properties)
    references Properties(ID)

Reset par to the default values at startup

From Quick-R

par()              # view current settings
opar <- par()      # make a copy of current settings
par(col.lab="red") # red x and y labels 
hist(mtcars$mpg)   # create a plot with these new settings 
par(opar)          # restore original settings

What is the difference between dim and set in vba

Dim: you are defining a variable (here: r is a variable of type Range)

Set: you are setting the property (here: set the value of r to Range("A1") - this is not a type, but a value).

You have to use set with objects, if r were a simple type (e.g. int, string), then you would just write:

Dim r As Integer
r=5

Add Whatsapp function to website, like sms, tel

This is possible by creating the following link:

whatsapp://send?text=Hello this has been opened from the browser&phone=+PHONENUMBER&abid=+PHONENUMBER

Thanks to:

https://forum.ionicframework.com/t/open-whatsapp-intent-with-msg-specific-contact/73903/4

I have tested this on iOS, Windows Phone and Android

if statement in ng-click

If you do have to do it this way, here's a few ways of doing it:

Disabling the button with ng-disabled

By far the easiest solution.

<input ng-disabled="!profileForm.$valid" ng-click="updateMyProfile()" ... >

Hiding the button (and showing something else) with ng-if

Might be OK if you're showing/hiding some complex markup.

<div ng-if="profileForm.$valid">
    <input ng-click="updateMyProfile()" ... >
</div>
<div ng-if="!profileForm.$valid">
    Sorry! We need all form fields properly filled out to continue.
</div>

(remember, there's no ng-else ...)

A mix of both

Communicating to the user where the button is (he won't look for it any longer), but explain why it can't be clicked.

<input ng-disabled="!profileForm.$valid" ng-click="updateMyProfile()" ... >
<div ng-if="!profileForm.$valid">
    Sorry! We need all form fields properly filled out to continue.
</div>

Best way to require all files from a directory in ruby?

If it's a directory relative to the file that does the requiring (e.g. you want to load all files in the lib directory):

Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }

Edit: Based on comments below, an updated version:

Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

How can I write variables inside the tasks file in ansible

NOTE: Using set_fact as described below sets a fact/variable onto the remote servers that the task is running against. This fact/variable will then persist across subsequent tasks for the entire duration of your playbook.

Also, these facts are immutable (for the duration of the playbook), and cannot be changed once set.


ORIGINAL ANSWER

Use set_fact before your task to set facts which seem interchangeable with variables:

- name: Set Apache URL
  set_fact:
    apache_url: 'http://example.com/apache'

- name: Download Apache
  shell: wget {{ apache_url }}

See http://docs.ansible.com/set_fact_module.html for the official word.

Method has the same erasure as another method in type

Define a single Method without type like void add(Set ii){}

You can mention the type while calling the method based on your choice. It will work for any type of set.

LINQ equivalent of foreach for IEnumerable<T>

Keep your Side Effects out of my IEnumerable

I'd like to do the equivalent of the following in LINQ, but I can't figure out how:

As others have pointed out here and abroad LINQ and IEnumerable methods are expected to be side-effect free.

Do you really want to "do something" to each item in the IEnumerable? Then foreach is the best choice. People aren't surprised when side-effects happen here.

foreach (var i in items) i.DoStuff();

I bet you don't want a side-effect

However in my experience side-effects are usually not required. More often than not there is a simple LINQ query waiting to be discovered accompanied by a StackOverflow.com answer by either Jon Skeet, Eric Lippert, or Marc Gravell explaining how to do what you want!

Some examples

If you are actually just aggregating (accumulating) some value then you should consider the Aggregate extension method.

items.Aggregate(initial, (acc, x) => ComputeAccumulatedValue(acc, x));

Perhaps you want to create a new IEnumerable from the existing values.

items.Select(x => Transform(x));

Or maybe you want to create a look-up table:

items.ToLookup(x, x => GetTheKey(x))

The list (pun not entirely intended) of possibilities goes on and on.

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Align the form to the center in Bootstrap 4

<div class="d-flex justify-content-center align-items-center container ">

    <div class="row ">


        <form action="">
            <div class="form-group">
                <label for="inputUserName" class="control-label">Enter UserName</label>
                <input type="email" class="form-control" id="inputUserName" aria-labelledby="emailnotification">
                <small id="emailnotification" class="form-text text-muted">Enter Valid Email Id</small>
            </div>
            <div class="form-group">
                <label for="inputPassword" class="control-label">Enter Password</label>
                <input type="password" class="form-control" id="inputPassword" aria-labelledby="passwordnotification">

            </div>
        </form>

    </div>

</div>

How to append a jQuery variable value inside the .html tag

HTML :

<div id="myDiv">
    <form id="myForm">
    </form> 
</div>

jQuery :

var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';

$("#myDiv form#myForm").html(chbx);

//to insert dynamically created form 
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");

Demo

What is the correct format to use for Date/Time in an XML file

If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ")); That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.

Video format or MIME type is not supported

FIXED IT!

I was losing my mind over this one. Reset firefox, tried safe mode, removed plugins, debugged using developers tools. All were to no avail and didn't get me any further with getting my online videos back to normal viewing condition. This however did the trick perfectly.

Within Firefox or whatever flavor of Firefox you have(CyberFox being my favorite choice here), simply browse to https://get.adobe.com/flashplayer/

VERIFY FIRST that the website detected you're using FireFox and has set your download for the flash player to be for Firefox.

Don't just click download. PLEASE PLEASE PLEASE SAVE YOURSELF the migraine and ALWAYS make sure that the middle section labeled "Optional offer:" is absolutely NOT CHECKED, it will be checked by default so always UNCHECK it before proceeding to download.

After it's finished downloading, close out of Firefox. Run the downloaded setup file As Administrator. It takes only a few seconds or so to complete, so after it's done, open up Firefox again and try viewing anything that was previously throwing this error. Should be back to normal now.

Enjoy!

Python Request Post with param data

Assign the response to a value and test the attributes of it. These should tell you something useful.

response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
  • status_code should just reconfirm the code you were given before, of course

How to concatenate int values in java?

NOTE: when you try to use + operator on (string + int) it converts int into strings and concatnates them ! so you need to convert only one int to string

public class scratch {

public static void main(String[] args){

    int a=1;
    int b=0;
    int c=2;
    int d=2;
    int e=1;
    System.out.println( String.valueOf(a)+b+c+d+e) ;
}

What's the difference between utf8_general_ci and utf8_unicode_ci?

According to this post, there is a considerably large performance benefit on MySQL 5.7 when using utf8mb4_general_ci in stead of utf8mb4_unicode_ci: https://www.percona.com/blog/2019/02/27/charset-and-collation-settings-impact-on-mysql-performance/

adb command not found in linux environment

I found the solution to my problem. In my ~/.bashrc:

export PATH=${PATH}:/path/to/android-sdk/tools

However adb is not located in the android-sdk/tools/, rather in android-sdk/platform-tools/. So I added the following

export PATH=${PATH}:/path/to/android-sdk/tools:/path/to/android-sdk/platform-tools

And that solved the problem for me.

Is there an XSLT name-of element?

<xsl:value-of select="name(.)" /> : <xsl:value-of select="."/>

Using Panel or PlaceHolder

The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.

The Panel does have outer HTML tags but does have some cool extra properties.

  • BackImageUrl: Gets/Sets the background image's URL for the panel

  • HorizontalAlign: Gets/Sets the
    horizontal alignment of the parent's contents

  • Wrap: Gets/Sets whether the
    panel's content wraps

There is a good article at startvbnet here.

grep exclude multiple strings

The greps can be chained. For example:

tail -f admin.log | grep -v "Nopaging the limit is" | grep -v "keyword to remove is"

Wait one second in running program

Maybe try this code:

void wait (double x) {
    DateTime t = DateTime.Now;
    DateTime tf = DateTime.Now.AddSeconds(x);

    while (t < tf) {
        t = DateTime.Now;
    }
}

Add CSS or JavaScript files to layout head from views or partial views

Try the out-of-the-box solution (ASP.NET MVC 4 or later):

@{
    var bundle = BundleTable.Bundles.GetRegisteredBundles().First(b => b.Path == "~/js");

    bundle.Include("~/Scripts/myFile.js");
}

Get ID from URL with jQuery

My url is like this http://www.default-search.net/?sid=503 . I want to get 503 . I wrote the following code .

var baseUrl = (window.location).href; // You can also use document.URL
var koopId = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
alert(koopId)//503

If you use

var v = window.location.pathname;
console.log(v)

You will get only "/";

How can I get date and time formats based on Culture Info?

You can retrieve the format strings from the CultureInfo DateTimeFormat property, which is a DateTimeFormatInfo instance. This in turn has properties like ShortDatePattern and ShortTimePattern, containing the format strings:

CultureInfo us = new CultureInfo("en-US");
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;
string shortUsTimeFormatString = us.DateTimeFormat.ShortTimePattern;

CultureInfo uk = new CultureInfo("en-GB");
string shortUkDateFormatString = uk.DateTimeFormat.ShortDatePattern;
string shortUkTimeFormatString = uk.DateTimeFormat.ShortTimePattern;

If you simply want to format the date/time using the CultureInfo, pass it in as your IFormatter when converting the DateTime to a string, using the ToString method:

string us = myDate.ToString(new CultureInfo("en-US"));
string uk = myDate.ToString(new CultureInfo("en-GB"));

OAuth2 and Google API: access token expiration time?

You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.

However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).

EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:

  1. It is a parameter in the response (expires_in)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
  2. There is also an API that returns the remaining lifetime of the access_token:

    https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

    This will return a json array that will contain an expires_in parameter, which is the number of seconds left in the lifetime of the token.

Tkinter: How to use threads to preventing main event loop from "freezing"

I will submit the basis for an alternate solution. It is not specific to a Tk progress bar per se, but it can certainly be implemented very easily for that.

Here are some classes that allow you to run other tasks in the background of Tk, update the Tk controls when desired, and not lock up the gui!

Here's class TkRepeatingTask and BackgroundTask:

import threading

class TkRepeatingTask():

    def __init__( self, tkRoot, taskFuncPointer, freqencyMillis ):
        self.__tk_   = tkRoot
        self.__func_ = taskFuncPointer        
        self.__freq_ = freqencyMillis
        self.__isRunning_ = False

    def isRunning( self ) : return self.__isRunning_ 

    def start( self ) : 
        self.__isRunning_ = True
        self.__onTimer()

    def stop( self ) : self.__isRunning_ = False

    def __onTimer( self ): 
        if self.__isRunning_ :
            self.__func_() 
            self.__tk_.after( self.__freq_, self.__onTimer )

class BackgroundTask():

    def __init__( self, taskFuncPointer ):
        self.__taskFuncPointer_ = taskFuncPointer
        self.__workerThread_ = None
        self.__isRunning_ = False

    def taskFuncPointer( self ) : return self.__taskFuncPointer_

    def isRunning( self ) : 
        return self.__isRunning_ and self.__workerThread_.isAlive()

    def start( self ): 
        if not self.__isRunning_ :
            self.__isRunning_ = True
            self.__workerThread_ = self.WorkerThread( self )
            self.__workerThread_.start()

    def stop( self ) : self.__isRunning_ = False

    class WorkerThread( threading.Thread ):
        def __init__( self, bgTask ):      
            threading.Thread.__init__( self )
            self.__bgTask_ = bgTask

        def run( self ):
            try :
                self.__bgTask_.taskFuncPointer()( self.__bgTask_.isRunning )
            except Exception as e: print repr(e)
            self.__bgTask_.stop()

Here's a Tk test which demos the use of these. Just append this to the bottom of the module with those classes in it if you want to see the demo in action:

def tkThreadingTest():

    from tkinter import Tk, Label, Button, StringVar
    from time import sleep

    class UnitTestGUI:

        def __init__( self, master ):
            self.master = master
            master.title( "Threading Test" )

            self.testButton = Button( 
                self.master, text="Blocking", command=self.myLongProcess )
            self.testButton.pack()

            self.threadedButton = Button( 
                self.master, text="Threaded", command=self.onThreadedClicked )
            self.threadedButton.pack()

            self.cancelButton = Button( 
                self.master, text="Stop", command=self.onStopClicked )
            self.cancelButton.pack()

            self.statusLabelVar = StringVar()
            self.statusLabel = Label( master, textvariable=self.statusLabelVar )
            self.statusLabel.pack()

            self.clickMeButton = Button( 
                self.master, text="Click Me", command=self.onClickMeClicked )
            self.clickMeButton.pack()

            self.clickCountLabelVar = StringVar()            
            self.clickCountLabel = Label( master,  textvariable=self.clickCountLabelVar )
            self.clickCountLabel.pack()

            self.threadedButton = Button( 
                self.master, text="Timer", command=self.onTimerClicked )
            self.threadedButton.pack()

            self.timerCountLabelVar = StringVar()            
            self.timerCountLabel = Label( master,  textvariable=self.timerCountLabelVar )
            self.timerCountLabel.pack()

            self.timerCounter_=0

            self.clickCounter_=0

            self.bgTask = BackgroundTask( self.myLongProcess )

            self.timer = TkRepeatingTask( self.master, self.onTimer, 1 )

        def close( self ) :
            print "close"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass            
            self.master.quit()

        def onThreadedClicked( self ):
            print "onThreadedClicked"
            try: self.bgTask.start()
            except: pass

        def onTimerClicked( self ) :
            print "onTimerClicked"
            self.timer.start()

        def onStopClicked( self ) :
            print "onStopClicked"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass                        

        def onClickMeClicked( self ):
            print "onClickMeClicked"
            self.clickCounter_+=1
            self.clickCountLabelVar.set( str(self.clickCounter_) )

        def onTimer( self ) :
            print "onTimer"
            self.timerCounter_+=1
            self.timerCountLabelVar.set( str(self.timerCounter_) )

        def myLongProcess( self, isRunningFunc=None ) :
            print "starting myLongProcess"
            for i in range( 1, 10 ):
                try:
                    if not isRunningFunc() :
                        self.onMyLongProcessUpdate( "Stopped!" )
                        return
                except : pass   
                self.onMyLongProcessUpdate( i )
                sleep( 1.5 ) # simulate doing work
            self.onMyLongProcessUpdate( "Done!" )                

        def onMyLongProcessUpdate( self, status ) :
            print "Process Update: %s" % (status,)
            self.statusLabelVar.set( str(status) )

    root = Tk()    
    gui = UnitTestGUI( root )
    root.protocol( "WM_DELETE_WINDOW", gui.close )
    root.mainloop()

if __name__ == "__main__": 
    tkThreadingTest()

Two import points I'll stress about BackgroundTask:

1) The function you run in the background task needs to take a function pointer it will both invoke and respect, which allows the task to be cancelled mid way through - if possible.

2) You need to make sure the background task is stopped when you exit your application. That thread will still run even if your gui is closed if you don't address that!

How can I get sin, cos, and tan to use degrees instead of radians?

You can use a function like this to do the conversion:

function toDegrees (angle) {
  return angle * (180 / Math.PI);
}

Note that functions like sin, cos, and so on do not return angles, they take angles as input. It seems to me that it would be more useful to you to have a function that converts a degree input to radians, like this:

function toRadians (angle) {
  return angle * (Math.PI / 180);
}

which you could use to do something like tan(toRadians(45)).

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

Binding IIS Express to an IP Address

As mentioned above, edit the application host.config. An easy way to find this is run your site in VS using IIS Express. Right click the systray icon, show all applications. Choose your site, and then click on the config link at the bottom to open it.

I'd suggest adding another binding entry, and leave the initial localhost one there. This additional binding will appear in the IIS Express systray as a separate application under the site.

To avoid having to run VS as admin (lots of good reasons not to run as admin), add a netsh rule as follows (obviously replacing the IP and port with your values) - you'll need an admin cmd.exe for this, it only needs to be run once:

netsh http add urlacl url=http://192.168.1.121:51652/ user=\Everyone

netsh can add rules like url=http://+:51652/ but I failed to get this to place nicely with IIS Express. You can use netsh http show urlacl to list existing rules, and they can be deleted with netsh http delete urlacl url=blah.

Further info: http://msdn.microsoft.com/en-us/library/ms733768.aspx

How does jQuery work when there are multiple elements with the same ID value?

If you have multiple elements with same id or same name, just assign same class to those multiple elements and access them by index & perform your required operation.

  <div>
        <span id="a" class="demo">1</span>
        <span id="a" class="demo">2</span>
        <span>3</span>
    </div>

JQ:

$($(".demo")[0]).val("First span");
$($(".demo")[1]).val("Second span");

What is the difference between window, screen, and document in Javascript?

The window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is also available in short as document.property.

How to sort dates from Oldest to Newest in Excel?

Saw this ages after posting, but if anyone has the same problem I had, my dates were all the format DD.MM.YYYY (SPSS output) even formatting them to date in Excel still only let me sort from A-Z so basically the 1st-31st irrelevant of month.

Doing a find and replace of all "." to "/" fixed this so that they are now in the format of DD/MM/YYYY. Not sure why it didn't work in the other format when the cell type counted as date.

Generating PDF files with JavaScript

Even if you could generate the PDF in-memory in JavaScript, you would still have the issue of how to transfer that data to the user. It's hard for JavaScript to just push a file at the user.

To get the file to the user, you would want to do a server submit in order to get the browser to bring up the save dialog.

With that said, it really isn't too hard to generate PDFs. Just read the spec.

How to check if ping responded or not in a batch file

I have made a variant solution based on paxdiablo's post

Place the following code in Waitlink.cmd

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
:loop
set state=up
ping -n 1 !ipaddr! >nul: 2>nul:
if not !errorlevel!==0 set state=down
echo.Link is !state!
if "!state!"=="up" (
  goto :endloop
)
ping -n 6 127.0.0.1 >nul: 2>nul:
goto :loop
:endloop
endlocal

For example use it from another batch file like this

call Waitlink someurl.com
net use o: \\someurl.com\myshare

The call to waitlink will only return when a ping was succesful. Thanks to paxdiablo and Gabe. Hope this helps someone else.

Python Progress Bar

This answer doesn't rely on external packages, I also think that most people just want a ready-made piece of code. The code below can be adapted to fit your needs by customizing: bar progress symbol '#', bar size, text prefix etc.

import sys

def progressbar(it, prefix="", size=60, file=sys.stdout):
    count = len(it)
    def show(j):
        x = int(size*j/count)
        file.write("%s[%s%s] %i/%i\r" % (prefix, "#"*x, "."*(size-x), j, count))
        file.flush()        
    show(0)
    for i, item in enumerate(it):
        yield item
        show(i+1)
    file.write("\n")
    file.flush()

Usage:

import time

for i in progressbar(range(15), "Computing: ", 40):
    time.sleep(0.1) # any calculation you need

Output:

Computing: [################........................] 4/15
  • Doesn't require a second thread. Some solutions/packages above require.

  • Works with any iterable it means anything that len() can be used on. A list, a dict of anything for example ['a', 'b', 'c' ... 'g']

  • Works with generators only have to wrap it with a list(). For example for i in progressbar(list(your_generator), "Computing: ", 40): Unless the work is done in the generator. In that case you need another solution (like tqdm).

You can also change output by changing file to sys.stderr for example

How to assign from a function which returns more than one value?

functionReturningTwoValues <- function() { 
  results <- list()
  results$first <- 1
  results$second <-2
  return(results) 
}
a <- functionReturningTwoValues()

I think this works.

How to iterate a loop with index and element in Swift

Use .enumerated() like this in functional programming:

list.enumerated().forEach { print($0.offset, $0.element) } 

Convert integer into byte array (Java)

Can also shift -

byte[] ba = new byte[4];
int val = Integer.MAX_VALUE;

for(byte i=0;i<4;i++)
    ba[i] = (byte)(val >> i*8);
    //ba[3-i] = (byte)(val >> i*8); //Big-endian

Assign null to a SqlParameter

Consider using the Nullable(T) structure available. It'll let you only set values if you have them, and your SQL Command objects will recognize the nullable value and process accordingly with no hassle on your end.

How to get the last N records in mongodb?

You can try this method:

Get the total number of records in the collection with

db.dbcollection.count() 

Then use skip:

db.dbcollection.find().skip(db.dbcollection.count() - 1).pretty()

Convert double to Int, rounded down

Another option either using Double or double is use Double.valueOf(double d).intValue();. Simple and clean

css selector to match an element without attribute x

Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/

What is the easiest way to get current GMT time in Unix timestamp format?

I like this method:

import datetime, time

dts = datetime.datetime.utcnow()
epochtime = round(time.mktime(dts.timetuple()) + dts.microsecond/1e6)

The other methods posted here are either not guaranteed to give you UTC on all platforms or only report whole seconds. If you want full resolution, this works, to the micro-second.

How to create a connection string in asp.net c#

Demo :

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

Based on your question:

<connectionStrings>
    <add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
    </connectionStrings>

Refer links:

http://www.connectionstrings.com/store-connection-string-in-webconfig/

Retrive connection string from web.config file:

write the below code in your file where you want;

string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;

SqlConnection con = new SqlConnection(connstring);

or you can go in your way like

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);

Note:

The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)

Global Events in Angular

The following code as an example of a replacement for $scope.emit() or $scope.broadcast() in Angular 2 using a shared service to handle events.

import {Injectable} from 'angular2/core';
import * as Rx from 'rxjs/Rx';

@Injectable()
export class EventsService {
    constructor() {
        this.listeners = {};
        this.eventsSubject = new Rx.Subject();

        this.events = Rx.Observable.from(this.eventsSubject);

        this.events.subscribe(
            ({name, args}) => {
                if (this.listeners[name]) {
                    for (let listener of this.listeners[name]) {
                        listener(...args);
                    }
                }
            });
    }

    on(name, listener) {
        if (!this.listeners[name]) {
            this.listeners[name] = [];
        }

        this.listeners[name].push(listener);
    }

    off(name, listener) {
        this.listeners[name] = this.listeners[name].filter(x => x != listener);
    }

    broadcast(name, ...args) {
        this.eventsSubject.next({
            name,
            args
        });
    }
}

Example usage:

Broadcast:

function handleHttpError(error) {
    this.eventsService.broadcast('http-error', error);
    return ( Rx.Observable.throw(error) );
}

Listener:

import {Inject, Injectable} from "angular2/core";
import {EventsService}      from './events.service';

@Injectable()
export class HttpErrorHandler {
    constructor(eventsService) {
        this.eventsService = eventsService;
    }

    static get parameters() {
        return [new Inject(EventsService)];
    }

    init() {
        this.eventsService.on('http-error', function(error) {
            console.group("HttpErrorHandler");
            console.log(error.status, "status code detected.");
            console.dir(error);
            console.groupEnd();
        });
    }
}

It can support multiple arguments:

this.eventsService.broadcast('something', "Am I a?", "Should be b", "C?");

this.eventsService.on('something', function (a, b, c) {
   console.log(a, b, c);
});

When should an Excel VBA variable be killed or set to Nothing?

I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:

Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)

When UserForm was destroyed (after Unload Me) the memory allocated for the data loaded in the mainPicture was not being de-allocated. I had to add an explicit

mainPicture = Nothing

in the terminate event.

What does "both" mean in <div style="clear:both">

Clear:both gives you that space between them.

For example your code:

  <div style="float:left">Hello</div>
  <div style="float:right">Howdy dere pardner</div>

Will currently display as :

Hello  ...................   Howdy dere pardner

If you add the following to above snippet,

  <div style="clear:both"></div>

In between them it will display as:

Hello ................ 
                       Howdy dere pardner

giving you that space between hello and Howdy dere pardner.

Js fiiddle http://jsfiddle.net/Qk5vR/1/

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

For Saturday and Sunday You can do something like this

             $('#orderdate').datepicker({
                               daysOfWeekDisabled: [0,6]
                 });

How do you set the title color for the new Toolbar?

Option 1) The quick and easy way (Toolbar only)

Since appcompat-v7-r23 you can use the following attributes directly on your Toolbar or its style:

app:titleTextColor="@color/primary_text"
app:subtitleTextColor="@color/secondary_text"

If your minimum SDK is 23 and you use native Toolbar just change the namespace prefix to android.

In Java you can use the following methods:

toolbar.setTitleTextColor(Color.WHITE);
toolbar.setSubtitleTextColor(Color.WHITE);

These methods take a color int not a color resource ID!

Option 2) Override Toolbar style and theme attributes

layout/xxx.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.MyApp.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    style="@style/Widget.MyApp.Toolbar.Solid"/>

values/styles.xml

<style name="Widget.MyApp.Toolbar.Solid" parent="Widget.AppCompat.ActionBar">
    <item name="android:background">@color/actionbar_color</item>
    <item name="android:elevation" tools:ignore="NewApi">4dp</item>
    <item name="titleTextAppearance">...</item>
</style>

<style name="ThemeOverlay.MyApp.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
    <!-- Parent theme sets colorControlNormal to textColorPrimary. -->
    <item name="android:textColorPrimary">@color/actionbar_title_text</item>
</style>

Help! My icons changed color too!

@PeterKnut reported this affects the color of overflow button, navigation drawer button and back button. It also changes text color of SearchView.

Concerning the icon colors: The colorControlNormal inherits from

  • android:textColorPrimary for dark themes (white on black)
  • android:textColorSecondary for light themes (black on white)

If you apply this to the action bar's theme, you can customize the icon color.

<item name="colorControlNormal">#de000000</item>

There was a bug in appcompat-v7 up to r23 which required you to also override the native counterpart like so:

<item name="android:colorControlNormal" tools:ignore="NewApi">?colorControlNormal</item>

Help! My SearchView is a mess!

Note: This section is possibly obsolete.

Since you use the search widget which for some reason uses different back arrow (not visually, technically) than the one included with appcompat-v7, you have to set it manually in the app's theme. Support library's drawables get tinted correctly. Otherwise it would be always white.

<item name="homeAsUpIndicator">@drawable/abc_ic_ab_back_mtrl_am_alpha</item>

As for the search view text...there's no easy way. After digging through its source I found a way to get to the text view. I haven't tested this so please let me know in the comments if this didn't work.

SearchView sv = ...; // get your search view instance in onCreateOptionsMenu
// prefix identifier with "android:" if you're using native SearchView
TextView tv = sv.findViewById(getResources().getIdentifier("id/search_src_text", null, null));
tv.setTextColor(Color.GREEN); // and of course specify your own color

Bonus: Override ActionBar style and theme attributes

Appropriate styling for a default action appcompat-v7 action bar would look like this:

<!-- ActionBar vs Toolbar. -->
<style name="Widget.MyApp.ActionBar.Solid" parent="Widget.AppCompat.ActionBar.Solid">
    <item name="background">@color/actionbar_color</item> <!-- No prefix. -->
    <item name="elevation">4dp</item> <!-- No prefix. -->
    <item name="titleTextStyle">...</item> <!-- Style vs appearance. -->
</style>

<style name="Theme.MyApp" parent="Theme.AppCompat">
    <item name="actionBarStyle">@style/Widget.MyApp.ActionBar.Solid</item>
    <item name="actionBarTheme">@style/ThemeOverlay.MyApp.ActionBar</item>
    <item name="actionBarPopupTheme">@style/ThemeOverlay.AppCompat.Light</item>
</style>

How to catch SQLServer timeout exceptions

When a client sends ABORT, no transactions are rolled back. To avoid this behavior we have to use SET_XACT_ABORT ON https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-ver15

jQuery .scrollTop(); + animation

for this you can use callback method

body.animate({
      scrollTop:0
    }, 500, 
    function(){} // callback method use this space how you like
);

PHP PDO: charset, set names?

I just want to add that you have to make sure your database is created with COLLATE utf8_general_ci or whichever collation you want to use, Else you might end up with another one than intended.

In phpmyadmin you can see the collation by clicking your database and choose operations. If you try create tables with another collation than your database, your tables will end up with the database collation anyways.

So make sure the collation for your database is right before creating tables. Hope this saves someone a few hours lol

Xcode 8 shows error that provisioning profile doesn't include signing certificate

To fix this,

I just enable the "Automatic manage signing" at project settings general tab, Before enabling that i was afraid that it may have some side effects but once i enable that works for me.

Hope this helps for others! enter image description here

Showing all errors and warnings

Set these on php.ini:

;display_startup_errors = On
display_startup_errors=off
display_errors =on
html_errors= on

From your PHP page, use a suitable filter for error reporting.

error_reporting(E_ALL);

Filers can be made according to requirements.

E_ALL
E_ALL | E_STRICT

Comparing two columns, and returning a specific adjacent cell in Excel

In cell D2 and copied down:

=IF(COUNTIF($A$2:$A$5,C2)=0,"",VLOOKUP(C2,$A$2:$B$5,2,FALSE))

Early exit from function?

if you are looking for a script to avoid submitting form when some errors found, this method should work

function verifyData(){
     if (document.MyForm.FormInput.value.length == "") {
          alert("Write something!");
     }
     else {
          document.MyForm.submit();
     }
}

change the Submit Button type to "button"

<input value="Save" type="button" onClick="verifyData()">

hope this help.

PHP convert string to hex and hex to string

You can try the following code to convert the image to hex string

<?php
$image = 'sample.bmp';
$file = fopen($image, 'r') or die("Could not open $image");
while ($file && !feof($file)){
$chunk = fread($file, 1000000); # You can affect performance altering
this number. YMMV.
# This loop will be dog-slow, almost for sure...
# You could snag two or three bytes and shift/add them,
# but at 4 bytes, you violate the 7fffffff limit of dechex...
# You could maybe write a better dechex that would accept multiple bytes
# and use substr... Maybe.
for ($byte = 0; $byte < strlen($chunk); $byte++)){
echo dechex(ord($chunk[$byte]));
}
}
?>

jQuery detect if string contains something

You could use String.prototype.indexOf to accomplish that. Try something like this:

_x000D_
_x000D_
$('.type').keyup(function() {_x000D_
  var v = $(this).val();_x000D_
  if (v.indexOf('> <') !== -1) {_x000D_
    console.log('contains > <');_x000D_
  }_x000D_
  console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
_x000D_
_x000D_

Update

Modern browsers also have a String.prototype.includes method.

Ways to insert javascript into URL?

It depends on your application and its use as to the level of security you need.

In terms of security, you should be validating all values you get from the querystring or post parameters, to ensure they're valid.

You may also wish to add logging for others, including analysis of weblogs so you can determine if an attempt to hack your system is occuring.

I don't believe it's possible to inject javascript into a URL and have this run, unless your application is using parameters without validating them first.

How to insert a SQLite record with a datetime set to 'now' in Android application?

To me, the problem looks like you're sending "datetime('now')" as a string, rather than a value.

My thought is to find a way to grab the current date/time and send it to your database as a date/time value, or find a way to use SQLite's built-in (DATETIME('NOW')) parameter

Check out the anwsers at this SO.com question - they might lead you in the right direction.

Hopefully this helps!

SQL Server remove milliseconds from datetime

select * from table
     where DATEADD(ms, DATEDIFF(ms, '20000101', date), '20000101') > '2010-07-20 03:21:52'

You'll have to trim milliseconds before comparison, which will be slow over many rows

Do one of these to fix this:

  • created a computed column with the expressions above to compare against
  • remove milliseconds on insert/update to avoid the read overhead
  • If SQL Server 2008, use datetime2(0)

Mythical man month 10 lines per developer day - how close on large projects?

I think project size and the number of developers involved are big factors in this. I'm far above this over my career but I've worked alone all that time so there's no loss to working with other programmers.

How to force browser to download file?

This is from a php script which solves the problem perfectly with every browser I've tested (FF since 3.5, IE8+, Chrome)

header("Content-Disposition: attachment; filename=\"".$fname_local."\"");
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($fname));

So as far as I can see, you're doing everything correctly. Have you checked your browser settings?

Example of Named Pipes

using System;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StartServer();
            Task.Delay(1000).Wait();


            //Client
            var client = new NamedPipeClientStream("PipesOfPiece");
            client.Connect();
            StreamReader reader = new StreamReader(client);
            StreamWriter writer = new StreamWriter(client);

            while (true)
            {
                string input = Console.ReadLine();
                if (String.IsNullOrEmpty(input)) break;
                writer.WriteLine(input);
                writer.Flush();
                Console.WriteLine(reader.ReadLine());
            }
        }

        static void StartServer()
        {
            Task.Factory.StartNew(() =>
            {
                var server = new NamedPipeServerStream("PipesOfPiece");
                server.WaitForConnection();
                StreamReader reader = new StreamReader(server);
                StreamWriter writer = new StreamWriter(server);
                while (true)
                {
                    var line = reader.ReadLine();
                    writer.WriteLine(String.Join("", line.Reverse()));
                    writer.Flush();
                }
            });
        }
    }
}

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I had the same issue after trying many combination I had this working note I have compatibility checked for intranet

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<head runat="server">

Disabling radio buttons with jQuery

I've refactored your code a bit, this should work:

jQuery("#loadActive").click(writeData);

function writeData() {
    jQuery("#chatTickets input:radio").attr('disabled',true);
}

If there are more than two radio buttons on your form, you'll have to modify the selector, for example, you can use the starts with attribute filter to pick out the radios whose ID starts with ticketID:

function writeData() {
    jQuery("#chatTickets input[id^=ticketID]:radio").attr('disabled',true);
}

How do you get the contextPath from JavaScript, the right way?

I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.

You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:

function getContextPath() {
   return "<%=request.getContextPath()%>";
}

It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.

At this point I agree with @BalusC to use EL:

function getContextPath() {
   return "${pageContext.request.contextPath}";
}

or depending on the version of JSP fallback to JSTL:

function getContextPath() {
   return "<c:out value="${pageContext.request.contextPath}" />";
}

Why do access tokens expire?

In addition to the other responses:

Once obtained, Access Tokens are typically sent along with every request from Clients to protected Resource Servers. This induce a risk for access token stealing and replay (assuming of course that access tokens are of type "Bearer" (as defined in the initial RFC6750).

Examples of those risks, in real life:

  • Resource Servers generally are distributed application servers and typically have lower security levels compared to Authorization Servers (lower SSL/TLS config, less hardening, etc.). Authorization Servers on the other hand are usually considered as critical Security infrastructure and are subject to more severe hardening.

  • Access Tokens may show up in HTTP traces, logs, etc. that are collected legitimately for diagnostic purposes on the Resource Servers or clients. Those traces can be exchanged over public or semi-public places (bug tracers, service-desk, etc.).

  • Backend RS applications can be outsourced to more or less trustworthy third-parties.

The Refresh Token, on the other hand, is typically transmitted only twice over the wires, and always between the client and the Authorization Server: once when obtained by client, and once when used by client during refresh (effectively "expiring" the previous refresh token). This is a drastically limited opportunity for interception and replay.

Last thought, Refresh Tokens offer very little protection, if any, against compromised clients.

Which Android IDE is better - Android Studio or Eclipse?

Both are equally good. With Android Studio you have ADT tools integrated, and with eclipse you need to integrate them manually. With Android Studio, it feels like a tool designed from the outset with Android development in mind. Go ahead, they have same features.

What is the purpose of class methods?

Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions.

If you have a class MyClass, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a classmethod. Then it'll be available to subclasses.

How does C compute sin() and other math functions?

Concerning trigonometric function like sin(), cos(),tan() there has been no mention, after 5 years, of an important aspect of high quality trig functions: Range reduction.

An early step in any of these functions is to reduce the angle, in radians, to a range of a 2*p interval. But p is irrational so simple reductions like x = remainder(x, 2*M_PI) introduce error as M_PI, or machine pi, is an approximation of p. So, how to do x = remainder(x, 2*p)?

Early libraries used extended precision or crafted programming to give quality results but still over a limited range of double. When a large value was requested like sin(pow(2,30)), the results were meaningless or 0.0 and maybe with an error flag set to something like TLOSS total loss of precision or PLOSS partial loss of precision.

Good range reduction of large values to an interval like -p to p is a challenging problem that rivals the challenges of the basic trig function, like sin(), itself.

A good report is Argument reduction for huge arguments: Good to the last bit (1992). It covers the issue well: discusses the need and how things were on various platforms (SPARC, PC, HP, 30+ other) and provides a solution algorithm the gives quality results for all double from -DBL_MAX to DBL_MAX.


If the original arguments are in degrees, yet may be of a large value, use fmod() first for improved precision. A good fmod() will introduce no error and so provide excellent range reduction.

// sin(degrees2radians(x))
sin(degrees2radians(fmod(x, 360.0))); // -360.0 < fmod(x,360) < +360.0

Various trig identities and remquo() offer even more improvement. Sample: sind()

Print line numbers starting at zero using awk

If Perl is an option, you can try this:

perl -ne 'printf "%s,$_" , $.-1' file

$_ is the line
$. is the line number

How to add double quotes to a string that is inside a variable?

You could use &quot; instead of ". It will be displayed correctly by the browser.

Update .NET web service to use TLS 1.2

We actually just upgraded a .NET web service to 4.6 to allow TLS 1.2.

What Artem is saying were the first steps we've done. We recompiled the framework of the web service to 4.6 and we tried change the registry key to enable TLS 1.2, although this didn't work: the connection was still in TLS 1.0. Also, we didn't want to disallow SLL 3.0, TLS 1.0 or TLS 1.1 on the machine: other web services could be using this; we rolled-back our changes on the registry.

We actually changed the Web.Config files to tell IIS: "hey, run me in 4.6 please".

Here's the changes we added in the web.config + recompilation in .NET 4.6:

<system.web>
    <compilation targetFramework="4.6"/> <!-- Changed framework 4.0 to 4.6 -->

    <!--Added this httpRuntime -->
    <httpRuntime targetFramework="4.6" />

    <authentication mode="Windows"/>
    <pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>

And the connection changed to TLS 1.2, because IIS is now running the web service in 4.6 (told explicitly) and 4.6 is using TLS 1.2 by default.

Java how to sort a Linked List?

In order to sort Strings alphabetically you will need to use a Collator, like:

 LinkedList<String> list = new LinkedList<String>();
 list.add("abc");
 list.add("Bcd");
 list.add("aAb");
 Collections.sort(list, new Comparator<String>() {
     @Override
     public int compare(String o1, String o2) {
         return Collator.getInstance().compare(o1, o2);
     }
 });

Because if you just call Collections.sort(list) you will have trouble with strings that contain uppercase characters.

For instance in the code I pasted, after the sorting the list will be: [aAb, abc, Bcd] but if you just call Collections.sort(list); you will get: [Bcd, aAb, abc]

Note: When using a Collator you can specify the locale Collator.getInstance(Locale.ENGLISH) this is usually pretty handy.

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

How to position a div in bottom right corner of a browser?

Try this:

#foo
{
    position: absolute;
    top: 100%;
    right: 0%;
}

Twitter Bootstrap scrollable table rows and fixed header

Interesting question, I tried doing this by just doing a fixed position row, but this way seems to be a much better one. Source at bottom.

css

thead { display:block; background: green; margin:0px; cell-spacing:0px; left:0px; }
tbody { display:block; overflow:auto; height:100px; }
th { height:50px; width:80px; }
td { height:50px; width:80px; background:blue; margin:0px; cell-spacing:0px;}

html

<table>
    <thead>
        <tr><th>hey</th><th>ho</th></tr>
    </thead>
    <tbody>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
</tbody>

http://www.imaputz.com/cssStuff/bigFourVersion.html

How do I get the title of the current active window using c#?

If it happens that you need the Current Active Form from your MDI application: (MDI- Multi Document Interface).

Form activForm;
activForm = Form.ActiveForm.ActiveMdiChild;

automatically execute an Excel macro on a cell change

I prefer this way, not using a cell but a range

    Dim cell_to_test As Range, cells_changed As Range

    Set cells_changed = Target(1, 1)
    Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )

    If Not Intersect(cells_changed, cell_to_test) Is Nothing Then 
       Macro
    End If

Bootstrap - Removing padding or margin when screen size is smaller

The problem here is much more complex than removing the container padding since the grid structure relies on this padding when applying negative margins for the enclosed rows.

Removing the container padding in this case will cause an x-axis overflow caused by all the rows inside of this container class, this is one of the most stupid things about the Bootstrap Grid.

Logically it should be approached by

  1. Never using the .container class for anything other than rows
  2. Make a clone of the .container class that has no padding for use with non-grid html
  3. For removing the .container padding on mobile you can manually remove it with media queries then overflow-x: hidden; which is not very reliable but works in most cases.

If you are using LESS the end result will look like this

@media (max-width: @screen-md-max) {
    .container{
        padding: 0;
        overflow-x: hidden;
    }
}

Change the media query to whatever size you want to target.

Final thoughts, I would highly recommend using the Foundation Framework Grid as its way more advanced

Output data with no column headings using PowerShell

First we grab the command output, then wrap it and select one of its properties. There is only one and its "Name" which is what we want. So we select the groups property with ".name" then output it.

to text file

 (Get-ADGroupMember 'Domain Admins' |Select name).name | out-file Admins1.txt

to csv

(Get-ADGroupMember 'Domain Admins' |Select name).name | export-csv -notypeinformation "Admins1.csv"

How to check if $_GET is empty?

I would use the following if statement because it is easier to read (and modify in the future)


if(!isset($_GET) || !is_array($_GET) || count($_GET)==0) {
   // empty, let's make sure it's an empty array for further reference
   $_GET=array();
   // or unset it 
   // or set it to null
   // etc...
}

Why powershell does not run Angular commands?

script1.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170

This error happens due to a security measure which won't let scripts be executed on your system without you having approved of it. You can do so by opening up a powershell with administrative rights (search for powershell in the main menu and select Run as administrator from the context menu) and entering:

set-executionpolicy remotesigned

flutter remove back button on appbar

add automaticallyImplyLeading: false, into your Scaffold's Appbar

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

You need to tell it that you are using SSL:

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

In case you miss anything, here is working code:

String  d_email = "[email protected]",
            d_uname = "Name",
            d_password = "urpassword",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "[email protected]",
            m_subject = "Indoors Readable File: " + params[0].getName(),
            m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
    Properties props = new Properties();
    props.put("mail.smtp.user", d_email);
    props.put("mail.smtp.host", d_host);
    props.put("mail.smtp.port", d_port);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", d_port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SMTPAuthenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);
    try {
        msg.setSubject(m_subject);
        msg.setFrom(new InternetAddress(d_email));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));

Transport transport = session.getTransport("smtps");
            transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

        } catch (AddressException e) {
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

As far as I remember, I used the update-java-alternatives script instead of the update-alternatives. And it did set the JAVA_HOME for me correctly.

Python - How to concatenate to a string in a for loop?

endstring = ''
for s in list:
    endstring += s

Run a command shell in jenkins

I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.

Error :

Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessImpl.create(Native Method)
    at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
    at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
    at hudson.Proc$LocalProc.<init>(Proc.java:250)
    at hudson.Proc$LocalProc.<init>(Proc.java:219)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
    at hudson.Launcher$ProcStarter.start(Launcher.java:455)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
    at hudson.model.Build$BuildExecution.build(Build.java:206)
    at hudson.model.Build$BuildExecution.doRun(Build.java:163)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
    at hudson.model.Run.execute(Run.java:1853)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE

Solution :

1 - Install Cygwin and note the directory where it gets installed.

It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.

2 - Tell Jenkins where sh.exe is located.

Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.

That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.

How to remove a Gitlab project?

  • Click on Project you want to delete.
  • Click Setting on right buttom corner.
  • click general than go to advance
  • than remove project

Call a child class method from a parent class object

Many of the answers here are suggesting implementing variant types using "Classical Object-Oriented Decomposition". That is, anything which might be needed on one of the variants has to be declared at the base of the hierarchy. I submit that this is a type-safe, but often very bad, approach. You either end up exposing all internal properties of all the different variants (most of which are "invalid" for each particular variant) or you end up cluttering the API of the hierarchy with tons of procedural methods (which means you have to recompile every time a new procedure is dreamed up).

I hesitate to do this, but here is a shameless plug for a blog post I wrote that outlines about 8 ways to do variant types in Java. They all suck, because Java sucks at variant types. So far the only JVM language that gets it right is Scala.

http://jazzjuice.blogspot.com/2010/10/6-things-i-hate-about-java-or-scala-is.html

The Scala creators actually wrote a paper about three of the eight ways. If I can track it down, I'll update this answer with a link.

UPDATE: found it here.

How to allow only integers in a textbox?

You can use RegularExpressionValidator

<asp:TextBox ID="viewTextBox" runat="server" Text="0"></asp:TextBox>
<asp:RegularExpressionValidator ID="viewRegularExpressionValidator" runat="server" ValidationExpression="[0-9]{1,50}" ControlToValidate="viewTextBox" ErrorMessage="Please Enter numbers only">*</asp:RegularExpressionValidator>

How can I hide an HTML table row <tr> so that it takes up no space?

position: absolute will remove it from the layout flow and should solve your problem - the element will remain in the DOM but won't affect others.

JPA Query selecting only specific columns without using Criteria Query?

Yes, it is possible. All you have to do is change your query to something like SELECT i.foo, i.bar FROM ObjectName i WHERE i.id = 10. The result of the query will be a List of array of Object. The first element in each array is the value of i.foo and the second element is the value i.bar. See the relevant section of JPQL reference.

Android "hello world" pushnotification example

you can follow this tutorial

http://www.androidbegin.com/tutorial/android-google-cloud-messaging-gcm-tutorial/

it helped me to do a push notification; or you can follow this other tutorial

http://www.tutorialeshtml5.com/2013/10/tutorial-simple-de-gcm-traves-de-php.html

but it's in spanish but you can download the code.

How to handle back button in activity

For both hardware device back button and soft home (back) button e.g. " <- " this is what works for me. (*Note I have an app bar / toolbar in the activity)

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            //finish();
            onBackPressed();
            break;
    }
    return true;
}



@Override
public void onBackPressed() {
   //Execute your code here
   finish();

}

Cheers!

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

I think I had the same requirement as Tim, but none of the answers provide for a 'viewport edge-to-edge columns with normal internal gutters' solution. Or another way to put it: how can I get my first and last columns to break into the container padding and flow to the edge of the viewport, while still maintaining normal gutters between the columns.

full width rows

From what I can tell, there is no neat and clean solution. This is what works for me, but it is well outside anything that would be supported by Bootstrap. But it works for now (Bootstrap 3.3.5 & 4.0-alpha).

http://www.bootply.com/ioWBaljBAd

Sample HTML:

<div class="container">
  <div class="row full-width-row">
    <div>
      <div class="col-sm-4 col-md-3">…</div>
      <div class="col-sm-4 col-md-3">…</div>
      <div class="col-sm-4 col-md-3">…</div>
      <div class="col-sm-4 col-md-3">…</div>
    </div>
  </div>
</div>

CSS:

.full-width-row {
  overflow-x: hidden;
}

.full-width-row > div {
  margin-left: -15px;
  margin-right: -15px;
}

The trick is to nest a div in between the row and the columns to generate the extra -15px margin to push into the container padding. The extra negative margin creates horizontal scroll (into whitespace) on small viewports. Adding overflow-x: hidden to the .row is required to suppress it.

This works the same for .container-fluid as .container.

How to handle static content in Spring MVC?

After encountering and going through the same decision making process described here, I decided to go with the ResourceServlet proposal which works out quite nicely.

Note that you get more information on how to use webflow in your maven build process here: http://static.springsource.org/spring-webflow/docs/2.0.x/reference/html/ch01s05.html

If you use the standard Maven central repository the artifact is (in opposite to the above referred springsource bundle):

<dependency>
    <groupId>org.springframework.webflow</groupId>
    <artifactId>spring-js</artifactId>
    <version>2.0.9.RELEASE</version>
</dependency> 

SSH to Vagrant box in Windows?

I think a better answer to this question would be the following:

https://eamann.com/tech/linux-flavored-windows/

Eric wrote a nice article on how to turn your windows computer into a Linux environment. Even with hacks to get Vim working natively in cmd.

If you run through this guide, which basically gets you to install git cli, and with some hacks, you can bring up a command prompt and type vagrant ssh while in the folder of your vagrant box and it will properly do the right things, no need to configure ssh keys etc. All that comes with ssh and the git cli /bin.

The power of this is that you can then actually run powershell and still get all the *nix goodness. This really simplifies your environment and helps with running Vagrant and other things.

TL;DR Download Git cli and add git/bin to PATH. Hack vim.bat in /bin to work for windows. Use ssh natively in cmd.

Button button = findViewById(R.id.button) always resolves to null in Android Studio

R.id.button is not part of R.layout.activity_main. How should the activity find it in the content view?

The layout that contains the button is displayed by the Fragment, so you have to get the Button there, in the Fragment.

How to style input and submit button with CSS?

HTML

<input type="submit" name="submit" value="Send" id="submit" />

CSS

#submit {
 color: #fff;
 font-size: 0;
 width: 135px;
 height: 60px;
 border: none;
 margin: 0;
 padding: 0;
 background: #0c0 url(image) 0 0 no-repeat; 
}

Rename MySQL database

In case you need to do that from the command line, just copy, adapt & paste this snippet:

mysql -e "CREATE DATABASE \`new_database\`;"
for table in `mysql -B -N -e "SHOW TABLES;" old_database`
do 
  mysql -e "RENAME TABLE \`old_database\`.\`$table\` to \`new_database\`.\`$table\`"
done
mysql -e "DROP DATABASE \`old_database\`;"

Securely storing passwords for use in python script

Know the master key yourself. Don't hard code it.

Use py-bcrypt (bcrypt), powerful hashing technique to generate a password yourself.

Basically you can do this (an idea...)

import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)

save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.

This is basically how login should work these days.

Debug JavaScript in Eclipse

MyEclipse (eclipse based, subscription required) and Webclipse (an eclipse plug-in, currently free), from my company, Genuitec, have newly engineered (as of 2015) JavaScript debugging built in:

enter image description here

You can debug both generic web applications and Node.js files.

Fixed positioning in Mobile Safari

This fixed position div can be achieved in just 2 lines of code which moves the div on scroll to the bottom of the page.

window.onscroll = function() {
  document.getElementById('fixedDiv').style.top =
     (window.pageYOffset + window.innerHeight - 25) + 'px';
};

Excel Formula: Count cells where value is date

There is no interactive solution in Excel because some functions are not vector-friendly, like CELL, above quoted. For example, it's possible counting all the numbers whose absolute value is less than 3, because ABS is accepted inside a formula array.

So I've used the following array formula (Ctrl+Shift+Enter after edit with no curly brackets)

             ={SUM(IF(ABS(F1:F15)<3,1,0))}

If Column F has

                   F
          1 ...    2
          2 ....   4
          3 ....  -2
          4 ....   1
          5 .....  5

It counts 3! (-2,2 and 1). In order to show how ABS is array-friendly function let's do a simple test: Select G1:G5, digit =ABS(F1:F5) in the formula bar and press Ctrl+Shift+Enter. It's like someone write Abs(F1:F5)(1), Abs(F1:F5)(2), etc.

                   F    G
          1 ...    2  =ABS(F1:F5) => 2 
          2 ....   4  =ABS(F1:F5) => 4
          3 ....  -2  =ABS(F1:F5) => 2
          4 ....   1  =ABS(F1:F5) => 1
          5 .....  5  =ABS(F1:F5) => 5

Now I put some mixed data, including 2 date values.

                   F
          1 ...    Fab-25-2012
          2 ....   4
          3 ....   May-5-2013
          4 ....   Ball
          5 .....  5

In this case, CELL fails and return 1

             ={SUM(IF(CELL("format",F1:F15)="D4",1,0))}

It happens because CELL return the format of first cell of the range. (D4 is a m-d-y format)

So the only thing left is programming! A UDF(User defined Function) for formula array must return a variant array:

Function TypeCell(R As Range) As Variant
Dim V() As Variant
Dim Cel As Range
Dim I As Integer
Application.Volatile '// For revaluation in interactive environment
ReDim V(R.Cells.Count - 1) As Variant
I = 0
For Each Cel In R
   V(I) = VarType(Cel) '// Output array has the same size of input range.
   I = I + 1
Next Cel
TypeCell = V
End Function

Now is easy (the constant VbDate is 7):

             =SUM(IF(TypeCell(F1:F5)=7,1,0))  

It shows 2. That technique can be used for any shape of cells. I've tested vertical, horizontal and rectangular shapes, since you fill using for each order inside the function.

Cross-Domain Cookies

Yes, it is absolutely possible to get the cookie from domain1.com by domain2.com. I had the same problem for a social plugin of my social network, and after a day of research I found the solution.

First, on the server side you need to have the following headers:

header("Access-Control-Allow-Origin: http://origin.domain:port");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type, *");

Within the PHP-file you can use $_COOKIE[name]

Second, on the client side:

Within your ajax request you need to include 2 parameters

crossDomain: true
xhrFields: { withCredentials: true }

Example:

type: "get",
url: link,
crossDomain: true,
dataType: 'json',
xhrFields: {
  withCredentials: true
}

$(window).width() not the same as media query

yes, that's due to scrollbar. Right answer source: enter link description here

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

iPhone get SSID without private library

This works for me on the device (not simulator). Make sure you add the systemconfiguration framework.

#import <SystemConfiguration/CaptiveNetwork.h>

+ (NSString *)currentWifiSSID {
    // Does not work on the simulator.
    NSString *ssid = nil;
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info[@"SSID"]) {
            ssid = info[@"SSID"];
        }
    }
    return ssid;
}

Set default value of an integer column SQLite

It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).

It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).

Here is the code I used:

CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY>       INTEGER    UNIQUE
                                PRIMARY KEY,
<MY_TABLE_SERIAL>    TEXT       DEFAULT (<MY_VALUE>) 
                                NOT NULL
<THE_REST_COLUMNS>
);

Nullable type as a generic parameter possible?

Just had to do something incredible similar to this. My code:

public T IsNull<T>(this object value, T nullAlterative)
{
    if(value != DBNull.Value)
    {
        Type type = typeof(T);
        if (type.IsGenericType && 
            type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
        {
            type = Nullable.GetUnderlyingType(type);
        }

        return (T)(type.IsEnum ? Enum.ToObject(type, Convert.ToInt32(value)) :
            Convert.ChangeType(value, type));
    }
    else 
        return nullAlternative;
}

What are major differences between C# and Java?

The following is a great in depth reference by Dare Obasanjo on the differences between C# and Java. I always find myself referring to this article when switching between the two.

http://www.25hoursaday.com/CsharpVsJava.html

Difference between a user and a schema in Oracle?

It's very simple.

If USER has OBJECTS
then call it SCHEMA
else
     call it USER
end if;

A user may be given access to schema objects owned by different Users.

How to clear the interpreter console?

I'm new to python (really really new) and in one of the books I'm reading to get acquainted with the language they teach how to create this little function to clear the console of the visible backlog and past commands and prints:

Open shell / Create new document / Create function as follows:

def clear():
    print('\n' * 50)

Save it inside the lib folder in you python directory (mine is C:\Python33\Lib) Next time you nedd to clear your console just call the function with:

clear()

that's it. PS: you can name you function anyway you want. Iv' seen people using "wiper" "wipe" and variations.

How to change the color of the axis, ticks and labels for a plot in matplotlib

As a quick example (using a slightly cleaner method than the potentially duplicate question):

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')

plt.show()

alt text

Alternatively

[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]

String.Replace ignoring case

.Net Core has this method built-in: Replace(String, String, StringComparison) Doc. Now we can simply write: "...".Replace("oldValue", "newValue", StringComparison.OrdinalIgnoreCase)

How can I calculate an md5 checksum of a directory?

Technically you only need to run ls -lR *.py | md5sum. Unless you are worried about someone modifying the files and touching them back to their original dates and never changing the files' sizes, the output from ls should tell you if the file has changed. My unix-foo is weak so you might need some more command line parameters to get the create time and modification time to print. ls will also tell you if permissions on the files have changed (and I'm sure there are switches to turn that off if you don't care about that).

One-liner if statements, how to convert this if-else-statement

return (expression) ? value1 : value2;

If value1 and value2 are actually true and false like in your example, you may as well just

return expression;

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

import 'rxjs/add/operator/map';

&

npm install rxjs@6 rxjs-compat@6 --save

worked for me

How to check if input is numeric in C++

If you already have the string, you can use this function:

bool isNumber( const string& s )
{
  bool hitDecimal=0;
  for( char c : s )
  {
    if( c=='.' && !hitDecimal ) // 2 '.' in string mean invalid
      hitDecimal=1; // first hit here, we forgive and skip
    else if( !isdigit( c ) ) 
      return 0 ; // not ., not 
  }
  return 1 ;
}

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

You can try this to ignore "https":

pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org  [your package..]

How to redirect from one URL to another URL?

Why javascript?

http://www.instant-web-site-tools.com/html-redirect.html

<html>
<meta http-equiv="REFRESH" content="0;url=http://www.URL2.com"> 
</html>

Unless I'm missunderstanding...

HTML5 validation when the input type is not "submit"

You should use form tag enclosing your inputs. And input type submit.
This works.

<form id="testform">
<input type="text" id="example" name="example"  required>
<button type="submit"  onclick="submitform()" id="save">Save</button>
</form>

Since HTML5 Validation works only with submit button you have to keep it there. You can avoid the form submission though when valid by preventing the default action by writing event handler for form.

document.getElementById('testform').onsubmit= function(e){
     e.preventDefault();
}

This will give your validation when invalid and will not submit form when valid.

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

How do I group Windows Form radio buttons?

I like the concept of grouping RadioButtons in WPF. There is a property GroupName that specifies which RadioButton controls are mutually exclusive (http://msdn.microsoft.com/de-de/library/system.windows.controls.radiobutton.aspx).

So I wrote a derived class for WinForms that supports this feature:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.ComponentModel;

namespace Use.your.own
{
    public class AdvancedRadioButton : CheckBox
    {
        public enum Level { Parent, Form };

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the level that specifies which RadioButton controls are affected."),
        DefaultValue(Level.Parent)]
        public Level GroupNameLevel { get; set; }

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the name that specifies which RadioButton controls are mutually exclusive.")]
        public string GroupName { get; set; }

        protected override void OnCheckedChanged(EventArgs e)
        {
            base.OnCheckedChanged(e);

            if (Checked)
            {
                var arbControls = (dynamic)null;
                switch (GroupNameLevel)
                {
                    case Level.Parent:
                        if (this.Parent != null)
                            arbControls = GetAll(this.Parent, typeof(AdvancedRadioButton));
                        break;
                    case Level.Form:
                        Form form = this.FindForm();
                        if (form != null)
                            arbControls = GetAll(this.FindForm(), typeof(AdvancedRadioButton));
                        break;
                }
                if (arbControls != null)
                    foreach (Control control in arbControls)
                        if (control != this &&
                            (control as AdvancedRadioButton).GroupName == this.GroupName)
                            (control as AdvancedRadioButton).Checked = false;
            }
        }

        protected override void OnClick(EventArgs e)
        {
            if (!Checked)
                base.OnClick(e);
        }

        protected override void OnPaint(PaintEventArgs pevent)
        {
            CheckBoxRenderer.DrawParentBackground(pevent.Graphics, pevent.ClipRectangle, this);

            RadioButtonState radioButtonState;
            if (Checked)
            {
                radioButtonState = RadioButtonState.CheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.CheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.CheckedDisabled;
            }
            else
            {
                radioButtonState = RadioButtonState.UncheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.UncheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.UncheckedDisabled;
            }

            Size glyphSize = RadioButtonRenderer.GetGlyphSize(pevent.Graphics, radioButtonState);
            Rectangle rect = pevent.ClipRectangle;
            rect.Width -= glyphSize.Width;
            rect.Location = new Point(rect.Left + glyphSize.Width, rect.Top);

            RadioButtonRenderer.DrawRadioButton(pevent.Graphics, new System.Drawing.Point(0, rect.Height / 2 - glyphSize.Height / 2), rect, this.Text, this.Font, this.Focused, radioButtonState);
        }

        private IEnumerable<Control> GetAll(Control control, Type type)
        {
            var controls = control.Controls.Cast<Control>();

            return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                      .Concat(controls)
                                      .Where(c => c.GetType() == type);
        }
    }
}

Why doesn't JUnit provide assertNotEquals methods?

It's better to use the Hamcrest for negative assertions rather than assertFalse as in the former the test report will show a diff for the assertion failure.

If you use assertFalse, you just get an assertion failure in the report. i.e. lost information on cause of the failure.

SQL Server database backup restore on lower version

No, is not possible to downgrade a database. 10.50.1600 is the SQL Server 2008 R2 version. There is absolutely no way you can restore or attach this database to the SQL Server 2008 instance you are trying to restore on (10.00.1600 is SQL Server 2008). Your only options are:

  • upgrade this instance to SQL Server 2008 R2 or
  • restore the backup you have on a SQL Server 2008 R2 instance, export all the data and import it on a SQL Server 2008 database.

Are HTTPS URLs encrypted?

As the other answers have already pointed out, https "URLs" are indeed encrypted. However, your DNS request/response when resolving the domain name is probably not, and of course, if you were using a browser, your URLs might be recorded too.

What is the difference between a "line feed" and a "carriage return"?

Both of these are primary from the old printing days.

Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r.

Line feed LF signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.

For more sundry details, the mighty wikipedia to the rescue.

How to reset par(mfrow) in R

You can reset the mfrow parameter

par(mfrow=c(1,1))

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

Do you mean that require() is not resolved? You need to either add require.js to your project or enable Node.js Globals predefined library in Settings/Languages and Frameworks/JavaScript/Libraries.

(Edited settings path by @yurik)

In WebStorm 2016.x-2017.x: make sure that the Node.js Core library is enabled in Settings (Preferences) | Languages & Frameworks | Node.js and NPM

In IntelliJ 2018.3.2+ go to Settings (Preferences) | Languages & Frameworks | Node.js and NPM and enable Coding assistance for Node.js

AndroidStudio: Failed to sync Install build tools

enter image description here

Start the project structure( file>structure) You can see: on the left, modules list;

on the right, Properties>Build Tools Version there maybe are more than one modules.

change "Build Tools Version" for every Module.

it works.

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!

Enter image description here

ActionBarActivity cannot resolve a symbol

If the same error occurs in ADT/Eclipse

Add Action Bar Sherlock library in your project.

Now, to remove the "import The import android.support.v7 cannot be resolved" error download a jar file named as android-support-v7-appcompat.jar and add it in your project lib folder.

This will surely removes your both errors.

iPhone - Get Position of UIView within entire UIWindow

For me this code worked best:

private func getCoordinate(_ view: UIView) -> CGPoint {
    var x = view.frame.origin.x
    var y = view.frame.origin.y
    var oldView = view

    while let superView = oldView.superview {
        x += superView.frame.origin.x
        y += superView.frame.origin.y
        if superView.next is UIViewController {
            break //superView is the rootView of a UIViewController
        }
        oldView = superView
    }

    return CGPoint(x: x, y: y)
}

Is there a Mutex in Java?

To ensure that a Semaphore is binary you just need to make sure you pass in the number of permits as 1 when creating the semaphore. The Javadocs have a bit more explanation.

How to integrate SAP Crystal Reports in Visual Studio 2017

I had the same problem and I solved by installing Service pack 22 and it fixed it.

How to unpublish an app in Google Play Developer Console

Click on Store Listing and then click on 'Unpublish App'.

See image for details

Does WhatsApp offer an open API?

  1. is the correct answer. WhatsApp is intentionally a closed system without an API for external access.

There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.

For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).

Map vs Object in JavaScript

An object behaves like a dictionary because Javascript is dynamically typed, allowing you to add or remove properties at any time.

But Map() is much better because it:

  • Provides get, set, has, and delete methods.
  • Accepts any type for the keys instead of just strings.
  • Provides an iterator for easy for-of usage and maintains order of results.
  • Doesn't have edge cases with prototypes and other properties showing up during iteration or copying.
  • Supports millions of items.
  • Is very fast.

If you need a dictionary then you should just use a Map().

However, if you're only using string-based keys and need maximum read performance, then objects might be a better choice. This is because Javascript engines compile objects down to C++ classes in the background. The access path for properties on these classes is very optimized and much faster than a function call for Map().get().

These classes are also cached, so creating a new object with the same exact properties means the engine will reuse an existing background class. Adding or removing a property causes the shape of the class to change and the backing class to be re-compiled, which is why using an object as a dictionary with lots of additions and deletions is very slow, but reads of existing keys without changing the object are very fast.

So if you have a write-once read-heavy workload with string keys then you can use an object as a high-performance dictionary, but for everything else use a Map().

How to get css background color on <tr> tag to span entire row

I prefer to use border-spacing as it allows more flexibility. For instance, you could do

table {
  border-spacing: 0 2px;
}

Which would only collapse the vertical borders and leave the horizontal ones in tact, which is what it sounds like the OP was actually looking for.

Note that border-spacing: 0 is not the same as border-collapse: collapse. You will need to use the latter if you want to add your own border to a tr as seen here.

Laravel 5 Application Key

From the line

'key' => env('APP_KEY', 'SomeRandomString'),

APP_KEY is a global environment variable that is present inside the .env file.

You can replace the application key if you trigger

php artisan key:generate

command. This will always generate the new key.

The output may be like this:


Application key [Idgz1PE3zO9iNc0E3oeH3CHDPX9MzZe3] set successfully.

Application key [base64:uynE8re8ybt2wabaBjqMwQvLczKlDSQJHCepqxmGffE=] set successfully.

Base64 encoding should be the default in Laravel 5.4

Note that when you first create your Laravel application, key:generate is automatically called.

If you change the key be aware that passwords saved with Hash::make() will no longer be valid.

Automated Python to Java translation

Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc

In fact, this is probably pretty easy to knock up in Python.

I worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.

Here's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.

How to get the containing form of an input?

I needed to use element.attr('form') instead of element.form.

I use Firefox on Fedora 12.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

In my case, because I had reinstalled iis, I needed to register iis with dot net 4 using this command:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

redirect COPY of stdout to log file from within bash script itself

Solution for busybox, macOS bash, and non-bash shells

The accepted answer is certainly the best choice for bash. I'm working in a Busybox environment without access to bash, and it does not understand the exec > >(tee log.txt) syntax. It also does not do exec >$PIPE properly, trying to create an ordinary file with the same name as the named pipe, which fails and hangs.

Hopefully this would be useful to someone else who doesn't have bash.

Also, for anyone using a named pipe, it is safe to rm $PIPE, because that unlinks the pipe from the VFS, but the processes that use it still maintain a reference count on it until they are finished.

Note the use of $* is not necessarily safe.

#!/bin/sh

if [ "$SELF_LOGGING" != "1" ]
then
    # The parent process will enter this branch and set up logging

    # Create a named piped for logging the child's output
    PIPE=tmp.fifo
    mkfifo $PIPE

    # Launch the child process with stdout redirected to the named pipe
    SELF_LOGGING=1 sh $0 $* >$PIPE &

    # Save PID of child process
    PID=$!

    # Launch tee in a separate process
    tee logfile <$PIPE &

    # Unlink $PIPE because the parent process no longer needs it
    rm $PIPE    

    # Wait for child process, which is running the rest of this script
    wait $PID

    # Return the error code from the child process
    exit $?
fi

# The rest of the script goes here

Fitting a Normal distribution to 1D data

Here you are not fitting a normal distribution. Replacing sns.distplot(data) by sns.distplot(data, fit=norm, kde=False) should do the trick.

Adding a column to a data.frame

Easily: Your data frame is A

b <- A[,1]
b <- b==1
b <- cumsum(b)

Then you get the column b.

Testing if value is a function

You could simply use the typeof operator along with a ternary operator for short:

onsubmit="return typeof valid =='function' ? valid() : true;"

If it is a function we call it and return it's return value, otherwise just return true

Edit:

I'm not quite sure what you really want to do, but I'll try to explain what might be happening.

When you declare your onsubmit code within your html, it gets turned into a function and thus its callable from the JavaScript "world". That means that those two methods are equivalent:

HTML: <form onsubmit="return valid();" />
JavaScript: myForm.onsubmit = function() { return valid(); };

These two will be both functions and both will be callable. You can test any of those using the typeof operator which should yeld the same result: "function".

Now if you assign a string to the "onsubmit" property via JavaScript, it will remain a string, hence not callable. Notice that if you apply the typeof operator against it, you'll get "string" instead of "function".

I hope this might clarify a few things. Then again, if you want to know if such property (or any identifier for the matter) is a function and callable, the typeof operator should do the trick. Although I'm not sure if it works properly across multiple frames.

Cheers

How can I explicitly free memory in Python?

You can't explicitly free memory. What you need to do is to make sure you don't keep references to objects. They will then be garbage collected, freeing the memory.

In your case, when you need large lists, you typically need to reorganize the code, typically using generators/iterators instead. That way you don't need to have the large lists in memory at all.

http://www.prasannatech.net/2009/07/introduction-python-generators.html

Joining 2 SQL SELECT result sets into one

Use a FULL OUTER JOIN:

select 
   a.col_a,
   a.col_b,
   b.col_c
from
   (select col_a,col_bfrom tab1) a
join 
   (select col_a,col_cfrom tab2) b 
on a.col_a= b.col_a

How do I save and restore multiple variables in python?

You should look at the shelve and pickle modules. If you need to store a lot of data it may be better to use a database

Is it possible to decrypt MD5 hashes?

MD5 is a cryptographic (one-way) hash function, so there is no direct way to decode it. The entire purpose of a cryptographic hash function is that you can't undo it.

One thing you can do is a brute-force strategy, where you guess what was hashed, then hash it with the same function and see if it matches. Unless the hashed data is very easy to guess, it could take a long time though.

Type converting slices of interfaces

In case you need more shorting your code, you can creating new type for helper

type Strings []string

func (ss Strings) ToInterfaceSlice() []interface{} {
    iface := make([]interface{}, len(ss))
    for i := range ss {
        iface[i] = ss[i]
    }
    return iface
}

then

a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()

Java socket API: How to tell if a connection has been closed?

Thats how I handle it

 while(true) {
        if((receiveMessage = receiveRead.readLine()) != null ) {  

        System.out.println("first message same :"+receiveMessage);
        System.out.println(receiveMessage);      

        }
        else if(receiveRead.readLine()==null)
        {

        System.out.println("Client has disconected: "+sock.isClosed()); 
        System.exit(1);
         }    } 

if the result.code == null