Programs & Examples On #G360

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

if( [txtMobile.text length] == 0 )
{
    [Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}

How do you write multiline strings in Go?

For me this is what I use if adding \n is not a problem.

fmt.Sprintf("Hello World\nHow are you doing today\nHope all is well with your go\nAnd code")

Else you can use the raw string

multiline := `Hello Brothers and sisters of the Code
              The grail needs us.
             `

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

Tip #2

Can't you use the classical 2> redirection operator.

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL
if(!$?){
   'foo'
}

I don't like errors so I avoid them at all costs.

Count Rows in Doctrine QueryBuilder

For people who are using only Doctrine DBAL and not the Doctrine ORM, they will not be able to access the getQuery() method because it doesn't exists. They need to do something like the following.

$qb = new QueryBuilder($conn);
$count = $qb->select("count(id)")->from($tableName)->execute()->fetchColumn(0);

pass JSON to HTTP POST Request

you can pass the json object as the body(third argument) of the fetch request.

Composer killed while updating

Increase the memory limit for composer

php -d memory_limit=4G /usr/local/bin/composer update

User Authentication in ASP.NET Web API

I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.

The client side code (CoffeeScript) to get the token is:

getAuthenticationToken = (username, password) ->
    dataToSend = "username=" + username + "&password=" + password
    dataToSend += "&grant_type=password"
    $.post("/token", dataToSend).success saveAccessToken

If successful the following is called, which saves the authentication token locally:

saveAccessToken = (response) ->
    window.authenticationToken = response.access_token

Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:

{ "Authorization": "Bearer " + window.authenticationToken }

SQL Inner join 2 tables with multiple column conditions and update

You should join T1 and T2 tables using sql joins in order to analyze from two tables. Link for learn joins : https://www.w3schools.com/sql/sql_join.asp

HTTP response header content disposition for attachments

Try changing your Content Type (media type) to application/x-download and your Content-Disposition to: attachment;filename=" + fileName;

response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);

php how to go one level up on dirname(__FILE__)

dirname(__DIR__,level);
dirname(__DIR__,1);

level is how many times will you go back to the folder

send bold & italic text on telegram bot with html

To Send bold,italic,fixed width code you can use this :

# Sending a HTML formatted message
bot.send_message(chat_id=@yourchannelname, 
             text="*boldtext* _italictext_ `fixed width font` [link]   (http://google.com).", 
             parse_mode=telegram.ParseMode.MARKDOWN)

make sure you have enabled the bot as your admin .Then only it can send message

How do I run .sh or .bat files from Terminal?

Type in

chmod 755 scriptname.sh

In other words, give yourself permission to run the file. I'm guessing you only have r/w permission on it.

In PANDAS, how to get the index of a known value?

To get the index by value, simply add .index[0] to the end of a query. This will return the index of the first row of the result...

So, applied to your dataframe:

In [1]: a[a['c2'] == 1].index[0]     In [2]: a[a['c1'] > 7].index[0]   
Out[1]: 0                            Out[2]: 4                         

Where the query returns more than one row, the additional index results can be accessed by specifying the desired index, e.g. .index[n]

In [3]: a[a['c2'] >= 7].index[1]     In [4]: a[(a['c2'] > 1) & (a['c1'] < 8)].index[2]  
Out[3]: 4                            Out[4]: 3 

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

I had same problem in eclipse windows that I couldn't added dependant .class files from the JNI. In order resolve the same, I ported all the code to NetBeans IDE.

Can not add all the classes files from the JNI/JNA folder in Eclipse (JAVA, Windows 7)

How to Apply Mask to Image in OpenCV?

You can use the mask to copy only the region of interest of an original image to a destination one:

cvCopy(origImage,destImage,mask);

where mask should be an 8-bit single channel array.

See more at the OpenCV docs

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Where is svcutil.exe in Windows 7?

To find any file location

  1. In windows start menu Search box
  2. type in svcutil.exe
  3. Wait for results to populate
  4. Right click on svcutil.exe and Select 'Open file location'
  5. Copy Windows explorer path

How do I Alter Table Column datatype on more than 1 column?

ALTER TABLE can do multiple table alterations in one statement, but MODIFY COLUMN can only work on one column at a time, so you need to specify MODIFY COLUMN for each column you want to change:

ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100);

Also, note this warning from the manual:

When you use CHANGE or MODIFY, column_definition must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.

This version of the application is not configured for billing through Google Play

The problem also occurs, when you have added an in-app purchase after you uploaded the apk, but you have not published the application in the play store (alpha, beta and production).

Which basically means, that you have to add the In-App purchase AFTER you have published the apk in the Play store (alpha, beta and production). Otherwise you wont be able to purchase or query for the In-App purchase.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

It's very easy to get memory leaks in a PHP script - especially if you use abstraction, such as an ORM. Try using Xdebug to profile your script and find out where all that memory went.

How to determine the current language of a wordpress page when using polylang?

Simple:

if(pll_current_language() == 'en'){
   //do your work here
}

WPF Button with Image

Most simple approach would be using the Image tag.

<Button Name="btn" Width="26" Height="26" Click="btnClick"> 
   <Image Source="Resource/btn-icon.png"/>
</Button>

Suppose your image file is added in Resource folder

Get element type with jQuery

Use Nodename over tagName :

nodeName contains all functionalities of tagName, plus a few more. Therefore nodeName is always the better choice.

see DOM Core

Creating dummy variables in pandas for python

The following code returns dataframe with the 'Category' column replaced by categorical columns:

df_with_dummies = pd.get_dummies(df, prefix='Category_', columns=['Category'])

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html

JavaScript hashmap equivalent

This looks like a pretty robust solution: https://github.com/flesler/hashmap

It will even work well for functions and objects that look identical. The only hack it uses is adding an obscure member to an object to identify it. If your program doesn't overwrite that obscure variable (it's something like hashid), you're golden.

How to hide the soft keyboard from inside a fragment?

Use this:

Button loginBtn = view.findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
      InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
   }
});

How do I create a SQL table under a different schema?

The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.

USE [DBName] 
GO 
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema] 
GO

Javascript date regex DD/MM/YYYY

Try using this..

[0-9]{2}[/][0-9]{2}[/][0-9]{4}$

this should work with this pattern DD/DD/DDDD where D is any digit (0-9)

How to handle anchor hash linking in AngularJS

Based on @Stoyan I came up with the following solution:

app.run(function($location, $anchorScroll){
    var uri = window.location.href;

    if(uri.length >= 4){

        var parts = uri.split('#!#');
        if(parts.length > 1){
            var anchor = parts[parts.length -1];
            $location.hash(anchor);
            $anchorScroll();
        }
    }
});

Auto start node.js server on boot

I know there are multiple ways to achieve this as per solutions shared above. I haven't tried all of them but some third party services lack clarity around what are all tasks being run in the background. I have achieved this through a powershell script similar to the one mentioned as windows batch file. I have scheduled it using Windows Tasks Scheduler to run every minute. This has been quite efficient and transparent so far. The advantage I have here is that I am checking the process explicitly before starting it again. This wouldn't cause much overhead to the CPU on the server. Also you don't have to explicitly place the file into the startup folders.

function CheckNodeService ()
{

$node = Get-Process node -ErrorAction SilentlyContinue

if($node)
{
    echo 'Node Running'
}
else
{
    echo 'Node not Running'
    Start-Process "C:\Program Files\nodejs\node.exe" -ArgumentList "app.js" -WorkingDirectory "E:\MyApplication"
    echo 'Node started'

}
}

CheckNodeService

Detect when an HTML5 video finishes

Here is a simple approach which triggers when the video ends.

<html>
<body>

    <video id="myVideo" controls="controls">
        <source src="video.mp4" type="video/mp4">
        etc ...
    </video>

</body>
<script type='text/javascript'>

    document.getElementById('myVideo').addEventListener('ended', function(e) {

        alert('The End');

    })

</script>
</html> 

In the 'EventListener' line substitute the word 'ended' with 'pause' or 'play' to capture those events as well.

Is there any method to get the URL without query string?

location.toString().replace(location.search, "")

Want to move a particular div to right

You can use float on that particular div, e.g.

<div style="float:right;">

Float the div you want more space to have to the left as well:

<div style="float:left;">

If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

<div style="position:absolute; left:-500px; top:30px;"> 

etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

Import pfx file into particular certificate store from command line

Anchoring my findings here for future readers.

Import certificate to Trusted Root Certification Authorities on Local Machine:

CERTUTIL -addstore -enterprise -f -v root "somCertificat.cer"

Import pfx to Personal on local machine

CERTUTIL -f -p somePassword -importpfx "somePfx.pfx"

Import pfx to Trusted People on local machine - Link to importpfx.exe

importpfx.exe -f "somePfx.pfx" -p "somePassword" -t MACHINE -s "TRUSTEDPEOPLE"

Import certificate to Trusted People on local machine

Certutil -addstore -f "TRUSTEDPEOPLE" "someCertificate.cer"

Using a .php file to generate a MySQL dump

<?php
    $toDay = date('d-m-Y');

    $dbhost =   "localhost";
    $dbuser =   "YOUR DB USER";
    $dbpass =   "USER PASSWORD";
    $dbname =   "DB NAME";

    exec("mysqldump --user=$dbuser --password='$dbpass' --host=$dbhost $dbname > /home/....../public_html/".$toDay."_DB.sql");


?>

CSS rounded corners in IE8

Rounded corners in IE8

Internet Explorer 8 (and earlier versions) doesn't support rounded corners, however there are few other solutions you may consider:

  • Use Rounded Corners Images instead (this generator is a good resource)

  • Use a jQuery Corner plugin from here

  • Use a very good script called CSS3 PIE from here (Pro's & Con's here)

  • Checkout CSS Juice from here

  • Another good script is IE-CSS3 from here

Even though CSS PIE is the most popular solution, I'm suggesting you to review all other solutions and choose what works best for your needs.

Hope it was useful. Good Luck!

How do you set your pythonpath in an already-created virtualenv?

  1. Initialize your virtualenv
cd venv

source bin/activate
  1. Just set or change your python path by entering command following:
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
  1. for checking python path enter in python:
   python

      \>\> import sys

      \>\> sys.path

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

Just set the memory_limit specifying the full route of your composer.phar file and update, in my case with the command:

php -d memory_limit=-1 C:/wamp64/composer.phar update

How to create table using select query in SQL Server?

An example statement that uses a sub-select :

select * into MyNewTable
from
(
select 
  * 
from 
[SomeOtherTablename]
where 
  EventStartDatetime >= '01/JAN/2018' 
)
) mysourcedata
;

note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.

The database should reply with a message like: (9999 row(s) affected)

String concatenation: concat() vs "+" operator

I ran a similar test as @marcio but with the following loop instead:

String c = a;
for (long i = 0; i < 100000L; i++) {
    c = c.concat(b); // make sure javac cannot skip the loop
    // using c += b for the alternative
}

Just for good measure, I threw in StringBuilder.append() as well. Each test was run 10 times, with 100k reps for each run. Here are the results:

  • StringBuilder wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.
  • a += b takes about 40000ms (40s) for each run.
  • concat only requires 10000ms (10s) per run.

I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect a += b spends much of the time creating new objects of StringBuilder and then converting them back to String.

ALTER DATABASE failed because a lock could not be placed on database

I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn't able to use any of the alter database commands because an exclusive lock couldn't be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.

Stacking DIVs on top of each other?

Position the outer div however you want, then position the inner divs using absolute. They'll all stack up.

_x000D_
_x000D_
.inner {_x000D_
  position: absolute;_x000D_
}
_x000D_
<div class="outer">_x000D_
   <div class="inner">1</div>_x000D_
   <div class="inner">2</div>_x000D_
   <div class="inner">3</div>_x000D_
   <div class="inner">4</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you run a command as an administrator from the Windows command line?

I would set up a shortcut, either to CMD or to the thing you want to run, then set the properties of the shortcut to require admin, and then run the shortcut from your batch file. I haven't tested to confirm it will respect the properties, but I think it's more elegant and doesn't require activating the Administrator account.

Also if you do it as a scheduled task (which can be set up from code) there is an option to run it elevated there.

How do you clone an Array of Objects in Javascript?

I use the new ECMAScript 6 Object.assign method :

let oldObject = [1,3,5,"test"];
let newObject = Object.assign({}, oldObject);

the first argument of this method is the array to be update, we pass an empty object because we want to have a new object.

we can also use this syntax, which is the same but shorter :

let newObject = [...oldObject];

How can I clone a private GitLab repository?

If you are using Windows,

  1. make a folder and open git bash from there

  2. in the git bash,

    git clone [email protected]:Example/projectName.git

How to perform keystroke inside powershell?

function Do-SendKeys {
    param (
        $SENDKEYS,
        $WINDOWTITLE
    )
    $wshell = New-Object -ComObject wscript.shell;
    IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
    Sleep 1
    IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'

How can I format decimal property to currency?

You can create an extension method. I find this to be a good practice as you may need to lock down a currency display regardless of the browser setting. For instance you may want to display $5,000.00 always instead of 5 000,00 $ (#CanadaProblems)

public static class DecimalExtensions
{
    public static string ToCurrency(this decimal decimalValue)
    {
        return $"{decimalValue:C}";
    }
}

How do I concatenate two strings in C?

Without GNU extension:

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

int main(void) {
    const char str1[] = "First";
    const char str2[] = "Second";
    char *res;

    res = malloc(strlen(str1) + strlen(str2) + 1);
    if (!res) {
        fprintf(stderr, "malloc() failed: insufficient memory!\n");
        return EXIT_FAILURE;
    }

    strcpy(res, str1);
    strcat(res, str2);

    printf("Result: '%s'\n", res);
    free(res);
    return EXIT_SUCCESS;
}

Alternatively with GNU extension:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    const char str1[] = "First";
    const char str2[] = "Second";
    char *res;

    if (-1 == asprintf(&res, "%s%s", str1, str2)) {
        fprintf(stderr, "asprintf() failed: insufficient memory!\n");
        return EXIT_FAILURE;
    }

    printf("Result: '%s'\n", res);
    free(res);
    return EXIT_SUCCESS;
}

See malloc, free and asprintf for more details.

Is there a simple JavaScript slider?

The code below should be enough to get you started. Tested in Opera, IE and Chrome.

<script>
var l=0;
function f(i){
im = 'i' + l;
d=document.all[im];
d.height=99;
document.all.f1.t1.value=i;
im = 'i' + i;
d=document.all[im];
d.height=1;
l=i;
}
</script>
<center>
<form id='f1'>
<input type=text value=0 id='t1'>
</form>
<script>
for (i=0;i<=50;i++)
 {
 s = "<img src='j.jpg' height=99 width=9 onMouseOver='f(" + i + ")' id='i" + i + "'>";
 document.write(s);
 }
</script>

Unsuccessful append to an empty NumPy array

I might understand the question incorrectly, but if you want to declare an array of a certain shape but with nothing inside, the following might be helpful:

Initialise empty array:

>>> a = np.zeros((0,3)) #or np.empty((0,3)) or np.array([]).reshape(0,3)
>>> a
array([], shape=(0, 3), dtype=float64)

Now you can use this array to append rows of similar shape to it. Remember that a numpy array is immutable, so a new array is created for each iteration:

>>> for i in range(3):
...     a = np.vstack([a, [i,i,i]])
...
>>> a
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.]])

np.vstack and np.hstack is the most common method for combining numpy arrays, but coming from Matlab I prefer np.r_ and np.c_:

Concatenate 1d:

>>> a = np.zeros(0)
>>> for i in range(3):
...     a = np.r_[a, [i, i, i]]
...
>>> a
array([ 0.,  0.,  0.,  1.,  1.,  1.,  2.,  2.,  2.])

Concatenate rows:

>>> a = np.zeros((0,3))
>>> for i in range(3):
...     a = np.r_[a, [[i,i,i]]]
...
>>> a
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.]])

Concatenate columns:

>>> a = np.zeros((3,0))
>>> for i in range(3):
...     a = np.c_[a, [[i],[i],[i]]]
...
>>> a
array([[ 0.,  1.,  2.],
       [ 0.,  1.,  2.],
       [ 0.,  1.,  2.]])

Byte Array to Hex String

Or, if you are a fan of functional programming:

>>> a = [133, 53, 234, 241]
>>> "".join(map(lambda b: format(b, "02x"), a))
8535eaf1
>>>

Python pandas Filtering out nan from a data selection of a column of strings

Simplest of all solutions:

filtered_df = df[df['name'].notnull()]

Thus, it filters out only rows that doesn't have NaN values in 'name' column.

For multiple columns:

filtered_df = df[df[['name', 'country', 'region']].notnull().all(1)]

Transaction marked as rollback only: How do I find the cause

apply the below code in productRepository

@Query("update Product set prodName=:name where prodId=:id ") @Transactional @Modifying int updateMyData(@Param("name")String name, @Param("id") Integer id);

while in junit test apply below code

@Test
public void updateData()
{
  int i=productRepository.updateMyData("Iphone",102);

  System.out.println("successfully updated ... ");
  assertTrue(i!=0);

}

it is working fine for my code

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

Should I use the Reply-To header when sending emails as a service to others?

After reading all of this, I might just embed a hyperlink in the email body like this:

To reply to this email, click here <a href="mailto:...">[email protected]</a>

How to import multiple csv files in a single load?

Using Spark 2.0+, we can load multiple CSV files from different directories using df = spark.read.csv(['directory_1','directory_2','directory_3'.....], header=True). For more information, refer the documentation here

possible EventEmitter memory leak detected

By default, a maximum of 10 listeners can be registered for any single event.

If it's your code, you can specify maxListeners via:

const emitter = new EventEmitter()
emitter.setMaxListeners(100)
// or 0 to turn off the limit
emitter.setMaxListeners(0)

But if it's not your code you can use the trick to increase the default limit globally:

require('events').EventEmitter.prototype._maxListeners = 100;

Of course you can turn off the limits but be careful:

// turn off limits by default (BE CAREFUL)
require('events').EventEmitter.prototype._maxListeners = 0;

BTW. The code should be at the very beginning of the app.

ADD: Since node 0.11 this code also works to change the default limit:

require('events').EventEmitter.defaultMaxListeners = 0

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

Here's how you can mock your FileConnection

Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
                                                           MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
              .Throws(new IOException());

Then instantiate your Transfer class and use the mock in your method call

Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);

Update:

First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.

Since you are setting those properties using another dependency, I would write it like this:

public class Transfer
{
    public Transfer(IInternalConfig internalConfig)
    {
        source = internalConfig.GetFileConnection("source");
        destination = internalConfig.GetFileConnection("destination");
    }

    //you should consider making these private or protected fields
    public virtual IFileConnection source { get; set; }
    public virtual IFileConnection destination { get; set; }

    public virtual void GetFile(IFileConnection connection, 
        string remoteFilename, string localFilename)
    {
        connection.Get(remoteFilename, localFilename);
    }

    public virtual void PutFile(IFileConnection connection, 
        string localFilename, string remoteFilename)
    {
        connection.Get(remoteFilename, localFilename);
    }

    public virtual void TransferFiles(string sourceName, string destName)
    {
        var tempName = Path.GetTempFileName();
        GetFile(source, sourceName, tempName);
        PutFile(destination, tempName, destName);
    }
}

This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.

How to delete an element from a Slice in Golang

here is the playground example with pointers in it. https://play.golang.org/p/uNpTKeCt0sH

package main

import (
    "fmt"
)

type t struct {
    a int
    b string
}

func (tt *t) String() string{
    return fmt.Sprintf("[%d %s]", tt.a, tt.b)
}

func remove(slice []*t, i int) []*t {
  copy(slice[i:], slice[i+1:])
  return slice[:len(slice)-1]
}

func main() {
    a := []*t{&t{1, "a"}, &t{2, "b"}, &t{3, "c"}, &t{4, "d"}, &t{5, "e"}, &t{6, "f"}}
    k := a[3]
    a = remove(a, 3)
    fmt.Printf("%v  ||  %v", a, k)
}

When should I use Kruskal as opposed to Prim (and vice versa)?

In kruskal Algorithm we have number of edges and number of vertices on a given graph but on each edge we have some value or weight on behalf of which we can prepare a new graph which must be not cyclic or not close from any side For Example

graph like this _____________ | | | | | | |__________| | Give name to any vertex a,b,c,d,e,f .

printf and long double

From the printf manpage:

l (ell) A following integer conversion corresponds to a long int or unsigned long int argument, or a following n conversion corresponds to a pointer to a long int argument, or a following c conversion corresponds to a wint_t argument, or a following s conversion corresponds to a pointer to wchar_t argument.

and

L A following a, A, e, E, f, F, g, or G conversion corresponds to a long double argument. (C99 allows %LF, but SUSv2 does not.)

So, you want %Le , not %le

Edit: Some further investigation seems to indicate that Mingw uses the MSVC/win32 runtime(for stuff like printf) - which maps long double to double. So mixing a compiler (like gcc) that provides a native long double with a runtime that does not seems to .. be a mess.

Redirect non-www to www in .htaccess

RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
RewriteRule (.*) http://www.domain.com/$1 [L,R=301]

This will redirect your domain which is not started with WWW It is not redirect your all sub domain.

It is useful.

Finding smallest value in an array most efficiently

The stl contains a bunch of methods that should be used dependent to the problem.

std::find
std::find_if
std::count
std::find
std::binary_search
std::equal_range
std::lower_bound
std::upper_bound

Now it contains on your data what algorithm to use. This Artikel contains a perfect table to help choosing the right algorithm.


In the special case where min max should be determined and you are using std::vector or ???* array

std::min_element
std::max_element

can be used.

How does the @property decorator work in Python?

The best explanation can be found here: Python @Property Explained – How to Use and When? (Full Examples) by Selva Prabhakaran | Posted on November 5, 2018

It helped me understand WHY not only HOW.

https://www.machinelearningplus.com/python/python-property/

How to add form validation pattern in Angular 2?

You could build your form using FormBuilder as it let you more flexible way to configure form.

export class MyComp {
  form: ControlGroup;

  constructor(@Inject()fb: FormBuilder) {  
    this.form = fb.group({  
      foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]  
    });  
  }

Then in your template :

<input type="text" ngControl="foo" />
<div *ngIf="!form.foo.valid">Please correct foo entry !</div> 

You can also customize ng-invalid CSS class.

As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.

export class MyValidators {
  static regex(pattern: string): Function {
    return (control: Control): {[key: string]: any} => {
      return control.value.match(pattern) ? null : {pattern: true};
    };
  }
}

Hope that it help you.

Change <br> height using CSS

Take a look at the line-height property. Trying to style the <br> tag is not the answer.

Example:

<p id="single-spaced">
    This<br>
    text<br>
    is<br>
    single-spaced.
</p>
<p id="double-spaced" style="line-height: 200%;">
    This<br>
    text<br>
    is<br>
    double-spaced.
</p>

How can I declare dynamic String array in Java

no, there is no way to make array length dynamic in java. you can use ArrayList or other List implementations instead.

difference between @size(max = value ) and @min(value) @max(value)

From the documentation I get the impression that in your example it would be intended to use:

@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)

Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. Supported data types:

BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

grep from tar.gz without extracting [faster one]

Both the below options work well.

$ zgrep -ai 'CDF_FEED' FeedService.log.1.05-31-2019-150003.tar.gz | more
2019-05-30 19:20:14.568 ERROR 281 --- [http-nio-8007-exec-360] DrupalFeedService  : CDF_FEED_SERVICE::CLASSIFICATION_ERROR:408: Classification failed even after maximum retries for url : abcd.html

$ zcat FeedService.log.1.05-31-2019-150003.tar.gz | grep -ai 'CDF_FEED'
2019-05-30 19:20:14.568 ERROR 281 --- [http-nio-8007-exec-360] DrupalFeedService  : CDF_FEED_SERVICE::CLASSIFICATION_ERROR:408: Classification failed even after maximum retries for url : abcd.html

Change the Bootstrap Modal effect

A riot.js solution:

My riot.js Example nests the animated-modal tag inside an order profile tag.

Note, this assumes jquery and riot.js is loaded before.

animated-modal tag contents:

<a id='{ opts.el }' href="" class='pull-right'>edit</a>

    <div class="modal animated" id="{ opts.el }-modal" tabindex="-1" role="dialog" aria-labelledby="animatedModal">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <button onclick={ cancelForm } id='{ opts.el }-cancel-1' type="button" class="close" ><span>&times;</span></button>
            <h4 class="modal-title" id="animatedModal">{ opts.title }</h4>
          </div>
          <div class="modal-body">
              <yield/>
          </div>
          <div class="modal-footer">
            <button onclick={ cancelForm } id='{ opts.el }-cancel-2' onclick={ cancelForm } type="button" class="btn btn-default">Close</button>
            <button onclick={ saveForm } type="button" class="btn btn-primary">Save changes</button>
          </div>

        </div>
      </div>
    </div>

    <script>
    var self = this
    self.modalBtn = `#${opts.el}`
    self.modal = `#${opts.el}-modal`
    self.animateInClass = opts.animatein || 'fadeIn'
    self.animateOutClass = opts.animateout || 'fadeOut'
    self.closeModalBtn = `#${ opts.el }-cancel-1, #${ opts.el }-cancel-2`
    self.animationsStr = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend'

    this.on('mount',function(){
        self.initModal()
        self.update()
    })

    this.initModal = function(){
        modal = $(self.modal)
        modalBtn = $(self.modalBtn)
        closeModalBtn = `#${ opts.el }-cancel-1`

        modalBtn.click(function(){
            $(self.modal).addClass(self.animateInClass)
            $(self.modal).modal('show') 
        })

        $(self.modal).on('show.bs.modal',function(){
            $(self.closeModalBtn).one('click',function(){
                $(self.modal).removeClass(self.animateInClass).addClass(self.animateOutClass)

                $(self.modal).on(self.animationsStr,function(){
                    $(self.modal).modal('hide') 
                })
            })
        })

        $(self.modal).on('hidden.bs.modal',function(evt){
            $(self.modal).removeClass(self.animateOutClass)
            $(self.modal).off(self.animationsStr)
            $(self.closeModalBtn).off('click')
        })
    }

    this.cancelForm = function(e){
        this.parent.cancelForm()
    }

    this.showEdit = function(e){
        this.parent.showEdit()
    }

    this.saveForm = function(e){
        this.parent.saveForm()
    }

    dashboard_v2.bus.on('closeModal',function(){
        try{
            $(`#${ opts.el }-cancel-1`).trigger('click')
        }catch(e){}

    })
</script>

And the Profile Tag to nest in:

profile tag contents:

<div class="row">
        <div class="col-md-12">
            <div class="eshop-product-body">

                <animated-modal>
                    title='Order Edit'
                    el='order-modal-1'>

                    <div class="row">
                        <div class="col-md-6 col-md-offset-3">
                            <form id='profile-form'>
                                <div class="form-group">
                                    <label>Organization</label>
                                    <input id='organization' type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
                                </div>

                                <div class="form-group">
                                    <label>Contact</label>
                                    <input id='contact' type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
                                </div>

                                <div class="form-group">
                                    <label>Phone</label>
                                    <input id='phone' type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
                                </div>

                                <div class="form-group">
                                    <label>Email</label>
                                    <input id='email' type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
                                </div>
                            </form>
                        </div>
                    </div>

                </animated-modal>

                <h3>Profile</h3>

                <ul class='profile-list'>
                    <li>Organization: { opts.data.profile.organization }</li>
                    <li>Contact: { opts.data.profile.contact_full_name }</li>
                    <li>Phone: { opts.data.profile.phone_number }</li>
                    <li>Email: { opts.data.profile.email }</li>
                </ul>
            </div>
        </div>
    </div>

    <script>
        var self = this     

        this.on('mount',function(){

        })

        this.cancelForm = function(e){

        }

        this.showEdit = function(e){

        }

        this.saveForm = function(e){

        }
    </script>

jQuery exclude elements with certain class in selector

To add some info that helped me today, a jQuery object/this can also be passed in to the .not() selector.

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $(".navitem").click(function(){_x000D_
        $(".navitem").removeClass("active");_x000D_
        $(".navitem").not($(this)).addClass("active");_x000D_
    });_x000D_
});
_x000D_
.navitem_x000D_
{_x000D_
    width: 100px;_x000D_
    background: red;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    position: relative;_x000D_
    text-align: center;_x000D_
}_x000D_
.navitem.active_x000D_
{_x000D_
    background:green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="navitem">Home</div>_x000D_
<div class="navitem">About</div>_x000D_
<div class="navitem">Pricing</div>
_x000D_
_x000D_
_x000D_

The above example can be simplified, but wanted to show the usage of this in the not() selector.

How to check type of variable in Java?

a.getClass().getName() - will give you the datatype of the actual object referred to by a, but not the datatype that the variable a was originally declared as or subsequently cast to.

boolean b = a instanceof String - will give you whether or not the actual object referred to by a is an instance of a specific class. Again, the datatype that the variable a was originally declared as or subsequently cast to has no bearing on the result of the instanceof operator.

I took this information from: How do you know a variable type in java?

This can happen. I'm trying to parse a String into an int and I'd like to know if my Integer.parseInt(s.substring(a, b)) is kicking out an int or garbage before I try to sum it up.

By the way, this is known as Reflection. Here's some more information on the subject: http://docs.oracle.com/javase/tutorial/reflect/

jquery select element by xpath

First create an xpath selector function.

function _x(STR_XPATH) {
    var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
    var xnodes = [];
    var xres;
    while (xres = xresult.iterateNext()) {
        xnodes.push(xres);
    }

    return xnodes;
}

To use the xpath selector with jquery, you can do like this:

$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');

Hope this can help.

docker container ssl certificates

You can use relative path to mount the volume to container:

docker run -v `pwd`/certs:/container/path/to/certs ...

Note the back tick on the pwd which give you the present working directory. It assumes you have the certs folder in current directory that the docker run is executed. Kinda great for local development and keep the certs folder visible to your project.

Throw HttpResponseException or return Request.CreateErrorResponse?

If you are not returning HttpResponseMessage and instead are returning entity/model classes directly, an approach which I have found useful is to add the following utility function to my controller

private void ThrowResponseException(HttpStatusCode statusCode, string message)
{
    var errorResponse = Request.CreateErrorResponse(statusCode, message);
    throw new HttpResponseException(errorResponse);
}

and simply call it with the appropriate status code and message

UIButton action in table view cell

class TableViewCell: UITableViewCell {
   @IBOutlet weak var oneButton: UIButton!
   @IBOutlet weak var twoButton: UIButton!
}


class TableViewController: UITableViewController {

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell

    cell.oneButton.addTarget(self, action: #selector(TableViewController.oneTapped(_:)), for: .touchUpInside)
    cell.twoButton.addTarget(self, action: #selector(TableViewController.twoTapped(_:)), for: .touchUpInside)

    return cell
}

func oneTapped(_ sender: Any?) {

    print("Tapped")
}

func twoTapped(_ sender: Any?) {

    print("Tapped")
   }
}

How to get changes from another branch

You are almost there :)

All that is left is to

git checkout featurex
git merge our-team

This will merge our-team into featurex.

The above assumes you have already committed/stashed your changes in featurex, if that is not the case you will need to do this first.

Consider defining a bean of type 'service' in your configuration [Spring boot]

Even after doing all the method suggested, i was getting the same error. After trying hard, i got to know that hibernate's maven dependency was added in my pom.xml, as i removed it, application started successfully.

I removed this dependency:

<dependency> <groupId>org.hibernate.javax.persistence</groupId>
 <artifactId>hibernate-jpa-2.0-api</artifactId>
             <version>1.0.1.Final</version>
         </dependency>

Java method to swap primitives

You can't create a method swap, so that after calling swap(x,y) the values of x and y will be swapped. You could create such a method for mutable classes by swapping their contents¹, but this would not change their object identity and you could not define a general method for this.

You can however write a method that swaps two items in an array or list if that's what you want.

¹ For example you could create a swap method that takes two lists and after executing the method, list x will have the previous contents of list y and list y will have the previous contents of list x.

List of phone number country codes

Country Data NPM Package.

If you're using node or NPM in general, you should take a look at the thorough Country Data package.

Since you're trying to get the Country from a phone number, you face two major obstacles:

  1. Parsing the phone number to get the Country code.

  2. Handling situations where a Country code can belong to more than one Country. e.g. Country Code of "+1" belongs to the United States and Canada.

However, the Country Data package will allow you to do something like this:

var CountryDataLookup = require('country-data').lookup;

lookup.countries({countryCallingCodes: '+1'})

And these are the returning objects:

[ { alpha2: 'CA',
    alpha3: 'CAN',
    countryCallingCodes: [ '+1' ],
    currencies: [ 'CAD' ],
    ioc: 'CAN',
    languages: [ 'eng', 'fra' ],
    name: 'Canada',
    status: 'assigned' },
  { alpha2: 'UM',
    alpha3: 'UMI',
    countryCallingCodes: [ '+1' ],
    currencies: [ 'USD' ],
    ioc: '',
    languages: [ 'eng' ],
    name: 'United States Minor Outlying Islands',
    status: 'assigned' },
  { alpha2: 'US',
    alpha3: 'USA',
    countryCallingCodes: [ '+1' ],
    currencies: [ 'USD' ],
    ioc: 'USA',
    languages: [ 'eng' ],
    name: 'United States',
    status: 'assigned' } ]

Casting LinkedHashMap to Complex Object

You can use ObjectMapper.convertValue(), either value by value or even for the whole list. But you need to know the type to convert to:

POJO pojo = mapper.convertValue(singleObject, POJO.class);
// or:
List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { });

this is functionally same as if you did:

byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);

but avoids actual serialization of data as JSON, instead using an in-memory event sequence as the intermediate step.

I want to vertical-align text in select box

Your best option will probably be to adjust the top padding & compare across browsers. It's not perfect, but I think it's as close as you can get.

padding-top:4px;

The amount of padding you need will depend on the font size.

Tip: If your font is set in px, set padding in px as well. If your font is set in em, set the padding in em too.

EDIT

These are the options I think you have, since vertical-align isn't consistant across the browsers.

A. Remove height attribute and let the browser handle it. This usually works the best for me.

 <style>
    select{
        border: 1px solid #ABADB3;
        margin: 0;
        padding: auto 0;
        font-size:14px;
    }
    </style>
    <select>
        <option>option 1</option>
        <option>number 2</option>
    </select>

B. Add top-padding to push down the text. (Pushed down the arrow in some browsers)

<style>
select{
    height: 28px !important;
    border: 1px solid #ABADB3;
    margin: 0;
    padding: 4px 0 0 0;
    font-size:14px;
}
</style>
<select>
    <option>option 1</option>
    <option>number 2</option>
</select>

C. You can make the font larger to try and match the select height a little nicer.

<style>
select{
    height: 28px !important;
    border: 1px solid #ABADB3;
    margin: 0;
    padding: 0 0 0 0;
    font-size:17px;
}
</style>
<select>
    <option>option 1</option>
    <option>number 2</option>
</select>

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I was facing this issue. It solved when I logged in into iTunes Connect in Chrome browser than Safari. My app was in processed state already.

Powershell: count members of a AD group

The Get-ADGroupMember cmdlet would solve this in a much more efficient way than you're tying.

As an example:

$users = Get-ADGroupMember -Identity 'Group Name'
$users.count
132

EDIT:

In order to clarify things, and to make your script simpler. Here's a generic script that will work for your environment that outputs the user count for each group matching your filters.

$groups = Get-ADGroup -filter {(name -like "WA*") -or (name -like "workstation*")}
foreach($group in $groups){
  $countUser = (Get-ADGroupMember $group.DistinguishedName).count
  Write-Host "The group $($group.Name) has $countUser user(s)."
}

jQuery.css() - marginLeft vs. margin-left?

when is marginLeft being used:

$("div").css({
    marginLeft:'12px',
    backgroundPosition:'10px -10px',
    minHeight: '40px'
});

As you can see, attributes that has a hyphen on it are converted to camelcased format. Using the margin-left from the previous code block above would make JavaScript bonkers because it will treat the hyphen as an operation for subtraction.

when is margin-left used:

$("div").css("margin-left","12px").css("background-position","10px -10px").css("min-height","40px");

Theoretically, both code blocks will do the same thing. We can allow hyphens on the second block because it is a string value while compared to the first block, it is somewhat an object.
Now that should make sense.

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

Why not check if for nothing?

if not inputbox("bleh") = nothing then
'Code
else
' Error
end if

This is what i typically use, because its a little easier to read.

Git - What is the difference between push.default "matching" and "simple"

Git v2.0 Release Notes

Backward compatibility notes

When git push [$there] does not say what to push, we have used the traditional "matching" semantics so far (all your branches were sent to the remote as long as there already are branches of the same name over there). In Git 2.0, the default is now the "simple" semantics, which pushes:

  • only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or

  • only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.

You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.

When git add -u and git add -A are run inside a subdirectory without specifying which paths to add on the command line, they operate on the entire tree for consistency with git commit -a and other commands (these commands used to operate only on the current subdirectory). Say git add -u . or git add -A . if you want to limit the operation to the current directory.

git add <path> is the same as git add -A <path> now, so that git add dir/ will notice paths you removed from the directory and record the removal. In older versions of Git, git add <path> used to ignore removals. You can say git add --ignore-removal <path> to add only added or modified paths in <path>, if you really want to.

Regular expression to match exact number of characters?

What you have is correct, but this is more consice:

^[A-Z]{3}$

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Abstract Class vs Interface in C++

Pure Virtual Functions are mostly used to define:

a) abstract classes

These are base classes where you have to derive from them and then implement the pure virtual functions.

b) interfaces

These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.

Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.

Can a variable number of arguments be passed to a function?

Yes. You can use *args as a non-keyword argument. You will then be able to pass any number of arguments.

def manyArgs(*arg):
  print "I was called with", len(arg), "arguments:", arg

>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2, 3)
I was called with 3 arguments: (1, 2, 3)

As you can see, Python will unpack the arguments as a single tuple with all the arguments.

For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.

Is there any kind of hash code function in JavaScript?

JavaScript objects can only use strings as keys (anything else is converted to a string).

You could, alternatively, maintain an array which indexes the objects in question, and use its index string as a reference to the object. Something like this:

var ObjectReference = [];
ObjectReference.push(obj);

set['ObjectReference.' + ObjectReference.indexOf(obj)] = true;

Obviously it's a little verbose, but you could write a couple of methods that handle it and get and set all willy nilly.

Edit:

Your guess is fact -- this is defined behaviour in JavaScript -- specifically a toString conversion occurs meaning that you can can define your own toString function on the object that will be used as the property name. - olliej

This brings up another interesting point; you can define a toString method on the objects you want to hash, and that can form their hash identifier.

VBA: Conditional - Is Nothing

Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.

Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.

Sub test()

Dim dict As Object
Set dict = CreateObject("scripting.dictionary")

If Not dict Is Nothing Then
    MsgBox "Dict is something!"  '<--- This shows
Else
    MsgBox "Dict is nothing!"
End If

End Sub

However if you declare an object but never create it, it's nothing.

Sub test()

Dim temp As Object

If Not temp Is Nothing Then
    MsgBox "Temp is something!"
Else
    MsgBox "Temp is nothing!" '<---- This shows
End If

End Sub

How does one extract each folder name from a path?

Here's a modification of Wolf's answer that leaves out the root and fixes what seemed to be a couple of bugs. I used it to generate a breadcrumbs and I didn't want the root showing.

this is an extension of the DirectoryInfo type.

public static List<DirectoryInfo> PathParts(this DirectoryInfo source, string rootPath)
{
  if (source == null) return null;
  DirectoryInfo root = new DirectoryInfo(rootPath);
  var pathParts = new List<DirectoryInfo>();
  var di = source;

  while (di != null && di.FullName != root.FullName)
  {
    pathParts.Add(di);
    di = di.Parent;
  }

  pathParts.Reverse();
  return pathParts;
}

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

I tried using phyatt's AspectRatioPixmapLabel class, but experienced a few problems:

  • Sometimes my app entered an infinite loop of resize events. I traced this back to the call of QLabel::setPixmap(...) inside the resizeEvent method, because QLabel actually calls updateGeometry inside setPixmap, which may trigger resize events...
  • heightForWidth seemed to be ignored by the containing widget (a QScrollArea in my case) until I started setting a size policy for the label, explicitly calling policy.setHeightForWidth(true)
  • I want the label to never grow more than the original pixmap size
  • QLabel's implementation of minimumSizeHint() does some magic for labels containing text, but always resets the size policy to the default one, so I had to overwrite it

That said, here is my solution. I found that I could just use setScaledContents(true) and let QLabel handle the resizing. Of course, this depends on the containing widget / layout honoring the heightForWidth.

aspectratiopixmaplabel.h

#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H

#include <QLabel>
#include <QPixmap>

class AspectRatioPixmapLabel : public QLabel
{
    Q_OBJECT
public:
    explicit AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent = 0);
    virtual int heightForWidth(int width) const;
    virtual bool hasHeightForWidth() { return true; }
    virtual QSize sizeHint() const { return pixmap()->size(); }
    virtual QSize minimumSizeHint() const { return QSize(0, 0); }
};

#endif // ASPECTRATIOPIXMAPLABEL_H

aspectratiopixmaplabel.cpp

#include "aspectratiopixmaplabel.h"

AspectRatioPixmapLabel::AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent) :
    QLabel(parent)
{
    QLabel::setPixmap(pixmap);
    setScaledContents(true);
    QSizePolicy policy(QSizePolicy::Maximum, QSizePolicy::Maximum);
    policy.setHeightForWidth(true);
    this->setSizePolicy(policy);
}

int AspectRatioPixmapLabel::heightForWidth(int width) const
{
    if (width > pixmap()->width()) {
        return pixmap()->height();
    } else {
        return ((qreal)pixmap()->height()*width)/pixmap()->width();
    }
}

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

How to write data to a text file without overwriting the current data

First of all check if the filename already exists, If yes then create a file and close it at the same time then append your text using AppendAllText. For more info check the code below.


string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt"; 
string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;


 if (!File.Exists(str_Path))
 {
     File.Create(str_Path).Close();
    File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }
 else if (File.Exists(str_Path))
 {

     File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }

How to assign execute permission to a .sh file in windows to be executed in linux

As far as I know the permission system in Linux is set up in such a way to prevent exactly what you are trying to accomplish.

I think the best you can do is to give your Linux user a custom unzip one-liner to run on the prompt:

unzip zip_name.zip && chmod +x script_name.sh

If there are multiple scripts that you need to give execute permission to, write a grant_perms.sh as follows:

#!/bin/bash
# file: grant_perms.sh

chmod +x script_1.sh
chmod +x script_2.sh
...
chmod +x script_n.sh

(You can put the scripts all on one line for chmod, but I found separate lines easier to work with in vim and with shell script commands.)

And now your unzip one-liner becomes:

unzip zip_name.zip && source grant_perms.sh

Note that since you are using source to run grant_perms.sh, it doesn't need execute permission

Find first element in a sequence that matches a predicate

I don't think there's anything wrong with either solutions you proposed in your question.

In my own code, I would implement it like this though:

(x for x in seq if predicate(x)).next()

The syntax with () creates a generator, which is more efficient than generating all the list at once with [].

How to check if element is visible after scrolling?

Most answers here don't take into account that an element can also be hidden because it is scrolled out of view of a div, not only of the whole page.

To cover that possibility, you basically have to check if the element is positioned inside the bounds of each of its parents.

This solution does exactly that:

function(element, percentX, percentY){
    var tolerance = 0.01;   //needed because the rects returned by getBoundingClientRect provide the position up to 10 decimals
    if(percentX == null){
        percentX = 100;
    }
    if(percentY == null){
        percentY = 100;
    }

    var elementRect = element.getBoundingClientRect();
    var parentRects = [];

    while(element.parentElement != null){
        parentRects.push(element.parentElement.getBoundingClientRect());
        element = element.parentElement;
    }

    var visibleInAllParents = parentRects.every(function(parentRect){
        var visiblePixelX = Math.min(elementRect.right, parentRect.right) - Math.max(elementRect.left, parentRect.left);
        var visiblePixelY = Math.min(elementRect.bottom, parentRect.bottom) - Math.max(elementRect.top, parentRect.top);
        var visiblePercentageX = visiblePixelX / elementRect.width * 100;
        var visiblePercentageY = visiblePixelY / elementRect.height * 100;
        return visiblePercentageX + tolerance > percentX && visiblePercentageY + tolerance > percentY;
    });
    return visibleInAllParents;
};

It also lets you specify to what percentage it has to be visible in each direction.
It doesn't cover the possibility that it may be hidden due to other factors, like display: hidden.

This should work in all major browsers, since it only uses getBoundingClientRect. I personally tested it in Chrome and Internet Explorer 11.

How to create the pom.xml for a Java project with Eclipse

To create pom.xml file follow the next steps:

  1. Right click on the current project
  2. Select Configure option
  3. Select Convert to Maven Project
  4. Complete all fields in Create new POM window
  5. Check "Delete original references from project"
  6. Click on Finish button

If eclipse show the the error "Maven error “Failure to transfer…", follow the next steps

  1. Copy the dependency to pom.

    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-archiver</artifactId>
        <version>2.5</version>
    </dependency>
    
  2. Click right on your project

  3. Select Maven
  4. Select Update project
  5. Select Force Update of Snapshots/Releases

Change Screen Orientation programmatically using a Button

Yes it is implementable!

ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

ActivityInfo

http://developer.android.com/reference/android/content/pm/ActivityInfo.html

Refer the link:

Button buttonSetPortrait = (Button)findViewById(R.id.setPortrait);
Button buttonSetLandscape = (Button)findViewById(R.id.setLandscape);

buttonSetPortrait.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
   }

});

buttonSetLandscape.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
   }

});

http://android-er.blogspot.in/2011/08/set-screen-orientation-programmatically.html

Java maximum memory on Windows XP

sun's JDK/JRE needs a contiguous amount of memory if you allocate a huge block.

The OS and initial apps tend to allocate bits and pieces during loading which fragments the available RAM. If a contiguous block is NOT available, the SUN JDK cannot use it. JRockit from Bea(acquired by Oracle) can allocate memory from pieces.

Bower: ENOGIT Git is not installed or not in the PATH

I had the same problem and needed to restart the cmd - and the problem goes away.

Retrieve the position (X,Y) of an HTML element relative to the browser window

I successfully used Andy E's solution to position a bootstrap 2 modal depending on what link in a table row a user clicks on. The page is a Tapestry 5 page and javascript below is imported in the java page class.

javascript:

function setLinkPosition(clientId){
var bodyRect = document.body.getBoundingClientRect(),
elemRect = clientId.getBoundingClientRect(),
offset   = elemRect.top - bodyRect.top;
offset   = offset + 20;
$('#serviceLineModal').css("top", offset);

}

My modal code:

<div id="serviceLineModal" class="modal hide fade add-absolute-position" data-backdrop="static" 
 tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="top:50%;">
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
    <h3 id="myModalLabel">Modal header</h3>
</div>

<div class="modal-body">
    <t:zone t:id="modalZone" id="modalZone">
        <p>You selected service line number: ${serviceLineNumberSelected}</p>
    </t:zone>
</div>

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <!-- <button class="btn btn-primary">Save changes</button> -->
</div>

The link in the loop:

<t:loop source="servicesToDisplay" value="service" encoder="encoder">
<tr style="border-right: 1px solid black;">       
    <td style="white-space:nowrap;" class="add-padding-left-and-right no-border"> 
        <a t:type="eventLink" t:event="serviceLineNumberSelected" t:context="service.serviceLineNumber" 
            t:zone="pageZone" t:clientId="modalLink${service.serviceLineNumber}"
            onmouseover="setLinkPosition(this);">
            <i class="icon-chevron-down"></i> <!-- ${service.serviceLineNumber} -->
        </a>
    </td>

And the java code in the page class:

void onServiceLineNumberSelected(String number){
    checkForNullSession();
    serviceLineNumberSelected = number;
    addOpenServiceLineDialogCommand();
    ajaxResponseRenderer.addRender(modalZone);
}

protected void addOpenServiceLineDialogCommand() {
    ajaxResponseRenderer.addCallback(new JavaScriptCallback() {
        @Override
        public void run(JavaScriptSupport javascriptSupport) {
            javascriptSupport.addScript("$('#serviceLineModal').modal('show');");
        }
    });
}

Hope this helps someone, this post helped out.

Making RGB color in Xcode

Yeah.ios supports RGB valur to range between 0 and 1 only..its close Range [0,1]

Multi-dimensional arrays in Bash

If you want to use a bash script and keep it easy to read recommend putting the data in structured JSON, and then use lightweight tool jq in your bash command to iterate through the array. For example with the following dataset:

[

    {"specialId":"123",
    "specialName":"First"},

    {"specialId":"456",
    "specialName":"Second"},

    {"specialId":"789",
    "specialName":"Third"}
]

You can iterate through this data with a bash script and jq like this:

function loopOverArray(){

    jq -c '.[]' testing.json | while read i; do
        # Do stuff here
        echo "$i"
    done
}

loopOverArray

Outputs:

{"specialId":"123","specialName":"First"}
{"specialId":"456","specialName":"Second"}
{"specialId":"789","specialName":"Third"}

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

After creating a second project in the workspace in eclipse, I had this problem. I believe it is because I created it with a different SDK version and this ovewrote the android-support-v7-appcompat library.

I tried to clean everything up but to no avail. Ultimately, the suggestion above to edit project.properties and change target=android-21 and set my project to Android 5.0, fixed it.

How to read file binary in C#?

using (FileStream fs = File.OpenRead(binarySourceFile.Path))
    using (BinaryReader reader = new BinaryReader(fs))
    {              
        // Read in all pairs.
        while (reader.BaseStream.Position != reader.BaseStream.Length)
        {
            Item item = new Item();
            item.UniqueId = reader.ReadString();
            item.StringUnique = reader.ReadString();
            result.Add(item);
        }
    }
    return result;  

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

List of tables, db schema, dump etc using the Python sqlite3 API

Some might find my function useful if you just want to print out all of the tables and columns in your db.

In the loop, I query each TABLE with LIMIT 0 so it just returns the header info without all the data. You make an empty df out of it, and use the iterable df.columns to print each column name out.

conn = sqlite3.connect('example.db')
c = conn.cursor()

def table_info(c, conn):
    '''
    prints out all of the columns of every table in db
    c : cursor object
    conn : database connection object
    '''
    tables = c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
    for table_name in tables:
        table_name = table_name[0] # tables is a list of single item tuples
        table = pd.read_sql_query("SELECT * from {} LIMIT 0".format(table_name), conn)
        print(table_name)
        for col in table.columns:
            print('\t-' + col)
        print()

table_info(c, conn)
Results will be:

table1
    -column1
    -column2

table2
    -column1
    -column2
    -column3 

etc.

Sort ObservableCollection<string> through C#

I created an extension method to the ObservableCollection

public static void MySort<TSource,TKey>(this ObservableCollection<TSource> observableCollection, Func<TSource, TKey> keySelector)
    {
        var a = observableCollection.OrderBy(keySelector).ToList();
        observableCollection.Clear();
        foreach(var b in a)
        {
            observableCollection.Add(b);
        }
    }

It seems to work and you don't need to implement IComparable

Running Python in PowerShell?

As far as I have understood your question, you have listed two issues.

PROBLEM 1:

You are not able to execute the Python scripts by double clicking the Python file in Windows.

REASON:

The script runs too fast to be seen by the human eye.

SOLUTION:

Add input() in the bottom of your script and then try executing it with double click. Now the cmd will be open until you close it.

EXAMPLE:

print("Hello World")
input()

PROBLEM 2:

./ issue

SOLUTION:

Use Tab to autocomplete the filenames rather than manually typing the filename with ./ autocomplete automatically fills all this for you.

USAGE:

CD into the directory in which .py files are present and then assume the filename is test.py then type python te and then press Tab, it will be automatically converted to python ./test.py.

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

Regex matching in a Bash if statement

In case someone wanted an example using variables...

#!/bin/bash

# Only continue for 'develop' or 'release/*' branches
BRANCH_REGEX="^(develop$|release//*)"

if [[ $BRANCH =~ $BRANCH_REGEX ]];
then
    echo "BRANCH '$BRANCH' matches BRANCH_REGEX '$BRANCH_REGEX'"
else
    echo "BRANCH '$BRANCH' DOES NOT MATCH BRANCH_REGEX '$BRANCH_REGEX'"
fi

How do I find out which computer is the domain controller in Windows programmatically?

In cmd on Windows, type the following commande:

nltest /dclist:{domainname}

It lists all domain controllers in particular domain

Python Set Comprehension

primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}

I simplified the test a bit - if all(x%y instead of if not any(not x%y

I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.

pairs = {(x, x+2) for x in primes if x+2 in primes}

Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.

What is simplest way to read a file into String?

Another alternative approach is:

How do I create a Java string from the contents of a file?

Other option is to use utilities provided open source libraries
http://commons.apache.org/io/api-1.4/index.html?org/apache/commons/io/IOUtils.html

Why java doesn't provide such a common util API ?
a) to keep the APIs generic so that encoding, buffering etc is handled by the programmer.
b) make programmers do some work and write/share opensource util libraries :D ;-)

Auto-redirect to another HTML page

If you want to redirect your webpage to another HTML FILE, just use as followed:

<meta http-equiv="refresh" content"2;otherpage.html">

2 being the seconds you want the client to wait before redirecting. Use "url=" only when it's an URL, to redirect to an HTML file just write the name after the ';'

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

What is the problem with shadowing names defined in outer scopes?

There isn't any big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data argument as yadda, but miss one of the places it is used in the function's body... Now data refers to the global, and you start having weird behaviour - where you would have a much more obvious NameError if you didn't have a global name data.

Also remember that in Python everything is an object (including modules, classes and functions), so there's no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it - bad luck - foo.

Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.

None of this is much of a problem if you have short functions, good naming and a decent unit test coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.

Correct way to quit a Qt program?

QApplication is derived from QCoreApplication and thereby inherits quit() which is a public slot of QCoreApplication, so there is no difference between QApplication::quit() and QCoreApplication::quit().

As we can read in the documentation of QCoreApplication::quit() it "tells the application to exit with return code 0 (success).". If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call QCoreApplication::exit() because you can provide a non-zero returnCode which, by convention, indicates an error.

It is important to note that "if the event loop is not running, this function (QCoreApplication::exit()) does nothing", so in that case you should call exit(EXIT_FAILURE).

How to filter empty or NULL names in a QuerySet?

Name.objects.filter(alias__gt='',alias__isnull=False)

Java, how to compare Strings with String Arrays

If I understand your question correctly, it appears you want to know the following:

How do I check if my String array contains usercode, the String that was just inputted?

See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.

How to check if a function exists on a SQL database

I know this thread is old but I just wanted to add this answer for those who believe it's safer to Alter than Drop and Create. The below will Alter the Function if it exists or Create it if doesn't:

  IF NOT EXISTS (SELECT *
               FROM   sys.objects
               WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                      AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
       EXEC('CREATE FUNCTION [dbo].[foo]() RETURNS INT AS BEGIN RETURN 0 END')
  GO
  ALTER FUNCTION [dbo].[foo]
  AS
  ...

How to create materialized views in SQL Server?

When indexed view is not an option, and quick updates are not necessary, you can create a hack cache table:

select * into cachetablename from myviewname
alter table cachetablename add primary key (columns)
-- OR alter table cachetablename add rid bigint identity primary key
create index...

then sp_rename view/table or change any queries or other views that reference it to point to the cache table.

schedule daily/nightly/weekly/whatnot refresh like

begin transaction
truncate table cachetablename
insert into cachetablename select * from viewname
commit transaction

NB: this will eat space, also in your tx logs. Best used for small datasets that are slow to compute. Maybe refactor to eliminate "easy but large" columns first into an outer view.

Android Service Stops When App Is Closed

I'm in the same situation, so far I learned when the app is closed the service get closed also because they are in a one thread, so the service should be on another thread in order fot it not to be closed, look into that and look into keeping the service alive with alarm manager here an example http://www.vogella.com/articles/AndroidServices/article.html this way your service won't be shown in notification.

lastly, after all the research I've done I'm coming to realize that the best choice for a long running service is startForeground(), because it is made for that and the system actually deals with your service well.

How to use ConfigurationManager

I found some answers, but I don't know if it is the right way.This is my solution for now. Fortunatelly it didn´t broke my design mode.

    `
    /// <summary>
    /// set config, if key is not in file, create
    /// </summary>
    /// <param name="key">Nome do parâmetro</param>
    /// <param name="value">Valor do parâmetro</param>
    public static void SetConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// Get key value, if not found, return null
    /// </summary>
    /// <param name="key"></param>
    /// <returns>null if key is not found, else string with value</returns>
    public static string GetConfig(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }`

How to delete a row from GridView?

Delete the row from the table dtPrf_Mstr rather than from the grid view.

MySQL vs MongoDB 1000 reads

Do you have concurrency, i.e simultaneous users ? If you just run 1000 times the query straight, with just one thread, there will be almost no difference. Too easy for these engines :)

BUT I strongly suggest that you build a true load testing session, which means using an injector such as JMeter with 10, 20 or 50 users AT THE SAME TIME so you can really see a difference (try to embed this code inside a web page JMeter could query).

I just did it today on a single server (and a simple collection / table) and the results are quite interesting and surprising (MongoDb was really faster on writes & reads, compared to MyISAM engine and InnoDb engine).

This really should be part of your test : concurrency & MySQL engine. Then, data/schema design & application needs are of course huge requirements, beyond response times. Let me know when you get results, I'm also in need of inputs about this!

Use CASE statement to check if column exists in table - SQL Server

select case
         when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
         then 0
         else 1
       end

Height equal to dynamic width (CSS fluid layout)

Using jQuery you can achieve this by doing

var cw = $('.child').width();
$('.child').css({'height':cw+'px'});

Check working example at http://jsfiddle.net/n6DAu/1/

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

try using concatenation of string

Statistics(string date)
    {
        this->date += date;
    }

acually this was a part of a class..

Javascript string/integer comparisons

The alert() wants to display a string, so it will interpret "2">"10" as a string.

Use the following:

var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);

var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

How can I check if string contains characters & whitespace, not just whitespace?

This can be fast solution

return input < "\u0020" + 1;

Twitter bootstrap 3 two columns full height

Ok, I've achieved the same thing using Bootstrap 3.0

Example with the latest bootstrap

http://jsfiddle.net/HDNQS/1/

The HTML:

<div class="header">
    whatever
</div>
<div class="container-fluid wrapper">
    <div class="row">
        <div class="col-md-3 navigation"></div>
        <div class="col-md-9 content"></div>
    </div>
</div>

The SCSS:

html, body, .wrapper {
    padding: 0;
    margin: 0;
    height: 100%;
}

$headerHeight: 43px;

.navigation, .content {
    display: table-cell;
    float: none;
    vertical-align: top;
}

.wrapper {
    display: table;
    width: 100%;
    margin-top: -$headerHeight;
    padding-top: $headerHeight;
}

.header {
    height: $headerHeight;
}

.row {
    height: 100%;
    margin: 0;
    display: table-row;
    &:before, &:after {
        content: none;
    }
}

.navigation {
    background: #4a4d4e;
    padding-left: 0;
    padding-right: 0;
}

How to convert entire dataframe to numeric while preserving decimals?

df2 <- data.frame(apply(df1, 2, function(x) as.numeric(as.character(x))))

sql query to return differences between two tables

For a simple smoke test where you you're trying to ensure two tables match w/out worrying about column names:

--ensure tables have matching records
Select count (*) from tbl_A
Select count (*) from tbl_B

--create temp table of all records in both tables
Select * into #demo from tbl_A 
Union All
Select * from tbl_B

--Distinct #demo records = Total #demo records/2 = Total tbl_A records = total tbl_B records
Select distinct * from #demo 

You can easily write a store procedure to compare a batch of tables.

Richtextbox wpf binding

 <RichTextBox>
     <FlowDocument PageHeight="180">
         <Paragraph>
             <Run Text="{Binding Text, Mode=TwoWay}"/>
          </Paragraph>
     </FlowDocument>
 </RichTextBox>

This seems to be the easiest way by far and isn't displayed in any of these answers.

In the view model just have the Text variable.

In Python, what happens when you import inside of a function?

The very first time you import goo from anywhere (inside or outside a function), goo.py (or other importable form) is loaded and sys.modules['goo'] is set to the module object thus built. Any future import within the same run of the program (again, whether inside or outside a function) just look up sys.modules['goo'] and bind it to barename goo in the appropriate scope. The dict lookup and name binding are very fast operations.

Assuming the very first import gets totally amortized over the program's run anyway, having the "appropriate scope" be module-level means each use of goo.this, goo.that, etc, is two dict lookups -- one for goo and one for the attribute name. Having it be "function level" pays one extra local-variable setting per run of the function (even faster than the dictionary lookup part!) but saves one dict lookup (exchanging it for a local-variable lookup, blazingly fast) for each goo.this (etc) access, basically halving the time such lookups take.

We're talking about a few nanoseconds one way or another, so it's hardly a worthwhile optimization. The one potentially substantial advantage of having the import within a function is when that function may well not be needed at all in a given run of the program, e.g., that function deals with errors, anomalies, and rare situations in general; if that's the case, any run that does not need the functionality will not even perform the import (and that's a saving of microseconds, not just nanoseconds), only runs that do need the functionality will pay the (modest but measurable) price.

It's still an optimization that's only worthwhile in pretty extreme situations, and there are many others I would consider before trying to squeeze out microseconds in this way.

Given an RGB value, how do I create a tint (or shade)?

Some definitions

  • A shade is produced by "darkening" a hue or "adding black"
  • A tint is produced by "ligthening" a hue or "adding white"

Creating a tint or a shade

Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:

  • RGB:

    • To shade:

      newR = currentR * (1 - shade_factor)
      newG = currentG * (1 - shade_factor)
      newB = currentB * (1 - shade_factor)
      
    • To tint:

      newR = currentR + (255 - currentR) * tint_factor
      newG = currentG + (255 - currentG) * tint_factor
      newB = currentB + (255 - currentB) * tint_factor
      
    • More generally, the color resulting in layering a color RGB(currentR,currentG,currentB) with a color RGBA(aR,aG,aB,alpha) is:

      newR = currentR + (aR - currentR) * alpha
      newG = currentG + (aG - currentG) * alpha
      newB = currentB + (aB - currentB) * alpha
      

    where (aR,aG,aB) = black = (0,0,0) for shading, and (aR,aG,aB) = white = (255,255,255) for tinting

  • HSV or HSB:

    • To shade: lower the Value / Brightness or increase the Saturation
    • To tint: lower the Saturation or increase the Value / Brightness
  • HSL:
    • To shade: lower the Lightness
    • To tint: increase the Lightness

There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB and want to use the HSV model to shade for example, you can just convert to HSV, do the shading and convert back to RGB. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :

Comparing the models

  • RGB has the advantage of being really simple to implement, but:
    • you can only shade or tint your color relatively
    • you have no idea if your color is already tinted or shaded
  • HSV or HSB is kind of complex because you need to play with two parameters to get what you want (Saturation & Value / Brightness)
  • HSL is the best from my point of view:
    • supported by CSS3 (for webapp)
    • simple and accurate:
      • 50% means an unaltered Hue
      • >50% means the Hue is lighter (tint)
      • <50% means the Hue is darker (shade)
    • given a color you can determine if it is already tinted or shaded
    • you can tint or shade a color relatively or absolutely (by just replacing the Lightness part)

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

From python 3.5: merging and summing

Thanks to @tokeinizer_fsj that told me in a comment that I didn't get completely the meaning of the question (I thought that add meant just adding keys that eventually where different in the two dictinaries and, instead, i meant that the common key values should be summed). So I added that loop before the merging, so that the second dictionary contains the sum of the common keys. The last dictionary will be the one whose values will last in the new dictionary that is the result of the merging of the two, so I thing the problem is solved. The solution is valid from python 3.5 and following versions.

a = {
    "a": 1,
    "b": 2,
    "c": 3
}

b = {
    "a": 2,
    "b": 3,
    "d": 5
}

# Python 3.5

for key in b:
    if key in a:
        b[key] = b[key] + a[key]

c = {**a, **b}
print(c)

>>> c
{'a': 3, 'b': 5, 'c': 3, 'd': 5}

Reusable code

a = {'a': 1, 'b': 2, 'c': 3}
b = {'b': 3, 'c': 4, 'd': 5}


def mergsum(a, b):
    for k in b:
        if k in a:
            b[k] = b[k] + a[k]
    c = {**a, **b}
    return c


print(mergsum(a, b))

How to check if a folder exists

Using java.nio.file.Files:

Path path = ...;

if (Files.exists(path)) {
    // ...
}

You can optionally pass this method LinkOption values:

if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {

There's also a method notExists:

if (Files.notExists(path)) {

Escape double quotes for JSON in Python

Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:

>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}

if var == False

Use not

var = False
if not var:
    print 'learnt stuff'

In Python, how do I use urllib to see if a website is 404 or 200?

For Python 3:

import urllib.request, urllib.error

url = 'http://www.google.com/asdfsf'
try:
    conn = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
    # Return code error (e.g. 404, 501, ...)
    # ...
    print('HTTPError: {}'.format(e.code))
except urllib.error.URLError as e:
    # Not an HTTP-specific error (e.g. connection refused)
    # ...
    print('URLError: {}'.format(e.reason))
else:
    # 200
    # ...
    print('good')

Foreign key referring to primary keys across multiple tables?

Assuming that I have understood your scenario correctly, this is what I would call the right way to do this:

Start from a higher-level description of your database! You have employees, and employees can be "ce" employees and "sn" employees (whatever those are). In object-oriented terms, there is a class "employee", with two sub-classes called "ce employee" and "sn employee".

Then you translate this higher-level description to three tables: employees, employees_ce and employees_sn:

  • employees(id, name)
  • employees_ce(id, ce-specific stuff)
  • employees_sn(id, sn-specific stuff)

Since all employees are employees (duh!), every employee will have a row in the employees table. "ce" employees also have a row in the employees_ce table, and "sn" employees also have a row in the employees_sn table. employees_ce.id is a foreign key to employees.id, just as employees_sn.id is.

To refer to an employee of any kind (ce or sn), refer to the employees table. That is, the foreign key you had trouble with should refer to that table!

C#: Assign same value to multiple variables in single statement

Something a little shorter in syntax but taking what the others have already stated.

int num1, num2 = num1 = 1;

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

What's the difference between JPA and Hibernate?

JPA is the interface, Hibernate is one implementation of that interface.

How to create jobs in SQL Server Express edition

SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.

What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:

backup.bat:

sqlcmd -i backup.sql

backup.sql:

backup database TeamCity to disk = 'c:\backups\MyBackup.bak'

Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.

The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE queries instead.


If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.

It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:

How do I get started with the SQL Server Maintenance Solution on SQL Server Express?

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

  1. Download MaintenanceSolution.sql.

  2. Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.

  3. Create cmd files to execute the stored procedures; for example:
    sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txt

  4. In Windows Scheduled Tasks, create tasks to call the cmd files.

  5. Schedule the tasks.

  6. Start the tasks and verify that they are completing successfully.

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Is there a way to get the git root directory in one command?

In case anyone needs a POSIX compliant way of doing this, without needing git executable:

git-root:

#$1: Path to child directory
git_root_recurse_parent() {
    # Check if cwd is a git root directory
    if [ -d .git/objects -a -d .git/refs -a -f .git/HEAD ] ; then
        pwd
        return 0
    fi

    # Check if recursion should end (typically if cwd is /)
    if [ "${1}" = "$(pwd)" ] ; then
        return 1
    fi

    # Check parent directory in the same way
    local cwd=$(pwd)
    cd ..
    git_root_recurse_parent "${cwd}"
}

git_root_recurse_parent

If you just want the functionality as part of a script, remove the shebang, and replace the last git_root_recurse_parent line with:

git_root() {
    (git_root_recurse_parent)
}

Dockerfile copy keep subdirectory structure

Remove star from COPY, with this Dockerfile:

FROM ubuntu
COPY files/ /files/
RUN ls -la /files/*

Structure is there:

$ docker build .
Sending build context to Docker daemon 5.632 kB
Sending build context to Docker daemon 
Step 0 : FROM ubuntu
 ---> d0955f21bf24
Step 1 : COPY files/ /files/
 ---> 5cc4ae8708a6
Removing intermediate container c6f7f7ec8ccf
Step 2 : RUN ls -la /files/*
 ---> Running in 08ab9a1e042f
/files/folder1:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2

/files/folder2:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2
 ---> 03ff0a5d0e4b
Removing intermediate container 08ab9a1e042f
Successfully built 03ff0a5d0e4b

python pandas extract year from datetime: df['year'] = df['date'].year is not working

Probably already too late to answer but since you have already parse the dates while loading the data, you can just do this to get the day

df['date'] = pd.DatetimeIndex(df['date']).year

Get file name from URI string in C#

As of 2020, handles query strings & encoded URLs

public static string GetFileNameFromUrl (string url)
{
    var decoded = HttpUtility.UrlDecode(url);

    if (decoded.IndexOf("?") is {} queryIndex && queryIndex != -1)
    {
        decoded = decoded.Substring(0, queryIndex);
    }

    return Path.GetFileName(decoded);
}

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

Generally, .c and .h files are for C or C-compatible code, everything else is C++.

Many folks prefer to use a consistent pairing for C++ files: .cpp with .hpp, .cxx with .hxx, .cc with .hh, etc. My personal preference is for .cpp and .hpp.

When to use Task.Delay, when to use Thread.Sleep?

The biggest difference between Task.Delay and Thread.Sleep is that Task.Delay is intended to run asynchronously. It does not make sense to use Task.Delay in synchronous code. It is a VERY bad idea to use Thread.Sleep in asynchronous code.

Normally you will call Task.Delay() with the await keyword:

await Task.Delay(5000);

or, if you want to run some code before the delay:

var sw = new Stopwatch();
sw.Start();
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;

Guess what this will print? Running for 0.0070048 seconds. If we move the await delay above the Console.WriteLine instead, it will print Running for 5.0020168 seconds.

Let's look at the difference with Thread.Sleep:

class Program
{
    static void Main(string[] args)
    {
        Task delay = asyncTask();
        syncCode();
        delay.Wait();
        Console.ReadLine();
    }

    static async Task asyncTask()
    {
        var sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("async: Starting");
        Task delay = Task.Delay(5000);
        Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        await delay;
        Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        Console.WriteLine("async: Done");
    }

    static void syncCode()
    {
        var sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("sync: Starting");
        Thread.Sleep(5000);
        Console.WriteLine("sync: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        Console.WriteLine("sync: Done");
    }
}

Try to predict what this will print...

async: Starting
async: Running for 0.0070048 seconds
sync: Starting
async: Running for 5.0119008 seconds
async: Done
sync: Running for 5.0020168 seconds
sync: Done

Also, it is interesting to notice that Thread.Sleep is far more accurate, ms accuracy is not really a problem, while Task.Delay can take 15-30ms minimal. The overhead on both functions is minimal compared to the ms accuracy they have (use Stopwatch Class if you need something more accurate). Thread.Sleep still ties up your Thread, Task.Delay release it to do other work while you wait.

What does the "__block" keyword mean?

hope this will help you

let suppose we have a code like:

{
     int stackVariable = 1;

     blockName = ^()
     {
      stackVariable++;
     }
}

it will give an error like "variable is not assignable" because the stack variable inside the block are by default immutable.

adding __block(storage modifier) ahead of it declaration make it mutable inside the block i.e __block int stackVariable=1;

Force HTML5 youtube video

I've found the solution :

You have to add the html5=1 in the src attribute of the iframe :

<iframe src="http://www.youtube.com/embed/dP15zlyra3c?html5=1"></iframe>

The video will be displayed as HTML5 if available, or fallback into flash player.

Eclipse: How to install a plugin manually?

  1. Download your plugin
  2. Open Eclipse
  3. From the menu choose: Help / Install New Software...
  4. Click the Add button
  5. In the Add Repository dialog that appears, click the Archive button next to the Location field
  6. Select your plugin file, click OK

You could also just copy plugins to the eclipse/plugins directory, but it's not recommended.

How can I install Apache Ant on Mac OS X?

If you're a homebrew user instead of macports, homebrew has an ant recipe.

brew install ant

Check if a given key already exists in a dictionary and increment it

Agreed with cgoldberg. How I do it is:

try:
    dict[key] += 1
except KeyError:
    dict[key] = 1

So either do it as above, or use a default dict as others have suggested. Don't use if statements. That's not Pythonic.

What are the main performance differences between varchar and nvarchar SQL Server data types?

Generally speaking; Start out with the most expensive datatype that has the least constraints. Put it in production. If performance starts to be an issue, find out what's actually being stored in those nvarchar columns. Is there any characters in there that wouldn't fit into varchar? If not, switch to varchar. Don't try to pre-optimize before you know where the pain is. My guess is that the choice between nvarchar/varchar is not what's going to slow down your application in the foreseable future. There will be other parts of the application where performance tuning will give you much more bang for the bucks.

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

You can do the following to install java 8 on your machine. First get the link of tar that you want to install. You can do this by:

  1. go to java downloads page and find the appropriate download.
  2. Accept the license agreement and download it.
  3. In the download page in your browser right click and copy link address.

Then in your terminal:

$ cd /tmp
$ wget http://download.oracle.com/otn-pub/java/jdk/8u74-b02/jdk-8u74-linux-x64.tar.gz\?AuthParam\=1458001079_a6c78c74b34d63befd53037da604746c
$ tar xzf jdk-8u74-linux-x64.tar.gz?AuthParam=1458001079_a6c78c74b34d63befd53037da604746c
$ sudo mv jdk1.8.0_74 /opt
$ cd /opt/jdk1.8.0_74/
$ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0_91/bin/java 2
$ sudo update-alternatives --config java // select version
$ sudo update-alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_91/bin/jar 2
$ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_91/bin/javac 2
$ sudo update-alternatives --set jar /opt/jdk1.8.0_91/bin/jar
$ sudo update-alternatives --set javac /opt/jdk1.8.0_74/bin/javac
$ java -version // you should have the updated java

How to get value of selected radio button?

You can use .find() to select checked element:

var radio = Array.from(document.querySelectorAll('#rate input'))

var value = radio.length && radio.find(r => r.checked).value

start/play embedded (iframe) youtube-video on click of an image

You are supposed to be able to specify a domain that is safe for scripting. the api document mentions "As an extra security measure, you should also include the origin parameter to the URL" http://code.google.com/apis/youtube/iframe_api_reference.html src="http://www.youtube.com/embed/J---aiyznGQ?enablejsapi=1&origin=mydomain.com" would be the src of your iframe.

however it is not very well documented. I am trying something similar right now.

Breaking out of a for loop in Java

You can use:

for (int x = 0; x < 10; x++) {
  if (x == 5) { // If x is 5, then break it.
    break;
  }
}

Printing Exception Message in java

The output looks correct to me:

Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1

I think Invalid Javascript code: .. is the start of the exception message.

Normally the stacktrace isn't returned with the message:

try {
    throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
    System.out.println(e.getMessage()); // prints "hu?"
}

So maybe the code you are calling catches an exception and rethrows a ScriptException. In this case maybe e.getCause().getMessage() can help you.

Android error: Failed to install *.apk on device *: timeout

I know it sounds silly, but after trying everything recomended for this timeout issue on when running on a device, I decided to try changing the cable and it worked. It's a Coby Kyros MID7015.

Trying another cable is a good and simple option to take a chance on.

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

To change to x86:

  1. Create a setup project for your solution.
  2. After you create it, Go to Solution Explorer, right click the setup project.
    • Press Configuration Manager.
    • Click on: "Active Solution Platform" combobox and select New (If there is no x86 displayed)
    • Select from first combo x86 then press OK.
    • rebuild Setup project, then rebuild All the project.

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

How do I merge my local uncommitted changes into another Git branch?

Stashing, temporary commits and rebasing may all be overkill. If you haven't added the changed files to the index, yet, then you may be able to just checkout the other branch.

git checkout branch2

This will work so long as no files that you are editing are different between branch1 and branch2. It will leave you on branch2 with you working changes preserved. If they are different then you can specify that you want to merge your local changes with the changes introduced by switching branches with the -m option to checkout.

git checkout -m branch2

If you've added changes to the index then you'll want to undo these changes with a reset first. (This will preserve your working copy, it will just remove the staged changes.)

git reset

How to download file in swift?

Background session (URLSessionDownloadTask, URLSessionUploadTask) allows you to download/upload/cache files in background mode even if app was terminated. In this case when task is done iOS wakes up it (in background) and allows make some competition block in a limited time frame. It is a part of background-transfers approach. It works because the downloading task is executed on nsurlsessiond daemon process[About]

[Background tasks]

How to create a new file in unix?

The command is lowercase: touch filename.

Keep in mind that touch will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch

If you always want an empty file, one way to do so would be to use:

echo "" > filename

403 Forbidden error when making an ajax Post request in Django framework

The fastest solution if you are not embedding js into your template is:

Put <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> before your reference to script.js file in your template, then add csrfmiddlewaretoken into your data dictionary:

$.ajax({
            type: 'POST',
            url: somepathname + "do_it/",
            data: {csrfmiddlewaretoken: window.CSRF_TOKEN},
            success: function() {
                console.log("Success!");
            }
        })

If you do embed your js into the template, it's as simple as: data: {csrfmiddlewaretoken: '{{ csrf_token }}'}

Identifying country by IP address

I think what you're looking for is an IP Geolocation database or service provider. There are many out there and some are free (get what you pay for).

Although I haven't used this service before, it claims to be in real-time. https://kickfire.com/kf-api

Here's another IP geo location API from Abstract API - https://www.abstractapi.com/ip-geolocation-api

But just do a google search on IP geo and you'll get more results than you need.

Getting list of Facebook friends with latest API

Using CodeIgniter OAuth2/0.4.0 sparks,

in Auth.php file,

$user = $provider->get_user_info($token);

$friends = $provider->get_friends_list($token);
print_r($friends);

and in Facebook.php file under Provider, add the following function,

    public function get_friends_list(OAuth2_Token_Access $token)
    {
            $url = 'https://graph.facebook.com/me/friends?'.http_build_query(array(
                    'access_token' => $token->access_token,
            ));
            $friends = json_decode(file_get_contents($url),TRUE);

            return $friends;
    }

prints the facebenter code hereook friends.

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

Why you got this error:

Android studio does not come with build tools for different android versions when you download it. It also does not make sense since there are multiple versions of build tools and each of them will take hundreds of megabytes on your hard drive. This is why Android Studio installation package is 1 GB while Xcode, which has all the build tools, is 6 GB

When you choose a specific build version in the build.gradle file, your android studio may or may not have that version of build tool installed. And if not, you will see the error complaining about it.

How to fix it

You just need to install the specific version of build tool mentioned in build.gradle like this:

  1. Click File > Settings (on a Mac, Android Studio > Preferences) to open the Settings dialog.
  2. Go to Appearance & Behavior > System Settings > Android SDK (Or simply search for Android SDK on the search bar)
  3. Go to SDK Tools tab > Check the Show Package Details check box
  4. Select the specific version of the build tool and click on the Apply button
  5. After the installation, sync the project

Demos

(I choose a different version just to show you how to apply the changes by that apply button :) )

enter image description here

And then sync the project. The error is gone now!

enter image description here

what happens when you type in a URL in browser

First the computer looks up the destination host. If it exists in local DNS cache, it uses that information. Otherwise, DNS querying is performed until the IP address is found.

Then, your browser opens a TCP connection to the destination host and sends the request according to HTTP 1.1 (or might use HTTP 1.0, but normal browsers don't do it any more).

The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the client (=your browser)

The browser then uses HTML parser to re-create document structure which is later presented to you on screen. If it finds references to external resources, such as pictures, css files, javascript files, these are is delivered the same way as the HTML document itself.

Why does npm install say I have unmet dependencies?

I was trying to work on an automated deployment system that runs npm install, so a lot of these solutions wouldn't work for me in an automated fasion. I wasn't in a position to go deleting/re-creating node_modules/ nor could I easily change Node.js versions.

So I ended up running npm shrinkwrap - adding the npm-shrinkwrap.json file to my deployment bundle, and running installs from there. That fixed the problem for me; with the shrinkwrap file as a 'helper', npm seemed to be able to find the right packages and get them installed for me. (Shrinkwrap has other features as well, but this was what I needed it for in this particular case).

What’s the best way to get an HTTP response code from a URL?

Here's a solution that uses httplib instead.

import httplib

def get_status_code(host, path="/"):
    """ This function retreives the status code of a website by requesting
        HEAD data from the host. This means that it only requests the headers.
        If the host cannot be reached or something else goes wrong, it returns
        None instead.
    """
    try:
        conn = httplib.HTTPConnection(host)
        conn.request("HEAD", path)
        return conn.getresponse().status
    except StandardError:
        return None


print get_status_code("stackoverflow.com") # prints 200
print get_status_code("stackoverflow.com", "/nonexistant") # prints 404

Error handling in getJSON calls

$.getJSON() is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).

'generic' would be something like:

$.ajaxSetup({
      "error":function() { alert("error");  }
});

And the 'specific' way:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });

Kubernetes service external ip pending

Use NodePort:

$ kubectl run user-login --replicas=2 --labels="run=user-login" --image=kingslayerr/teamproject:version2  --port=5000

$ kubectl expose deployment user-login --type=NodePort --name=user-login-service

$ kubectl describe services user-login-service

(Note down the port)

$ kubectl cluster-info

(IP-> Get The IP where master is running)

Your service is accessible at (IP):(port)

Calling virtual functions inside constructors

Other answers have already explained why virtual function calls don't work as expected when called from a constructor. I'd like to instead propose another possible work around for getting polymorphic-like behavior from a base type's constructor.

By adding a template constructor to the base type such that the template argument is always deduced to be the derived type it's possible to be aware of the derived type's concrete type. From there, you can call static member functions for that derived type.

This solution does not allow non-static member functions to be called. While execution is in the base type's constructor, the derived type's constructor hasn't even had time to go through it's member initialization list. The derived type portion of the instance being created hasn't begun being initialized it. And since non-static member functions almost certainly interact with data members it would be unusual to want to call the derived type's non-static member functions from the base type's constructor.

Here is a sample implementation :

#include <iostream>
#include <string>

struct Base {
protected:
    template<class T>
    explicit Base(const T*) : class_name(T::Name())
    {
        std::cout << class_name << " created\n";
    }

public:
    Base() : class_name(Name())
    {
        std::cout << class_name << " created\n";
    }


    virtual ~Base() {
        std::cout << class_name << " destroyed\n";
    }

    static std::string Name() {
        return "Base";
    }

private:
    std::string class_name;
};


struct Derived : public Base
{   
    Derived() : Base(this) {} // `this` is used to allow Base::Base<T> to deduce T

    static std::string Name() {
        return "Derived";
    }
};

int main(int argc, const char *argv[]) {

    Derived{};  // Create and destroy a Derived
    Base{};     // Create and destroy a Base

    return 0;
}

This example should print

Derived created
Derived destroyed
Base created
Base destroyed

When a Derived is constructed, the Base constructor's behavior depends on the actual dynamic type of the object being constructed.

How to replace text in a column of a Pandas dataframe?

If you only need to replace characters in one specific column, somehow regex=True and in place=True all failed, I think this way will work:

data["column_name"] = data["column_name"].apply(lambda x: x.replace("characters_need_to_replace", "new_characters"))

lambda is more like a function that works like a for loop in this scenario. x here represents every one of the entries in the current column.

The only thing you need to do is to change the "column_name", "characters_need_to_replace" and "new_characters".

Adding onClick event dynamically using jQuery

try this approach if you know your object client name ( it is not important that it is Button or TextBox )

$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');

try this ones if you want add onClick event to a server object with JQuery

$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');

String.equals() with multiple conditions (and one action on result)

Your current implementation is correct. The suggested is not possible but the pseudo code would be implemented with multiple equal() calls and ||.

How to select only date from a DATETIME field in MySQL?

In the interest of actually putting a working solution to this question:

SELECT ... WHERE `myDateColumn` >= DATE(DATE_FORMAT(NOW(),'%Y-%m-%d'));

Obviously, you could change the NOW() function to any date or variable you want.

How to generate different random numbers in a loop in C++?

Do not use rand(); use new C++11 facilities (e.g. std::mt19937, std::uniform_int_distribution, etc.) instead.

You can use code like this (live here on Ideone):

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

int main()
{
    // Random seed
    random_device rd;

    // Initialize Mersenne Twister pseudo-random number generator
    mt19937 gen(rd());

    // Generate pseudo-random numbers
    // uniformly distributed in range (1, 100)
    uniform_int_distribution<> dis(1, 100);

    // Generate ten pseudo-random numbers
    for (int i = 0; i < 10; i++)
    {
        int randomX = dis(gen);
        cout << "\nRandom X = " << randomX;
    }
}

P.S.

Consider watching this video from Going Native 2013 conference for more details about rand()-related problems:

rand() Considered Harmful

Iterating through a variable length array

for(int i = 0; i < array.length; i++)
{
    System.out.println(array[i]);
}

or

for(String value : array)
{
    System.out.println(value);
}

The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.

Just for completeness you can do the while loop this way:

int index = 0;

while(index < myArray.length)
{
  final String value;

  value = myArray[index];
  System.out.println(value);
  index++;
}

But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).

Control cannot fall through from one case label

Since it wasn't mentioned in the other answers, I'd like to add that if you want case SearchAuthors to be executed right after the first case, just like omitting the break in some other programming languages where that is allowed, you can simply use goto.

switch (searchType)
{
    case "SearchBooks":
    Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
    goto case "SearchAuthors";

    case "SearchAuthors":
    Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
    break;
}

How to convert a string variable containing time to time_t type in c++?

This should work:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);


when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

Modify as needed.

Parse JSON in TSQL

I developed my own SQL Server 2016+ JSON parser a while ago. I use this in all my projects - very good performance. I hope it can help someone else too.

Full code of the function:

ALTER FUNCTION [dbo].[SmartParseJSON] (@json NVARCHAR(MAX))
RETURNS @Parsed TABLE (Parent NVARCHAR(MAX),Path NVARCHAR(MAX),Level INT,Param NVARCHAR(4000),Type NVARCHAR(255),Value NVARCHAR(MAX),GenericPath NVARCHAR(MAX))
AS
BEGIN
    -- Author: Vitaly Borisov
    -- Create date: 2018-03-23
    ;WITH crData AS (
        SELECT CAST(NULL AS NVARCHAR(4000)) COLLATE DATABASE_DEFAULT AS [Parent]
            ,j.[Key] AS [Param],j.Value,j.Type
            ,j.[Key] AS [Path],0 AS [Level]
            ,j.[Key] AS [GenericPath]
        FROM OPENJSON(@json) j
        UNION ALL
        SELECT CAST(d.Path AS NVARCHAR(4000)) COLLATE DATABASE_DEFAULT AS [Parent]
            ,j.[Key] AS [Param],j.Value,j.Type 
            ,d.Path + CASE d.Type WHEN 5 THEN '.' WHEN 4 THEN '[' ELSE '' END + j.[Key] + CASE d.Type WHEN 4 THEN ']' ELSE '' END AS [Path]
            ,d.Level+1
            ,d.GenericPath + CASE d.Type WHEN 5 THEN '.' + j.[Key] ELSE '' END AS [GenericPath]
        FROM crData d 
        CROSS APPLY OPENJSON(d.Value) j
        WHERE ISJSON(d.Value) = 1
    )
    INSERT INTO @Parsed(Parent, Path, Level, Param, Type, Value, GenericPath)
    SELECT d.Parent,d.Path,d.Level,d.Param
        ,CASE d.Type 
            WHEN 1 THEN CASE WHEN TRY_CONVERT(UNIQUEIDENTIFIER,d.Value) IS NOT NULL THEN 'UNIQUEIDENTIFIER' ELSE 'NVARCHAR(MAX)' END 
            WHEN 2 THEN 'INT' 
            WHEN 3 THEN 'BIT' 
            WHEN 4 THEN 'Array' 
            WHEN 5 THEN 'Object' 
                ELSE 'NVARCHAR(MAX)'
         END AS [Type]
        ,CASE 
            WHEN d.Type = 3 AND d.Value = 'true' THEN '1'
            WHEN d.Type = 3 AND d.Value = 'false' THEN '0'
                ELSE d.Value
         END AS [Value]
        ,d.GenericPath
    FROM crData d
    OPTION(MAXRECURSION 1000) /*Limit to 1000 levels deep*/
    ;
    RETURN;
END
GO

Example of use:

DECLARE @json NVARCHAR(MAX) = '{"Objects":[{"SomeKeyID":1,"Value":3}],"SomeParam":"Lalala"}';
SELECT j.Parent, j.Path, j.Level, j.Param, j.Type, j.Value, j.GenericPath 
FROM dbo.SmartParseJSON(@json) j;

Example of multilevel use:

DECLARE @json NVARCHAR(MAX) = '{"Objects":[{"SomeKeyID":1,"Value":3}],"SomeParam":"Lalala"}';
DROP TABLE IF EXISTS #ParsedData;
SELECT j.Parent, j.Path, j.Level, j.Param, j.Type, j.Value, j.GenericPath 
INTO #ParsedData
FROM dbo.SmartParseJSON(@json) j;

SELECT COALESCE(p2.GenericPath,p.GenericPath) AS [GenericPath]
    ,COALESCE(p2.Param,p.Param) AS [Param]
    ,COALESCE(p2.Value,p.Value) AS [Value]
FROM #ParsedData p
LEFT JOIN #ParsedData p1 ON p1.Parent = p.Path AND p1.Level = 1
LEFT JOIN #ParsedData p2 ON p2.Parent = p1.Path AND p2.Level = 2
WHERE p.Level = 0
;
DROP TABLE IF EXISTS #ParsedData;

android: how to align image in the horizontal center of an imageview?

<ImageView
    android:id="@+id/img"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center" />

In Flask, What is request.args and how is it used?

request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method:

get(key, default=None, type=None)

Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible.

Subprocess check_output returned non-zero exit status 1

For Windows users: Try deleting files: java.exe, javaw.exe and javaws.exe from Windows\System32

My issue was the java version 1.7 installed.

Access properties file programmatically with Spring?

CREDIT: Programmatic access to properties in Spring without re-reading the properties file

I've found a nice implementation of accessing the properties programmatically in spring without reloading the same properties that spring has already loaded. [Also, It is not required to hardcode the property file location in the source]

With these changes, the code looks cleaner & more maintainable.

The concept is pretty simple. Just extend the spring default property placeholder (PropertyPlaceholderConfigurer) and capture the properties it loads in the local variable

public class SpringPropertiesUtil extends PropertyPlaceholderConfigurer {

    private static Map<String, String> propertiesMap;
    // Default as in PropertyPlaceholderConfigurer
    private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK;

    @Override
    public void setSystemPropertiesMode(int systemPropertiesMode) {
        super.setSystemPropertiesMode(systemPropertiesMode);
        springSystemPropertiesMode = systemPropertiesMode;
    }

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
        super.processProperties(beanFactory, props);

        propertiesMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
            propertiesMap.put(keyStr, valueStr);
        }
    }

    public static String getProperty(String name) {
        return propertiesMap.get(name).toString();
    }

}

Usage Example

SpringPropertiesUtil.getProperty("myProperty")

Spring configuration changes

<bean id="placeholderConfigMM" class="SpringPropertiesUtil">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
    <property name="locations">
    <list>
        <value>classpath:myproperties.properties</value>
    </list>
    </property>
</bean>

Hope this helps to solve the problems you have