Programs & Examples On #Javascript injection

How to dynamically insert a <script> tag via jQuery after page load?

Here's the correct way to do it with modern (2014) JQuery:

$(function () {
  $('<script>')
    .attr('type', 'text/javascript')
    .text('some script here')
    .appendTo('head');
})

or if you really want to replace a div you could do:

$(function () {
  $('<script>')
    .attr('type', 'text/javascript')
    .text('some script here')
    .replaceAll('#someelement');
});

Preventing HTML and Script injections in Javascript

Try this method to convert a 'string that could potentially contain html code' to 'text format':

$msg = "<div></div>";
$safe_msg = htmlspecialchars($msg, ENT_QUOTES);
echo $safe_msg;

Hope this helps!

CSS disable text selection

Don't apply these properties to the whole body. Move them to a class and apply that class to the elements you want to disable select:

.disable-select {
  -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
}

What is console.log in jQuery?

It has nothing to do with jQuery, it's just a handy js method built into modern browsers.

Think of it as a handy alternative to debugging via window.alert()

How to delete selected text in the vi editor

Highlighting with your mouse only highlights characters on the terminal. VI doesn't really get this information, so you have to highlight differently.

Press 'v' to enter a select mode, and use arrow keys to move that around. To delete, press x. To select lines at a time, press shift+v. To select blocks, try ctrl+v. That's good for, say, inserting lots of comment lines in front of your code :).

I'm OK with VI, but it took me a while to improve. My work mates recommended me this cheat sheet. I keep a printout on the wall for those odd moments when I forget something.

Happy hacking!

RS256 vs HS256: What's the difference?

short answer, specific to OAuth2,

  • HS256 user client secret to generate the token signature and same secret is required to validate the token in back-end. So you should have a copy of that secret in your back-end server to verify the signature.
  • RS256 use public key encryption to sign the token.Signature(hash) will create using private key and it can verify using public key. So, no need of private key or client secret to store in back-end server, but back-end server will fetch the public key from openid configuration url in your tenant (https://[tenant]/.well-known/openid-configuration) to verify the token. KID parameter inside the access_toekn will use to detect the correct key(public) from openid-configuration.

Equivalent of LIMIT for DB2

Support for OFFSET and LIMIT was recently added to DB2 for i 7.1 and 7.2. You need the following DB PTF group levels to get this support:

  • SF99702 level 9 for IBM i 7.2
  • SF99701 level 38 for IBM i 7.1

See here for more information: OFFSET and LIMIT documentation, DB2 for i Enhancement Wiki

Where should I put the log4j.properties file?

I've spent a great deal of time to figure out why the log4j.properties file is not seen.
Then I noticed it was visible for the project only when it was in both MyProject/target/classes/ and MyProject/src/main/resources folders.
Hope it'll be useful to somebody.
PS: The project was maven-based.

Java: Date from unix timestamp

If you are converting a timestamp value on a different machine, you should also check the timezone of that machine. For example;

The above decriptions will result different Date values, if you run with EST or UTC timezones.

To set the timezone; aka to UTC, you can simply rewrite;

    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    java.util.Date time= new java.util.Date((Long.parseLong(timestamp)*1000));

Repeat string to certain length

Yay recursion!

def trunc(s,l):
    if l > 0:
        return s[:l] + trunc(s, l - len(s))
    return ''

Won't scale forever, but it's fine for smaller strings. And it's pretty.

I admit I just read the Little Schemer and I like recursion right now.

ASP.Net MVC 4 Form with 2 submit buttons/actions

We can have this in 2 ways,

Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within

ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons

Or

Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code

if (Request.Form["btnSubmit1"] != null)
{
 //
}
if (Request.Form["btnSubmit2"] != null)
{
 //
}

Best way to parseDouble with comma as decimal separator?

Double.parseDouble(p.replace(',','.'))

...is very quick as it searches the underlying character array on a char-by-char basis. The string replace versions compile a RegEx to evaluate.

Basically replace(char,char) is about 10 times quicker and since you'll be doing these kind of things in low-level code it makes sense to think about this. The Hot Spot optimiser will not figure it out... Certainly doesn't on my system.

How to get different colored lines for different plots in a single figure?

I would like to offer a minor improvement on the last loop answer given in the previous post (that post is correct and should still be accepted). The implicit assumption made when labeling the last example is that plt.label(LIST) puts label number X in LIST with the line corresponding to the Xth time plot was called. I have run into problems with this approach before. The recommended way to build legends and customize their labels per matplotlibs documentation ( http://matplotlib.org/users/legend_guide.html#adjusting-the-order-of-legend-item) is to have a warm feeling that the labels go along with the exact plots you think they do:

...
# Plot several different functions...
labels = []
plotHandles = []
for i in range(1, num_plots + 1):
    x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
    plotHandles.append(x)
    labels.append(some label)
plt.legend(plotHandles, labels, 'upper left',ncol=1)

**: Matplotlib Legends not working

Adding div element to body or document in JavaScript

Try this out:-

http://jsfiddle.net/adiioo7/vmfbA/

Use

document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';

instead of

document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';

Edit:- Ideally you should use body.appendChild method instead of changing the innerHTML

var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);

Python debugging tips

Getting a stack trace from a running Python application

There are several tricks here. These include

  • Breaking into an interpreter/printing a stack trace by sending a signal
  • Getting a stack trace out of an unprepared Python process
  • Running the interpreter with flags to make it useful for debugging

In Android, how do I set margins in dp programmatically?

When you are in a custom View, you can use getDimensionPixelSize(R.dimen.dimen_value), in my case, I added the margin in LayoutParams created on init method.

In Kotlin

init {
    LayoutInflater.from(context).inflate(R.layout.my_layout, this, true)
    layoutParams = LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply {
    val margin = resources.getDimensionPixelSize(R.dimen.dimen_value)
    setMargins(0, margin, 0, margin)
}

in Java:

public class CustomView extends LinearLayout {

    //..other constructors

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        int margin = getResources().getDimensionPixelSize(R.dimen.spacing_dime);
        params.setMargins(0, margin, 0, margin);
        setLayoutParams(params);
    }
}

How do I access the $scope variable in browser's console using AngularJS?

Put a breakpoint in your code at a somewhere close to a reference to the $scope variable (so that the $scope is in the current 'plain old JavaScript' scope). Then your can inspect the $scope value in the console.

Most efficient way to find smallest of 3 numbers Java?

Simply use this math function

System.out.println(Math.min(a,b,c));

You will get the answer in single line.

Bootstrap 3: Using img-circle, how to get circle from non-square image?

the problem mainly is because the width have to be == to the height, and in the case of bs, the height is set to auto so here is a fix for that in js instead

function img_circle() {
    $('.img-circle').each(function() {
        $w = $(this).width();
        $(this).height($w);
    });
}

$(document).ready(function() {
    img_circle();
});

$(window).resize(function() {
    img_circle();
});

Excel CSV. file with more than 1,048,576 rows of data

Excel 2007+ is limited to somewhat over 1 million rows ( 2^20 to be precise), so it will never load your 2M line file. I think that the technique you refer to as splitting is the built-in thing Excel has, but afaik that only works for width problems, not for length problems.

The really easiest way I see right away is to use some file splitting tool - there's tons of 'em and use that to load the resulting partial csv files into multiple worksheets.

ps: "excel csv files" don't exist, there are only files produced by Excel that use one of the formats commonly referred to as csv files...

How to print a groupby object

If you're simply looking for a way to display it, you could use describe():

grp = df.groupby['colName']
grp.describe()

This gives you a neat table.

How to view file history in Git?

Looks like you want git diff and/or git log. Also check out gitk

gitk path/to/file
git diff path/to/file
git log path/to/file

Change default icon

Run it not through Visual Studio - then the icon should look just fine.

I believe it is because when you debug, Visual Studio runs <yourapp>.vshost.exe and not your application. The .vshost.exe file doesn't use your icon.

Ultimately, what you have done is correct.

  1. Go to the Project properties
  2. under Application tab change the default icon to your own
  3. Build the project
  4. Locate the .exe file in your favorite file explorer.

There, the icon should look fine. If you run it by clicking that .exe the icon should be correct in the application as well.

Django: How can I call a view function from template?

Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.

inside templateHTML.html:

<form action="#" method="get">
 <input type="text" value="8" name="mytextbox" size="1"/>
 <input type="submit" class="btn" value="Click" name="mybtn">
</form>

inside view.py:

import mypythoncode

def request_page(request):
  if(request.GET.get('mybtn')):
    mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')

Change default date time format on a single database in SQL Server

Use:

select * from mytest
EXEC sp_rename 'mytest.eid', 'id', 'COLUMN'
alter table mytest add id int not null identity(1,1)
update mytset set eid=id
ALTER TABLE mytest DROP COLUMN eid

ALTER TABLE [dbo].[yourtablename] ADD DEFAULT (getdate()) FOR [yourfieldname]

It's working 100%.

How can I render a list select box (dropdown) with bootstrap?

Another option is to make the Bootstrap dropdown behave like a select using jQuery...

$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.btn-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
});

http://www.bootply.com/b4NKREUPkN

JFrame: How to disable window resizing?

Use setResizable on your JFrame

yourFrame.setResizable(false);

But extending JFrame is generally a bad idea.

How do I implement charts in Bootstrap?

Definitely late to the party; anyway, for those interested, picking up on Lan's mention of HTML5 canvas, you can use gRaphaël Charting which has a MIT License (instead of HighCharts dual license). It's not Bootstrap-specific either, so it's more of a general suggestion.

I have to admit that HighCharts demos seem very pretty, and I have to warn that gRaphaël is quite hard to understand before becoming proficient with it. Anyway you can easily add nice features to your gRaphaël charts (say, tooltips or zooming effects), so it may be worth the effort.

NameError: global name 'xrange' is not defined in Python 3

I agree with the last answer.But there is another way to solve this problem.You can download the package named future,such as pip install future.And in your .py file input this "from past.builtins import xrange".This method is for the situation that there are many xranges in your file.

Firefox Add-on RESTclient - How to input POST parameters?

If you want to submit a POST request

  1. You have to set the “request header” section of the Firefox plugin to have a “name” = “Content-Type” and “value” = “application/x-www-form-urlencoded
  2. Now, you are able to submit parameter like “name=mynamehere&title=TA” in the “request body” text area field

SQL Server Convert Varchar to Datetime

As has been said, datetime has no format/string representational format.

You can change the string output with some formatting.

To convert your string to a datetime:

declare @date nvarchar(25) 
set @date = '2011-09-28 18:01:00' 

-- To datetime datatype
SELECT CONVERT(datetime, @date)

Gives:

-----------------------
2011-09-28 18:01:00.000

(1 row(s) affected)

To convert that to the string you want:

-- To VARCHAR of your desired format
SELECT CONVERT(VARCHAR(10), CONVERT(datetime, @date), 105) +' '+ CONVERT(VARCHAR(8), CONVERT(datetime, @date), 108)

Gives:

-------------------
28-09-2011 18:01:00

(1 row(s) affected)

Datatables - Search Box outside datatable

More recent versions have a different syntax:

var table = $('#example').DataTable();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Note that this example uses the variable table assigned when datatables is first initialised. If you don't have this variable available, simply use:

var table = $('#example').dataTable().api();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Since: DataTables 1.10

– Source: https://datatables.net/reference/api/search()

Override body style for content in an iframe

I have a blog and I had a lot of trouble finding out how to resize my embedded gist. Post manager only allows you to write text, place images and embed HTML code. Blog layout is responsive itself. It's built with Wix. However, embedded HTML is not. I read a lot about how it's impossible to resize components inside body of generated iFrames. So, here is my suggestion:

If you only have one component inside your iFrame, i.e. your gist, you can resize only the gist. Forget about the iFrame.

I had problems with viewport, specific layouts to different user agents and this is what solved my problem:

<script language="javascript" type="text/javascript" src="https://gist.github.com/roliveiravictor/447f994a82238247f83919e75e391c6f.js"></script>

<script language="javascript" type="text/javascript">

function windowSize() {
  let gist = document.querySelector('#gist92442763');

  let isMobile = {
    Android: function() {
        return /Android/i.test(navigator.userAgent)
    },
    BlackBerry: function() {
        return /BlackBerry/i.test(navigator.userAgent)
    },
    iOS: function() {
        return /iPhone|iPod/i.test(navigator.userAgent)
    },
    Opera: function() {
        return /Opera Mini/i.test(navigator.userAgent)
    },
    Windows: function() {
        return /IEMobile/i.test(navigator.userAgent) || /WPDesktop/i.test(navigator.userAgent)
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

  if(isMobile.any()) {
    gist.style.width = "36%";
    gist.style.WebkitOverflowScrolling = "touch"
    gist.style.position = "absolute"
  } else {
    gist.style.width = "auto !important";
  }
}

windowSize();

window.addEventListener('onresize', function() {
    windowSize();
});

</script>

<style type="text/css">

.gist-data {
  max-height: 300px;
}

.gist-meta {
  display: none;
}

</style>

The logic is to set gist (or your component) css based on user agent. Make sure to identify your component first, before applying to query selector. Feel free to take a look how responsiveness is working.

Preferred method to store PHP arrays (json_encode vs serialize)

First, I changed the script to do some more benchmarking (and also do 1000 runs instead of just 1):

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Make a big, honkin test array
// You may need to adjust this depth to avoid memory limit errors
$testArray = fillArray(0, 5);

$totalJsonTime = 0;
$totalSerializeTime = 0;
$totalJsonWins = 0;

for ($i = 0; $i < 1000; $i++) {
    // Time json encoding
    $start = microtime(true);
    $json = json_encode($testArray);
    $jsonTime = microtime(true) - $start;
    $totalJsonTime += $jsonTime;

    // Time serialization
    $start = microtime(true);
    $serial = serialize($testArray);
    $serializeTime = microtime(true) - $start;
    $totalSerializeTime += $serializeTime;

    if ($jsonTime < $serializeTime) {
        $totalJsonWins++;
    }
}

$totalSerializeWins = 1000 - $totalJsonWins;

// Compare them
if ($totalJsonTime < $totalSerializeTime) {
    printf("json_encode() (wins: $totalJsonWins) was roughly %01.2f%% faster than serialize()\n", ($totalSerializeTime / $totalJsonTime - 1) * 100);
} else {
    printf("serialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than json_encode()\n", ($totalJsonTime / $totalSerializeTime - 1) * 100);
}

$totalJsonTime = 0;
$totalJson2Time = 0;
$totalSerializeTime = 0;
$totalJsonWins = 0;

for ($i = 0; $i < 1000; $i++) {
    // Time json decoding
    $start = microtime(true);
    $orig = json_decode($json, true);
    $jsonTime = microtime(true) - $start;
    $totalJsonTime += $jsonTime;

    $start = microtime(true);
    $origObj = json_decode($json);
    $jsonTime2 = microtime(true) - $start;
    $totalJson2Time += $jsonTime2;

    // Time serialization
    $start = microtime(true);
    $unserial = unserialize($serial);
    $serializeTime = microtime(true) - $start;
    $totalSerializeTime += $serializeTime;

    if ($jsonTime < $serializeTime) {
        $totalJsonWins++;
    }
}

$totalSerializeWins = 1000 - $totalJsonWins;


// Compare them
if ($totalJsonTime < $totalSerializeTime) {
    printf("json_decode() was roughly %01.2f%% faster than unserialize()\n", ($totalSerializeTime / $totalJsonTime - 1) * 100);
} else {
    printf("unserialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than json_decode()\n", ($totalJsonTime / $totalSerializeTime - 1) * 100);
}

// Compare them
if ($totalJson2Time < $totalSerializeTime) {
    printf("json_decode() was roughly %01.2f%% faster than unserialize()\n", ($totalSerializeTime / $totalJson2Time - 1) * 100);
} else {
    printf("unserialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than array json_decode()\n", ($totalJson2Time / $totalSerializeTime - 1) * 100);
}

function fillArray( $depth, $max ) {
    static $seed;
    if (is_null($seed)) {
        $seed = array('a', 2, 'c', 4, 'e', 6, 'g', 8, 'i', 10);
    }
    if ($depth < $max) {
        $node = array();
        foreach ($seed as $key) {
            $node[$key] = fillArray($depth + 1, $max);
        }
        return $node;
    }
    return 'empty';
}

I used this build of PHP 7:

PHP 7.0.14 (cli) (built: Jan 18 2017 19:13:23) ( NTS ) Copyright (c) 1997-2016 The PHP Group Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies with Zend OPcache v7.0.14, Copyright (c) 1999-2016, by Zend Technologies

And my results were:

serialize() (wins: 999) was roughly 10.98% faster than json_encode() unserialize() (wins: 987) was roughly 33.26% faster than json_decode() unserialize() (wins: 987) was roughly 48.35% faster than array json_decode()

So clearly, serialize/unserialize is the fastest method, while json_encode/decode is the most portable.

If you consider a scenario where you read/write serialized data 10x or more often than you need to send to or receive from a non-PHP system, you are STILL better off to use serialize/unserialize and have it json_encode or json_decode prior to serialization in terms of time.

How do I disable Git Credential Manager for Windows?

pretty old topic but this is maybe a help for someone searching for the problem where the above tips does not solved it.

I use

git credential-manager remove -force

Could not load file or assembly 'System.Web.Mvc'

We want to add it because we are making a class library that uses it.

For me it is here...

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies

Reload activity in Android

After login I had the same problem so I used

@Override
protected void onRestart() {
    this.recreate();
    super.onRestart();
}

What is an API key?

Think of it this way, the "Public API Key" is similar to a user name that your database is using as a login to a verification server. The "Private API Key" would then be similar to the password. By the site/databse using this method, the security is maintained on the third party/verification server in order to authentic request of posting or editing your site/database.

The API string is just the URL of the login for your site/database to contact the verification server.

Can you animate a height change on a UITableViewCell when selected?

I just resolved this problem with a little hack:

static int s_CellHeight = 30;
static int s_CellHeightEditing = 60;

- (void)onTimer {
    cellHeight++;
    [tableView reloadData];
    if (cellHeight < s_CellHeightEditing)
        heightAnimationTimer = [[NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(onTimer) userInfo:nil repeats:NO] retain];
}

- (CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        if (isInEdit) {
            return cellHeight;
        }
        cellHeight = s_CellHeight;
        return s_CellHeight;
}

When I need to expand the cell height I set isInEdit = YES and call the method [self onTimer] and it animates the cell growth until it reach the s_CellHeightEditing value :-)

Get selected item value from Bootstrap DropDown with specific ID

Works GReat.

Category Question Apple Banana Cherry
<input type="text" name="cat_q" id="cat_q">  

$(document).ready(function(){
    $("#btn_cat div a").click(function(){
       alert($(this).text());

    });
});

Entity Framework - Generating Classes

1) First you need to generate EDMX model using your database. To do that you should add new item to your project:

  • Select ADO.NET Entity Data Model from the Templates list.
  • On the Choose Model Contents page, select the Generate from Database option and click Next.
  • Choose your database.
  • On the Choose Your Database Objects page, check the Tables. Choose Views or Stored Procedures if you need.

So now you have Model1.edmx file in your project.

2) To generate classes using your model:

  • Open your EDMX model designer.
  • On the design surface Right Click –> Add Code Generation Item…
  • Select Online templates.
  • Select EF 4.x DbContext Generator for C#.
  • Click ‘Add’.

Notice that two items are added to your project:

  • Model1.tt (This template generates very simple POCO classes for each entity in your model)
  • Model1.Context.tt (This template generates a derived DbContext to use for querying and persisting data)

3) Read/Write Data example:

 var dbContext = new YourModelClass(); //class derived from DbContext
 var contacts = from c in dbContext.Contacts select c; //read data
 contacts.FirstOrDefault().FirstName = "Alex"; //edit data
 dbContext.SaveChanges(); //save data to DB

Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.

Why use static_cast<int>(x) instead of (int)x?

C Style casts are easy to miss in a block of code. C++ style casts are not only better practice; they offer a much greater degree of flexibility.

reinterpret_cast allows integral to pointer type conversions, however can be unsafe if misused.

static_cast offers good conversion for numeric types e.g. from as enums to ints or ints to floats or any data types you are confident of type. It does not perform any run time checks.

dynamic_cast on the other hand will perform these checks flagging any ambiguous assignments or conversions. It only works on pointers and references and incurs an overhead.

There are a couple of others but these are the main ones you will come across.

Laravel 5.4 create model, controller and migration in single artisan command

To make mode, controllers with resources, You can type CMD as follows :

 php artisan make:model Todo -mcr

or you can check by typing

php artisan help make:model

where you can get all the ideas

jquery toggle slide from left to right and back

Sliding from the right:

$('#example').animate({width:'toggle'},350);

Sliding to the left:

$('#example').toggle({ direction: "left" }, 1000);

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

If you are using variables with the same name as your column, it could be that you forgot the '@' variable marker. In an INSERT statement it will be detected as a column.

CSS styling in Django forms

If you don't want to add any code to the form (as mentioned in the comments to @shadfc's Answer), it is certainly possible, here are two options.

First, you just reference the fields individually in the HTML, rather than the entire form at once:

<form action="" method="post">
    <ul class="contactList">
        <li id="subject" class="contact">{{ form.subject }}</li>
        <li id="email" class="contact">{{ form.email }}</li>
        <li id="message" class="contact">{{ form.message }}</li>
    </ul>
    <input type="submit" value="Submit">
</form>

(Note that I also changed it to a unsorted list.)

Second, note in the docs on outputting forms as HTML, Django:

The Field id, is generated by prepending 'id_' to the Field name. The id attributes and tags are included in the output by default.

All of your form fields already have a unique id. So you would reference id_subject in your CSS file to style the subject field. I should note, this is how the form behaves when you take the default HTML, which requires just printing the form, not the individual fields:

<ul class="contactList">
    {{ form }}  # Will auto-generate HTML with id_subject, id_email, email_message 
    {{ form.as_ul }} # might also work, haven't tested
</ul>

See the previous link for other options when outputting forms (you can do tables, etc).

Note - I realize this isn't the same as adding a class to each element (if you added a field to the Form, you'd need to update the CSS also) - but it's easy enough to reference all of the fields by id in your CSS like this:

#id_subject, #id_email, #email_message 
{color: red;}

How to show and update echo on same line

My favorite way is called do the sleep to 50. here i variable need to be used inside echo statements.

for i in $(seq 1 50); do
  echo -ne "$i%\033[0K\r"
  sleep 50
done
echo "ended"

auto refresh for every 5 mins

Install an interval:

<script type="text/javascript">    
    setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>

Insert PHP code In WordPress Page and Post

When I was trying to accomplish something very similar, I ended up doing something along these lines:

wp-content/themes/resources/functions.php

add_action('init', 'my_php_function');
function my_php_function() {
    if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
        // add desired php code here
    }
}

How to connect a Windows Mobile PDA to Windows 10

I haven't managed to get WMDC working on Windows 10 (it hanged on splash screen upon start), so I've finally uninstalled it. But now I have a Portable Devices / Compact device in the Device Manager and I can browse my Windows Compact 7 device within Windows Explorer. All my apps using RAPI also work. Maybe this is the result of installing/uninstalling WMDC, or probably this functionality was already presented on Windows 10 and I've just overlooked it initially.

Quick Way to Implement Dictionary in C

here is a quick implement, i used it to get a 'Matrix'(sruct) from a string. you can have a bigger array and change its values on the run also:

typedef struct  { int** lines; int isDefined; }mat;
mat matA, matB, matC, matD, matE, matF;

/* an auxilary struct to be used in a dictionary */
typedef struct  { char* str; mat *matrix; }stringToMat;

/* creating a 'dictionary' for a mat name to its mat. lower case only! */
stringToMat matCases [] =
{
    { "mat_a", &matA },
    { "mat_b", &matB },
    { "mat_c", &matC },
    { "mat_d", &matD },
    { "mat_e", &matE },
    { "mat_f", &matF },
};

mat* getMat(char * str)
{
    stringToMat* pCase;
    mat * selected = NULL;
    if (str != NULL)
    {
        /* runing on the dictionary to get the mat selected */
        for(pCase = matCases; pCase != matCases + sizeof(matCases) / sizeof(matCases[0]); pCase++ )
        {
            if(!strcmp( pCase->str, str))
                selected = (pCase->matrix);
        }
        if (selected == NULL)
            printf("%s is not a valid matrix name\n", str);
    }
    else
        printf("expected matrix name, got NULL\n");
    return selected;
}

Does delete on a pointer to a subclass call the base class destructor?

no it will not call destructor for class A, you should call it explicitly (like PoweRoy told), delete line 'delete ptr;' in example to compare ...

  #include <iostream>

  class A
  {
     public:
        A(){};
        ~A();
  };

  A::~A()
  {
     std::cout << "Destructor of A" << std::endl;
  }

  class B
  {
     public:
        B(){ptr = new A();};
        ~B();
     private:
        A* ptr;
  };

  B::~B()
  {
     delete ptr;
     std::cout << "Destructor of B" << std::endl;
  }

  int main()
  {
     B* b = new B();
     delete b;
     return 0;
  }

C++ code file extension? .cc vs .cpp

.C and .cc seem to be standard for the (few) Unix-oriented C++ programs I've seen. I've always used .cpp myself, since I only really work on Windows and that's been the standard there since like forever.

I recommend .cpp personally, because... it stands for "C Plus Plus". It is of course vitally important that file extensions are acronyms, but should this rationale prove insufficiently compelling other important things are non-use of the shift key (which rules out .C and .c++) and avoidance of regular expression metacharacters where possible (which rules out .c++ -- unfortunately you can't really avoid the . of course.).

This doesn't rule out .cc, so even though it doesn't really stand for anything (or does it?) it is probably a good choice for Linux-oriented code.

Edittext change border color with shape.xml

This is work for me: Drwable->New->Drawable Resource File->create xml file

  <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid android:color="#e0e0e0" />
        <stroke android:width="2dp" android:color="#a4b0ba" />
    </shape>

Objective-C : BOOL vs bool

As mentioned above BOOL could be an unsigned char type depending on your architecture, while bool is of type int. A simple experiment will show the difference why BOOL and bool can behave differently:

bool ansicBool = 64;
if(ansicBool != true) printf("This will not print\n");

printf("Any given vlaue other than 0 to ansicBool is evaluated to %i\n", ansicBool);

BOOL objcBOOL = 64;
if(objcBOOL != YES) printf("This might print depnding on your architecture\n");

printf("BOOL will keep whatever value you assign it: %i\n", objcBOOL);

if(!objcBOOL) printf("This will not print\n");

printf("! operator will zero objcBOOL %i\n", !objcBOOL);

if(!!objcBOOL) printf("!! will evaluate objcBOOL value to %i\n", !!objcBOOL);

To your surprise if(objcBOOL != YES) will evaluates to 1 by the compiler, since YES is actually the character code 1, and in the eyes of compiler, character code 64 is of course not equal to character code 1 thus the if statement will evaluate to YES/true/1 and the following line will run. However since a none zero bool type always evaluates to the integer value of 1, the above issue will not effect your code. Below are some good tips if you want to use the Objective-C BOOL type vs the ANSI C bool type:

  • Always assign the YES or NO value and nothing else.
  • Convert BOOL types by using double not !! operator to avoid unexpected results.
  • When checking for YES use if(!myBool) instead of if(myBool != YES) it is much cleaner to use the not ! operator and gives the expected result.

How to call a function from a string stored in a variable?

As already mentioned, there are a few ways to achieve this with possibly the safest method being call_user_func() or if you must you can also go down the route of $function_name(). It is possible to pass arguments using both of these methods as so

$function_name = 'foobar';

$function_name(arg1, arg2);

call_user_func_array($function_name, array(arg1, arg2));

If the function you are calling belongs to an object you can still use either of these

$object->$function_name(arg1, arg2);

call_user_func_array(array($object, $function_name), array(arg1, arg2));

However if you are going to use the $function_name() method it may be a good idea to test for the existence of the function if the name is in any way dynamic

if(method_exists($object, $function_name))
{
    $object->$function_name(arg1, arg2);
}

Reload an iframe with jQuery

This is possible with simple JavaScript.

  • In iFrame1, make a JavaScript function that is called in the body tag onload. I have it check a server side variable that I set, so it does not try to run the JavaScript function in iframe2 unless I have taken a specific action in iframe1. You could set this up as a function fired by a button press or however you want to in iframe1.
  • Then in iframe2, you have the second function I list below. The function in iframe1 basically goes to the parent page and then uses the window.frames syntax to fire a JavaScript function in iframe2. Just make sure to use the id/name of iframe2 and not the src.
//function in iframe1
function refreshIframe2()
{
    if (<cfoutput>#didValidation#</cfoutput> == 1)
    {   
         parent.window.frames.iframe2.refreshPage();
    }
}

//function in iframe2
function refreshPage()
{   
    document.location.reload();
}

How to access the php.ini file in godaddy shared hosting linux

As pointed out by @Jason, for most shared hosting environments, having a copy of php.ini file in your public_html directory works to override the system default settings. A great way to do this is by copying the hosting company's copy. Put this in a file, say copyini.php

<?php
  system("cp /path/to/php/conf/file/php.ini  /home/yourusername/public_html/php.ini");
?>

Get /path/to/php/conf/file/php.ini from the output of phpinfo(); in a file. Then in your ini file, make your amendments Delete all files created during this process (Apart from php.ini of course :-) )

Method List in Visual Studio Code

Visual Studio Code market place has a very nice extension named Go To Method for navigating only methods in a code file.

Hit Ctrl+Shift+P and type the install extensions and press enter

enter image description here

Now type Add to method in search box of extensions market place and press enter.

enter image description here

Click install to install the extension.

Last step is to bind a keyboard shortcut to the command workbench.action.gotoMethod to make it a real productivity thing for a developer.

create table with sequence.nextval in oracle

In Oracle 12c, you can now specify the CURRVAL and NEXTVAL sequence pseudocolumns as default values for a column. Alternatively, you can use Identity columns; see:

E.g.,

CREATE SEQUENCE t1_seq;
CREATE TABLE t1 (
  id          NUMBER DEFAULT t1_seq.NEXTVAL,
  description VARCHAR2(30)
);

How to generate the "create table" sql statement for an existing table in postgreSQL

Generate the create table statement for a table in postgresql from linux commandline:

Create a table for a demo:

CREATE TABLE your_table(
    thekey   integer NOT NULL,  ticker   character varying(10) NOT NULL,
    date_val date,              open_val numeric(10,4) NOT NULL
); 

pg_dump can output the table-create psql:

pg_dump -U your_user your_database -t your_table --schema-only

Which prints:

-- pre-requisite database and table configuration omitted
CREATE TABLE your_table (                                                                                                      
    thekey integer NOT NULL,                                                                                                   
    ticker character varying(10) NOT NULL,                                                                                     
    date_val date,                                                                                                             
    open_val numeric(10,4) NOT NULL                                                                                            
);                                                                                                                   
-- post-requisite database and table configuration omitted
  

Explanation:

pg_dump helps us get information about the database itself. -U stands for username. My pgadmin user has no password set, so I don't have to put in a password. The -t option means specify for one table. --schema-only means print only data about the table, and not the data in the table. Here is the exact command I use:

Get the table name and datatype information from postgresql with SQL:

CREATE TABLE your_table(  thekey integer NOT NULL,
                          ticker character varying(10) NOT NULL,
                          date_val date,
                          open_val numeric(10,4) NOT NULL
); 

SELECT table_name, column_name, data_type 
FROM information_schema.columns 
WHERE table_name = 'your_table'; 

Which prints:

+----------------------------------------------+ 
¦ table_name ¦ column_name ¦     data_type     ¦ 
+------------+-------------+-------------------¦ 
¦ your_table ¦ thekey      ¦ integer           ¦ 
¦ your_table ¦ ticker      ¦ character varying ¦ 
¦ your_table ¦ date_val    ¦ date              ¦ 
¦ your_table ¦ open_val    ¦ numeric           ¦ 
+----------------------------------------------+ 

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

Example on ToggleButton

I think what are attempting is semantically same as a radio button when 1 is when one of the options is selected and 0 is the other option.

I suggest using the radio button provided by Android by default.

Here is how to use it- http://www.mkyong.com/android/android-radio-buttons-example/

and the android documentation is here-

http://developer.android.com/guide/topics/ui/controls/radiobutton.html

Thanks.

How to Customize a Progress Bar In Android

In case of complex ProgressBar like this,

enter image description here

use ClipDrawable.

NOTE : I've not used ProgressBar here in this example. I've achieved this using ClipDrawable by clipping image with Animation.

A Drawable that clips another Drawable based on this Drawable's current level value. You can control how much the child Drawable gets clipped in width and height based on the level, as well as a gravity to control where it is placed in its overall container. Most often used to implement things like progress bars, by increasing the drawable's level with setLevel().

NOTE : The drawable is clipped completely and not visible when the level is 0 and fully revealed when the level is 10,000.

I've used this two images to make this CustomProgressBar.

scall.png

scall.png

ballon_progress.png

ballon_progress.png

MainActivity.java

public class MainActivity extends ActionBarActivity {

private EditText etPercent;
private ClipDrawable mImageDrawable;

// a field in your class
private int mLevel = 0;
private int fromLevel = 0;
private int toLevel = 0;

public static final int MAX_LEVEL = 10000;
public static final int LEVEL_DIFF = 100;
public static final int DELAY = 30;

private Handler mUpHandler = new Handler();
private Runnable animateUpImage = new Runnable() {

    @Override
    public void run() {
        doTheUpAnimation(fromLevel, toLevel);
    }
};

private Handler mDownHandler = new Handler();
private Runnable animateDownImage = new Runnable() {

    @Override
    public void run() {
        doTheDownAnimation(fromLevel, toLevel);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    etPercent = (EditText) findViewById(R.id.etPercent);

    ImageView img = (ImageView) findViewById(R.id.imageView1);
    mImageDrawable = (ClipDrawable) img.getDrawable();
    mImageDrawable.setLevel(0);
}

private void doTheUpAnimation(int fromLevel, int toLevel) {
    mLevel += LEVEL_DIFF;
    mImageDrawable.setLevel(mLevel);
    if (mLevel <= toLevel) {
        mUpHandler.postDelayed(animateUpImage, DELAY);
    } else {
        mUpHandler.removeCallbacks(animateUpImage);
        MainActivity.this.fromLevel = toLevel;
    }
}

private void doTheDownAnimation(int fromLevel, int toLevel) {
    mLevel -= LEVEL_DIFF;
    mImageDrawable.setLevel(mLevel);
    if (mLevel >= toLevel) {
        mDownHandler.postDelayed(animateDownImage, DELAY);
    } else {
        mDownHandler.removeCallbacks(animateDownImage);
        MainActivity.this.fromLevel = toLevel;
    }
}

public void onClickOk(View v) {
    int temp_level = ((Integer.parseInt(etPercent.getText().toString())) * MAX_LEVEL) / 100;

    if (toLevel == temp_level || temp_level > MAX_LEVEL) {
        return;
    }
    toLevel = (temp_level <= MAX_LEVEL) ? temp_level : toLevel;
    if (toLevel > fromLevel) {
        // cancel previous process first
        mDownHandler.removeCallbacks(animateDownImage);
        MainActivity.this.fromLevel = toLevel;

        mUpHandler.post(animateUpImage);
    } else {
        // cancel previous process first
        mUpHandler.removeCallbacks(animateUpImage);
        MainActivity.this.fromLevel = toLevel;

        mDownHandler.post(animateDownImage);
    }
}
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/etPercent"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:inputType="number"
        android:maxLength="3" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ok"
        android:onClick="onClickOk" />

</LinearLayout>

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/scall" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/clip_source" />

</FrameLayout>

clip_source.xml

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
    android:clipOrientation="vertical"
    android:drawable="@drawable/ballon_progress"
    android:gravity="bottom" />

In case of complex HorizontalProgressBar just change cliporientation in clip_source.xml like this,

android:clipOrientation="horizontal"

You can download complete demo from here.

setHintTextColor() in EditText

Programmatically in Java - At least API v14+

exampleEditText.setHintTextColor(getResources().getColor(R.color.your_color));

What static analysis tools are available for C#?

Have you seen CAT.NET?

From the blurb -

CAT.NET is a binary code analysis tool that helps identify common variants of certain prevailing vulnerabilities that can give rise to common attack vectors such as Cross-Site Scripting (XSS), SQL Injection and XPath Injection.

I used an early beta and it did seem to turn up a few things worth looking at.

What is the difference between Integer and int in Java?

int is a primitive type and not an object. That means that there are no methods associated with it. Integer is an object with methods (such as parseInt).

With newer java there is functionality for auto boxing (and unboxing). That means that the compiler will insert Integer.valueOf(int) or integer.intValue() where needed. That means that it is actually possible to write

Integer n = 9;

which is interpreted as

Integer n = Integer.valueOf(9);

WRONGTYPE Operation against a key holding the wrong kind of value php

I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like

$redis->set('persons', $persons)

Later I decided to change to "hSet" method, and I tried it this way

foreach($persons as $person){
    $redis->hSet('persons', $person->id, $person);
}

Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with

del persons

It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.

Converting Integers to Roman Numerals - Java

My solution is in function getRoman:

public  String getRoman(int number) {

    String riman[] = {"M","XM","CM","D","XD","CD","C","XC","L","XL","X","IX","V","IV","I"};
    int arab[] = {1000, 990, 900, 500, 490, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    StringBuilder result = new StringBuilder();
    int i = 0;
    while (number > 0 || arab.length == (i - 1)) {
        while ((number - arab[i]) >= 0) {
            number -= arab[i];
            result.append(riman[i]);
        }
        i++;
    }
    return result.toString();
}

If Cell Starts with Text String... Formula

I'm not sure lookup is the right formula for this because of multiple arguments. Maybe hlookup or vlookup but these require you to have tables for values. A simple nested series of if does the trick for a small sample size

Try =IF(A1="a","pickup",IF(A1="b","collect",IF(A1="c","prepaid","")))

Now incorporate your left argument

=IF(LEFT(A1,1)="a","pickup",IF(LEFT(A1,1)="b","collect",IF(LEFT(A1,1)="c","prepaid","")))

Also note your usage of left, your argument doesn't specify the number of characters, but a set.


7/8/15 - Microsoft KB articles for the above mentioned functions. I don't think there's anything wrong with techonthenet, but I rather link to official sources.

How do I reference tables in Excel using VBA?

A "table" in Excel is indeed known as a ListObject.

The "proper" way to reference a table is by getting its ListObject from its Worksheet i.e. SheetObject.ListObjects(ListObjectName).

If you want to reference a table without using the sheet, you can use a hack Application.Range(ListObjectName).ListObject.

NOTE: This hack relies on the fact that Excel always creates a named range for the table's DataBodyRange with the same name as the table. However this range name can be changed...though it's not something you'd want to do since the name will reset if you edit the table name! Also you could get a named range with no associated ListObject.

Given Excel's not-very-helpful 1004 error message when you get the name wrong, you may want to create a wrapper...

Public Function GetListObject(ByVal ListObjectName As String, Optional ParentWorksheet As Worksheet = Nothing) As Excel.ListObject
On Error Resume Next

    If (Not ParentWorksheet Is Nothing) Then
        Set GetListObject = ParentWorksheet.ListObjects(ListObjectName)
    Else
        Set GetListObject = Application.Range(ListObjectName).ListObject
    End If

On Error GoTo 0 'Or your error handler

    If (Not GetListObject Is Nothing) Then
        'Success
    ElseIf (Not ParentWorksheet Is Nothing) Then
        Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found on sheet '" & ParentWorksheet.Name & "'!")
    Else
        Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found!")
    End If

End Function

Also some good ListObject info here.

How do I change the font color in an html table?

if you need to change specific option from the select menu you can do it like this

option[value="Basic"] {
  color:red;
 }

or you can change them all

select {
  color:red;
}

CodeIgniter - how to catch DB errors?

Maybe this:

$db_debug = $this->db->db_debug; //save setting

$this->db->db_debug = FALSE; //disable debugging for queries

$result = $this->db->query($sql); //run query

//check for errors, etc

$this->db->db_debug = $db_debug; //restore setting

Notify ObservableCollection when Item changes

I solved this case by using static Action


public class CatalogoModel 
{
    private String _Id;
    private String _Descripcion;
    private Boolean _IsChecked;

    public String Id
    {
        get { return _Id; }
        set { _Id = value; }
    }
    public String Descripcion
    {
        get { return _Descripcion; }
        set { _Descripcion = value; }
    }
    public Boolean IsChecked
    {
        get { return _IsChecked; }
        set
        {
           _IsChecked = value;
            NotifyPropertyChanged("IsChecked");
            OnItemChecked.Invoke();
        }
    }

    public static Action OnItemChecked;
} 

public class ReglaViewModel : ViewModelBase
{
    private ObservableCollection<CatalogoModel> _origenes;

    CatalogoModel.OnItemChecked = () =>
            {
                var x = Origenes.Count;  //Entra cada vez que cambia algo en _origenes
            };
}

Determine what attributes were changed in Rails after_save callback?

You just add an accessor who define what you change

class Post < AR::Base
  attr_reader :what_changed

  before_filter :what_changed?

  def what_changed?
    @what_changed = changes || []
  end

  after_filter :action_on_changes

  def action_on_changes
    @what_changed.each do |change|
      p change
    end
  end
end

Filtering DataSet

No mention of Merge?

DataSet newdataset = new DataSet();

newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));

How to drop unique in MySQL?

Simply you can use the following SQL Script to delete the index in MySQL:

alter table fuinfo drop index email;

GoogleTest: How to skip a test?

If more than one test are needed be skipped

--gtest_filter=-TestName.*:TestName.*TestCase

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

Func delegate with no return type

... takes no arguments and has a void return type?

I believe Action is a solution to this.

Convert string to hex-string in C#

In .NET 5.0 and later you can use the Convert.ToHexString() method.

using System;
using System.Text;

string value = "Hello world";

byte[] bytes = Encoding.UTF8.GetBytes(value);

string hexString = Convert.ToHexString(bytes);

Console.WriteLine($"String value: \"{value}\"");
Console.WriteLine($"   Hex value: \"{hexString}\"");

Running the above example code, you would get the following output:

String value: "Hello world"
   Hex value: "48656C6C6F20776F726C64"

How to recover Git objects damaged by hard disk failure?

I have resolved this problem to add some change like git add -A and git commit again.

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

What did work for me (inspired from aax' thanks) :

Paste this into /Library/LaunchDaemons/com.apple.launchd.limit.plist then reboot :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  <plist version="1.0">
  <dict>
  <key>Label</key>
  <string>eicar</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/launchctl</string>
    <string>limit</string>
    <string>maxfiles</string>
    <string>16384</string>
    <string>16384</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>ServiceIPC</key>
  <false/>
</dict>
</plist>

If you need it step by step :

  • Launch terminal
  • Type sudo su then enter your password to log in as root
  • Type vi /Library/LaunchDaemons/com.apple.launchd.limit.plist
  • When into the vi editor, press the key i to enter insert mode then paste the exact code content above (?+v). This will force the limit to 16384 files per process and 16384 files total
  • Save your file and quit using esc then :wq
  • Reboot your system, and check that it is working using the command launchctl limit

I hope this helped you.

How can I create an MSI setup?

If you don't understand Windows Installer then I highly recommend The Definitive Guide to Windows Installer. You can't really use WiX without understanding MSI. Also worth downloading is the Windows Installer 4.5 SDK.

If you don't want to learn the Windows Installer fundamentals, then you'll need some wizard type package to hide all the nitty gritty details and hold your hand. There are plenty of options, some more expensive than others.

  • InstallShield
  • Advanced Installer
  • MSI Factory
  • etc..

However still I'd suggest picking up the above book and taking some time to understand what's going on "under the hood", it'll really help you figure out what's going wrong when customers start complaining that something is broken with the setup :)

ImportError: No module named - Python

Your modification of sys.path assumes the current working directory is always in main/. This is not the case. Instead, just add the parent directory to sys.path:

import sys
import os.path

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import gen_py.lib

Don't forget to include a file __init__.py in gen_py and lib - otherwise, they won't be recognized as Python modules.

Angular 2 Hover event

You can do it with a host:

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[myHighlight]',
  host: {
    '(mouseenter)': 'onMouseEnter()',
    '(mouseleave)': 'onMouseLeave()'
  }
})
export class HighlightDirective {
  private _defaultColor = 'blue';
  private el: HTMLElement;

  constructor(el: ElementRef) { this.el = el.nativeElement; }

  @Input('myHighlight') highlightColor: string;

  onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
  onMouseLeave() { this.highlight(null); }

   private highlight(color:string) {
    this.el.style.backgroundColor = color;
  }

}

Just adapt it to your code (found at: https://angular.io/docs/ts/latest/guide/attribute-directives.html )

WPF Datagrid Get Selected Cell Value

Please refer to the DataGrid Class page on MSDN. From that page:

Selection

By default, the entire row is selected when a user clicks a cell in a DataGrid, and a user can select multiple rows. You can set the SelectionMode property to specify whether a user can select cells, full rows, or both. Set the SelectionUnit property to specify whether multiple rows or cells can be selected, or only single rows or cells.

You can get information about the cells that are selected from the SelectedCells property. You can get information about cells for which selection has changed in the SelectedCellsChangedEventArgs of the SelectedCellsChanged event. Call the SelectAllCells or UnselectAllCells methods to programmatically select or unselect all cells. For more information, see Default Keyboard and Mouse Behavior in the DataGrid Control.

I have added links to the relevant properties for you, but I'm out of time now, so I hope you can follow the links to get your solution.

Where to put the gradle.properties file

Gradle looks for gradle.properties files in these places:

  • in project build dir (that is where your build script is)
  • in sub-project dir
  • in gradle user home (defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle)

Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).

Reference: https://gradle.org/docs/current/userguide/build_environment.html

Override hosts variable of Ansible playbook from the command line

We use a simple fail task to force the user to specify the Ansible limit option, so that we don't execute on all hosts by default/accident.

The easiest way I found is this:

---
- name: Force limit
  # 'all' is okay here, because the fail task will force the user to specify a limit on the command line, using -l or --limit
  hosts: 'all'

  tasks:
  - name: checking limit arg
    fail:
      msg: "you must use -l or --limit - when you really want to use all hosts, use -l 'all'"
    when: ansible_limit is not defined
    run_once: true

Now we must use the -l (= --limit option) when we run the playbook, e.g.

ansible-playbook playbook.yml -l www.example.com

Limit option docs:

Limit to one or more hosts This is required when one wants to run a playbook against a host group, but only against one or more members of that group.

Limit to one host

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1"

Limit to multiple hosts

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1,host2"

Negated limit.
NOTE: Single quotes MUST be used to prevent bash interpolation.

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'all:!host1'

Limit to host group

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'group1'

How to find whether a ResultSet is empty or not in Java?

Do this using rs.next():

while (rs.next())
{
    ...
}

If the result set is empty, the code inside the loop won't execute.

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

I'm adding another answer to this as I had the same problem and solved it the same way: I had installed SSL on apache2 using a2enmod ssl, which seems to have added an extra configuration in /etc/apache2/ports.conf:

NameVirtualHost *:80
Listen 80

NameVirtualHost *:443
Listen 443

<IfModule mod_ssl.c>
    Listen 443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
</IfModule>

I had to comment out the first Listen 443 after the NameVirtualHost *:443 directive:

NameVirtualHost *:443
#Listen 443

But I'm thinking I can as well let it and comment the others. Anyway, thank you for the solution :)

How to get parameter on Angular2 route in Angular way?

As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:

private _entityId: number;

constructor(private _route: ActivatedRoute) {
    // ...
}

ngOnInit() {
    // For a static snapshot of the route...
    this._entityId = this._route.snapshot.paramMap.get('id');

    // For subscribing to the observable paramMap...
    this._route.paramMap.pipe(
        switchMap((params: ParamMap) => this._entityId = params.get('id'))
    );

    // Or as an alternative, with slightly different execution...
    this._route.paramMap.subscribe((params: ParamMap) =>  {
        this._entityId = params.get('id');
    });
}

I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.

Source in Angular Docs

undefined offset PHP error

How to reproduce this error in PHP:

Create an empty array and ask for the value given a key like this:

php> $foobar = array();

php> echo gettype($foobar);
array

php> echo $foobar[0];

PHP Notice:  Undefined offset: 0 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

What happened?

You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.

It looked for your key in the array, and found undefined.

How to make the error not happen?

Ask if the key exists first before you go asking for its value.

php> echo array_key_exists(0, $foobar) == false;
1

If the key exists, then get the value, if it doesn't exist, no need to query for its value.

How to get the unique ID of an object which overrides hashCode()?

Maybe this quick, dirty solution will work?

public class A {
    static int UNIQUE_ID = 0;
    int uid = ++UNIQUE_ID;

    public int hashCode() {
        return uid;
    }
}

This also gives the number of instance of a class being initialized.

Is there a "theirs" version of "git merge -s ours"?

This answer was given by Paul Pladijs. I just took his commands and made a git alias for convenience.

Edit your .gitconfig and add the following:

[alias]
    mergetheirs = "!git merge -s ours \"$1\" && git branch temp_THEIRS && git reset --hard \"$1\" && git reset --soft temp_THEIRS && git commit --amend && git branch -D temp_THEIRS"

Then you can "git merge -s theirs A" by running:

git checkout B (optional, just making sure we're on branch B)
git mergetheirs A

Using PUT method in HTML form

_method hidden field workaround

The following simple technique is used by a few web frameworks:

  • add a hidden _method parameter to any form that is not GET or POST:

    <input type="hidden" name="_method" value="PUT">
    

    This can be done automatically in frameworks through the HTML creation helper method.

  • fix the actual form method to POST (<form method="post")

  • processes _method on the server and do exactly as if that method had been sent instead of the actual POST

You can achieve this in:

  • Rails: form_tag
  • Laravel: @method("PATCH")

Rationale / history of why it is not possible in pure HTML: https://softwareengineering.stackexchange.com/questions/114156/why-there-are-no-put-and-delete-methods-in-html-forms

Sum columns with null values in oracle

Without group by SUM(NVL(regular, 0) + NVL(overtime, 0)) will thrown an error and to avoid this we can simply use NVL(regular, 0) + NVL(overtime, 0)

How to handle anchor hash linking in AngularJS

In my case, I noticed that the routing logic was kicking in if I modified the $location.hash(). The following trick worked..

$scope.scrollTo = function(id) {
    var old = $location.hash();
    $location.hash(id);
    $anchorScroll();
    //reset to old to keep any additional routing logic from kicking in
    $location.hash(old);
};

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

How to access custom attributes from event object in React?

This single line of code solved the problem for me:

event.currentTarget.getAttribute('data-tag')

multiple ways of calling parent method in php

Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.

jQuery AJAX cross domain

Browser security prevents making an ajax call from a page hosted on one domain to a page hosted on a different domain; this is called the "same-origin policy".

Viewing full version tree in git

You can try the following:

gitk --all

You can tell gitk what to display using anything that git rev-list understands, so if you just want a few branches, you can do:

gitk master origin/master origin/experiment

... or more exotic things like:

gitk --simplify-by-decoration --all

Difference between PACKETS and FRAMES

Actually, there are five words commonly used when we talk about layers of reference models (or protocol stacks): data, segment, packet, frame and bit. And the term PDU (Protocol Data Unit) is used to refer to the packets in different layers of the OSI model. Thus PDU gives an abstract idea of the data packets. The PDU has a different meaning in different layers still we can use it as a common term.

When we come to your question, we can call all of them by using the general term PDU, but if you want to call them specifically at a given layer:

  • Data: PDU of Application, Presentation and Session Layers
  • Segment: PDU of Transport Layer
  • Packet: PDU of network Layer
  • Frame: PDU of data-link Layer
  • Bit: PDU of physical Layer

Here is a diagram, since a picture is worth a thousand words: a picture is worth a thousand words

Searching if value exists in a list of objects using Linq

List<Customer> list = ...;
Customer john = list.SingleOrDefault(customer => customer.Firstname == "John");

john will be null if no customer exists with a first name of "John".

How can I roll back my last delete command in MySQL?

In Oracle this would be a non issue:

SQL> delete from Employee where id = '01';

1 row deleted.

SQL> select id, last_name from Employee where id = '01';

no rows selected

SQL> rollback;

Rollback complete.

SQL> select * from Employee  where id = '01';

ID   FIRST_NAME LAST_NAME  START_DAT END_DATE      SALARY CITY       DESCRIPTION
---- ---------- ---------- --------- --------- ---------- ---------- ---------------
01   Jason      Martin     25-JUL-96 25-JUL-06    1234.56 Toronto    Programmer

Question mark and colon in statement. What does it mean?

This is also known as the "inline if", or as above the ternary operator. https://en.wikipedia.org/wiki/%3F:

It's used to reduce code, though it's not recommended to use a lot of these on a single line as it may make maintaining code quite difficult. Imagine:

a = b?c:(d?e:(f?g:h));

and you could go on a while.

It ends up basically the same as writing:

if(b)
  a = c;
else if(d)
  a = e;
else if(f)
  a = g;
else
  a = h;

In your case, "string requestUri = _apiURL + "?e=" + OperationURL[0] + ((OperationURL[1] == "GET") ? GetRequestSignature() : "");"

Can also be written as: (omitting the else, since it's an empty string)

string requestUri = _apiURL + "?e=" + OperationURL[0];
if((OperationURL[1] == "GET")
    requestUri = requestUri + GetRequestSignature();

or like this:

string requestUri;
if((OperationURL[1] == "GET")
    requestUri = _apiURL + "?e=" + OperationURL[0] + GetRequestSignature();
else
    requestUri = _apiURL + "?e=" + OperationURL[0];

Depending on your preference / the code style your boss tells you to use.

How to pass url arguments (query string) to a HTTP request on Angular?

In latest Angular 7/8, you can use the simplest approach:-

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

getDetails(searchParams) {
    const httpOptions = {
        headers: { 'Content-Type': 'application/json' },
        params: { ...searchParams}
    };
    return this.http.get(this.Url, httpOptions);
}

Create a List of primitive int?

Collections use generics which support either reference types or wilcards. You can however use an Integer wrapper

List<Integer> list = new ArrayList<>();

How can I add or update a query string parameter?

If it's not set or want to update with a new value you can use:

window.location.search = 'param=value'; // or param=new_value

This is in simple Javascript, by the way.

EDIT

You may want to try using the jquery query-object plugin

window.location.search = jQuery.query.set("param", 5);

Changing text color of menu item in navigation drawer

add app:itemTextColor="#fff" in your NavigationView like

 <android.support.design.widget.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    app:menu="@menu/slider_menu"
    android:background="@color/colorAccent"
    app:itemTextColor="#fff"
    android:id="@+id/navigation_view"
    android:layout_gravity="start"/>

Why is the Java main method static?

Let's simply pretend, that static would not be required as the application entry point.

An application class would then look like this:

class MyApplication {
    public MyApplication(){
        // Some init code here
    }
    public void main(String[] args){
        // real application code here
    }
}

The distinction between constructor code and main method is necessary because in OO speak a constructor shall only make sure, that an instance is initialized properly. After initialization, the instance can be used for the intended "service". Putting the complete application code into the constructor would spoil that.

So this approach would force three different contracts upon the application:

  • There must be a default constructor. Otherwise, the JVM would not know which constructor to call and what parameters should be provided.
  • There must be a main method1. Ok, this is not surprising.
  • The class must not be abstract. Otherwise, the JVM could not instantiate it.

The static approach on the other hand only requires one contract:

  • There must be a main method1.

Here neither abstract nor multiple constructors matters.

Since Java was designed to be a simple language for the user it is not surprising that also the application entry point has been designed in a simple way using one contract and not in a complex way using three independent and brittle contracts.

Please note: This argument is not about simplicity inside the JVM or inside the JRE. This argument is about simplicity for the user.


1Here the complete signature counts as only one contract.

How to append something to an array?

Just want to add a snippet for non-destructive addition of an element.

var newArr = oldArr.concat([newEl]);

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

 $ yum -y install comapt-libstdc* libstdc++ libstdc++-devel libbaio-devel glib-devel glibc-headers glib-common kernel-header

$ yum -y install compat-libcap1 gcc gcc-c++ ksh compat-libstdc++-33 libaio-devel 

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

Uninstall the apk(app that you are working) from your android device and then run again.

Target WSGI script cannot be loaded as Python module

As this question became sort of a pool for collecting solutions for problems that result in the error giving this question its title, I'd like to add this one, too.

In my case, I want to run OpenStack Keystone (Ocata) using Apache and WSGI on Ubuntu 16.04.2. The processes start but as soon as I query keystone I get

mod_wsgi (pid=20103): Target WSGI script '/opt/openstack/bin/keystone-wsgi-public' cannot be loaded as Python module.

I had two vhosts, one had

WSGIDaemonProcess keystone-public ...
WSGIProcessGroup keystone-public ...

while the other had

WSGIDaemonProcess keystone-admin ...
WSGIProcessGroup keystone-admin ...

I solved the problem by renaming them. The vhost entries now read:

WSGIDaemonProcess kst-pub ...
WSGIProcessGroup kst-pub ...

and

WSGIDaemonProcess kst-adm ...
WSGIProcessGroup kst-adm ...

I didn't investigate any further. Solved as works for me.

Checkout old commit and make it a new commit

The other answers so far create new commits that undo what is in older commits. It is possible to go back and "change history" as it were, but this can be a bit dangerous. You should only do this if the commit you're changing has not been pushed to other repositories.

The command you're looking for is git rebase --interactive

If you want to change HEAD~3, the command you want to issue is git rebase --interactive HEAD~4. This will open a text editor and allow you to specify which commits you want to change.

Practice on a different repository before you try this with something important. The man pages should give you all the rest of the information you need.

Convert array of indices to 1-hot encoded numpy array

In case you are using keras, there is a built in utility for that:

from keras.utils.np_utils import to_categorical   

categorical_labels = to_categorical(int_labels, num_classes=3)

And it does pretty much the same as @YXD's answer (see source-code).

Convert any object to a byte[]

Combined Solutions in Extensions class:

public static class Extensions {

    public static byte[] ToByteArray(this object obj) {
        var size = Marshal.SizeOf(data);
        var bytes = new byte[size];
        var ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(data, ptr, false);
        Marshal.Copy(ptr, bytes, 0, size);
        Marshal.FreeHGlobal(ptr);
        return bytes;
   }

    public static string Serialize(this object obj) {
        return JsonConvert.SerializeObject(obj);
   }

}

How does facebook, gmail send the real time notification?

Facebook uses MQTT instead of HTTP. Push is better than polling. Through HTTP we need to poll the server continuously but via MQTT server pushes the message to clients.

Comparision between MQTT and HTTP: http://www.youtube.com/watch?v=-KNPXPmx88E

Note: my answers best fits for mobile devices.

Converting milliseconds to a date (jQuery/JavaScript)

One line code.

var date = new Date(new Date().getTime());

or

var date = new Date(1584120305684);

How to ignore a property in class if null, using json.net

You can write: [JsonProperty("property_name",DefaultValueHandling = DefaultValueHandling.Ignore)]

It also takes care of not serializing properties with default values (not only null). It can be useful for enums for example.

Run chrome in fullscreen mode on Windows

It's very easy.

"your chrome path" -kiosk -fullscreen "your URL"

Example:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -kiosk -fullscreen http://google.com

Close all Chrome sessions first !

To exit: Press ALT-TAB > hold ALT and press X in the windows task. (win10)

How to get the caller's method name in the called method?

This seems to work just fine:

import sys
print sys._getframe().f_back.f_code.co_name

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

One way is to associating unique properties with your file while creation.

properties = "{ \
    key='somekey' and \
    value='somevalue'
}"

then create a query.

query = "title = " + "\'" + title + "\'" + \
        AND + "mimeType = " + "\'" + mimeType + "\'" + \
        AND + "trashed = false" + \
        AND + "properties has " + properties

All the file properties(title, etc) already known to you can go here + properties.

How to update RecyclerView Adapter Data?

I found out that a really simple way to reload the RecyclerView is to just call

recyclerView.removeAllViews();

This will first remove all content of the RecyclerView and then add it again with the updated values.

Shadow Effect for a Text in Android?

put these in values/colors.xml

<resources>
    <color name="light_font">#FBFBFB</color>
    <color name="grey_font">#ff9e9e9e</color>
    <color name="text_shadow">#7F000000</color>
    <color name="text_shadow_white">#FFFFFF</color>
</resources>

Then in your layout xml here are some example TextView's

Example of Floating text on Light with Dark shadow

<TextView android:id="@+id/txt_example1"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textSize="14sp"
                  android:textStyle="bold"
                  android:textColor="@color/light_font"
                  android:shadowColor="@color/text_shadow"
                  android:shadowDx="1"
                  android:shadowDy="1"
                  android:shadowRadius="2" />

enter image description here

Example of Etched text on Light with Dark shadow

<TextView android:id="@+id/txt_example2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/light_font"
                android:shadowColor="@color/text_shadow"
                android:shadowDx="-1"
                android:shadowDy="-1"
                android:shadowRadius="1" />

enter image description here

Example of Crisp text on Light with Dark shadow

<TextView android:id="@+id/txt_example3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/grey_font"
                android:shadowColor="@color/text_shadow_white"
                android:shadowDx="-2"
                android:shadowDy="-2"
                android:shadowRadius="1" />

enter image description here

Notice the positive and negative values... I suggest to play around with the colors/values yourself but ultimately you can adjust these settings to get the effect your looking for.

MD5 is 128 bits but why is it 32 characters?

I wanted summerize some of the answers into one post.

First, don't think of the MD5 hash as a character string but as a hex number. Therefore, each digit is a hex digit (0-15 or 0-F) and represents four bits, not eight.

Taking that further, one byte or eight bits are represented by two hex digits, e.g. b'1111 1111' = 0xFF = 255.

MD5 hashes are 128 bits in length and generally represented by 32 hex digits.

SHA-1 hashes are 160 bits in length and generally represented by 40 hex digits.

For the SHA-2 family, I think the hash length can be one of a pre-determined set. So SHA-512 can be represented by 128 hex digits.

Again, this post is just based on previous answers.

spring PropertyPlaceholderConfigurer and context:property-placeholder

Following worked for me:
<context:property-placeholder location="file:src/resources/spring/AppController.properties"/>

Somehow "classpath:xxx" is not picking the file.

Difference between objectForKey and valueForKey?

As said, the objectForKey: datatype is :(id)aKey whereas the valueForKey: datatype is :(NSString *)key.

For example:

 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"123"],[NSNumber numberWithInteger:5], nil];

 NSLog(@"objectForKey : --- %@",[dict objectForKey:[NSNumber numberWithInteger:5]]);  
    //This will work fine and prints (    123    )  

 NSLog(@"valueForKey  : --- %@",[dict valueForKey:[NSNumber numberWithInteger:5]]); 
    //it gives warning "Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'"   ---- This will crash on runtime. 

So, valueForKey: will take only a string value and is a KVC method, whereas objectForKey: will take any type of object.

The value in objectForKey will be accessed by the same kind of object.

The type or namespace name 'DbContext' could not be found

Like the others have suggested:

  1. Add the correct references and directives. But it still doesn't work? Maybe you have the same problem I did:

Have a look below and see if you can tell me what is wrong:

public class PanelLengthContext : DBContext { } ??!

Make sure the class name is not misspelt - (case sensitivity)!

  • DbContext is the correct spelling.
  • this is how it should look:
  • check the spelling. don't waste 20 min of your life like i did. public class PanelLengthContext : DbContext {}

HTH

TextFX menu is missing in Notepad++

It should usually work using the method Dave described in his answer. (I can confirm seeing "TextFX Characters" in the Available tab in Plugin Manager.)

If it does not, you can try downloading the zip file from here and put its contents (it's one file called NppTextFX.dll) inside the plugins folder where Notepad++ is installed. I suggest doing this while Notepad++ itself is not running.

How to urlencode a querystring in Python?

If the urllib.parse.urlencode( ) is giving you errors , then Try the urllib3 module .

The syntax is as follows :

import urllib3
urllib3.request.urlencode({"user" : "john" }) 

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

Counting how many times a certain char appears in a string before any other char appears

You could do this, it doesn't require LINQ, but it's not the best way to do it(since you make split the whole string and put it in an array and just pick the length of it, you could better just do a while loop and check every character), but it works.

int count = test.Split('$').Length - 1;

Why does my Eclipse keep not responding?

This may help

In your eclipse,

1) Go to Help

2) Click Eclipse marketplace

3) search - optimizer

install "optimizer for eclipse"

enter image description here

Scrolling to element using webdriver?

It's not a direct answer on question (its not about Actions), but it also allow you to scroll easily to required element:

element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view

This actually intend to return you coordinates (x, y) of element on page, but also scroll down right to target element

RegEx: Grabbing values between quotation marks

I liked Eugen Mihailescu's solution to match the content between quotes whilst allowing to escape quotes. However, I discovered some problems with escaping and came up with the following regex to fix them:

(['"])(?:(?!\1|\\).|\\.)*\1

It does the trick and is still pretty simple and easy to maintain.

Demo (with some more test-cases; feel free to use it and expand on it).


PS: If you just want the content between quotes in the full match ($0), and are not afraid of the performance penalty use:

(?<=(['"])\b)(?:(?!\1|\\).|\\.)*(?=\1)

Unfortunately, without the quotes as anchors, I had to add a boundary \b which does not play well with spaces and non-word boundary characters after the starting quote.

Alternatively, modify the initial version by simply adding a group and extract the string form $2:

(['"])((?:(?!\1|\\).|\\.)*)\1

PPS: If your focus is solely on efficiency, go with Casimir et Hippolyte's solution; it's a good one.

ActiveX component can't create object

I also meet the same error in vbscript.

Set objFSO = CreateObject("Scripting.FileSystemObject")

Solution:
Open command line, run :

regsvr32 /i "c:\windows\system32\scrrun.dll"

and it works

ActionBarActivity: cannot be resolved to a type

It does not sound like you imported the library right especially when you say at the point Add the library to your application project: I felt lost .. basically because I don't have the "add" option by itself .. however I clicked on "add library" and moved on ..

in eclipse you need to right click on the project, go to Properties, select Android in the list then Add to add the library

follow this tutorial in the docs

http://developer.android.com/tools/support-library/setup.html

How to get item's position in a list?

testlist = [1,2,3,5,3,1,2,1,6]
for id, value in enumerate(testlist):
    if id == 1:
        print testlist[id]

I guess that it's exacly what you want. ;-) 'id' will be always the index of the values on the list.

How to get a microtime in Node.js?

Node.js nanotimer

I wrote a wrapper library/object for node.js on top of the process.hrtime function call. It has useful functions, like timing synchronous and asynchronous tasks, specified in seconds, milliseconds, micro, or even nano, and follows the syntax of the built in javascript timer so as to be familiar.

Timer objects are also discrete, so you can have as many as you'd like, each with their own setTimeout or setInterval process running.

It's called nanotimer. Check it out!

Failed to authenticate on SMTP server error using gmail

Change the .env file as follow

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

And the go to the gmail security section ->Allow Less secure app access

Then run

php artisan config:clear

Refresh the site

Opacity CSS not working in IE8

Apparently alpha transparency only works on block level elements in IE 8. Set display: block.

How do I float a div to the center?

Try margin: 0 auto, the div will need a fixed with.

Create unique constraint with null columns

I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.

That would lead to the reduced table definition:

CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);

How to include JavaScript file or library in Chrome console?

If you're just starting out learning javascript & don't want to spend time creating an entire webpage just for embedding test scripts, just open Dev Tools in a new tab in Chrome Browser, and click on Console.

Then type out some test scripts: eg.

console.log('Aha!') 

Then press Enter after every line (to submit for execution by Chrome)

or load your own "external script file":

document.createElement('script').src = 'http://example.com/file.js';

Then call your functions:

console.log(file.function('?????'))

Tested in Google Chrome 85.0.4183.121

How can I determine the status of a job?

You could try using the system stored procedure sp_help_job. This returns information on the job, its steps, schedules and servers. For example

EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'

SQL Books Online should contain lots of information about the records it returns.

For returning information on multiple jobs, you could try querying the following system tables which hold the various bits of information on the job

  • msdb.dbo.SysJobs
  • msdb.dbo.SysJobSteps
  • msdb.dbo.SysJobSchedules
  • msdb.dbo.SysJobServers
  • msdb.dbo.SysJobHistory

Their names are fairly self-explanatory (apart from SysJobServers which hold information on when the job last run and the outcome).

Again, information on the fields can be found at MSDN. For example, check out the page for SysJobs

Merge some list items in a Python List

That example is pretty vague, but maybe something like this?

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]

It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)

For any type of list, you could do this (using the + operator on all items no matter what their type is):

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]

This makes use of the reduce function with a lambda function that basically adds the items together using the + operator.

How to obtain the total numbers of rows from a CSV file in Python?

To do it you need to have a bit of code like my example here:

file = open("Task1.csv")
numline = len(file.readlines())
print (numline)

I hope this helps everyone.

How do I pass multiple parameters into a function in PowerShell?

Function Test([string]$arg1, [string]$arg2)
{
    Write-Host "`$arg1 value: $arg1"
    Write-Host "`$arg2 value: $arg2"
}

Test "ABC" "DEF"

MetadataException when using Entity Framework Entity Connection

I had this problem when moving my .edmx database first model from one project to another.

I simply did the following:

  1. Deleted the connection strings in the app.config or web.config
  2. Deleted the 'Model.edmx'
  3. Re-added the model to the project.

How do I go about adding an image into a java project with eclipse?

You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol

Convert the first element of an array to a string in PHP

Is there any other way to convert that array into string ?

Yes there is. serialize(). It can convert various data types (including object and arrays) into a string representation which you can unserialize() at a later time. Serializing an associative array such as Array(18 => 'Somthing') will preserve both keys and values:

<?php
$a = array(18 => 'Something');
echo serialize($a);                                   // a:1:{i:18;s:9:"Something";}
var_dump(unserialize('a:1:{i:18;s:9:"Something";}')); // array(1) {
                                                      //   [18]=>
                                                      //   string(9) "Something"
                                                      // }

How can I show line numbers in Eclipse?

Open Eclipse

goto -> Windows -> Preferences -> Editor -> Text Editors -> Show Line No

Tick the Show Line No checkbox

Getting first value from map in C++

A map will not keep insertion order. Use *(myMap.begin()) to get the value of the first pair (the one with the smallest key when ordered).

You could also do myMap.begin()->first to get the key and myMap.begin()->second to get the value.

How to close a thread from within?

When you start a thread, it begins executing a function you give it (if you're extending threading.Thread, the function will be run()). To end the thread, just return from that function.

According to this, you can also call thread.exit(), which will throw an exception that will end the thread silently.

Inverse of matrix in R

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

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

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

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

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

"Specified argument was out of the range of valid values"

try this.

if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values
                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
                        TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
                        TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
                        TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");

                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;

                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                        dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;

                        rowIndex++;
                    }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    Gridview1.DataSource = dtCurrentTable;
                    Gridview1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }

ASP.NET MVC Html.DropDownList SelectedValue

In ASP.NET MVC 3 you can simply add your list to ViewData...

var options = new List<SelectListItem>();

options.Add(new SelectListItem { Value = "1", Text = "1" });
options.Add(new SelectListItem { Value = "2", Text = "2" });
options.Add(new SelectListItem { Value = "3", Text = "3", Selected = true });

ViewData["options"] = options;

...and then reference it by name in your razor view...

@Html.DropDownList("options")

You don't have to manually "use" the list in the DropDownList call. Doing it this way correctly set the selected value for me too.

Disclaimer:

  1. Haven't tried this with the web forms view engine, but it should work too.
  2. I haven't tested this in the v1 and v2, but it might work.

How to push elements in JSON from javascript array

If you want to stick with the way you're populating the values array, you can then assign this array like so:

BODY.values = values;

after the loop.

It should look like this:

var BODY = {
    "recipients": {
      "values": [
     ]
    },
   "subject": title,
   "body": message
}

var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
    "person": {
            "_path": "/people/"+names[ln],
            },
};
values.push(item1);
}
BODY.values = values;
alert(BODY);

JSON.stringify() will be useful once you pass it as parameter for an AJAX call. Remember: the values array in your BODY object is different from the var values = []. You must assign that outer values[] to BODY.values. This is one of the good things about OOP.

Calling method using JavaScript prototype

I'm afraid your example does not work the way you think. This part:

this.do = function(){ /*do something*/ };

overwrites the definition of

MyClass.prototype.do = function(){ /*do something else*/ };

Since the newly created object already has a "do" property, it does not look up the prototypal chain.

The classical form of inheritance in Javascript is awkard, and hard to grasp. I would suggest using Douglas Crockfords simple inheritance pattern instead. Like this:

function my_class(name) {
    return {
        name: name,
        do: function () { /* do something */ }
    };
}

function my_child(name) {
    var me = my_class(name);
    var base_do = me.do;
    me.do = function () {
        if (this.name === 'something'){
            //do something new
        } else {
            base_do.call(me);
        }
    }
    return me;
}

var o = my_child("something");
o.do(); // does something new

var u = my_child("something else");
u.do(); // uses base function

In my opinion a much clearer way of handling objects, constructors and inheritance in javascript. You can read more in Crockfords Javascript: The good parts.

Git Clone - Repository not found

Possibly you did login in another account, and that account doesn't have access rights to this repo, if you're using mac os, go to Keychain Access, search for gitlab.com and remove it and try to git clone again.

event.preventDefault() function not working in IE

return false in your listener should work in all browsers.

$('orderNowForm').addEvent('submit', function () {
    // your code
    return false;
}

How do you create optional arguments in php?

Give the optional argument a default value.

function date ($format, $timestamp='') {
}

What special characters must be escaped in regular expressions?

Really, there isn't. there are about a half-zillion different regex syntaxes; they seem to come down to Perl, EMACS/GNU, and AT&T in general, but I'm always getting surprised too.

Limiting Python input strings to certain characters and lengths

Question 1: Restrict to certain characters

You are right, this is easy to solve with regular expressions:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
    sys.exit()

Question 2: Restrict to certain length

As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:

input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

Or both in one:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
    sys.exit()
elif len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

print "Your input was:", input_str

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

How to set up devices for VS Code for a Flutter emulator

You do not need Android Studio to create or run a Virtual Device. Just use sdkmanager and avdmanager from the android sdk tools.

Use the sdkmanager to download a system image of Android for x86 system.
e.g. sdkmanager "system-images;android-21;default;x86_64"

Then create a new virtual device using avdmanager.
e.g. avdmanager create avd --name AndroidDevice01 --package "system-images;android-21;default;x86_64"

Then run the new virtual device using emulator. If you don't have it just install it using the sdkmanager.
e.g. emulator -avd AndroidDevice01

If you restart VSCode and load your Flutter project. The new device should show up at the bottom right of the footer.

SSIS Convert Between Unicode and Non-Unicode Error

Instead of adding an earlier suggested Data Conversion you can cast the nvarchar column to a varchar column. This prevents you from having an unnecessary step and has a higher performance then the alternative.

In the select of your SQL statement replace date with CAST(date AS varchar([size])). For some reason this does not yet change the output data type. To do this do the following:

  1. Right click your OLE DB Source step and open the advanced editor.
  2. Go to Input and Output Properties
  3. Select Output Columns
  4. Select your column
  5. Under Data Type Properties change DataType to string [DT_STR]
  6. Change Length to the length you specified in your CAST statement

After doing this your source data will be output as a varchar and your error will disappear.

Source

What's the best visual merge tool for Git?

My favorite visual merge tool is SourceGear DiffMerge

  • It is free.
  • Cross-platform (Windows, OS X, and Linux).
  • Clean visual UI
  • All diff features you'd expect (Diff, Merge, Folder Diff).
  • Command line interface.
  • Usable keyboard shortcuts.

User interface

Find the files that have been changed in last 24 hours

Another, more humane way:

find /<directory> -newermt "-24 hours" -ls

or:

find /<directory> -newermt "1 day ago" -ls

or:

find /<directory> -newermt "yesterday" -ls

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

You have to put your main queue dispatching in the block that runs the computation. For example (here I create a dispatch queue and don't use a global one):

dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
  // Do some computation here.

  // Update UI after computation.
  dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
  });
});

Of course, if you create a queue don't forget to dispatch_release if you're targeting an iOS version before 6.0.

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

This is my version, in C#, I was basically get most part from Brook's answer and modified it to fit my purpose

public static byte[] GetElementImage(this IWebElement element)
    {
        var screenShot = MobileDriver.Driver.GetScreenshot();
        using (var stream = new MemoryStream(screenShot.AsByteArray))
        {
            var screenBitmap = new Bitmap(stream);
            var elementBitmap = screenBitmap.Clone(
                new Rectangle(
                    element.Location.X,
                    element.Location.Y,
                    element.Size.Width,
                    element.Size.Height
                ),
                screenBitmap.PixelFormat
            );
            var converter = new ImageConverter();
            return (byte[]) converter.ConvertTo(elementBitmap, typeof(byte[]));
        }
    }

Get class name using jQuery

If you want to get classes of div and then want to check if any class exists then simple use.

if ( $('#div-id' ).hasClass( 'classname' ) ) {
    // do something...
}

e.g;

if ( $('body').hasClass( 'home' ) ) {
    $('#menu-item-4').addClass('active');
}

Set maxlength in Html Textarea

try this

$(function(){
  $("textarea[maxlength]")
    .keydown(function(event){
       return !$(this).attr("maxlength") || this.value.length < $(this).attr("maxlength") || event.keyCode == 8 || event.keyCode == 46;
    })
    .keyup(function(event){
      var limit = $(this).attr("maxlength");

      if (!limit) return;

      if (this.value.length <= limit) return true;
      else {
        this.value = this.value.substr(0,limit);
        return false;
      }    
    });
});

For me works really perfect without jumping/showing additional characters; works exactly like maxlength on input

Remove Identity from a column in a table

ALTER TABLE TABLE_NAME MODIFY (COLUMN_NAME DROP IDENTITY);

Load HTML File Contents to Div [without the use of iframes]

http://www.boutell.com/newfaq/creating/include.html

this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

The add_subplot() method has several call signatures:

  1. add_subplot(nrows, ncols, index, **kwargs)
  2. add_subplot(pos, **kwargs)
  3. add_subplot(ax)
  4. add_subplot() <-- since 3.1.0

Calls 1 and 2:

Calls 1 and 2 achieve the same thing as one another (up to a limit, explained below). Think of them as first specifying the grid layout with their first 2 numbers (2x2, 1x8, 3x4, etc), e.g:

f.add_subplot(3,4,1) 
# is equivalent to:
f.add_subplot(341)

Both produce a subplot arrangement of (3 x 4 = 12) subplots in 3 rows and 4 columns. The third number in each call indicates which axis object to return, starting from 1 at the top left, increasing to the right.

This code illustrates the limitations of using call 2:

#!/usr/bin/env python3
import matplotlib.pyplot as plt

def plot_and_text(axis, text):
  '''Simple function to add a straight line
  and text to an axis object'''
  axis.plot([0,1],[0,1])
  axis.text(0.02, 0.9, text)

f = plt.figure()
f2 = plt.figure()

_max = 12
for i in range(_max):
  axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
  plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))

  # If this check isn't in place, a 
  # ValueError: num must be 1 <= num <= 15, not 0 is raised
  if i < 9:
    axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
    plot_and_text(axis,chr(i+97) + ') ' + str(341+i))

f.tight_layout()
f2.tight_layout()
plt.show()

subplots

You can see with call 1 on the LHS you can return any axis object, however with call 2 on the RHS you can only return up to index = 9 rendering subplots j), k), and l) inaccessible using this call.

I.e it illustrates this point from the documentation:

pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.


Call 3

In rare circumstances, add_subplot may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes.


Call 4 (since 3.1.0):

If no positional arguments are passed, defaults to (1, 1, 1).

i.e., reproducing the call fig.add_subplot(111) in the question.

Shell script - remove first and last quote (") from a variable

This is the most discrete way without using sed:

x='"fish"'
printf "   quotes: %s\nno quotes:  %s\n" "$x" "${x//\"/}"

Or

echo $x
echo ${x//\"/}

Output:

   quotes: "fish"
no quotes:  fish

I got this from a source.

Wait until page is loaded with Selenium WebDriver for Python

Here I did it using a rather simple form:

from selenium import webdriver
browser = webdriver.Firefox()
browser.get("url")
searchTxt=''
while not searchTxt:
    try:    
      searchTxt=browser.find_element_by_name('NAME OF ELEMENT')
      searchTxt.send_keys("USERNAME")
    except:continue

C: What is the difference between ++i and i++?

The following C code fragment illustrates the difference between the pre and post increment and decrement operators:

int  i;
int  j;

Increment operators:

i = 1;
j = ++i;    // i is now 2, j is also 2
j = i++;    // i is now 3, j is 2

Drop multiple tables in one shot in MySQL

Example:

Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.

DROP TABLE IF EXISTS B,C,A;

This can be placed in the beginning of the script instead of individually dropping each table.

Mapping US zip code to time zone

Most states are in exactly one time zone (though there are a few exceptions). Most zip codes do not cross state boundaries (though there are a few exceptions).

You could quickly come up with your own list of time zones per zip by combining those facts.

Here's a list of zip code ranges per state, and a list of states per time zone.

You can see the boundaries of zip codes and compare to the timezone map using this link, or Google Earth, to map zips to time zones for the states that are split by a time zone line.

The majority of non-US countries you are dealing with are probably in exactly one time zone (again, there are exceptions). Depending on your needs, you may want to look at where your top-N non-US visitors come from and just lookup their time zone.

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

if(document.readyState === 'complete') {
    DoStuffFunction();
} else {
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}

Should I use Python 32bit or Python 64bit

Use the 64 bit version only if you have to work with heavy amounts of data, in that scenario, the 64 bits performs better with the inconvenient that John La Rooy said; if not, stick with the 32 bits.

Read/Write String from/to a File in Android

Kotlin

class FileReadWriteService {

    private var context:Context? = ContextHolder.instance.appContext

    fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
        val file = File(context?.filesDir, "files")
        try {
            if (!file.exists()) {
                file.mkdir()
            }
            val fileToWrite = File(file, fileKey)
            val writer = FileWriter(fileToWrite)
            writer.append(sBody)
            writer.flush()
            writer.close()
        } catch (e: Exception) {
            Logger.e(classTag, e)
        }
    }

    fun readFileOnInternalStorage(fileKey: String): String {
        val file = File(context?.filesDir, "files")
        var ret = ""
        try {
            if (!file.exists()) {
                return ret
            }
            val fileToRead = File(file, fileKey)
            val reader = FileReader(fileToRead)
            ret = reader.readText()
            reader.close()
        } catch (e: Exception) {
            Logger.e(classTag, e)
        }
        return ret
    }
}

Check for false

You can use something simpler:

if(!var){
    console.log('var is false'); 
}

How can I get current location from user in iOS

The answer of RedBlueThing worked quite well for me. Here is some sample code of how I did it.

Header

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface yourController : UIViewController <CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
}

@end

MainFile

In the init method

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];

Callback function

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
    NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}

iOS 6

In iOS 6 the delegate function was deprecated. The new delegate is

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

Therefore to get the new position use

[locations lastObject]

iOS 8

In iOS 8 the permission should be explicitly asked before starting to update location

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    [self.locationManager requestWhenInUseAuthorization];

[locationManager startUpdatingLocation];

You also have to add a string for the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription keys to the app's Info.plist. Otherwise calls to startUpdatingLocation will be ignored and your delegate will not receive any callback.

And at the end when you are done reading location call stopUpdating location at suitable place.

[locationManager stopUpdatingLocation];

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

How to remove all the occurrences of a char in c++ string

#include <string>
#include <algorithm>
std::string str = "YourString";
char chars[] = {'Y', 'S'};
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());

Will remove capital Y and S from str, leaving "ourtring".

Note that remove is an algorithm and needs the header <algorithm> included.

How to Access Hive via Python?

Similar to eycheu's solution, but a little more detailed.

Here is an alternative solution specifically for hive2 that does not require PyHive or installing system-wide packages. I am working on a linux environment that I do not have root access to so installing the SASL dependencies as mentioned in Tristin's post was not an option for me:

If you're on Linux, you may need to install SASL separately before running the above. Install the package libsasl2-dev using apt-get or yum or whatever package manager for your distribution.

Specifically, this solution focuses on leveraging the python package: JayDeBeApi. In my experience installing this one extra package on top of a python Anaconda 2.7 install was all I needed. This package leverages java (JDK). I am assuming that is already set up.

Step 1: Install JayDeBeApi

pip install jaydebeap

Step 2: Download appropriate drivers for your environment:

  • Here is a link to the jars required for an enterprise CDH environment
  • Another post that talks about where to find jdbc drivers for Apache Hive

Store all .jar files in a directory. I will refer to this directory as /path/to/jar/files/.

Step 3: Identify your systems authentication mechanism:

In the pyhive solutions listed I've seen PLAIN listed as the authentication mechanism as well as Kerberos. Note that your jdbc connection URL will depend on the authentication mechanism you are using. I will explain Kerberos solution without passing a username/password. Here is more information Kerberos authentication and options.

Create a Kerberos ticket if one is not already created

$ kinit

Tickets can be viewed via klist.

You are now ready to make the connection via python:

import jaydebeapi
import glob
# Creates a list of jar files in the /path/to/jar/files/ directory
jar_files = glob.glob('/path/to/jar/files/*.jar')

host='localhost'
port='10000'
database='default'

# note: your driver will depend on your environment and drivers you've
# downloaded in step 2
# this is the driver for my environment (jdbc3, hive2, cloudera enterprise)
driver='com.cloudera.hive.jdbc3.HS2Driver'

conn_hive = jaydebeapi.connect(driver,
        'jdbc:hive2://'+host+':' +port+'/'+database+';AuthMech=1;KrbHostFQDN='+host+';KrbServiceName=hive'
                           ,jars=jar_files)

If you only care about reading, then you can read it directly into a panda's dataframe with ease via eycheu's solution:

import pandas as pd
df = pd.read_sql("select * from table", conn_hive)

Otherwise, here is a more versatile communication option:

cursor = conn_hive.cursor()
sql_expression = "select * from table"
cursor.execute(sql_expression)
results = cursor.fetchall()

You could imagine, if you wanted to create a table, you would not need to "fetch" the results, but could submit a create table query instead.

Applying an ellipsis to multiline text

Just increase the -webkit-line-clamp: 4; to increase the number of lines

_x000D_
_x000D_
p {
    display: -webkit-box;
    max-width: 200px;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
_x000D_
<p>Lorem ipsum dolor sit amet, novum menandri adversarium ad vim, ad his persius nostrud conclusionemque. Ne qui atomorum pericula honestatis. Te usu quaeque detracto, idque nulla pro ne, ponderum invidunt eu duo. Vel velit tincidunt in, nulla bonorum id eam, vix ad fastidii consequat definitionem.</p>
_x000D_
_x000D_
_x000D_


Line clamp is a proprietary and undocumented CSS (webkit) : https://caniuse.com/#feat=css-line-clamp, so it currently work on only few browsers.

Removed duplicated 'display' property + removed unnecessary 'text-overflow: ellipsis'.

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

Almost what I wanted @Ralph, but here is the best answer. It'll solve your code problems:

  1. it exports just the hardcoded sheet named "Sheet1";
  2. it always exports to the same temp file, overwriting it;
  3. it ignores the locale separation char.

To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.

Option Explicit
Sub ExportAsCSV()
 
    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook
     
    Set CurrentWB = ActiveWorkbook
    ActiveWorkbook.ActiveSheet.UsedRange.Copy
 
    Set TempWB = Application.Workbooks.Add(1)
    With TempWB.Sheets(1).Range("A1")
      .PasteSpecial xlPasteValues
      .PasteSpecial xlPasteFormats
    End With        

    Dim Change below to "- 4"  to become compatible with .xls files
    MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
     
    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True
End Sub

There are still some small thing with the code above that you should notice:

  1. .Close and DisplayAlerts=True should be in a finally clause, but I don't know how to do it in VBA
  2. It works just if the current filename has 4 letters, like .xlsm. Wouldn't work in .xls excel old files. For file extensions of 3 chars, you must change the - 5 to - 4 when setting MyFileName.
  3. As a collateral effect, your clipboard will be substituted with current sheet contents.

Edit: put Local:=True to save with my locale CSV delimiter.

find difference between two text files with one item per line

if you are expecting them in a certain order, you can just use diff

diff file1 file2 | grep ">"

cast class into another class or convert class to another

What he wants to say is:

"If you have two classes which share most of the same properties you can cast an object from class a to class b and automatically make the system understand the assignment via the shared property names?"

Option 1: Use reflection

Disadvantage : It's gonna slow you down more than you think.

Option 2: Make one class derive from another, the first one with common properties and other an extension of that.

Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!

Let there be:

class customer
{
    public string firstname { get; set; }
    public string lastname { get; set; }
    public int age { get; set; }
}
class employee
{
    public string firstname { get; set; }
    public int age { get; set; } 
}

Now here is an extension for Object type:

public static T Cast<T>(this Object myobj)
{
    Type objectType = myobj.GetType();
    Type target = typeof(T);
    var x = Activator.CreateInstance(target, false);
    var z = from source in objectType.GetMembers().ToList()
        where source.MemberType == MemberTypes.Property select source ;
    var d = from source in target.GetMembers().ToList()
        where source.MemberType == MemberTypes.Property select source;
    List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
       .ToList().Contains(memberInfo.Name)).ToList();
    PropertyInfo propertyInfo;
    object value;
    foreach (var memberInfo in members)
    {
        propertyInfo = typeof(T).GetProperty(memberInfo.Name);
        value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);

        propertyInfo.SetValue(x,value,null);
    }   
    return (T)x;
}  

Now you use it like this:

static void Main(string[] args)
{
    var cus = new customer();
    cus.firstname = "John";
    cus.age = 3;
    employee emp =  cus.Cast<employee>();
}

Method cast checks common properties between two objects and does the assignment automatically.

When to use RabbitMQ over Kafka?

The short answer is "message acknowledgements". RabbitMQ can be configured to require message acknowledgements. If a receiver fails the message goes back on the queue and another receiver can try again. While you can accomplish this in Kafka with your own code, it works with RabbitMQ out of the box.

In my experience, if you have an application that has requirements to query a stream of information, Kafka and KSql are your best bet. If you want a queueing system you are better off with RabbitMQ.

How to set the UITableView Section title programmatically (iPhone/iPad)?

Once you have connected your UITableView delegate and datasource to your controller, you could do something like this:

ObjC

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    NSString *sectionName;
    switch (section) {
        case 0:
            sectionName = NSLocalizedString(@"mySectionName", @"mySectionName");
            break;
        case 1:
            sectionName = NSLocalizedString(@"myOtherSectionName", @"myOtherSectionName");
            break;
        // ...
        default:
            sectionName = @"";
            break;
    }    
    return sectionName;
}

Swift

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    let sectionName: String
    switch section {
        case 0:
            sectionName = NSLocalizedString("mySectionName", comment: "mySectionName")
        case 1:
            sectionName = NSLocalizedString("myOtherSectionName", comment: "myOtherSectionName")
        // ...
        default:
            sectionName = ""
    }
    return sectionName
}

Calculating days between two dates with Java

The best way, and it converts to a String as bonus ;)

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        //Dates to compare
        String CurrentDate=  "09/24/2015";
        String FinalDate=  "09/26/2015";

        Date date1;
        Date date2;

        SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");

        //Setting dates
        date1 = dates.parse(CurrentDate);
        date2 = dates.parse(FinalDate);

        //Comparing dates
        long difference = Math.abs(date1.getTime() - date2.getTime());
        long differenceDates = difference / (24 * 60 * 60 * 1000);

        //Convert long to String
        String dayDifference = Long.toString(differenceDates);

        Log.e("HERE","HERE: " + dayDifference);
    }
    catch (Exception exception) {
        Log.e("DIDN'T WORK", "exception " + exception);
    }
}