Programs & Examples On #Provider independent

How to Display blob (.pdf) in an AngularJS app

I faced difficulties using "window.URL" with Opera Browser as it would result to "undefined". Also, with window.URL, the PDF document never opened in Internet Explorer and Microsoft Edge (it would remain waiting forever). I came up with the following solution that works in IE, Edge, Firefox, Chrome and Opera (have not tested with Safari):

$http.post(postUrl, data, {responseType: 'arraybuffer'})
.success(success).error(failed);

function success(data) {
   openPDF(data.data, "myPDFdoc.pdf");
};

function failed(error) {...};

function openPDF(resData, fileName) {
    var ieEDGE = navigator.userAgent.match(/Edge/g);
    var ie = navigator.userAgent.match(/.NET/g); // IE 11+
    var oldIE = navigator.userAgent.match(/MSIE/g); 

    var blob = new window.Blob([resData], { type: 'application/pdf' });

    if (ie || oldIE || ieEDGE) {
       window.navigator.msSaveBlob(blob, fileName);
    }
    else {
       var reader = new window.FileReader();
       reader.onloadend = function () {
          window.location.href = reader.result;
       };
       reader.readAsDataURL(blob);
    }
}

Let me know if it helped! :)

getString Outside of a Context or Activity

BTW, one of the reason of symbol not found error may be that your IDE imported android.R; class instead of yours one. Just change import android.R; to import your.namespace.R;

So 2 basic things to get string visible in the different class:

//make sure you are importing the right R class
import your.namespace.R;

//don't forget about the context
public void some_method(Context context) {
   context.getString(R.string.YOUR_STRING);
}

What does "hard coded" mean?

"hard coding" means putting something into your source code. If you are not hard coding, then you do something like prompting the user for the data, or allow the user to put the data on the command line, or something like that.

So, to hard code the location of the file as being on the C: drive, you would just put the pathname of the file all together in your source code.

Here is an example.

int main()
{
    const char *filename = "C:\\myfile.txt";

    printf("Filename is: %s\n", filename);
}

The file name is "hard coded" as: C:\myfile.txt

The reason the backslash is doubled is because backslashes are special in C strings.

How do I change the formatting of numbers on an axis with ggplot?

x <- rnorm(10) * 100000
y <- seq(0, 1, length = 10)
p <- qplot(x, y)
library(scales)
p + scale_x_continuous(labels = comma)

How to send an email using PHP?

this is very basic method to send plain text email using mail function.

<?php
$to = '[email protected]';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <[email protected]>";
mail($to,$subject,$message,$from);

Linux: is there a read or recv from socket with timeout?

// works also after bind operation for WINDOWS

DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

How do you get the process ID of a program in Unix or Linux using Python?

The task can be solved using the following piece of code, [0:28] being interval where the name is being held, while [29:34] contains the actual pid.

import os

program_pid = 0
program_name = "notepad.exe"

task_manager_lines = os.popen("tasklist").readlines()
for line in task_manager_lines:
    try:
        if str(line[0:28]) == program_name + (28 - len(program_name) * ' ': #so it includes the whitespaces
            program_pid = int(line[29:34])
            break
    except:
        pass

print(program_pid)

Create a hexadecimal colour based on a string with JavaScript

Here's a solution I came up with to generate aesthetically pleasing pastel colours based on an input string. It uses the first two chars of the string as a random seed, then generates R/G/B based on that seed.

It could be easily extended so that the seed is the XOR of all chars in the string, rather than just the first two.

Inspired by David Crow's answer here: Algorithm to randomly generate an aesthetically-pleasing color palette

//magic to convert strings to a nice pastel colour based on first two chars
//
// every string with the same first two chars will generate the same pastel colour
function pastel_colour(input_str) {

    //TODO: adjust base colour values below based on theme
    var baseRed = 128;
    var baseGreen = 128;
    var baseBlue = 128;

    //lazy seeded random hack to get values from 0 - 256
    //for seed just take bitwise XOR of first two chars
    var seed = input_str.charCodeAt(0) ^ input_str.charCodeAt(1);
    var rand_1 = Math.abs((Math.sin(seed++) * 10000)) % 256;
    var rand_2 = Math.abs((Math.sin(seed++) * 10000)) % 256;
    var rand_3 = Math.abs((Math.sin(seed++) * 10000)) % 256;

    //build colour
    var red = Math.round((rand_1 + baseRed) / 2);
    var green = Math.round((rand_2 + baseGreen) / 2);
    var blue = Math.round((rand_3 + baseBlue) / 2);

    return { red: red, green: green, blue: blue };
}

GIST is here: https://gist.github.com/ro-sharp/49fd46a071a267d9e5dd

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

You need to CAST the ParentId as an nvarchar, so that the output is always the same data type.

SELECT Id   'PatientId',
       ISNULL(CAST(ParentId as nvarchar(100)),'')  'ParentId'
FROM Patients

Adding items in a Listbox with multiple columns

select propety

Row Source Type => Value List

Code :

ListbName.ColumnCount=2

ListbName.AddItem "value column1;value column2"

Can "git pull --all" update all my local branches?

The script from @larsmans, a bit improved:

#!/bin/sh

set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
  if ["$branch" -ne "$CURRENT"]; then
    git checkout "$branch" || exit 1
    git rebase "origin/$branch" || exit 1
  fi
done
git checkout "$CURRENT" || exit 1
git rebase "origin/$CURRENT" || exit 1

This, after it finishes, leaves working copy checked out from the same branch as it was before the script was called.

The git pull version:

#!/bin/sh

set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
  if ["$branch" -ne "$CURRENT"]; then
    git checkout "$branch" || exit 1
    git pull || exit 1
  fi
done
git checkout "$CURRENT" || exit 1
git pull || exit 1

BEGIN - END block atomic transactions in PL/SQL

You don't mention if this is an anonymous PL/SQL block or a declarative one ie. Package, Procedure or Function. However, in PL/SQL a COMMIT must be explicitly made to save your transaction(s) to the database. The COMMIT actually saves all unsaved transactions to the database from your current user's session.

If an error occurs the transaction implicitly does a ROLLBACK.

This is the default behaviour for PL/SQL.

Sending data through POST request from a node.js server to a node.js server

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring');
var http = require('http');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

I had the same issue. In my home folder I've got a script named sqlplus.sh that takes care of this for me, containing:

ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
export ORACLE_HOME
ORACLE_SID=XE
export ORACLE_SID
NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export NLS_LANG
PATH=$ORACLE_HOME/bin:$PATH
export PATH
sqlplus /nolog

Write to Windows Application Event Log

You can using the EventLog class, as explained on How to: Write to the Application Event Log (Visual C#):

var appLog = new EventLog("Application");
appLog.Source = "MySource";
appLog.WriteEntry("Test log message");

However, you'll need to configure this source "MySource" using administrative privileges:

Use WriteEvent and WriteEntry to write events to an event log. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.

MVC: How to Return a String as JSON

Use the following code in your controller:

return Json(new { success = string }, JsonRequestBehavior.AllowGet);

and in JavaScript:

success: function (data) {
    var response = data.success;
    ....
}

Rename computer and join to domain in one step with PowerShell

As nobody answer, I try something :

I think I understand why Attent one does not work. It's because joining a computer to a domain is somehow also renaming the computer (the domain name part, enter in the name of the machine).

So do you try to do it in full WMI way, you've got a method in Win32_ComputerSystem class called JoinDomainOrWorkgroup. Doing it on the same level perhaps gives you more chance to make it work.

pull access denied repository does not exist or may require docker login

The message usually comes when you put the wrong image name. Please check your image if it exists on the Docker repository with the correct tag. It helped me.

docker run -d -p 80:80 --name ngnix ngnix:latest
Unable to find image 'ngnix:latest' locally
docker: Error response from daemon: pull access denied for ngnix, repository does not exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
$ docker run -d -p 80:80 --name nginx nginx:latest
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx

How do you debug PHP scripts?

Komodo IDE works well with xdebug, even for the remore debugging. It needs minimum amount of configuration. All you need is a version of php that Komodo can use locally to step through the code on a breakpoint. If you have the script imported into komodo project, then you can set breakpoints with a mouse-click just how you would set it inside eclipse for debugging a java program. Remote debugging is obviously more tricky to get it to work correctly ( you might have to map the remote url with a php script in your workspace ) than a local debugging setup which is pretty easy to configure if you are on a MAC or a linux desktop.

\n or \n in php echo not print

Better use PHP_EOL ("End Of Line") instead. It's cross-platform.

E.g.:

$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>' . PHP_EOL;
echo '<p>' . $unit2 . '</p>';

When does Git refresh the list of remote branches?

To update the local list of remote branches:

git remote update origin --prune

To show all local and remote branches that (local) Git knows about

git branch -a

Converting XML to JSON using Python?

This stuff here is actively maintained and so far is my favorite: xml2json in python

Zoom to fit: PDF Embedded in HTML

Bit late response to this question, however I do have something to add that might be useful for others.

If you make use of an iFrame and set the pdf file path to the src, it will load zoomed out to 100%, which the equivalence of FitH

Android XML Percent Symbol

Per google official documentation, use %1$s and %2$s http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

Hello, %1$s! You have %2$d new messages.

SQL Server AS statement aliased column within WHERE statement

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

Source: http://msdn.microsoft.com/en-us/library/ms189499%28v=sql.110%29.aspx

Deleting Elements in an Array if Element is a Certain value VBA

Deleting Elements in an Array if Element is a Certain value VBA

to delete elements in an Array wih certain condition, you can code like this

For i = LBound(ArrValue, 2) To UBound(ArrValue, 2)
    If [Certain condition] Then
        ArrValue(1, i) = "-----------------------"
    End If
Next i

StrTransfer = Replace(Replace(Replace(join(Application.Index(ArrValue(), 1, 0), ","), ",-----------------------,", ",", , , vbBinaryCompare), "-----------------------,", "", , , vbBinaryCompare), ",-----------------------", "", , , vbBinaryCompare)
ResultArray = join( Strtransfer, ",")

I often manipulate 1D-Array with Join/Split but if you have to delete certain value in Multi Dimension I suggest you to change those Array into 1D-Array like this

strTransfer = Replace(Replace(Replace(Replace(Names.Add("A", MultiDimensionArray), Chr(34), ""), "={", ""), "}", ""), ";", ",")
'somecode to edit Array like 1st code on top of this comment
'then loop through this strTransfer to get right value in right dimension
'with split function.

How to display Wordpress search results?

WordPress include tags, categories and taxonomies in search results

This code is taken from http://atiblog.com/custom-search-results/

Some functions here are taken from twentynineteen theme.Because it is made on this theme.

This code example will help you to include tags, categories or any custom taxonomy in your search. And show the posts contaning these tags or categories.

You need to modify your search.php of your theme to do so.

<?php
$search=get_search_query();
$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) ); 
$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );
//if you have any custom taxonomy
$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );

$mcat=array();
$mtag=array();
$mcustom_taxonomy=array();

foreach($all_categories as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}

foreach($all_tags as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}

foreach($all_custom_taxonomy as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcustom_taxonomy,$all->term_id);
}
}

$matched_posts=array();
$args1= array( 'post_status' => 'publish','posts_per_page' => -1,'tax_query' =>array('relation' => 'OR',array('taxonomy' => 'category','field' => 'term_id','terms' =>$mcat),array('taxonomy' => 'post_tag','field' => 'term_id','terms' =>$mtag),array('taxonomy' => 'custom_taxonomy','field' => 'term_id','terms' =>$mcustom_taxonomy)));

$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($matched_posts,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {

}

?>
<?php
// now we will do the normal wordpress search
$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
array_push($matched_posts,get_the_id());
}
wp_reset_postdata();
} else {

}
$matched_posts= array_unique($matched_posts);
$matched_posts=array_values(array_filter($matched_posts));
//print_r($matched_posts);
?>

<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );
if ( $query3->have_posts() ) {
while ( $query3->have_posts() ) {
$query3->the_post();
get_template_part( 'template-parts/content/content', 'excerpt' );
}
twentynineteen_the_posts_navigation();
wp_reset_postdata();
} else {

}
?>

Intercept and override HTTP requests from WebView

You don't mention the API version, but since API 11 there's the method WebViewClient.shouldInterceptRequest

Maybe this could help?

Error: the entity type requires a primary key

The entity type 'DisplayFormatAttribute' requires a primary key to be defined.

In my case I figured out the problem was that I used properties like this:

public string LastName { get; set; }  //OK
public string Address { get; set; }   //OK 
public string State { get; set; }     //OK
public int? Zip { get; set; }         //OK
public EmailAddressAttribute Email { get; set; } // NOT OK
public PhoneAttribute PhoneNumber { get; set; }  // NOT OK

Not sure if there is a better way to solve it but I changed the Email and PhoneNumber attribute to a string. Problem solved.

How to display list items on console window in C#

While the answers with List<T>.ForEach are very good.

I found String.Join<T>(string separator, IEnumerable<T> values) method more useful.

Example :

List<string> numbersStrLst = new List<string>
            { "One", "Two", "Three","Four","Five"};

Console.WriteLine(String.Join(", ", numbersStrLst));//Output:"One, Two, Three, Four, Five"

int[] numbersIntAry = new int[] {1, 2, 3, 4, 5};
Console.WriteLine(String.Join("; ", numbersIntAry));//Output:"1; 2; 3; 4; 5"

Remarks :

If separator is null, an empty string (String.Empty) is used instead. If any member of values is null, an empty string is used instead.

Join(String, IEnumerable<String>) is a convenience method that lets you concatenate each element in an IEnumerable(Of String) collection without first converting the elements to a string array. It is particularly useful with Language-Integrated Query (LINQ) query expressions.

This should work just fine for the problem, whereas for others, having array values. Use other overloads of this same method, String.Join Method (String, Object[])

Reference: https://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx

How to insert pandas dataframe via mysqldb into database?

You might output your DataFrame as a csv file and then use mysqlimport to import your csv into your mysql.

EDIT

Seems pandas's build-in sql util provide a write_frame function but only works in sqlite.

I found something useful, you might try this

How to find third or n?? maximum salary from salary table?

another way to find last highest data based on date

SELECT A.JID,A.EntryDate,RefundDate,Comments,Refund, ActionBy FROM (
(select JID, Max(EntryDate) AS EntryDate from refundrequested GROUP BY JID) A 
Inner JOIN (SELECT JID,ENTRYDATE,refundDate,Comments,refund,ActionBy from refundrequested) B 
ON A.JID=B.JID AND A.EntryDate = B.EntryDate) 

Find MongoDB records where array field is not empty

db.find({ pictures: { $elemMatch: { $exists: true } } })

$elemMatch matches documents that contain an array field with at least one element that matches the specified query.

So you're matching all arrays with at least an element.

Folder is locked and I can't unlock it

To unlock a file in your working copy from command prompt that is currently locked by another user, use --force option.

$ svn unlock --force tree.jpg

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

PHP: Split string

The following will return you the "a" letter:

$a = array_shift(explode('.', 'a.b'));

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

CSS/HTML: What is the correct way to make text italic?

I'd say use <em> to emphasize inline elements. Use a class for block elements like blocks of text. CSS or not, the text still has to be tagged. Whether its for semantics or for visual aid, I'm assuming you'd be using it for something meaningful...

If you're emphasizing text for ANY reason, you could use <em>, or a class that italicizes your text.

It's OK to break the rules sometimes!

Disable asp.net button after click to prevent double clicking

<script type = "text/javascript">
function DisableButtons() {
    var inputs = document.getElementsByTagName("INPUT");
    for (var i in inputs) {
        if (inputs[i].type == "button" || inputs[i].type == "submit") {
            inputs[i].disabled = true;
        }
    }
}
window.onbeforeunload = DisableButtons;
</script>

How to use (install) dblink in PostgreSQL?

Installing modules usually requires you to run an sql script that is included with the database installation.

Assuming linux-like OS

find / -name dblink.sql

Verify the location and run it

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

For different values of k, the approach will be different so there won't be a generic answer in terms of k. For example, for k=1 one can take advantage of the sum of natural numbers, but for k = n/2, one has to use some kind of bitset. The same way for k=n-1, one can simply compare the only number in the bag with the rest.

LPCSTR, LPCTSTR and LPTSTR

To answer the first part of your question:

LPCSTR is a pointer to a const string (LP means Long Pointer)

LPCTSTR is a pointer to a const TCHAR string, (TCHAR being either a wide char or char depending on whether UNICODE is defined in your project)

LPTSTR is a pointer to a (non-const) TCHAR string

In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.

This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)

How to align text below an image in CSS?

Instead of images i choose background option:

HTML:

  <div class="class1">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>    
  <div class="class2">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>
  <div class="class3">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>        

CSS:

  .class1 {

    background: url("Some.png") no-repeat top center;
    text-align: center;

   }

  .class2 {

    background: url("Some2.png") no-repeat top center;
    text-align: center;

   }

  .class3 {

    background: url("Some3.png") no-repeat top center;
    text-align: center;

   }

How to Inspect Element using Safari Browser

In your Safari menu bar click Safari > Preferences & then select the Advanced tab.

Select: "Show Develop menu in menu bar"

Now you can click Develop in your menu bar and choose Show Web Inspector

You can also right-click and press "Inspect element".

How to add new contacts in android

These examples are fine, I wanted to point out that you can achieve the same result using an Intent. The intent opens the Contacts app with the fields you provide already filled in.

It's up to the user to save the newly created contact.

You can read about it here: https://developer.android.com/training/contacts-provider/modify-data.html

Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
contactIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);

contactIntent
        .putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name")
        .putExtra(ContactsContract.Intents.Insert.PHONE, "5555555555");

startActivityForResult(contactIntent, 1);

startActivityForResult() gives you the opportunity to see the result.

I've noticed the resultCode works on >5.0 devices,

but I have an older Samsung (<5) that always returns RESULT_CANCELLED (0).

Which I understand is the default return if an activity doesn't expect to return anything.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == 1)
    {
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show();
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show();
        }
    }
}

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

You should use urllib2, like this:

import urllib2
for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]:
    try:
        connection = urllib2.urlopen(url)
        print connection.getcode()
        connection.close()
    except urllib2.HTTPError, e:
        print e.getcode()

# Prints:
# 200 [from the try block]
# 404 [from the except block]

Why is 22 the default port number for SFTP?

From Wikipedia:

Applications implementing common services often use specifically reserved, well-known port numbers for receiving service requests from client hosts. This process is known as listening and involves the receipt of a request on the well-known port and reestablishing one-to-one server-client communications on another private port, so that other clients may also contact the well-known service port. The well-known ports are defined by convention overseen by the Internet Assigned Numbers Authority (IANA).

Source

So as others mentioned, it's a convention.

Best way to convert an ArrayList to a string

This is quite an old conversation by now and apache commons are now using a StringBuilder internally: http://commons.apache.org/lang/api/src-html/org/apache/commons/lang/StringUtils.html#line.3045

This will as we know improve performance, but if performance is critical then the method used might be somewhat inefficient. Whereas the interface is flexible and will allow for consistent behaviour across different Collection types it is somewhat inefficient for Lists, which is the type of Collection in the original question.

I base this in that we are incurring some overhead which we would avoid by simply iterating through the elements in a traditional for loop. Instead there are some additional things happening behind the scenes checking for concurrent modifications, method calls etc. The enhanced for loop will on the other hand result in the same overhead since the iterator is used on the Iterable object (the List).

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

Put in other words, this error is telling you that SQL Server does not know which B to select from the group.

Either you want to select one specific value (e.g. the MIN, SUM, or AVG) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B in the GROUP BY field list).


Consider the following data:

ID  A   B
1   1  13
1   1  79
1   2  13
1   2  13
1   2  42

The query

SELECT A, COUNT(B) AS T1 
FROM T2 
GROUP BY A

would return:

A  T1
1  2
2  3

which is all well and good.

However consider the following (illegal) query, which would produce this error:

SELECT A, COUNT(B) AS T1, B 
FROM T2 
GROUP BY A

And its returned data set illustrating the problem:

A  T1  B
1  2   13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...?
2  3   13? 42? ...?

However, the following two queries make this clear, and will not cause the error:

  1. Using an aggregate

    SELECT A, COUNT(B) AS T1, SUM(B) AS B
    FROM T2
    GROUP BY A
    

    would return:

    A  T1  B
    1  2   92
    2  3   68
    
  2. Adding the column to the GROUP BY list

    SELECT A, COUNT(B) AS T1, B
    FROM T2
    GROUP BY A, B
    

    would return:

    A  T1  B
    1  1   13
    1  1   79
    2  2   13
    2  1   42
    

Check file extension in upload form in PHP

pathinfo is cool but your code can be improved:

$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = array('jpg','png','gif');
if( ! in_array( $ext, $allowed ) ) {echo 'error';}

Of course simply checking the extension of the filename would not guarantee the file type as a valid image. You may consider using a function like getimagesize to validate uploaded image files.

Is it possible to decrypt MD5 hashes?

No, he must have been confused about the MD5 dictionaries.

Cryptographic hashes (MD5, etc...) are one way and you can't get back to the original message with only the digest unless you have some other information about the original message, etc. that you shouldn't.

Multiple types were found that match the controller named 'Home'

In Route.config

namespaces: new[] { "Appname.Controllers" }

How to set viewport meta for iPhone that handles rotation properly?

<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">

suport all iphones, all ipads, all androids.

Get exit code of a background process

#/bin/bash

#pgm to monitor
tail -f /var/log/messages >> /tmp/log&
# background cmd pid
pid=$!
# loop to monitor running background cmd
while :
do
    ps ax | grep $pid | grep -v grep
    ret=$?
    if test "$ret" != "0"
    then
        echo "Monitored pid ended"
        break
    fi
    sleep 5

done

wait $pid
echo $?

"message failed to fetch from registry" while trying to install any module

This problem is due to the https protocol, which is why the other solution works (by switching to the non-secure protocol).

For me, the best solution was to compile the latest version of node, which includes npm

apt-get purge nodejs npm
git clone https://github.com/nodejs/node ~/local/node
cd ~/local/node
./configure
make
make install

Java/ JUnit - AssertTrue vs AssertFalse

The point is semantics. In assertTrue, you are asserting that the expression is true. If it is not, then it will display the message and the assertion will fail. In assertFalse, you are asserting that an expression evaluates to false. If it is not, then the message is displayed and the assertion fails.

assertTrue (message, value == false) == assertFalse (message, value);

These are functionally the same, but if you are expecting a value to be false then use assertFalse. If you are expecting a value to be true, then use assertTrue.

How to detect when an @Input() value changes in Angular?

Use the ngOnChanges() lifecycle method in your component.

ngOnChanges is called right after the data-bound properties have been checked and before view and content children are checked if at least one of them has changed.

Here are the Docs.

Hide HTML element by id

you can use CSS selectors

a[href="/questions/ask"] { display:none; }

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

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

Address already in use: JVM_Bind

I notice you are using windows, which is particularly bad about using low port numbers for outgoing sockets. See here for how to reserve the port number that you want to rely on using for glassfish.

Search code inside a Github project

UPDATE

The bookmarklet hack below is broken due to XHR issues and API changes.

Thankfully Github now has "A Whole New Code Search" which does the job superbly.


Checkout this voodoo: Github code search userscript.

Follow the directions there, or if you hate bloating your browser with scripts and extensions, use my bookmarkified bundle of the userscript:

javascript:(function(){var s='https://raw.githubusercontent.com/skratchdot/github-enhancement-suite/master/build/github-enhancement-suite.user.js',t='text/javascript',d=document,n=navigator,e;(e=d.createElement('script')).src=s;e.type=t;d.getElementsByTagName('head')[0].appendChild(e)})();doIt('');void('');

Save the source above as the URL of a new bookmark. Browse to any Github repo, click the bookmark, and bam: in-page, ajaxified code search.

CAVEAT Github must index a repo before you can search it.

Before the Bookmarklet

Abracadabra...

After - Look in the second menubar after the leftmost tabs: Files, Commits, Branches...

Here's a sample search from the annotated ECMAScript 5.1 specification repository:

Sample search in the annotated ECMAScript 5.1 specification repository

How to consume a SOAP web service in Java

I will use CXF also you can think of AXIS 2 .

The best way to do it may be using JAX RS Refer this example

Example:

wsimport -p stockquote http://stockquote.xyz/quote?wsdl

This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.

I

Bi-directional Map in Java?

You can use the Google Collections API for that, recently renamed to Guava, specifically a BiMap

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

Node.js get file extension

import extname in order to return the extension the file:

import { extname } from 'path';
extname(file.originalname);

where file is the file 'name' of form

How can I select an element by name with jQuery?

You can get the element in JQuery by using its ID attribute like this:

$("#tcol1").hide();

How to do if-else in Thymeleaf?

<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a> 
</span>
</span>
</div>

enter image description here

Correct way to import lodash

I just put them in their own file and export it for node and webpack:

// lodash-cherries.js
module.exports = {
  defaults: require('lodash/defaults'),
  isNil: require('lodash/isNil'),
  isObject: require('lodash/isObject'),
  isArray: require('lodash/isArray'),
  isFunction: require('lodash/isFunction'),
  isInteger: require('lodash/isInteger'),
  isBoolean: require('lodash/isBoolean'),
  keys: require('lodash/keys'),
  set: require('lodash/set'),
  get: require('lodash/get'),
}

Laravel blank white screen

I was also getting same error when I start first time on laravel + Ubuntu 14.04 I just right click on bootstrap and storage folder >>> properties >>>permission>> Others Access >>> change it to "Create and delete files" Change permission for enclosed files

Thank you

How to create a custom navigation drawer in android

The tutorial Android Custom Navigation Drawer (via archive.org) contains a basic and a custom project. The latter shows how to setup a Navigation Drawer as shown in the screenshot:

NavigationDrawerCustom

The source code of the projects (via archive.org) is available for download.


The is also the Navigation Drawer - Live-O project ...

Navigation Drawer - Live-O

The source code of the project is available on GitHub.


The MaterialDrawer library aims to provide the easiest possible implementation of a navigation drawer for your application. It provides a great amount of out of the box customizations and also includes an easy to use header which can be used as AccountSwitcher.

MaterialDrawer library demo


Please note that Android Studio meanwhile has a template project to create a Navigation Drawer Activity as shown in the screenshot.

Navigation Drawer Activity

This repository keeps track of changes being made to the template.

C# how to change data in DataTable?

Try the SetField method:

table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);

This should get the job done and is a bit "cleaner" than using Rows[i][j].

Convert seconds to Hour:Minute:Second

Well I needed something that would reduce seconds into hours minutes and seconds, but would exceed 24 hours, and not reduce further down into days.

Here is a simple function that works. You can probably improve it... But here it is:

function formatSeconds($seconds)
{
    $hours = 0;$minutes = 0;
    while($seconds >= 60){$seconds -= 60;$minutes++;}
    while($minutes >= 60){$minutes -=60;$hours++;}
    $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
    $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
    $seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);
    return $hours.":".$minutes.":".$seconds;
}

If else on WHERE clause

try this ,hope it helps

select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
 CASE 
    WHEN invitee_status=1 THEN "attending" 
    WHEN invitee_status=2 THEN "unsure" 
    WHEN invitee_status=3 THEN "declined" 
    WHEN invitee_status=0 THEN "notreviwed" END
) AS  invitee_status
 FROM your_tbl

Favorite Visual Studio keyboard shortcuts

Ctrl+K, Ctrl+D - Format the current document.

Helped me fix indentation and remove unneeded spaces quickly

How to see remote tags?

Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote:

git ls-remote --tags /url/to/upstream/repo

(as illustrated in "When listing git-ls-remote why there's “^{}” after the tag name?")

xbmono illustrates in the comments that quotes are needed:

git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"

Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):

git push --follow-tags

See Push git commits & tags simultaneously.


Regarding Atlassian SourceTree specifically:

Note that, from this thread, SourceTree ONLY shows local tags.

There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015 since Dec. 2015.

A simple workaround:

see a list of only unpushed tags?

git push --tags

or check the "Push all tags" box on the "Push" dialog box, all tags will be pushed to your remote.

https://community.atlassian.com/tnckb94959/attachments/tnckb94959/sourcetree-questions/10923/1/Screen%20Shot%202015-12-15%20at%208.49.48%20AM.png

That way, you will be "sure that they are present in remote so that other developers can pull them".

Python syntax for "if a or b or c but not all of them"

To be clear, you want to made your decision based on how much of the parameters are logical TRUE (in case of string arguments - not empty)?

argsne = (1 if a else 0) + (1 if b else 0) + (1 if c else 0)

Then you made a decision:

if ( 0 < argsne < 3 ):
 doSth() 

Now the logic is more clear.

jQuery 1.9 .live() is not a function

.live was removed in 1.9, please see the upgrade guide: http://jquery.com/upgrade-guide/1.9/#live-removed

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

SQL Client for Mac OS X that works with MS SQL Server

I thought Sequel Pro for MySQL looked pretty interesting. It's hard to find one tool that works with all those databases (especially SQL Server 2005 . . . most people use SQL Server Management Studio and that's Windows only of course).

Set initial focus in an Android application

@Someone Somewhere I used this to clear focus:

editText.clearFocus();

and it helps

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

SQL is a declarative language, not a procedural language. That is, you construct a SQL statement to describe the results that you want. You are not telling the SQL engine how to do the work.

As a general rule, it is a good idea to let the SQL engine and SQL optimizer find the best query plan. There are many person-years of effort that go into developing a SQL engine, so let the engineers do what they know how to do.

Of course, there are situations where the query plan is not optimal. Then you want to use query hints, restructure the query, update statistics, use temporary tables, add indexes, and so on to get better performance.

As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times. Unfortunately, SQL Server does not seem to take advantage of this basic optimization method (you might call this common subquery elimination).

Temporary tables are a different matter, because you are providing more guidance on how the query should be run. One major difference is that the optimizer can use statistics from the temporary table to establish its query plan. This can result in performance gains. Also, if you have a complicated CTE (subquery) that is used more than once, then storing it in a temporary table will often give a performance boost. The query is executed only once.

The answer to your question is that you need to play around to get the performance you expect, particularly for complex queries that are run on a regular basis. In an ideal world, the query optimizer would find the perfect execution path. Although it often does, you may be able to find a way to get better performance.

How can I get the height and width of an uiimage?

Some of the anwsers above, don't work well when rotating device.

Try:

CGRect imageContent = self.myUIImage.bounds;
CGFloat imageWidth = imageContent.size.width;
CGFloat imageHeight = imageContent.size.height;

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

What's the difference between event.stopPropagation and event.preventDefault?

stopPropagation prevents further propagation of the current event in the capturing and bubbling phases.

preventDefault prevents the default action the browser makes on that event.

Examples

preventDefault

_x000D_
_x000D_
$("#but").click(function (event) {
  event.preventDefault()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>
_x000D_
_x000D_
_x000D_

stopPropagation

_x000D_
_x000D_
$("#but").click(function (event) {
  event.stopPropagation()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>
_x000D_
_x000D_
_x000D_

With stopPropagation, only the button's click handler is called while the div's click handler never fires.

Where as if you use preventDefault, only the browser's default action is stopped but the div's click handler still fires.

Below are some docs on the DOM event properties and methods from MDN:

For IE9 and FF you can just use preventDefault & stopPropagation.

To support IE8 and lower replace stopPropagation with cancelBubble and replace preventDefault with returnValue

Transposing a 2D-array in JavaScript

You can do it in in-place by doing only one pass:

function transpose(arr,arrLen) {
  for (var i = 0; i < arrLen; i++) {
    for (var j = 0; j <i; j++) {
      //swap element[i,j] and element[j,i]
      var temp = arr[i][j];
      arr[i][j] = arr[j][i];
      arr[j][i] = temp;
    }
  }
}

How to initialize a vector of vectors on a struct?

You use new to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

You have no reason to use new, since A is an automatic variable. You can simply initialise A using its constructor:

vector<vector<int> > A(dimension, vector<int>(dimension));

Proper way to empty a C-String

I'm a beginner but...Up to my knowledge,the best way is

strncpy(dest_string,"",strlen(dest_string));

jquery: get value of custom attribute

You can also do this by passing function with onclick event

<a onclick="getColor(this);" color="red">

<script type="text/javascript">

function getColor(el)
{
     color = $(el).attr('color');
     alert(color);
}

</script> 

JOIN two SELECT statement results

Try something like this:

SELECT 
* 
FROM
(SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1 
INNER JOIN
(SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON t1.ks = t2.ks

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

"Register" an .exe so you can run it from any command line in Windows

Another way could be through adding .LNK to your $PATHEX. Then just create a shortcut to your executable (ie: yourshortcut.lnk) and put it into any of the directories listed within $PATH.

WARNING NOTE: Know that any .lnk files located in any directories listed in your $PATH are now "PATH'ed" as well. For this reason, I would favor the batch file method mentionned earlier to this method.

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

How do I grant myself admin access to a local SQL Server instance?

I adopted a SQL 2012 database where I was not a sysadmin but was an administrator on the machine. I used SSMS with "Run as Administrator", added my NT account as a SQL login and set the server role to sysadmin. No problem.

Initializing array of structures

my_data is a struct with name as a field and data[] is arry of structs, you are initializing each index. read following:

5.20 Designated Initializers:

In a structure initializer, specify the name of a field to initialize with .fieldname =' before the element value. For example, given the following structure,

struct point { int x, y; };

the following initialization

struct point p = { .y = yvalue, .x = xvalue };

is equivalent to

struct point p = { xvalue, yvalue };

Another syntax which has the same meaning, obsolete since GCC 2.5, is fieldname:', as shown here:

struct point p = { y: yvalue, x: xvalue };

You can also write:

my_data data[] = {
    { .name = "Peter" },
    { .name = "James" },
    { .name = "John" },
    { .name = "Mike" }
};

as:

my_data data[] = {
    [0] = { .name = "Peter" },
    [1] = { .name = "James" },
    [2] = { .name = "John" },
    [3] = { .name = "Mike" }
}; 

or:

my_data data[] = {
    [0].name = "Peter",
    [1].name = "James",
    [2].name = "John",
    [3].name = "Mike"
}; 

Second and third forms may be convenient as you don't need to write in order for example all of the above example are equivalent to:

my_data data[] = {
    [3].name = "Mike",
    [1].name = "James",
    [0].name = "Peter",
    [2].name = "John"
}; 

If you have multiple fields in your struct (for example, an int age), you can initialize all of them at once using the following:

my_data data[] = {
    [3].name = "Mike",
    [2].age = 40,
    [1].name = "James",
    [3].age = 23,
    [0].name = "Peter",
    [2].name = "John"
}; 

To understand array initialization read Strange initializer expression?

Additionally, you may also like to read @Shafik Yaghmour's answer for switch case: What is “…” in switch-case in C code

Querying data by joining two tables in two database on different servers

You could try the following:

select customer1.Id,customer1.Name,customer1.city,CustAdd.phone,CustAdd.Country
from customer1
inner join [EBST08].[Test].[dbo].[customerAddress] CustAdd
on customer1.Id=CustAdd.CustId

Sublime Text 2 - View whitespace characters

A "quick and dirty" way is to use the find function and activate regular expressions.

Then just search for : \s for highlighting spaces \t for tabs \n for new-lines etc.

Adding blur effect to background in swift

let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
                    let blurEffectView = UIVisualEffectView(effect: blurEffect)
                    blurEffectView.backgroundColor = .black
                    blurEffectView.alpha = 0.5
                    blurEffectView.frame = topView.bounds
                    if !self.presenting {
                        blurEffectView.frame.origin.x = 0
                    } else {
                        blurEffectView.frame.origin.x = -topView.frame.width
                    }
                    blurEffectView.frame.origin.x = -topView.frame.width
                    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                    UIView.animate(withDuration: 0.2, delay: 0.0, options: [.curveEaseIn]) {
                        if !self.presenting {
                            blurEffectView.frame.origin.x = -topView.frame.width
                        } else {
                            blurEffectView.frame.origin.x = 0
                        }
                        view.addSubview(blurEffectView)
                    } completion: { (status) in
                        
                    }

Sibling package imports

For siblings package imports, you can use either the insert or the append method of the [sys.path][2] module:

if __name__ == '__main__' and if __package__ is None:
    import sys
    from os import path
    sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
    import api

This will work if you are launching your scripts as follows:

python examples/example_one.py
python tests/test_one.py

On the other hand, you can also use the relative import:

if __name__ == '__main__' and if __package__ is not None:
    import ..api.api

In this case you will have to launch your script with the '-m' argument (note that, in this case, you must not give the '.py' extension):

python -m packageName.examples.example_one
python -m packageName.tests.test_one

Of course, you can mix the two approaches, so that your script will work no matter how it is called:

if __name__ == '__main__':
    if __package__ is None:
        import sys
        from os import path
        sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
        import api
    else:
        import ..api.api

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

Convert Numeric value to Varchar

First convert the numeric value then add the 'S':

 select convert(varchar(10),StandardCost) +'S'
 from DimProduct where ProductKey = 212

How to change package name of Android Project in Eclipse?

Press F2 and then rename it (or right click on the project and select Rename). It changes wherever that package is declared in your project. It's automatically renamed all over.

How to make a div with no content have a width?

Use min-height: 1px; Everything has at least min-height of 1px so no extra space is taken up with nbsp or padding, or being forced to know the height first.

How to Generate Unique ID in Java (Integer)?

Unique at any time:

int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);

Calling a function of a module by using its name (a string)

Given a string, with a complete python path to a function, this is how I went about getting the result of said function:

import importlib
function_string = 'mypackage.mymodule.myfunc'
mod_name, func_name = function_string.rsplit('.',1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
result = func()

Data binding in React

To bind a control to your state you need to call a function on the component that updates the state from the control's event handler.

Rather than have an update function for all your form fields, you could create a generic update function using ES6 computed name feature and pass it the values it needs inline from the control like this:

_x000D_
_x000D_
class LovelyForm extends React.Component {_x000D_
  constructor(props) {_x000D_
  alert("Construct");_x000D_
    super(props);_x000D_
    this.state = {_x000D_
      field1: "Default 1",_x000D_
      field2: "Default 2"_x000D_
    };_x000D_
  }_x000D_
_x000D_
  update = (name, e) => {_x000D_
    this.setState({ [name]: e.target.value });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <form>_x000D_
        <p><input type="text" value={this.state.field1} onChange={(e) => this.update("field1", e)} />_x000D_
          {this.state.field1}</p>_x000D_
        <p><input type="text" value={this.state.field2} onChange={(e) => this.update("field2", e)} />_x000D_
          {this.state.field2}</p>_x000D_
      </form>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
ReactDOM.render(<LovelyForm/>, document.getElementById('example'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="example"></div>
_x000D_
_x000D_
_x000D_

How can my iphone app detect its own version number?

This is a good thing to handle with a revision control system. That way when you get a bug report from a user, you can check out that revision of code and (hopefully) reproduce the bug running the exact same code as the user.

The idea is that every time you do a build, you will run a script that gets the current revision number of your code and updates a file within your project (usually with some form of token replacement). You can then write an error handling routine that always includes the revision number in the error output, or you can display it on an "About" page.

PHP Constants Containing Arrays?

Using explode and implode function we can improvise a solution :

$array = array('lastname', 'email', 'phone');
define('DEFAULT_ROLES', implode (',' , $array));
echo explode(',' ,DEFAULT_ROLES ) [1]; 

This will echo email.

If you want it to optimize it more you can define 2 functions to do the repetitive things for you like this :

//function to define constant
function custom_define ($const , $array) {
    define($const, implode (',' , $array));
}

//function to access constant  
function return_by_index ($index,$const = DEFAULT_ROLES) {
            $explodedResult = explode(',' ,$const ) [$index];
    if (isset ($explodedResult))
        return explode(',' ,$const ) [$index] ;
}

Hope that helps . Happy coding .

Create a Date with a set timezone without using a string representation

I used the timezone-js package.

var timezoneJS  = require('timezone-js');
var tzdata = require('tzdata');

createDate(dateObj) {
    if ( dateObj == null ) {
        return null;
    }
    var nativeTimezoneOffset = new Date().getTimezoneOffset();
    var offset = this.getTimeZoneOffset();

    // use the native Date object if the timezone matches
    if ( offset == -1 * nativeTimezoneOffset ) {
        return dateObj;
    }

    this.loadTimeZones();

    // FIXME: it would be better if timezoneJS.Date was an instanceof of Date
    //        tried jquery $.extend
    //        added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
    return new timezoneJS.Date(dateObj,this.getTimeZoneName());
},

How can we stop a running java process through Windows cmd?

start javaw -DSTOP.PORT=8079 -DSTOP.KEY=secret -jar start.jar

start javaw -DSTOP.PORT=8079 -DSTOP.KEY=secret -jar start.jar --stop

How to find the port for MS SQL Server 2008?

Click on Start button in Windows.

Go to All Programs -> Microsoft SQL Server 2008 -> Configuration Tools -> SQL Server Configuration Manager

Click on SQL Native Client 10.0 Configuration -> Client Protocols -> TCP/IP double click ( Right click select Properties ) on TCP/IP.

You will find Default Port 1433.

Depending on connection, the port number may vary.

Oracle PL Sql Developer cannot find my tnsnames.ora file

Which Oracle client are you using?

Oracle 64bit 11g client isn't support in PLSQL Developer. Try to install 32bits client.

How can I determine if an image has loaded, using Javascript/jQuery?

There's a jQuery plugin called "imagesLoaded" that provides a cross-browser compatible method to check if an element's image(s) have been loaded.

Site: https://github.com/desandro/imagesloaded/

Usage for a container that has many images inside:

$('container').imagesLoaded(function(){
 console.log("I loaded!");
})

The plugin is great:

  1. works for checking a container with many images inside
  2. works for check an img to see if it has loaded

How to scroll to bottom in react?

Using React.createRef()

class MessageBox extends Component {
        constructor(props) {
            super(props)
            this.boxRef = React.createRef()
        }

        scrollToBottom = () => {
            this.boxRef.current.scrollTop = this.boxRef.current.scrollHeight
        }

        componentDidUpdate = () => {
            this.scrollToBottom()
        }

        render() {
            return (
                        <div ref={this.boxRef}></div>
                    )
        }
}

How to use PHP to connect to sql server

  1. first download below software https://www.microsoft.com/en-us/download/details.aspx?id=30679 - need to install

https://www.microsoft.com/en-us/download/details.aspx?id=20098 - when you run this software . it will extract dll file. and paste two dll file(php_pdo_sqlsrv_55_ts.dll,extension=php_sqlsrv_55_ts.dll) this location C:\wamp\bin\php\php5.6.40\ext\ (pls make sure your current version)

2)edit php.ini file add below line extension=php_pdo_sqlsrv_55_ts.dll extension=php_sqlsrv_55_ts.dll

Please refer screenshort add dll in your php.ini file

Check if value is zero or not null in python

The simpler way:

h = ''
i = None
j = 0
k = 1
print h or i or j or k

Will print 1

print k or j or i or h

Will print 1

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

I had a similar problem but all answers here didn't help me.

For me the problem was a failing test. If you are doing test driven development than a failing / not implemented test shouldn't break the build. I still want my project to build.

To solve this I added a configuration to surefire so that it ignores a failing test.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <testFailureIgnore>true</testFailureIgnore>
    </configuration>
</plugin>

How to compare 2 files fast using .NET?

The only thing that might make a checksum comparison slightly faster than a byte-by-byte comparison is the fact that you are reading one file at a time, somewhat reducing the seek time for the disk head. That slight gain may however very well be eaten up by the added time of calculating the hash.

Also, a checksum comparison of course only has any chance of being faster if the files are identical. If they are not, a byte-by-byte comparison would end at the first difference, making it a lot faster.

You should also consider that a hash code comparison only tells you that it's very likely that the files are identical. To be 100% certain you need to do a byte-by-byte comparison.

If the hash code for example is 32 bits, you are about 99.99999998% certain that the files are identical if the hash codes match. That is close to 100%, but if you truly need 100% certainty, that's not it.

Extension methods must be defined in a non-generic static class

I was scratching my head with this compiler error. My class was not an extension method, was working perfectly since months and needed to stay non-static. I had included a new method inside the class:

private static string TrimNL(this string Value)
{...}

I had copied the method from a sample and didn't notice the "this" modifier in the method signature, which is used in extension methods. Removing it solved the issue.

MD5 is 128 bits but why is it 32 characters?

That's 32 hex characters - 1 hex character is 4 bits.

Get the generated SQL statement from a SqlCommand object?

I also had this issue where some parameterized queries or sp's would give me a SqlException (mostly the string or binary data would be truncated), and the statements where hard to debug (As far as i know there currently is no sql-profiler support for SQL Azure)

I see a lot of simular code in reactions here. I ended up putting my solution in a Sql-Library project for future use.

The generator is available here: https://github.com/jeroenpot/SqlHelper/blob/master/Source/Mirabeau.MsSql.Library/SqlGenerator.cs

It supports both CommandType.Text and CommandType.StoredProcedure

And if you install the nuget-package you can generate it with this statement:

SqlDebugHelper.CreateExecutableSqlStatement(sql, parameters);

How to get the selected radio button’s value?

This works with any explorer.

document.querySelector('input[name="genderS"]:checked').value;

This is a simple way to get the value of any input type. You also do not need to include jQuery path.

OnChange event using React JS for drop down

React Hooks (16.8+):

const Dropdown = ({
  options
}) => {
  const [selectedOption, setSelectedOption] = useState(options[0].value);
  return (
      <select
        value={selectedOption}
        onChange={e => setSelectedOption(e.target.value)}>
        {options.map(o => (
          <option key={o.value} value={o.value}>{o.label}</option>
        ))}
      </select>
  );
};

Get IPv4 addresses from Dns.GetHostEntry()

    public Form1()
    {
        InitializeComponent();

        string myHost = System.Net.Dns.GetHostName();
        string myIP = null;

        for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
        {
            if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
            {
                myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
            }
        }
    }

Declare myIP and myHost in public Variable and use in any function of the form.

How to retrieve form values from HTTPPOST, dictionary or?

The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.


Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.

<input type="hidden"   name="TrackingID" 
<input type="text"     name="FirstName"  id="firstnametext" />
<input type="checkbox" name="IsLegal"  value="Do you accept terms and conditions?" />

Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string is nullable)) otherwise the AJAX or POST back will fail.

[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
    MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}

You can also post back a model without using any razor helpers. I have come across that this is needed some times.

public Class HomeModel
{
  public int HouseNumber { get; set; }
  public string StreetAddress { get; set; }
}

The HTML markup will simply be ...

<input type="text" name="variableName.HouseNumber" id="whateverid" >

and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.

[HttpPost]
public ActionResult PostBack(HomeModel variableName){
    postBack.HouseNumber; //The value user entered
    postBack.StreetAddress; //the default value of NULL.
}

When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.

TIP: The name of the parameter in the controller is the name defined in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !


Using List<> is bit more complex in its mark-up.

<input type="text" name="variableNameHere[0].HouseNumber" id="id"           value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber"                   value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">

Index on List<> MUST always be zero based and sequential. 0,1,2,3.

[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
     int counter = MyHomes.Count()
     foreach(var home in MyHomes)
     { ... }
}

Using IEnumerable<> for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.

<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id"      value="3">

<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3"   value="4">

<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23"    value="5">

And the code just needs to use IEnumerable and call ToList()

[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
     int counter = variableNameHere.ToList().Count()
     foreach(var home in variableNameHere)
     { ... }
}

It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.

So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.

Eclipse internal error while initializing Java tooling

check the Eclipse log (the intelligently named ".log" file in your workspace .metadata folder) and check for the complete stacktrace. In my case it was caused at method "org.eclipse.m2e.jdt.internal.MavenClasspathVariableInitializer.initialize(MavenClasspathVariableInitializer.java:30)" which lead to a never fixed "race condition during startup" bug. I would really recommend dumping Eclipse in favor of a more serious IDE; like IntelliJ or Netbeans. Using Eclipse means that you will invest 40-50% of your time trying to work around this kind of bugs, instead of being productive.

Equivalent of Oracle's RowID in SQL Server

Several of the answers above will work around the lack of a direct reference to a specific row, but will not work if changes occur to the other rows in a table. That is my criteria for which answers fall technically short.

A common use of Oracle's ROWID is to provide a (somewhat) stable method of selecting rows and later returning to the row to process it (e.g., to UPDATE it). The method of finding a row (complex joins, full-text searching, or browsing row-by-row and applying procedural tests against the data) may not be easily or safely re-used to qualify the UPDATE statement.

The SQL Server RID seems to provide the same functionality, but does not provide the same performance. That is the only issue I see, and unfortunately the purpose of retaining a ROWID is to avoid repeating an expensive operation to find the row in, say, a very large table. Nonetheless, performance for many cases is acceptable. If Microsoft adjusts the optimizer in a future release, the performance issue could be addressed.

It is also possible to simply use FOR UPDATE and keep the CURSOR open in a procedural program. However, this could prove expensive in large or complex batch processing.

Caveat: Even Oracle's ROWID would not be stable if the DBA, between the SELECT and the UPDATE, for example, were to rebuild the database, because it is the physical row identifier. So the ROWID device should only be used within a well-scoped task.

How do we update URL or query strings using javascript/jQuery without reloading the page?

Yes

document.location is the normal way.

However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.

Check out this thread on SO for more info:

What's the difference between window.location and document.location in JavaScript?

How do I activate a Spring Boot profile when running from IntelliJ?

In my case I used below configuration at VM options in IntelliJ , it was not picking the local configurations but after a restart of IntelliJ it picked configuration details from IntelliJ and service started running.

-Dspring.profiles.active=local

Compile Views in ASP.NET MVC

Using Visual Studio's Productivity Power Tools (free) extension helps a bit. Specifically, the Solution Error Visualizer feature. With it, compilation errors marked visually in the solution explorer (in the source file where the error was found). For some reason, however, this feature does not work as with other errors anywhere else in the code.

With MVC views, any compile-time errors will still be underlined in red in their respective .cs files, but signaling these errors is not propagated upwards in the Solution Explorer (in no way, even not in the containing source file).

Thanks for BlueClouds for correcting my previous statement.

I have just reported this as an issue on the extension's github project.

Pylint "unresolved import" error in Visual Studio Code

None of the answers here solved this error for me. Code would run, but I could not jump directly to function definitions. It was only for certain local packages. For one thing, python.jediEnabled is no longer a valid option. I did two things, but I am not sure the first was necessary:

  1. Download Pylance extension, change python.languageServer to "Pylance"
  2. Add "python.analysis.extraPaths": [ "path_to/src_file" ]

Apparently the root and src will be checked for local packages, but others must be added here.

Android Material Design Button Styles

I will add my answer since I don't use any of the other answers provided.

With the Support Library v7, all the styles are actually already defined and ready to use, for the standard buttons, all of these styles are available:

style="@style/Widget.AppCompat.Button"
style="@style/Widget.AppCompat.Button.Colored"
style="@style/Widget.AppCompat.Button.Borderless"
style="@style/Widget.AppCompat.Button.Borderless.Colored"

Widget.AppCompat.Button: enter image description here

Widget.AppCompat.Button.Colored: enter image description here

Widget.AppCompat.Button.Borderless enter image description here

Widget.AppCompat.Button.Borderless.Colored: enter image description here


To answer the question, the style to use is therefore

<Button style="@style/Widget.AppCompat.Button.Colored"
.......
.......
.......
android:text="Button"/>

How to change the color

For the whole app:

The color of all the UI controls (not only buttons, but also floating action buttons, checkboxes etc.) is managed by the attribute colorAccent as explained here. You can modify this style and apply your own color in your theme definition:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    ...
    <item name="colorAccent">@color/Orange</item>
</style>

For a specific button:

If you need to change the style of a specific button, you can define a new style, inheriting one of the parent styles described above. In the example below I just changed the background and font colors:

<style name="AppTheme.Button" parent="Widget.AppCompat.Button.Colored">
    <item name="colorButtonNormal">@color/Red</item>
    <item name="android:textColor">@color/White</item>
</style>

Then you just need to apply this new style on the button with:

android:theme="@style/AppTheme.Button"

To set a default button design in a layout, add this line to the styles.xml theme:

<item name="buttonStyle">@style/btn</item>

where @style/btn is your button theme. This sets the button style for all the buttons in a layout with a specific theme

Why should I use IHttpActionResult instead of HttpResponseMessage?

We have the following benefits of using IHttpActionResult over HttpResponseMessage:

  1. By using the IHttpActionResult we are only concentrating on the data to be send not on the status code. So here the code will be cleaner and very easy to maintain.
  2. Unit testing of the implemented controller method will be easier.
  3. Uses async and await by default.

What is a Windows Handle?

So at the most basic level a HANDLE of any sort is a pointer to a pointer or

#define HANDLE void **

Now as to why you would want to use it

Lets take a setup:

class Object{
   int Value;
}

class LargeObj{

   char * val;
   LargeObj()
   {
      val = malloc(2048 * 1000);
   }

}

void foo(Object bar){
    LargeObj lo = new LargeObj();
    bar.Value++;
}

void main()
{
   Object obj = new Object();
   obj.val = 1;
   foo(obj);
   printf("%d", obj.val);
}

So because obj was passed by value (make a copy and give that to the function) to foo, the printf will print the original value of 1.

Now if we update foo to:

void foo(Object * bar)
{
    LargeObj lo = new LargeObj();
    bar->val++;
}

There is a chance that the printf will print the updated value of 2. But there is also the possibility that foo will cause some form of memory corruption or exception.

The reason is this while you are now using a pointer to pass obj to the function you are also allocating 2 Megs of memory, this could cause the OS to move the memory around updating the location of obj. Since you have passed the pointer by value, if obj gets moved then the OS updates the pointer but not the copy in the function and potentially causing problems.

A final update to foo of:

void foo(Object **bar){
    LargeObj lo = LargeObj();
    Object * b = &bar;
    b->val++;
}

This will always print the updated value.

See, when the compiler allocates memory for pointers it marks them as immovable, so any re-shuffling of memory caused by the large object being allocated the value passed to the function will point to the correct address to find out the final location in memory to update.

Any particular types of HANDLEs (hWnd, FILE, etc) are domain specific and point to a certain type of structure to protect against memory corruption.

What is the App_Data folder used for in Visual Studio?

in IIS, highlight the machine, double-click "Request Filtering", open the "Hidden Segments" tab. "App_Data" is listed there as a restricted folder. Yes i know this thread is really old, but this is still applicable.

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

when using the categorical_crossentropy loss, your targets should be in categorical format (e.g. if you have 10 classes, the target for each sample should be a 10-dimensional vector that is all-zeros except for a 1 at the index corresponding to the class of the sample).

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

Check if a variable is a string in JavaScript

This is what works for me:

if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else

Permissions error when connecting to EC2 via SSH on Mac OSx

Two possibilities I can think of, although they are both mentioned in the link you referenced:

  1. You're not specifying the correct SSH keypair file or user name in the ssh command you're using to log into the server:

    ssh -i [full path to keypair file] root@[EC2 instance hostname or IP address]

  2. You don't have the correct permissions on the keypair file; you should use

    chmod 600 [keypair file]

to ensure that only you can read or write the file.

Try using the -v option with ssh to get more info on where exactly it's failing, and post back here if you''d like more help.

[Update]: OK, so this is what you should have seen if everything was set up properly:

debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: Next authentication method: publickey
debug1: Trying private key: ec2-keypair
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).

Are you running the ssh command from the directory containing the ec2-keypair file ? If so, try specifying -i ./ec2-keypair just to eliminate path problems. Also check "ls -l [full path to ec2-keypair]" file and make sure the permissions are 600 (displayed as rw-------). If none of that works, I'd suspect the contents of the keypair file, so try recreating it using the steps in your link.

How do you use https / SSL on localhost?

It is easy to create a self-signed certificate, import it, and bind it to your website.

1.) Create a self-signed certificate:

Run the following 4 commands, one at a time, from an elevated Command Prompt:

cd C:\Program Files (x86)\Windows Kits\8.1\bin\x64

makecert -r -n "CN=localhost" -b 01/01/2000 -e 01/01/2099 -eku 1.3.6.1.5.5.7.3.3 -sv localhost.pvk localhost.cer

cert2spc localhost.cer localhost.spc

pvk2pfx -pvk localhost.pvk -spc localhost.spc -pfx localhost.pfx

2.) Import certificate to Trusted Root Certification Authorities store:

start --> run --> mmc.exe --> Certificates plugin --> "Trusted Root Certification Authorities" --> Certificates

Right-click Certificates --> All Tasks --> Import Find your "localhost" Certificate at C:\Program Files (x86)\Windows Kits\8.1\bin\x64\

3.) Bind certificate to website:

start --> (IIS) Manager --> Click on your Server --> Click on Sites --> Click on your top level site --> Bindings

Add or edit a binding for https and select the SSL certificate called "localhost".

4.) Import Certificate to Chrome:

Chrome Settings --> Manage Certificates --> Import .pfx certificate from C:\certificates\ folder

Test Certificate by opening Chrome and navigating to https://localhost/

How to read input from console in a batch file?

If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough

set /p asd="Hit enter to continue"

at the end of your script and it'll keep the window open.

Note that this'll set asd as an environment variable, and can be replaced with anything else.

How to get a value of an element by name instead of ID

Use the name attribute selector:

$("input[name='nameGoesHere']").val();

It is a mandatory requirement to include quotes around the value, see: http://api.jquery.com/attribute-equals-selector/

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

After you get the error, run

EXEC sp_who2

Look for the database in the list. It's possible that a connection was not terminated. If you find any connections to the database, run

KILL <SPID>

where <SPID> is the SPID for the sessions that are connected to the database.

Try your script after all connections to the database are removed.

Unfortunately, I don't have a reason why you're seeing the problem, but here is a link that shows that the problem has occurred elsewhere.

http://www.geakeit.co.uk/2010/12/11/sql-take-offline-fails-alter-database-failed-because-a-lock-could-not-error-5061/

str_replace with array

Alternatively to the answer marked as correct, if you have to replace words instead of chars you can do it with this piece of code :

$query = "INSERT INTO my_table VALUES (?, ?, ?, ?);";
$values = Array("apple", "oranges", "mangos", "papayas");
foreach (array_fill(0, count($values), '?') as $key => $wildcard) {
    $query = substr_replace($query, '"'.$values[$key].'"', strpos($query, $wildcard), strlen($wildcard));
}
echo $query;

Demo here : http://sandbox.onlinephpfunctions.com/code/56de88aef7eece3d199d57a863974b84a7224fd7

ActiveX component can't create object

If its a 32 bit COM/Active X, use version 32 bit of cscript.exe/wscript.exe located in C:\Windows\SysWOW64\

How to convert C++ Code to C

Maybe good ol' cfront will do?

json.dumps vs flask.jsonify

consider

data={'fld':'hello'}

now

jsonify(data)

will yield {'fld':'hello'} and

json.dumps(data)

gives

"<html><body><p>{'fld':'hello'}</p></body></html>"

form_for but to post to a different action

The following works for me:

form_for @user, :url => {:action => "YourActionName"}

-didSelectRowAtIndexPath: not being called

I was having problem that control was not going in to didselect row after applying break point. problem was in view. I removed tab gesture from view. then its worked fine

How to pass all arguments passed to my bash script to a function of mine?

abc "$@"

$@ represents all the parameters given to your bash script.

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

If your text will be consumed by non-browsers then it's safer to type the character with the keyboard-combo option shift right bracket because &rsquo; will not be transformed into an apostrophe by a regular XML or JSON parser. (e.g. if you are serving this content to native Android/iOS apps).

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

Im my browser, this doesn't work at all. The tooltip field doesn't show a link, but <a href='#' onClick='alert('Hello World!')>The Link</a>. I'm using FF 3.6.12.

You'll have to do this by hand with JS and CSS. Begin here

Update ViewPager dynamically?

for those who still face the same problem which i faced before when i have a ViewPager with 7 fragments. the default for these fragments to load the English content from API service but the problem here that i want to change the language from settings activity and after finish settings activity i want ViewPager in main activity to refresh the fragments to match the language selection from the user and load the Arabic content if user chooses Arabic here what i did to work from the first time

1- You must use FragmentStatePagerAdapter as mentioned above.

2- on mainActivity i override the onResume and did the following

if (!(mPagerAdapter == null)) {
    mPagerAdapter.notifyDataSetChanged();
}

3-i overrided the getItemPosition() in mPagerAdapter and make it return POSITION_NONE.

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}

works like charm

Passing arguments to an interactive program non-interactively

Just want to add one more way. Found it elsewhere, and is quite simple. Say I want to pass yes for all the prompts at command line for a command "execute_command", Then I would simply pipe yes to it.

yes | execute_command

This will use yes as the answer to all yes/no prompts.

Print values for multiple variables on the same line from within a for-loop

Try out cat and sprintf in your for loop.

eg.

cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))

See here

Does a `+` in a URL scheme/host/path represent a space?

Thou shalt always encode URLs.

Here is how Ruby encodes your URL:

irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"

How do I redirect users after submit button click?

It would be

window.location="login.php";

REST / SOAP endpoints for a WCF service

You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>

An example of endpoint configuration in your scenario is

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>

so, the service will be available at

Apply [WebGet] to the operation contract to make it RESTful. e.g.

public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}

Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.

Reply to the post for SOAP and RESTful POX(XML)

For plain old XML as return format, this is an example that would work both for SOAP and XML.

[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}

POX behavior for REST Plain Old XML

<behavior name="poxBehavior">
  <webHttp/>
</behavior>

Endpoints

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>

Service will be available at

REST request try it in browser,

http://www.example.com/xml/accounts/A123

SOAP request client endpoint configuration for SOAP service after adding the service reference,

  <client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>

in C#

TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");

Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.

SelectedValue vs SelectedItem.Value of DropDownList

Be careful using SelectedItem.Text... If there is no item selected, then SelectedItem will be null and SelectedItem.Text will generate a null-value exception.

.NET should have provided a SelectedText property like the SelectedValue property that returns String.Empty when there is no selected item.

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

It is because * is used as a metacharacter to signify one or more occurences of previous character. So if i write M* then it will look for files MMMMMM..... ! Here you are using * as the only character so the compiler is looking for the character to find multiple occurences of,so it throws the exception.:)

CSS Pseudo-classes with inline styles

or you can simply try this in inline css

<textarea style="::placeholder{color:white}"/>

How do I loop through items in a list box and then remove those item?

while(listbox.Items.Remove(s)) ; should work, as well. However, I think the backwards solution is the fastest.

Running EXE with parameters

System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

How to add a margin to a table row <tr>

I gave up and inserted a simple jQuery code as below. This will add a tr after every tr, if you have so many trs like me. Demo: https://jsfiddle.net/acf9sph6/

<table>
  <tbody>
     <tr class="my-tr">
        <td>one line</td>
     </tr>
     <tr class="my-tr">
        <td>one line</td>
     </tr>
     <tr class="my-tr">
        <td>one line</td>
     </tr>
  </tbody>
</table>
<script>
$(function () {
       $("tr.my-tr").after('<tr class="tr-spacer"/>');
});
</script>
<style>
.tr-spacer
{
    height: 20px;
}
</style>

Unable to copy file - access to the path is denied

Old post, but this zombie is hitting VS 2017 (I haven't dug into why it's just "some" projects). In this case, it's not user permissions, rather IIS Express process is still using the files.

You'll see the icon in your task tray IIS Express icon

  1. Right Click
  2. Exit
  3. You should be able to rebuild without this annoying "permission denied" message.

This is also why "restarting Visual Studio" will "fix" the issue. Doing so, stops IIS Express.

Hth...

Redirect pages in JSP?

Extending @oopbase's answer with return; statement.

Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,

/* Some Import Statements here. */

if(null == session || !session.getAttribute("is_login").equals("1")) {
    response.sendRedirect("http://domain.com/login");
}

// ....

session.getAttribute("user_id");

// ....
/* Some More JSP+Java+HTML code here */

It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch block or handled if(null != session.getAttribute("attr_name")) everytime.

So by putting a return; statement I stopped further execution and forced to redirect page to certain location.

if(null == session || !session.getAttribute("is_login").equals("1")) {
    response.sendRedirect("http://domain.com/login");
    return;
}

Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).

Using StringWriter for XML Serialization

One problem with StringWriter is that by default it doesn't let you set the encoding which it advertises - so you can end up with an XML document advertising its encoding as UTF-16, which means you need to encode it as UTF-16 if you write it to a file. I have a small class to help with that though:

public sealed class StringWriterWithEncoding : StringWriter
{
    public override Encoding Encoding { get; }

    public StringWriterWithEncoding (Encoding encoding)
    {
        Encoding = encoding;
    }    
}

Or if you only need UTF-8 (which is all I often need):

public sealed class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

As for why you couldn't save your XML to the database - you'll have to give us more details about what happened when you tried, if you want us to be able to diagnose/fix it.

Difference between .dll and .exe?

An exe is an executible program whereas A DLL is a file that can be loaded and executed by programs dynamically.

JavaScript Number Split into individual digits

('' + 123456789).split('').map( x => +x ).reduce( (a,b) => a+b ) === 45

true

or without map

('' + 123456789).split('').reduce( (a,b) => (+a)+(+b) ) === 45

true

How do I determine height and scrolling position of window in jQuery?

From jQuery Docs:

const height = $(window).height();
const scrollTop = $(window).scrollTop();

http://api.jquery.com/scrollTop/
http://api.jquery.com/height/

jquery: $(window).scrollTop() but no $(window).scrollBottom()

try:

 $(window).scrollTop( $('body').height() );

Creating a list of pairs in java

If you want multiplicities, you can put it in map that maps pair to ammount. This way there will only be one pair of given values, but it can represent multiple occurances.

Then if you have lot of repeatet values and want to perform some operation on all values, you can save lot of computations.

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

What is the PostgreSQL equivalent for ISNULL()

Create the following function

CREATE OR REPLACE FUNCTION isnull(text, text) RETURNS text AS 'SELECT (CASE (SELECT $1 "
    "is null) WHEN true THEN $2 ELSE $1 END) AS RESULT' LANGUAGE 'sql'

And it'll work.

You may to create different versions with different parameter types.

window.open target _self v window.location.href?

Definitely the second method is preferred because you don't have the overhead of another function invocation:

window.location.href = "webpage.htm";

Losing Session State

Had a problem on IIS 8 when retrieving Content via Ajax. The issue was that MaximumWorkerProcesses was set to 2 and Javascript opened 17 concurrent requests. That was more than the AppPool could handle and a new pool (without auth-data) was opened.

Solution was to Change MaximumWorkerProcesses to 0 in IIS -> Server -> Application Pools -> [myPool] -> Advanced Settings -> Process Model -> MaximumWorkerProcesses.

What do column flags mean in MySQL Workbench?

This exact question is answered on mySql workbench-faq:

Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.

That means hover over an acronym in the mySql Workbench table editor.

Section 8.1.11.2, “The Columns Tab”

How to validate domain name in PHP?

<?php
function is_valid_domain_name($domain_name)
{
    return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name) //valid chars check
            && preg_match("/^.{1,253}$/", $domain_name) //overall length check
            && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name)   ); //length of each label
}
?>

Test cases:

is_valid_domain_name? [a]                       Y
is_valid_domain_name? [0]                       Y
is_valid_domain_name? [a.b]                     Y
is_valid_domain_name? [localhost]               Y
is_valid_domain_name? [google.com]              Y
is_valid_domain_name? [news.google.co.uk]       Y
is_valid_domain_name? [xn--fsqu00a.xn--0zwm56d] Y
is_valid_domain_name? [goo gle.com]             N
is_valid_domain_name? [google..com]             N
is_valid_domain_name? [google.com ]             N
is_valid_domain_name? [google-.com]             N
is_valid_domain_name? [.google.com]             N
is_valid_domain_name? [<script]                 N
is_valid_domain_name? [alert(]                  N
is_valid_domain_name? [.]                       N
is_valid_domain_name? [..]                      N
is_valid_domain_name? [ ]                       N
is_valid_domain_name? [-]                       N
is_valid_domain_name? []                        N

How to add the text "ON" and "OFF" to toggle button

_x000D_
_x000D_
.switch {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  width: 90px;_x000D_
  height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
  position: absolute;_x000D_
  cursor: pointer;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  background-color: #ca2222;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  height: 26px;_x000D_
  width: 26px;_x000D_
  left: 4px;_x000D_
  bottom: 4px;_x000D_
  background-color: white;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
  background-color: #2ab934;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
  box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
  -webkit-transform: translateX(55px);_x000D_
  -ms-transform: translateX(55px);_x000D_
  transform: translateX(55px);_x000D_
}_x000D_
_x000D_
/*------ ADDED CSS ---------*/_x000D_
.on_x000D_
{_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.on, .off_x000D_
{_x000D_
  color: white;_x000D_
  position: absolute;_x000D_
  transform: translate(-50%,-50%);_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  font-size: 10px;_x000D_
  font-family: Verdana, sans-serif;_x000D_
}_x000D_
_x000D_
input:checked+ .slider .on_x000D_
{display: block;}_x000D_
_x000D_
input:checked + .slider .off_x000D_
{display: none;}_x000D_
_x000D_
/*--------- END --------*/_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
  border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
  border-radius: 50%;}
_x000D_
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider round"><!--ADDED HTML --><span class="on">Confirmed</span><span class="off">NA</span><!--END--></div></label>
_x000D_
_x000D_
_x000D_

Bash integer comparison

Easier solution;

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...

Output

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1

Explanation

  • (( )) - Evaluates the expression using integers.
  • ${1:-2} - Uses parameter expansion to set a value of 2 if undefined.
  • >= 2 - True if the integer is greater than or equal to two 2.

Where does mysql store data?

From here:

Windows

  1. Locate the my.ini, which store in the MySQL installation folder.

For Example, C:\Program Files\MySQL\MySQL Server 5.1\my.ini

  1. Open the “my.ini” with our favor text editor.
#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.1/"
 
#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/"

Find the “datadir”, this is the where does MySQL stored the data in Windows.


Linux

  1. Locate the my.cnf with the find / -name my.cnf command.
yongmo@myserver:~$ find / -name my.cnf
find: /home/lost+found: Permission denied
find: /lost+found: Permission denied
/etc/mysql/my.cnf
  1. View the my.cnf file like this: cat /etc/mysql/my.cnf
yongmo@myserver:~$ cat /etc/mysql/my.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
[mysqld]
#
# * Basic Settings
#
user   = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket  = /var/run/mysqld/mysqld.sock
port   = 3306
basedir  = /usr
datadir  = /var/lib/mysql
tmpdir  = /tmp
language = /usr/share/mysql/english
skip-external-locking
  1. Find the “datadir”, this is where does MySQL stored the data in Linux system.

Is calling destructor manually always a sign of bad design?

There are cases when they are necessary:

In code I work on I use explicit destructor call in allocators, I have implementation of simple allocator that uses placement new to return memory blocks to stl containers. In destroy I have:

  void destroy (pointer p) {
    // destroy objects by calling their destructor
    p->~T();
  }

while in construct:

  void construct (pointer p, const T& value) {
    // initialize memory with placement new
    #undef new
    ::new((PVOID)p) T(value);
  }

there is also allocation being done in allocate() and memory deallocation in deallocate(), using platform specific alloc and dealloc mechanisms. This allocator was used to bypass doug lea malloc and use directly for example LocalAlloc on windows.

Angular 2 - innerHTML styling

The recommended version by Günter Zöchbauer works fine, but I have an addition to make. In my case I had an unstyled html-element and I did not know how to style it. Therefore I designed a pipe to add styling to it.

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';


@Pipe({
    name: 'StyleClass'
})
export class StyleClassPipe implements PipeTransform {

    constructor(private sanitizer: DomSanitizer) { }
    transform(html: any, styleSelector: any, styleValue: any): SafeHtml {
        const style = ` style = "${styleSelector}: ${styleValue};"`;
        const indexPosition = html.indexOf('>');
        const newHtml = [html.slice(0, indexPosition), style, html.slice(indexPosition)].join('');
        return this.sanitizer.bypassSecurityTrustHtml(newHtml);
    }

}

Then you can add style to any html-element like this:

<span [innerhtml]="Variable | StyleClass: 'margin': '0'"> </span>

With:

Variable = '<p> Test </p>'

Unix: How to delete files listed in a file

Just to provide an another way, you can also simply use the following command

$ cat to_remove
/tmp/file1
/tmp/file2
/tmp/file3
$ rm $( cat to_remove )

HTML image bottom alignment inside DIV container

<div> with some proportions

div {
  position: relative;
  width: 100%;
  height: 100%;
}

<img>'s with their own proportions

img {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: auto; /* to keep proportions */
  height: auto; /* to keep proportions */
  max-width: 100%; /* not to stand out from div */
  max-height: 100%; /* not to stand out from div */
  margin: auto auto 0; /* position to bottom and center */
}

No value accessor for form control

If you get this issue, then either

  • the formControlName is not located on the value accessor element.
  • or you're not importing the module for that element.

Find empty or NaN entry in Pandas Dataframe

I've resorted to

df[ (df[column_name].notnull()) & (df[column_name]!=u'') ].index

lately. That gets both null and empty-string cells in one go.

How to delete duplicate lines in a file without sorting it in Unix?

The first solution is also from http://sed.sourceforge.net/sed1line.txt

$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr '$!N;/^(.*)\n\1$/!P;D'
1
2
3
4
5

the core idea is:

print ONLY once of each duplicate consecutive lines at its LAST appearance and use D command to implement LOOP.

Explains:

  1. $!N;: if current line is NOT the last line, use N command to read the next line into pattern space.
  2. /^(.*)\n\1$/!P: if the contents of current pattern space is two duplicate string separated by \n, which means the next line is the same with current line, we can NOT print it according to our core idea; otherwise, which means current line is the LAST appearance of all of its duplicate consecutive lines, we can now use P command to print the chars in current pattern space util \n (\n also printed).
  3. D: we use D command to delete the chars in current pattern space util \n (\n also deleted), then the content of pattern space is the next line.
  4. and D command will force sed to jump to its FIRST command $!N, but NOT read the next line from file or standard input stream.

The second solution is easy to understood (from myself):

$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr 'p;:loop;$!N;s/^(.*)\n\1$/\1/;tloop;D'
1
2
3
4
5

the core idea is:

print ONLY once of each duplicate consecutive lines at its FIRST appearance and use : command & t command to implement LOOP.

Explains:

  1. read a new line from input stream or file and print it once.
  2. use :loop command set a label named loop.
  3. use N to read next line into the pattern space.
  4. use s/^(.*)\n\1$/\1/ to delete current line if the next line is same with current line, we use s command to do the delete action.
  5. if the s command is executed successfully, then use tloop command force sed to jump to the label named loop, which will do the same loop to the next lines util there are no duplicate consecutive lines of the line which is latest printed; otherwise, use D command to delete the line which is the same with thelatest-printed line, and force sed to jump to first command, which is the p command, the content of current pattern space is the next new line.

How to run composer from anywhere?

Some of this may be due to the OS your server is running. I recently did a migration to a new hosting environment running Ubuntu. Adding this alias alias composer="/path/to/your/composer" to .bashrc or .bash_aliases didn't work at first because of two reasons:

The server was running csh, not bash, by default. To check if this is an issue in your case, run echo $0. If the what is returned is -csh you will want to change it to bash, since some processes run by Composer will fail using csh/tcsh.

To change it, first check if bash is available on your server by running cat /etc/shells. If, in the list returned, you see bin/bash, you can change the default to bash by running chsh -s /bin/csh.

Now, at this point, you should be able to run Composer, but normally, on Ubuntu, you will have to load the script at every session by sourcing your Bash scripts by running source ~/.bashrc or source ~/.bash_profile. This is because, in most cases, Ubuntu won't load your Bash script, since it loads .profile as the default script.

To load your Bash scripts when you open a session, try adding this to your .profile (this is if your Bash script is .bashrc—modify accordingly if .bash_profile or other):

if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi

To test, close your session and reload. If it's working properly, running composer -v or which composer should behave as expected.

Add primary key to existing table

The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain UNIQUE values and column cannot contain NULL Values.

  -- DROP current primary key 
  ALTER TABLE tblPersons DROP CONSTRAINT <constraint_name>
  Example:
  ALTER TABLE tblPersons 
  DROP CONSTRAINT P_Id;


  -- ALTER TABLE tblpersion
  ALTER TABLE tblpersion add primary key (P_Id,LastName)

What is the best way to use a HashMap in C++?

A hash_map is an older, unstandardized version of what for standardization purposes is called an unordered_map (originally in TR1, and included in the standard since C++11). As the name implies, it's different from std::map primarily in being unordered -- if, for example, you iterate through a map from begin() to end(), you get items in order by key1, but if you iterate through an unordered_map from begin() to end(), you get items in a more or less arbitrary order.

An unordered_map is normally expected to have constant complexity. That is, an insertion, lookup, etc., typically takes essentially a fixed amount of time, regardless of how many items are in the table. An std::map has complexity that's logarithmic on the number of items being stored -- which means the time to insert or retrieve an item grows, but quite slowly, as the map grows larger. For example, if it takes 1 microsecond to lookup one of 1 million items, then you can expect it to take around 2 microseconds to lookup one of 2 million items, 3 microseconds for one of 4 million items, 4 microseconds for one of 8 million items, etc.

From a practical viewpoint, that's not really the whole story though. By nature, a simple hash table has a fixed size. Adapting it to the variable-size requirements for a general purpose container is somewhat non-trivial. As a result, operations that (potentially) grow the table (e.g., insertion) are potentially relatively slow (that is, most are fairly fast, but periodically one will be much slower). Lookups, which cannot change the size of the table, are generally much faster. As a result, most hash-based tables tend to be at their best when you do a lot of lookups compared to the number of insertions. For situations where you insert a lot of data, then iterate through the table once to retrieve results (e.g., counting the number of unique words in a file) chances are that an std::map will be just as fast, and quite possibly even faster (but, again, the computational complexity is different, so that can also depend on the number of unique words in the file).


1 Where the order is defined by the third template parameter when you create the map, std::less<T> by default.

best way to create object

In my humble opinion, this is just a matter of deciding if the arguments are optional or not. If an Person object shouldn't (logically) exist without Name and Age, they should be mandatory in the constructor. If they are optional, (i.e. their absence is not a threat to the good functioning of the object), use the setters.

Here's a quote from Symfony's docs on constructor injection:

There are several advantages to using constructor injection:

  • If the dependency is a requirement and the class cannot work without it then injecting it via the constructor ensures it is present when the class is used as the class cannot be constructed without it.
  • The constructor is only ever called once when the object is created, so you can be sure that the dependency will not change during the object's lifetime.

These advantages do mean that constructor injection is not suitable for working with optional dependencies. It is also more difficult to use in combination with class hierarchies: if a class uses constructor injection then extending it and overriding the constructor becomes problematic.

(Symfony is one of the most popular and respected php frameworks)

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Removing the title text of an iOS UIBarButtonItem

Just entering a single space for the Back button navigation item works!!

Git push hangs when pushing to Github?

I had two repositories, pushing to one of which worked fine. So, I compared their .git/config. The non-working one had at the end:

[http]
    sslVerify = false

The working one had instead:

[credential]
    helper = store

Changing .git/config solved the problem.

500 Internal Server Error for php file not for html

It was changing the line endings (from Windows CRLF to Unix LF) in the .htaccess file that fixed it for me.