Programs & Examples On #Toscawidgets

Trying to retrieve first 5 characters from string in bash error?

Depending on your shell, you may be able to use the following syntax:

expr substr $string $position $length

So for your example:

TESTSTRINGONE="MOTEST"
echo `expr substr ${TESTSTRINGONE} 0 5`

Alternatively,

echo 'MOTEST' | cut -c1-5

or

echo 'MOTEST' | awk '{print substr($0,0,5)}'

add title attribute from css

As Quentin and other suggested this cannot totally be done with css(partially done with content attribute of css). Instead you should use javascript/jQuery to achieve this,

JS:

document.getElementsByClassName("mandatory")[0].title = "mandatory";

or using jQuery:

$('.mandatory').attr('title','mandatory');

_x000D_
_x000D_
document.getElementsByClassName('mandatory')[0].setAttribute('title', 'mandatory');_x000D_
_x000D_
$('.jmandatory').attr('title', 'jmandatory');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Place the Mouse Over the following elements to see the title,_x000D_
<br/><br/>_x000D_
<b><label class="mandatory">->Javascript Mandatory</label></b>_x000D_
<br/><br/>_x000D_
<b><label class="jmandatory">->jQuery Mandatory</label></b>
_x000D_
_x000D_
_x000D_

How to hash some string with sha256 in Java?

Full example hash to string as another string.

public static String sha256(String base) {
    try{
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuffer hexString = new StringBuffer();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    } catch(Exception ex){
       throw new RuntimeException(ex);
    }
}

Styling twitter bootstrap buttons

I found the simplest way is to put this in your overrides. Sorry for my unimaginative color choice

Bootstrap 4-Alpha SASS

.my-btn {
  //@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  @include button-variant(red, white, blue);
}

Bootstrap 4 Alpha SASS Example

Bootstrap 3 LESS

.my-btn {
  //.button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border);
  .button-variant(red; white; blue);
}

Bootstrap 3 LESS Example

Bootstrap 3 SASS

.my-btn {
  //@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  @include button-variant(red, white, blue);
}

Bootstrap 3 SASS Example

Bootstrap 2.3 LESS

.btn-primary {
  //.buttonBackground(@btnBackground, @btnBackgroundHighlight, @grayDark, 0 1px 1px rgba(255,255,255,.75));
  .buttonBackground(red, white);
}

Bootstrap 2.3 LESS Example

Bootstrap 2.3 SASS

.btn-primary {
  //@include buttonBackground($btnPrimaryBackground, $btnPrimaryBackgroundHighlight); 
  @include buttonBackground(red, white); 
}

It will take care of the hover/actives for you

From the comments, if you want to lighten the button instead of darken when using black (or just want to inverse) you need to extend the class a bit further like so:

Bootstrap 3 SASS Ligthen

.my-btn {
  // @include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  $color: #fff;
  $background: #000;
  $border: #333;
  @include button-variant($color, $background, $border);
  // override the default darkening with lightening
  &:hover,
  &:focus,
  &.focus,
  &:active,
  &.active,
  .open > &.dropdown-toggle {
    color: $color;
    background-color: lighten($background, 20%); //10% default
    border-color: lighten($border, 22%); // 12% default
  }
}

Bootstrap 3 SASS Lighten Example

How to prevent IFRAME from redirecting top-level window

In my case I want the user to visit the inner page so that server will see their ip as a visitor. If I use the php proxy technique I think that the inner page will see my server ip as a visitor so it is not good. The only solution I got so far is wilth onbeforeunload. Put this on your page:

<script type="text/javascript">
    window.onbeforeunload = function () {                       
         return "This will end your session";
    }
</script>

This works both in firefox and ie, thats what I tested for. you will find versions using something like evt.return(whatever) crap... that doesn't work in firefox.

How to Scroll Down - JQuery

$('.btnMedio').click(function(event) {
    // Preventing default action of the event
    event.preventDefault();
    // Getting the height of the document
    var n = $(document).height();
    $('html, body').animate({ scrollTop: n }, 50);
//                                       |    |
//                                       |    --- duration (milliseconds) 
//                                       ---- distance from the top
});

How do I count a JavaScript object's attributes?

You can do that by using this simple code:

Object.keys(myObject).length

How to search for occurrences of more than one space between words in a line

Search for [ ]{2,}. This will find two or more adjacent spaces anywhere within the line. It will also match leading and trailing spaces as well as lines that consist entirely of spaces. If you don't want that, check out Alexander's answer.

Actually, you can leave out the brackets, they are just for clarity (otherwise the space character that is being repeated isn't that well visible :)).

The problem with \s{2,} is that it will also match newlines on Windows files (where newlines are denoted by CRLF or \r\n which is matched by \s{2}.

If you also want to find multiple tabs and spaces, use [ \t]{2,}.

How to get data from Magento System Configuration

for example if you want to get EMAIL ADDRESS from config->store email addresses. You can specify from wich store you will want the address:

$store=Mage::app()->getStore()->getStoreId(); 
/* Sender Name */
Mage::getStoreConfig('trans_email/ident_general/name',$store); 
/* Sender Email */
Mage::getStoreConfig('trans_email/ident_general/email',$store);

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

"SSL certificate verify failed" using pip to install packages

pip install --trusted-host pypi.python.org autopep8 (any package name)

This command will add pypi.python.org to the trusted sources and will install all the required package.

I ran into the error myself and typing this command helped me install all the pip packages of python.

Excel VBA Macro: User Defined Type Not Defined

Your error is caused by these:

Dim oTable As Table, oRow As Row,

These types, Table and Row are not variable types native to Excel. You can resolve this in one of two ways:

  1. Include a reference to the Microsoft Word object model. Do this from Tools | References, then add reference to MS Word. While not strictly necessary, you may like to fully qualify the objects like Dim oTable as Word.Table, oRow as Word.Row. This is called early-binding. enter image description here
  2. Alternatively, to use late-binding method, you must declare the objects as generic Object type: Dim oTable as Object, oRow as Object. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.

I have not tested your code but I suspect ActiveDocument won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:

Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long

Set wdApp = GetObject(,"Word.Application")

Application.ScreenUpdating = False

For Each oTable In wdApp.ActiveDocument.Tables

How do I vertically align text in a paragraph?

Below styles will vertically center it for you.

p.event_desc {
 font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
 line-height: 14px;
 height: 35px;
 display: table-cell;
 vertical-align: middle;
 margin: 0px;
}

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

Below Kotlin code will help

Bottom to Top or Slide to Up

private fun slideUp() {
    isMapInfoShown = true
    views!!.layoutMapInfo.visible()
    val animate = TranslateAnimation(
        0f,  // fromXDelta
        0f,  // toXDelta
        views!!.layoutMapInfo.height.toFloat(),  // fromYDelta
        0f  // toYDelta
    )

    animate.duration = 500
    animate.fillAfter = true
    views!!.layoutMapInfo.startAnimation(animate)
}

Top to Bottom or Slide to Down

private fun slideDown() {
    if (isMapInfoShown) {
        isMapInfoShown = false
        val animate = TranslateAnimation(
            0f,  // fromXDelta
            0f,  // toXDelta
            0f,  // fromYDelta
            views!!.layoutMapInfo.height.toFloat()  // toYDelta
        )

        animate.duration = 500
        animate.fillAfter = true
        views!!.layoutMapInfo.startAnimation(animate)
        views!!.layoutMapInfo.gone()
    }
}

Kotlin Extensions for Visible and Gone

fun View.visible() {
    this.visibility = View.VISIBLE
}


fun View.gone() {
    this.visibility = View.GONE
}

android: how to change layout on button click?

I would add an android:onClick to the layout and then change the layout in the activity.

So in the layout

<ImageView
(Other things like source etc.)
android:onClick="changelayout"
/>

Then in the activity add the following:

public void changelayout(View view){
    setContentView(R.layout.second_layout);
}

How to customise file type to syntax associations in Sublime Text?

for ST3

$language = "language u wish"

if exists,

go to ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

else

create ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

and set

{ "extensions": [ "yourextension" ] }

This way allows you to enable syntax for composite extensions (e.g. sql.mustache, js.php, etc ... )

How to check if a given directory exists in Ruby

You can also use Dir::exist? like so:

Dir.exist?('Directory Name')

Returns true if the 'Directory Name' is a directory, false otherwise.1

CSS disable hover effect

To disable the hover effect, I've got two suggestions:

  • if your hover effect is triggered by JavaScript, just use $.unbind('hover');
  • if your hover style is triggered by class, then just use $.removeClass('hoverCssClass');

Using CSS !important to override CSS will make your CSS very unclean thus that method is not recommended. You can always duplicate a CSS style with different class name to keep the same styling.

Calling Non-Static Method In Static Method In Java

You could create an instance of the class you want to call the method on, e.g.

new Foo().nonStaticMethod();

How to remove new line characters from data rows in mysql?

your syntax is wrong:

update mytable SET title = TRIM(TRAILING '\n' FROM title)

Addition:

If the newline character is at the start of the field:

update mytable SET title = TRIM(LEADING '\n' FROM title)

Regex: Use start of line/end of line signs (^ or $) in different context

Just use look-arounds to solve this:

(?<=^|,)garp(?=$|,)

The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.

Bootstrap 3 - Responsive mp4-video

This worked for me:

<video src="file.mp4" controls style="max-width:100%; height:auto"></video>

How to get current local date and time in Kotlin

Try this:

val date = Calendar.getInstance().time
val formatter = SimpleDateFormat.getDateTimeInstance() //or use getDateInstance()
val formatedDate = formatter.format(date)

You can use your own pattern as well, e.g.

val sdf = SimpleDateFormat("yyyy.MM.dd")
// 2020.02.02

To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates. The first three options require API level 29.

How to retrieve images from MySQL database and display in an html tag

add $row = mysql_fetch_object($result); after your mysql_query();

your html <img src="<?php echo $row->dvdimage; ?>" width="175" height="200" />

How to SELECT the last 10 rows of an SQL table which has no ID field?

you can with code select 10 row from end of table. select * from (SELECT * FROM table1 order by id desc LIMIT 10) as table2 order by id"

Java get last element of a collection

Iterables.getLast from Google Guava. It has some optimization for Lists and SortedSets too.

Auto insert date and time in form input field?

See the example, http://jsbin.com/ahehe

Use the JavaScript date formatting utility described here.

<input id="date" name="date" />

<script>
   document.getElementById('date').value = (new Date()).format("m/dd/yy");
</script>

Objective-C : BOOL vs bool

As mentioned above, BOOL is a signed char. bool - type from C99 standard (int).

BOOL - YES/NO. bool - true/false.

See examples:

bool b1 = 2;
if (b1) printf("REAL b1 \n");
if (b1 != true) printf("NOT REAL b1 \n");

BOOL b2 = 2;
if (b2) printf("REAL b2 \n");
if (b2 != YES) printf("NOT REAL b2 \n");

And result is

REAL b1
REAL b2
NOT REAL b2

Note that bool != BOOL. Result below is only ONCE AGAIN - REAL b2

b2 = b1;
if (b2) printf("ONCE AGAIN - REAL b2 \n");
if (b2 != true) printf("ONCE AGAIN - NOT REAL b2 \n");

If you want to convert bool to BOOL you should use next code

BOOL b22 = b1 ? YES : NO; //and back - bool b11 = b2 ? true : false;

So, in our case:

BOOL b22 = b1 ? 2 : NO;
if (b22)    printf("ONCE AGAIN MORE - REAL b22 \n");
if (b22 != YES) printf("ONCE AGAIN MORE- NOT REAL b22 \n");

And so.. what we get now? :-)

What is the difference between java and core java?

Core Java is Sun Microsystem's, used to refer to Java SE. And there are Java ME and Java EE (J2EE). So this is told in order to differentiate with the Java ME and J2EE. So I feel Core Java is only used to mention J2SE.

Java having 3 category:

J2SE(Java to Standard Edition) - Core Java

J2EE(Java to Enterprises Edition)- Advance Java + Framework

J2ME(Java to Micro Edition)

Thank You..

Github permission denied: ssh add agent has no identities

For my mac Big Sur, with gist from answers above, following steps work for me.

$ ssh-keygen -q -t rsa -N 'password' -f ~/.ssh/id_rsa
$ ssh-add ~/.ssh/id_rsa

And added ssh public key to git hub by following instruction;

https://docs.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account

If all gone well, you should be able to get the following result;

$ ssh -T [email protected]
Hi user_name! You've successfully authenticated,...

What is the simplest method of inter-process communication between 2 C# processes?

There's also MSMQ (Microsoft Message Queueing) which can operate across networks as well as on a local computer. Although there are better ways to communicate it's worth looking into: https://msdn.microsoft.com/en-us/library/ms711472(v=vs.85).aspx

What is the precise meaning of "ours" and "theirs" in git?

I suspect you're confused here because it's fundamentally confusing. To make things worse, the whole ours/theirs stuff switches roles (becomes backwards) when you are doing a rebase.

Ultimately, during a git merge, the "ours" branch refers to the branch you're merging into:

git checkout merge-into-ours

and the "theirs" branch refers to the (single) branch you're merging:

git merge from-theirs

and here "ours" and "theirs" makes some sense, as even though "theirs" is probably yours anyway, "theirs" is not the one you were on when you ran git merge.

While using the actual branch name might be pretty cool, it falls apart in more complex cases. For instance, instead of the above, you might do:

git checkout ours
git merge 1234567

where you're merging by raw commit-ID. Worse, you can even do this:

git checkout 7777777    # detach HEAD
git merge 1234567       # do a test merge

in which case there are no branch names involved!

I think it's little help here, but in fact, in gitrevisions syntax, you can refer to an individual path in the index by number, during a conflicted merge

git show :1:README
git show :2:README
git show :3:README

Stage #1 is the common ancestor of the files, stage #2 is the target-branch version, and stage #3 is the version you are merging from.


The reason the "ours" and "theirs" notions get swapped around during rebase is that rebase works by doing a series of cherry-picks, into an anonymous branch (detached HEAD mode). The target branch is the anonymous branch, and the merge-from branch is your original (pre-rebase) branch: so "--ours" means the anonymous one rebase is building while "--theirs" means "our branch being rebased".


As for the gitattributes entry: it could have an effect: "ours" really means "use stage #2" internally. But as you note, it's not actually in place at the time, so it should not have an effect here ... well, not unless you copy it into the work tree before you start.

Also, by the way, this applies to all uses of ours and theirs, but some are on a whole file level (-s ours for a merge strategy; git checkout --ours during a merge conflict) and some are on a piece-by-piece basis (-X ours or -X theirs during a -s recursive merge). Which probably does not help with any of the confusion.

I've never come up with a better name for these, though. And: see VonC's answer to another question, where git mergetool introduces yet more names for these, calling them "local" and "remote"!

Get the item doubleclick event of listview

i see this subject is high on google, there is my simple and working sample :)

XAML:

    <ListView Name="MainTCList" HorizontalAlignment="Stretch" MinHeight="440" Height="Auto" Margin="10,10,5.115,4" VerticalAlignment="Stretch" MinWidth="500" Width="Auto" Grid.Column="0" MouseDoubleClick="MainTCList_MouseDoubleClick" IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="UserTID" DisplayMemberBinding="{Binding UserTID}" Width="80"/>
                <GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" Width="410" />
            </GridView>
        </ListView.View>
    </ListView>

C#

    private void MainTCList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
            TC item = (TC)MainTCList.Items.CurrentItem;
            Wyswietlacz.Content = item.UserTID;  
    }

Wyswietlacz is a test Label to see item content :) I add here in this last line a method to Load Page with data from item.

Get integer value of the current year in Java

I use special functions in my library to work with days/month/year ints -

int[] int_dmy( long timestamp ) // remember month is [0..11] !!!
{
  Calendar cal = new GregorianCalendar(); cal.setTimeInMillis( timestamp );
  return new int[] { 
    cal.get( Calendar.DATE ), cal.get( Calendar.MONTH ), cal.get( Calendar.YEAR )
  };
};


int[] int_dmy( Date d ) { 
 ...
}

Insert all data of a datagridview to database at once

You have a syntax error Please try the following syntax as given below:

string StrQuery="INSERT INTO tableName VALUES ('" + dataGridView1.Rows[i].Cells[0].Value + "',' " + dataGridView1.Rows[i].Cells[1].Value + "', '" + dataGridView1.Rows[i].Cells[2].Value + "', '" + dataGridView1.Rows[i].Cells[3].Value + "',' " + dataGridView1.Rows[i].Cells[4].Value + "')";

How to read/write files in .Net Core?

Package: System.IO.FileSystem

System.IO.File.ReadAllText("MyTextFile.txt"); ?

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Is Tomcat running?

Create a Shell script that checks if tomcat is up or down and set a cron for sh to make it check every few minutes, and auto start tomcat if down. Sample Snippet of code below

TOMCAT_PID=$(ps -ef | awk '/[t]omcat/{print $2}')
echo TOMCAT PROCESSID $TOMCAT_PID

if [ -z "$TOMCAT_PID" ]
then
    echo "TOMCAT NOT RUNNING"
    sudo /opt/tomcat/bin/startup.sh
else
   echo "TOMCAT RUNNING"
fi

How do I print a double value without scientific notation using Java?

The following code detects if the provided number is presented in scientific notation. If so it is represented in normal presentation with a maximum of '25' digits.

 static String convertFromScientificNotation(double number) {
    // Check if in scientific notation
    if (String.valueOf(number).toLowerCase().contains("e")) {
        System.out.println("The scientific notation number'"
                + number
                + "' detected, it will be converted to normal representation with 25 maximum fraction digits.");
        NumberFormat formatter = new DecimalFormat();
        formatter.setMaximumFractionDigits(25);
        return formatter.format(number);
    } else
        return String.valueOf(number);
}

JQuery, Spring MVC @RequestBody and JSON - making it work together

In addition to the answers here...

if you are using jquery on the client side, this worked for me:

Java:

@RequestMapping(value = "/ajax/search/sync") 
public String sync(@RequestBody Foo json) {

Jquery (you need to include Douglas Crockford's json2.js to have the JSON.stringify function):

$.ajax({
    type: "post",
    url: "sync", //your valid url
    contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
    data: JSON.stringify(jsonobject), //json object or array of json objects
    success: function(result) {
        //do nothing
    },
    error: function(){
        alert('failure');
    }
});

sendUserActionEvent() is null

Same issue on a Galaxy Tab and on a Xperia S, after uninstall and install again it seems that disappear.

The code that suddenly appear to raise this problem is this:

public void unlockMainActivity() {
    SharedPreferences prefs = getSharedPreferences("CALCULATOR_PREFS", 0);
    boolean hasCode = prefs.getBoolean("HAS_CODE", false);
    Context context = this.getApplicationContext();
    Intent intent = null;

    if (!hasCode) {
        intent = new Intent(context, WellcomeActivity.class);
    } else {
        intent = new Intent(context, CalculatingActivity.class);
    }
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    (context).startActivity(intent);
}

How to check if a variable exists in a FreeMarker template?

For versions previous to FreeMarker 2.3.7

You can not use ?? to handle missing values, the old syntax is:

<#if userName?exists>
   Hi ${userName}, How are you?
</#if>

jquery: get id from class selector

$(".class").click(function(){
    alert($(this).attr('id'));
});

only on jquery button click we can do this class should be written there

Storing SHA1 hash values in MySQL

So the length is between 10 16-bit chars, and 40 hex digits.

In any case decide the format you are going to store, and make the field a fixed size based on that format. That way you won't have any wasted space.

How to log in to phpMyAdmin with WAMP, what is the username and password?

Sometimes it doesn't get login with username = root and password, then you can change the default settings or the reset settings.

Open config.inc.php file in the phpmyadmin folder

Instead of

$cfg['Servers'][$i]['AllowNoPassword'] = false;

change it to:

$cfg['Servers'][$i]['AllowNoPassword'] = true;

Do not specify any password and put the user name as it was before, which means root.

E.g.

$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';

This worked for me after i had edited my config.inc.php file.

Bootstrap footer at the bottom of the page

You can just add style="min-height:100vh" to your page content conteiner and place footer in another conteiner

Passing an array as an argument to a function in C

Arrays in C are converted, in most of the cases, to a pointer to the first element of the array itself. And more in detail arrays passed into functions are always converted into pointers.

Here a quote from K&R2nd:

When an array name is passed to a function, what is passed is the location of the initial element. Within the called function, this argument is a local variable, and so an array name parameter is a pointer, that is, a variable containing an address.

Writing:

void arraytest(int a[])

has the same meaning as writing:

void arraytest(int *a)

So despite you are not writing it explicitly it is as you are passing a pointer and so you are modifying the values in the main.

For more I really suggest reading this.

Moreover, you can find other answers on SO here

Disabling vertical scrolling in UIScrollView

A lot of answers include setting the contentOffset to 0. I had a case in which I wanted the view inside the scrollView to be centered. This did the job for me:

public func scrollViewDidScroll(_ scrollView: UIScrollView) {
    scrollView.contentOffset.y = -scrollView.contentInset.top
}

PHP - Extracting a property from an array of objects

    $object = new stdClass();
    $object->id = 1;

    $object2 = new stdClass();
    $object2->id = 2;

    $objects = [
        $object,
        $object2
    ];

    $ids = array_map(function ($object) {
        /** @var YourEntity $object */
        return $object->id;
        // Or even if you have public methods
        // return $object->getId()
    }, $objects);

Output: [1, 2]

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Finally got this error to go away on a restore. I moved to SQL2012 out of frustration, but I guess this would probably still work on 2008R2. I had to use the logical names:

RESTORE FILELISTONLY
FROM DISK = ‘location of your.bak file’

And from there I ran a restore statement with MOVE using logical names.

RESTORE DATABASE database1
FROM DISK = '\\database path\database.bak'
WITH
MOVE 'File_Data' TO 'E:\location\database.mdf',
MOVE 'File_DOCS' TO 'E:\location\database_1.ndf',
MOVE 'file' TO 'E:\location\database_2.ndf',
MOVE 'file' TO 'E:\location\database_3.ndf',
MOVE 'file_Log' TO 'E:\location\database.ldf'

When it was done restoring, I almost wept with joy.

Good luck!

Using current time in UTC as default value in PostgreSQL

What about

now()::timestamp

If your other timestamp are without time zone then this cast will yield the matching type "timestamp without time zone" for the current time.

I would like to read what others think about that option, though. I still don't trust in my understanding of this "with/without" time zone stuff.

EDIT: Adding Michael Ekoka's comment here because it clarifies an important point:

Caveat. The question is about generating default timestamp in UTC for a timestamp column that happens to not store the time zone (perhaps because there's no need to store the time zone if you know that all your timestamps share the same). What your solution does is to generate a local timestamp (which for most people will not necessarily be set to UTC) and store it as a naive timestamp (one that does not specify its time zone).

What is simplest way to read a file into String?

Using Apache Commons IO.

import org.apache.commons.io.FileUtils;

//...

String contents = FileUtils.readFileToString(new File("/path/to/the/file"), "UTF-8")

You can see de javadoc for the method for details.

Accessing dict keys like an attribute?

What would be the caveats and pitfalls of accessing dict keys in this manner?

As @Henry suggests, one reason dotted-access may not be used in dicts is that it limits dict key names to python-valid variables, thereby restricting all possible names.

The following are examples on why dotted-access would not be helpful in general, given a dict, d:

Validity

The following attributes would be invalid in Python:

d.1_foo                           # enumerated names
d./bar                            # path names
d.21.7, d.12:30                   # decimals, time
d.""                              # empty strings
d.john doe, d.denny's             # spaces, misc punctuation 
d.3 * x                           # expressions  

Style

PEP8 conventions would impose a soft constraint on attribute naming:

A. Reserved keyword (or builtin function) names:

d.in
d.False, d.True
d.max, d.min
d.sum
d.id

If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore ...

B. The case rule on methods and variable names:

Variable names follow the same convention as function names.

d.Firstname
d.Country

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.


Sometimes these concerns are raised in libraries like pandas, which permits dotted-access of DataFrame columns by name. The default mechanism to resolve naming restrictions is also array-notation - a string within brackets.

If these constraints do not apply to your use case, there are several options on dotted-access data structures.

Why do people hate SQL cursors so much?

Outside of the performance (non)issues, I think the biggest failing of cursors is they are painful to debug. Especially compared to code in most client applications where debugging tends to be comparatively easy and language features tend to be much easier. In fact, I contend that nearly anything one is doing in SQL with a cursor should probably be happening in the client app in the first place.

Altering column size in SQL Server

For Oracle For Database:

ALTER TABLE table_name MODIFY column_name VARCHAR2(255 CHAR);

TypeScript and array reduce function

With TypeScript generics you can do something like this.

class Person {
    constructor (public Name : string, public Age: number) {}
}

var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

How to log out user from web site using BASIC authentication?

Here's a very simple Javascript example using jQuery:

function logout(to_url) {
    var out = window.location.href.replace(/:\/\//, '://log:out@');

    jQuery.get(out).error(function() {
        window.location = to_url;
    });
}

This log user out without showing him the browser log-in box again, then redirect him to a logged out page

Sass and combined child selector

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}

Angular @ViewChild() error: Expected 2 arguments, but got 1

Use this

@ViewChild(ChildDirective, {static: false}) Component

Vim: faster way to select blocks of text in visual mode

simple just press Shift v line number gg

example: your current line to line 41 Just press Shift v 41 gg

psql - save results of command to a file

I assume that there exist some internal psql command for this, but you could also run the script command from util-linux-ng package:

DESCRIPTION Script makes a typescript of everything printed on your terminal.

Python loop for inside lambda

To add on to chepner's answer for Python 3.0 you can alternatively do:

x = lambda x: list(map(print, x))

Of course this is only if you have the means of using Python > 3 in the future... Looks a bit cleaner in my opinion, but it also has a weird return value, but you're probably discarding it anyway.

I'll just leave this here for reference.

Get enum values as List of String in Java 8

You can do (pre-Java 8):

List<Enum> enumValues = Arrays.asList(Enum.values());

or

List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));

Using Java 8 features, you can map each constant to its name:

List<String> enumNames = Stream.of(Enum.values())
                               .map(Enum::name)
                               .collect(Collectors.toList());

Disallow Twitter Bootstrap modal window from closing

<button type="button" class="btn btn-info btn-md" id="myBtn3">Static 
Modal</button>

<!-- Modal -->
<div class="modal fade" id="myModal3" role="dialog">
<div class="modal-dialog">
  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">×</button>
      <h4 class="modal-title">Static Backdrop</h4>
    </div>
    <div class="modal-body">
      <p>You cannot click outside of this modal to close it.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-
      dismiss="modal">Close</button>
    </div>
   </div>
  </div>
</div>
   <script>
    $("#myBtn3").click(function(){
     $("#myModal3").modal({backdrop: "static"});
    });
   });
  </script>

Scroll Automatically to the Bottom of the Page

So many answers trying to calculate the height of the document. But it wasn't calculating correctly for me. However, both of these worked:

jquery

    $('html,body').animate({scrollTop: 9999});

or just js

    window.scrollTo(0,9999);

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

How to parse this string in Java?

...
String str = "bla!/bla/bla/"

String parts[] = str.split("/");

//To get fist "bla!"
String dir1 = parts[0];

bootstrap 3 tabs not working properly

When I moved the following lines from the head section to the end of the body section it worked.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

How to replace all occurrences of a character in string?

As Kirill suggested, either use the replace method or iterate along the string replacing each char independently.

Alternatively you can use the find method or find_first_of depending on what you need to do. None of these solutions will do the job in one go, but with a few extra lines of code you ought to make them work for you. :-)

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

"Integer number too large" error message for 600851475143

At compile time the number "600851475143" is represented in 32-bit integer, try long literal instead at the end of your number to get over from this problem.

Postgresql query between date ranges

Just in case somebody land here... since 8.1 you can simply use:

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'

From the docs:

BETWEEN SYMMETRIC is the same as BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right. If it is not, those two arguments are automatically swapped, so that a nonempty range is always implied.

Using wget to recursively fetch a directory with arbitrary files in it

Recursive wget ignoring robots (for websites)

wget -e robots=off -r -np --page-requisites --convert-links 'http://example.com/folder/'

-e robots=off causes it to ignore robots.txt for that domain

-r makes it recursive

-np = no parents, so it doesn't follow links up to the parent folder

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I was in the same boat. Installed Eclipse, realized need CDT.

sudo apt-get install eclipse eclipse-cdt g++

This just adds the CDT package on top of existing installation - no un-installation etc. required.

Create an ISO date object in javascript

try below:

var temp_datetime_obj = new Date();

collection.find({
    start_date:{
        $gte: new Date(temp_datetime_obj.toISOString())
    }
}).toArray(function(err, items) { 
    /* you can console.log here */ 
});

Sorting dropdown alphabetically in AngularJS

For anyone who wants to sort the variable in third layer:

<select ng-option="friend.pet.name for friend in friends"></select>

you can do it like this

<select ng-option="friend.pet.name for friend in friends | orderBy: 'pet.name'"></select>

The type is defined in an assembly that is not referenced, how to find the cause?

In my case, I was referencing a library that was being built to the wrong Platform/Configuration (I had just created the referenced library).

Furthermore, I was unable to fix the problem in Visual Studio Configuration Manager -- unable to switch and create new Platforms and Configurations for this library. I fixed it by correcting the entries in the ProjectConfigurationPlatforms section of the .sln file for that project. All its permutations were set to Debug|Any CPU (I'm not sure how I did that). I overwrote the entries for the broken project with the ones for a working project and changed the GUID for each entry.

Entries for functioning project

{9E93345C-7A51-4E9A-ACB0-DAAB8F1A1267}.Release|x64.ActiveCfg = Release|x64 {9E93345C-7A51-4E9A-ACB0-DAAB8F1A1267}.Release|x64.Build.0 = Release|x64

Entries for corrupted project

{94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.ActiveCfg = Debug|Any CPU {94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.Build.0 = Debug|Any CPU

Corrupted entries now fixed

{94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.ActiveCfg = Release|x64 {94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.Build.0 = Release|x64

I hope this helps someone.

How to draw a rounded Rectangle on HTML Canvas?

Here's one I wrote... uses arcs instead of quadratic curves for better control over radius. Also, it leaves the stroking and filling up to you

    /* Canvas 2d context - roundRect
 *
 * Accepts 5 parameters, the start_x and start_y points, the end_x and end_y points, and the radius of the corners
 * 
 * No return value
 */

CanvasRenderingContext2D.prototype.roundRect = function(sx,sy,ex,ey,r) {
    var r2d = Math.PI/180;
    if( ( ex - sx ) - ( 2 * r ) < 0 ) { r = ( ( ex - sx ) / 2 ); } //ensure that the radius isn't too large for x
    if( ( ey - sy ) - ( 2 * r ) < 0 ) { r = ( ( ey - sy ) / 2 ); } //ensure that the radius isn't too large for y
    this.beginPath();
    this.moveTo(sx+r,sy);
    this.lineTo(ex-r,sy);
    this.arc(ex-r,sy+r,r,r2d*270,r2d*360,false);
    this.lineTo(ex,ey-r);
    this.arc(ex-r,ey-r,r,r2d*0,r2d*90,false);
    this.lineTo(sx+r,ey);
    this.arc(sx+r,ey-r,r,r2d*90,r2d*180,false);
    this.lineTo(sx,sy+r);
    this.arc(sx+r,sy+r,r,r2d*180,r2d*270,false);
    this.closePath();
}

Here is an example:

var _e = document.getElementById('#my_canvas');
var _cxt = _e.getContext("2d");
_cxt.roundRect(35,10,260,120,20);
_cxt.strokeStyle = "#000";
_cxt.stroke();

Call Python function from MATLAB

Since MATLAB seamlessly integrates with Java, you can use Jython to write your script and call that from MATLAB (you may have to add a thin pure JKava wrapper to actually call the Jython code). I never tried it, but I can't see why it won't work.

How to select data where a field has a min value in MySQL?

This is how I would do it (assuming I understand the question)

SELECT * FROM pieces ORDER BY price ASC LIMIT 1

If you are trying to select multiple rows where each of them may have the same price (which is the minimum) then @JohnWoo's answer should suffice.

Basically here we are just ordering the results by the price in ASCending order (increasing) and taking the first row of the result.

Read a file line by line assigning the value to a variable

The following will just print out the content of the file:

cat $Path/FileName.txt

while read line;
do
echo $line     
done

R - " missing value where TRUE/FALSE needed "

check the command : NA!=NA : you'll get the result NA, hence the error message.

You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

comments = c("no","yes",NA)
for (l in 1:length(comments)) {
    if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"

jQuery multiple conditions within if statement

Try

if (!(i == 'InvKey' || i == 'PostDate')) {

or

if (i != 'InvKey' || i != 'PostDate') {

that says if i does not equals InvKey OR PostDate

Detecting attribute change of value of an attribute I made

There is this extensions that adds an event listener to attribute changes.

Usage:

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
  src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>

Bind attrchange handler function to selected elements

$(selector).attrchange({
    trackValues: true, /* Default to false, if set to true the event object is 
                updated with old and new value.*/
    callback: function (event) { 
        //event               - event object
        //event.attributeName - Name of the attribute modified
        //event.oldValue      - Previous value of the modified attribute
        //event.newValue      - New value of the modified attribute
        //Triggered when the selected elements attribute is added/updated/removed
    }        
});

AJAX jQuery refresh div every 5 seconds

Try to not use setInterval.
You can resend request to server after successful response with timeout.
jQuery:

sendRequest(); //call function

function sendRequest(){
    $.ajax({
        url: "test.php",
        success: 
        function(result){
            $('#links').text(result); //insert text of test.php into your div
            setTimeout(function(){
                sendRequest(); //this will send request again and again;
            }, 5000);
        }
    });
}

Android Error - Open Failed ENOENT

Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt"); to open a stream to this file.

How can I add an item to a SelectList in ASP.net MVC

Here html helper for you

public static SelectList IndividualNamesOrAll(this SelectList Object)
{
    MedicalVarianceViewsDataContext LinqCtx = new MedicalVarianceViewsDataContext();

    //not correct need individual view!
    var IndividualsListBoxRaw =  ( from x in LinqCtx.ViewIndividualsNames 
                                 orderby x.FullName
                                 select x);

    List<SelectListItem> items = new SelectList (
                               IndividualsListBoxRaw, 
                              "First_Hospital_Case_Nbr", 
                              "FullName"
                               ).ToList();

    items.Insert(0, (new SelectListItem { Text = "All Individuals", 
                                        Value = "0.0", 
                                        Selected = true }));

    Object = new SelectList (items,"Value","Text");

    return Object;
}

How to close IPython Notebook properly?

Option 1

Open a different console and run

jupyter notebook stop [PORT]

The default [PORT] is 8888, so, assuming that Jupyter Notebooks is running on port 8888, just run

jupyter notebook stop

If it is on port 9000, then

jupyter notebook stop 9000

Option 2 (Source)

  1. Check runtime folder location

    jupyter --paths
    
  2. Remove all files in the runtime folder

    rm -r [RUNTIME FOLDER PATH]/*
    
  3. Use top to find any Jupyter Notebook running processes left and if so kill their PID.

    top | grep jupyter &
    kill [PID]
    

One can boilt it down to

TARGET_PORT=8888
kill -9 $(lsof -n -i4TCP:$TARGET_PORT | cut -f 2 -d " ")

Note: If one wants to launch one's Notebook on a specific IP/Port

jupyter notebook --ip=[ADD_IP] --port=[ADD_PORT] --allow-root &

How to convert string to double with proper cultureinfo

You need to define a single locale that you will use for the data stored in the database, the invariant culture is there for exactly this purpose.

When you display convert to the native type and then format for the user's culture.

E.g. to display:

string fromDb = "123.56";
string display = double.Parse(fromDb, CultureInfo.InvariantCulture).ToString(userCulture);

to store:

string fromUser = "132,56";
double value;
// Probably want to use a more specific NumberStyles selection here.
if (!double.TryParse(fromUser, NumberStyles.Any, userCulture, out value)) {
  // Error...
}
string forDB = value.ToString(CultureInfo.InvariantCulture);

PS. It, almost, goes without saying that using a column with a datatype that matches the data would be even better (but sometimes legacy applies).

Java; String replace (using regular expressions)?

If this is for any general math expression and parenthetical expressions are allowed, it will be very difficult (perhaps impossible) to do this with regular expressions.

If the only replacements are the ones you showed, it's not that hard to do. First strip out *'s, then use capturing like Can Berk Güder showed to handle the ^'s.

Char to int conversion in C

Try this :

char c = '5' - '0';

How to install Cmake C compiler and CXX compiler

Even though I had gcc already installed, I had to run

sudo apt-get install build-essential

to get rid of that error

How to use onSaveInstanceState() and onRestoreInstanceState()?

This happens because you use the savedValue in the onCreate() method. The savedValue is updated in onRestoreInstanceState() method, but onRestoreInstanceState() is called after the onCreate() method. You can either:

  1. Update the savedValue in onCreate() method, or
  2. Move the code that use the new savedValue in onRestoreInstanceState() method.

But I suggest you to use the first approach, making the code like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int display_mode = getResources().getConfiguration().orientation;

    if (display_mode == 1) {

        setContentView(R.layout.main_grid);
        mGrid = (GridView) findViewById(R.id.gridview);
        mGrid.setColumnWidth(95);
        mGrid.setVisibility(0x00000000);
        // mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

    } else {
        setContentView(R.layout.main_grid_land);
        mGrid = (GridView) findViewById(R.id.gridview);
        mGrid.setColumnWidth(95);
        Log.d("Mode", "land");
        // mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

    }
    if (savedInstanceState != null) {
        savedUser = savedInstanceState.getString("TEXT");
    } else {
        savedUser = ""
    }
    Log.d("savedUser", savedUser);
    if (savedUser.equals("admin")) { //value 0
        adapter.setApps(appManager.getApplications());
    } else if (savedUser.equals("prof")) { //value 1
        adapter.setApps(appManager.getTeacherApplications());
    } else {// default value
        appManager = new ApplicationManager(this, getPackageManager());
        appManager.loadApplications(true);
        bindApplications();
    }
}

Convert array to string in NodeJS

You can also cast an array to a string like...

newStr = String(aa);

I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.

Actionbar notification count icon (badge) like Google has

I don't like ActionView based solutions, my idea is:

  1. create a layout with TextView, that TextView will be populated by application
  2. when you need to draw a MenuItem:

    2.1. inflate layout

    2.2. call measure() & layout() (otherwise view will be 0px x 0px, it's too small for most use cases)

    2.3. set the TextView's text

    2.4. make "screenshot" of the view

    2.6. set MenuItem's icon based on bitmap created on 2.4

  3. profit!

so, result should be something like enter image description here

  1. create layout here is a simple example
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/counterPanel"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:background="@drawable/ic_menu_gallery">
    <RelativeLayout
        android:id="@+id/counterValuePanel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/counterBackground"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/unread_background" />

        <TextView
            android:id="@+id/count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"
            android:textSize="8sp"
            android:layout_centerInParent="true"
            android:textColor="#FFFFFF" />
    </RelativeLayout>
</FrameLayout>

@drawable/unread_background is that green TextView's background, @drawable/ic_menu_gallery is not really required here, it's just to preview layout's result in IDE.

  1. add code into onCreateOptionsMenu/onPrepareOptionsMenu

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
    
        MenuItem menuItem = menu.findItem(R.id.testAction);
        menuItem.setIcon(buildCounterDrawable(count, R.drawable.ic_menu_gallery));
    
        return true;
    }
    
  2. Implement build-the-icon method:

    private Drawable buildCounterDrawable(int count, int backgroundImageId) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
        view.setBackgroundResource(backgroundImageId);
    
        if (count == 0) {
            View counterTextPanel = view.findViewById(R.id.counterValuePanel);
            counterTextPanel.setVisibility(View.GONE);
        } else {
            TextView textView = (TextView) view.findViewById(R.id.count);
            textView.setText("" + count);
        }
    
        view.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
    
        return new BitmapDrawable(getResources(), bitmap);
    }
    

The complete code is here: https://github.com/cvoronin/ActionBarMenuItemCounter

"Post Image data using POSTMAN"

Now you can hover the key input and select "file", which will give you a file selector in the value column:

enter image description here

Change font-weight of FontAwesome icons?

Webkit browsers support the ability to add "stroke" to fonts. This bit of style makes fonts look thinner (assuming a white background):

-webkit-text-stroke: 2px white;

Example on codepen here: http://codepen.io/mackdoyle/pen/yrgEH Some people are using SVG for a cross-platform "stroke" solution: http://codepen.io/CrocoDillon/pen/dGIsK

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Single statement across multiple lines in VB.NET without the underscore character

No, the underscore is the only continuation character. Personally I prefer the occasional use of a continuation character to being forced to use it always as in C#, but apart from the comments issue (which I'd agree is sometimes annoying), getting things to line up is not an issue.

With VS2008 at any rate, just select the second and following lines, hit the tab key several times, and it moves the whole lot across.

If it goes a tiny bit too far, you can delete the excess space a character at a time. It's a little fiddly, but it stays put once it's saved.

On the rare cases where this isn't good enough, I sometimes use the following technique to get it all to line up:

dim results as String = ""
results += "from a in articles "
results += "where a.articleID = 4 " 'and now you can add comments
results += "select a.articleName"

It's not perfect, and I know those that prefer C# will be tut-tutting, but there it is. It's a style choice, but I still prefer it to endless semi-colons.

Now I'm just waiting for someone to tell me I should have used a StringBuilder ;-)

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

If primary key is not already defined on parent table then this issue may arise. Please try to define the primary key on existing table. For eg:

ALTER TABLE table_name
ADD PRIMARY KEY (the_column_which_is_primary_key);

httpd-xampp.conf: How to allow access to an external IP besides localhost?

For Ubuntu xampp,
Go to /opt/lampp/etc/extra/
and open httpd-xampp.conf file and add below lines to get remote access,
    Order allow,deny
    Require all granted
    Allow from all

in /opt/lampp/phpmyadmin section.

And restart lampp using, /opt/lampp/lampp restart

Is there a Sleep/Pause/Wait function in JavaScript?

You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout to kick off a function after a delay:

setTimeout(function(){alert("hi")}, 1000);

Depending on your needs, setInterval might be useful, too.

NPM global install "cannot find module"

On windows if you just did a clean install and you get this you need blow away your npm cache in \AppData\Roaming

Remove multiple objects with rm()

Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.

here "n" could be the number of temp variables present

rm(list = c(paste("temp",c(1:n),sep="")))

Adding days to a date in Python

In order to have have a less verbose code, and avoid name conflicts between datetime and datetime.datetime, you should rename the classes with CamelCase names.

from datetime import datetime as DateTime, timedelta as TimeDelta

So you can do the following, which I think it is clearer.

date_1 = DateTime.today() 
end_date = date_1 + TimeDelta(days=10)

Also, there would be no name conflict if you want to import datetime later on.

How can I display a list view in an Android Alert Dialog?

You can use a custom dialog.

Custom dialog layout. list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ListView
        android:id="@+id/lv"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"/>
</LinearLayout>

In your activity

Dialog dialog = new Dialog(Activity.this);
       dialog.setContentView(R.layout.list)

ListView lv = (ListView ) dialog.findViewById(R.id.lv);
dialog.setCancelable(true);
dialog.setTitle("ListView");
dialog.show();

Edit:

Using alertdialog

String names[] ={"A","B","C","D"};
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom, null);
alertDialog.setView(convertView);
alertDialog.setTitle("List");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names);
lv.setAdapter(adapter);
alertDialog.show();

custom.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

</ListView>

Snap

enter image description here

Is there a difference between /\s/g and /\s+/g?

+ means "one or more characters" and without the plus it means "one character." In your case both result in the same output.

How do I iterate through lines in an external file with shell?

This might work for you:

cat <<\! >names.txt
> alison
> barb
> charlie
> david
> !
OIFS=$IFS; IFS=$'\n'; NAMES=($(<names.txt)); IFS=$OIFS
echo "${NAMES[@]}"
alison barb charlie david
echo "${NAMES[0]}"
alison
for NAME in "${NAMES[@]}";do echo $NAME;done
alison
barb
charlie
david

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

Regular expression to detect semi-colon terminated C++ for & while loops

As Frank suggested, this is best without regex. Here's (an ugly) one-liner:

match_string = orig_string[orig_string.index("("):len(orig_string)-orig_string[::-1].index(")")]

Matching the troll line est mentioned in his comment:

orig_string = "for (int i = 0; i < 10; doSomethingTo(\"(\"));"
match_string = orig_string[orig_string.index("("):len(orig_string)-orig_string[::-1].index(")")]

returns (int i = 0; i < 10; doSomethingTo("("))

This works by running through the string forward until it reaches the first open paren, and then backward until it reaches the first closing paren. It then uses these two indices to slice the string.

How to find out if a file exists in C# / .NET?

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

Convert iterator to pointer?

Your function shouldn't take vector<int>*; it should take vector<int>::iterator or vector<int>::const_iterator as appropriate. Then, just pass in foo.begin() + 1.

String concatenation: concat() vs "+" operator

No, not quite.

Firstly, there's a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts.

To look under the hood, write a simple class with a += b;

public class Concat {
    String cat(String a, String b) {
        a += b;
        return a;
    }
}

Now disassemble with javap -c (included in the Sun JDK). You should see a listing including:

java.lang.String cat(java.lang.String, java.lang.String);
  Code:
   0:   new     #2; //class java/lang/StringBuilder
   3:   dup
   4:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   7:   aload_1
   8:   invokevirtual   #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   11:  aload_2
   12:  invokevirtual   #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   15:  invokevirtual   #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/    String;
   18:  astore_1
   19:  aload_1
   20:  areturn

So, a += b is the equivalent of

a = new StringBuilder()
    .append(a)
    .append(b)
    .toString();

The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance.

The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast.

Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder, a list of HotSpot JVM intrinsics.

did you specify the right host or port? error on Kubernetes

I was getting an error when running

sudo kubectl get pods
The connection to the server localhost:8080 was refused - did you specify the right host or port?

Finally for my environment this command parameter works

sudo kubectl --kubeconfig /etc/kubernetes/admin.conf get pods

when executing kubectl as non root.

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

Color not work, if you use for bootstrap font png image, as i.

[class^="icon-"],
[class*=" icon-"] {
  display: inline-block;
  width: 14px;
  height: 14px;
  margin-top: 1px;
  *margin-right: .3em;
  line-height: 14px;
  vertical-align: text-top;
  background-image: url("../img/glyphicons-halflings.png");
  background-position: 14px 14px;
  background-repeat: no-repeat;
}

HTML5 use css filter to colorize image, example

filter: invert(100%)  contrast(2) brightness(50%) sepia(40%) saturate(450%) hue-rotate(-50deg);

How to empty a char array?

char members[255] = {0};

Get a specific bit from byte

This

public static bool GetBit(this byte b, int bitNumber) {
   return (b & (1 << bitNumber)) != 0;
}

should do it, I think.

How to group pandas DataFrame entries by date in a non-unique column

This might be easier to explain with a sample dataset.

Create Sample Data

Let's assume we have a single column of Timestamps, date and another column we would like to perform an aggregation on, a.

df = pd.DataFrame({'date':pd.DatetimeIndex(['2012-1-1', '2012-6-1', '2015-1-1', '2015-2-1', '2015-3-1']),
                   'a':[9,5,1,2,3]}, columns=['date', 'a'])

df

        date  a
0 2012-01-01  9
1 2012-06-01  5
2 2015-01-01  1
3 2015-02-01  2
4 2015-03-01  3

There are several ways to group by year

  • Use the dt accessor with year property
  • Put date in index and use anonymous function to access year
  • Use resample method
  • Convert to pandas Period

.dt accessor with year property

When you have a column (and not an index) of pandas Timestamps, you can access many more extra properties and methods with the dt accessor. For instance:

df['date'].dt.year

0    2012
1    2012
2    2015
3    2015
4    2015
Name: date, dtype: int64

We can use this to form our groups and calculate some aggregations on a particular column:

df.groupby(df['date'].dt.year)['a'].agg(['sum', 'mean', 'max'])

      sum  mean  max
date                
2012   14     7    9
2015    6     2    3

put date in index and use anonymous function to access year

If you set the date column as the index, it becomes a DateTimeIndex with the same properties and methods as the dt accessor gives normal columns

df1 = df.set_index('date')
df1.index.year

Int64Index([2012, 2012, 2015, 2015, 2015], dtype='int64', name='date')

Interestingly, when using the groupby method, you can pass it a function. This function will be implicitly passed the DataFrame's index. So, we can get the same result from above with the following:

df1.groupby(lambda x: x.year)['a'].agg(['sum', 'mean', 'max'])

      sum  mean  max
2012   14     7    9
2015    6     2    3

Use the resample method

If your date column is not in the index, you must specify the column with the on parameter. You also need to specify the offset alias as a string.

df.resample('AS', on='date')['a'].agg(['sum', 'mean', 'max'])

             sum  mean  max
date                       
2012-01-01  14.0   7.0  9.0
2013-01-01   NaN   NaN  NaN
2014-01-01   NaN   NaN  NaN
2015-01-01   6.0   2.0  3.0

Convert to pandas Period

You can also convert the date column to a pandas Period object. We must pass in the offset alias as a string to determine the length of the Period.

df['date'].dt.to_period('A')

0   2012
1   2012
2   2015
3   2015
4   2015
Name: date, dtype: object

We can then use this as a group

df.groupby(df['date'].dt.to_period('Y'))['a'].agg(['sum', 'mean', 'max'])


      sum  mean  max
2012   14     7    9
2015    6     2    3

How can I parse a string with a comma thousand separator to a number?

Usually you should consider to use input fields which don't allow free text input for numeric values. But there might be cases, when you need to guess the input format. For example 1.234,56 in Germany means 1,234.56 in US. See https://salesforce.stackexchange.com/a/21404 for a list of countries which use comma as decimal.

I use the following function to do a best guess and strip off all non-numeric characters:

function parseNumber(strg) {
    var strg = strg || "";
    var decimal = '.';
    strg = strg.replace(/[^0-9$.,]/g, '');
    if(strg.indexOf(',') > strg.indexOf('.')) decimal = ',';
    if((strg.match(new RegExp("\\" + decimal,"g")) || []).length > 1) decimal="";
    if (decimal != "" && (strg.length - strg.indexOf(decimal) - 1 == 3) && strg.indexOf("0" + decimal)!==0) decimal = "";
    strg = strg.replace(new RegExp("[^0-9$" + decimal + "]","g"), "");
    strg = strg.replace(',', '.');
    return parseFloat(strg);
}   

Try it here: https://plnkr.co/edit/9p5Y6H?p=preview

Examples:

1.234,56 € => 1234.56
1,234.56USD => 1234.56
1,234,567€ => 1234567
1.234.567 => 1234567
1,234.567 => 1234.567
1.234 => 1234 // might be wrong - best guess
1,234 => 1234 // might be wrong - best guess
1.2345 => 1.2345
0,123 => 0.123

The function has one weak point: It is not possible to guess the format if you have 1,123 or 1.123 - because depending on the locale format both might be a comma or a thousands-separator. In this special case the function will treat separator as a thousands-separator and return 1123.

Creating instance list of different objects

If you can't be more specific than Object with your instances, then use:

List<Object> employees = new ArrayList<Object>();

Otherwise be as specific as you can:

List<? extends SpecificType> employees = new ArrayList<? extends SpecificType>();

best OCR (Optical character recognition) example in android

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

Let me explain using step-by-step guidance.

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

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

enter image description here

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

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

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

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

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

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

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

enter image description here

done it

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

enter image description here

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

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

enter image description here

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

How to shrink temp tablespace in oracle?

It will be increasing because you have a need for temporary storage space, possibly due to a cartesian product or a large sort operation.

The dynamic performance view V$TEMPSEG_USAGE will help diagnose the cause.

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

You need to check the browser compatibility before opting to test with Selenium:

https://github.com/SeleniumHQ/selenium/blob/master/java/CHANGELOG

This might help to answer the above question.

how to create a list of lists

Use append method, eg:

lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)

How to specify new GCC path for CMake

Do not overwrite CMAKE_C_COMPILER, but export CC (and CXX) before calling cmake:

export CC=/usr/local/bin/gcc
export CXX=/usr/local/bin/g++
cmake /path/to/your/project
make

The export only needs to be done once, the first time you configure the project, then those values will be read from the CMake cache.


UPDATE: longer explanation on why not overriding CMAKE_C(XX)_COMPILER after Jake's comment

I recommend against overriding the CMAKE_C(XX)_COMPILER value for two main reasons: because it won't play well with CMake's cache and because it breaks compiler checks and tooling detection.

When using the set command, you have three options:

  • without cache, to create a normal variable
  • with cache, to create a cached variable
  • force cache, to always force the cache value when configuring

Let's see what happens for the three possible calls to set:

Without cache

set(CMAKE_C_COMPILER /usr/bin/clang)
set(CMAKE_CXX_COMPILER /usr/bin/clang++)

When doing this, you create a "normal" variable CMAKE_C(XX)_COMPILER that hides the cache variable of the same name. That means your compiler is now hard-coded in your build script and you cannot give it a custom value. This will be a problem if you have multiple build environments with different compilers. You could just update your script each time you want to use a different compiler, but that removes the value of using CMake in the first place.

Ok, then, let's update the cache...

With cache

set(CMAKE_C_COMPILER /usr/bin/clang CACHE PATH "")
set(CMAKE_CXX_COMPILER /usr/bin/clang++ CACHE PATH "")

This version will just "not work". The CMAKE_C(XX)_COMPILER variable is already in the cache, so it won't get updated unless you force it.

Ah... let's use the force, then...

Force cache

set(CMAKE_C_COMPILER /usr/bin/clang CACHE PATH "" FORCE)
set(CMAKE_CXX_COMPILER /usr/bin/clang++ CACHE PATH "" FORCE)

This is almost the same as the "normal" variable version, the only difference is your value will be set in the cache, so users can see it. But any change will be overwritten by the set command.

Breaking compiler checks and tooling

Early in the configuration process, CMake performs checks on the compiler: Does it work? Is it able to produce executables? etc. It also uses the compiler to detect related tools, like ar and ranlib. When you override the compiler value in a script, it's "too late", all checks and detections are already done.

For instance, on my machine with gcc as default compiler, when using the set command to /usr/bin/clang, ar is set to /usr/bin/gcc-ar-7. When using an export before running CMake it is set to /usr/lib/llvm-3.8/bin/llvm-ar.

Copy the entire contents of a directory in C#

My solution is basically a modification of @Termininja's answer, however I have enhanced it a bit and it appears to be more than 5 times faster than the accepted answer.

public static void CopyEntireDirectory(string path, string newPath)
{
    Parallel.ForEach(Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories)
    ,(fileName) =>
    {
        string output = Regex.Replace(fileName, "^" + Regex.Escape(path), newPath);
        if (File.Exists(fileName))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(output));
            File.Copy(fileName, output, true);
        }
        else
            Directory.CreateDirectory(output);
    });
}

EDIT: Modifying @Ahmed Sabry to full parallel foreach does produce a better result, however the code uses recursive function and its not ideal in some situation.

public static void CopyEntireDirectory(DirectoryInfo source, DirectoryInfo target, bool overwiteFiles = true)
{
    if (!source.Exists) return;
    if (!target.Exists) target.Create();

    Parallel.ForEach(source.GetDirectories(), (sourceChildDirectory) =>
        CopyEntireDirectory(sourceChildDirectory, new DirectoryInfo(Path.Combine(target.FullName, sourceChildDirectory.Name))));

    Parallel.ForEach(source.GetFiles(), sourceFile =>
        sourceFile.CopyTo(Path.Combine(target.FullName, sourceFile.Name), overwiteFiles));
}

how to delete default values in text field using selenium?

This worked for me:

driver.findElement(yourElement).clear();
driver.findElement(yourelement).sendKeys("");

C# how to convert File.ReadLines into string array?

File.ReadLines() returns an object of type System.Collections.Generic.IEnumerable<String>
File.ReadAllLines() returns an array of strings.

If you want to use an array of strings you need to call the correct function.

You could use Jim solution, just use ReadAllLines() or you could change your return type.

This would also work:

System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");

You can use any generic collection which implements IEnumerable. IList for an example.

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

Can't install laravel installer via composer

On centos 7 I have used:

yum install php-pecl-zip

because any other solution didn't work for me.

Can I target all <H> tags with a single selector?

You could .class all the headings in Your document if You would like to target them with a single selector, as follows,

<h1 class="heading">...heading text...</h1>
<h2 class="heading">...heading text...</h2>

and in the css

.heading{
    color: #Dad;
    background-color: #DadDad;
}

I am not saying this is always best practice, but it can be useful, and for targeting syntax, easier in many ways,

so if You give all h1 through h6 the same .heading class in the html, then You can modify them for any html docs that utilize that css sheet.

upside, more global control versus "section div article h1, etc{}",

downside, instead of calling all the selectors in on place in the css, You will have much more typing in the html, yet I find that having a class in the html to target all headings can be beneficial, just be careful of precedence in the css, because conflicts could arise from

Splitting a string into chunks of a certain size

Using the Buffer extensions from the IX library

    static IEnumerable<string> Split( this string str, int chunkSize )
    {
        return str.Buffer(chunkSize).Select(l => String.Concat(l));
    }

How do I create a view controller file after creating a new view controller?

Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.

Having added a new view controller scene to your storyboard, you then have to:

  1. Create a UIViewController subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":

    Cocoa Touch Class

    And then select a unique name for the new view controller subclass:

    UIViewController subclass

  2. Specify this new subclass as the base class for the scene you just added to the storyboard.

    enter image description here

  3. Now hook up any IBOutlet and IBAction references for this new scene with the new view controller subclass.

slf4j: how to log formatted message, object array, exception

In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using

<encoder>
    <pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern> 
</encoder>

the %ex in pattern is what makes the difference

Merging cells in Excel using Apache POI

You can use :

sheet.addMergedRegion(new CellRangeAddress(startRowIndx, endRowIndx, startColIndx,endColIndx));

Make sure the CellRangeAddress does not coincide with other merged regions as that will throw an exception.

  • If you want to merge cells one above another, keep column indexes same
  • If you want to merge cells which are in a single row, keep the row indexes same
  • Indexes are zero based

For what you were trying to do this should work:

sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 0, 3));

Using onBackPressed() in Android Fragments

This works for me :D

    @Override
    public void onResume() {
    super.onResume();

    if(getView() == null){
        return;
    }

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                // handle back button's click listener
                return true;
            }
            return false;
        }
    });}

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

How to see the CREATE VIEW code for a view in PostgreSQL?

Kept having to return here to look up pg_get_viewdef (how to remember that!!), so searched for a more memorable command... and got it:

\d+ viewname

You can see similar sorts of commands by typing \? at the pgsql command line.

Bonus tip: The emacs command sql-postgres makes pgsql a lot more pleasant (edit, copy, paste, command history).

Why does IE9 switch to compatibility mode on my website?

To force IE to render in IE9 standards mode you should use

<meta http-equiv="X-UA-Compatible" content="IE=edge">

Some conditions may cause IE9 to jump down into the compatibility modes. By default this can occur on intranet sites.

Python - Extracting and Saving Video Frames

Following script will extract frames every half a second of all videos in folder. (Works on python 3.7)

import cv2
import os
listing = os.listdir(r'D:/Images/AllVideos')
count=1
for vid in listing:
    vid = r"D:/Images/AllVideos/"+vid
    vidcap = cv2.VideoCapture(vid)
    def getFrame(sec):
        vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
        hasFrames,image = vidcap.read()
        if hasFrames:
            cv2.imwrite("D:/Images/Frames/image"+str(count)+".jpg", image) # Save frame as JPG file
        return hasFrames
    sec = 0
    frameRate = 0.5 # Change this number to 1 for each 1 second
    
    success = getFrame(sec)
    while success:
        count = count + 1
        sec = sec + frameRate
        sec = round(sec, 2)
        success = getFrame(sec)

How do I tell what type of value is in a Perl variable?

At some point I read a reasonably convincing argument on Perlmonks that testing the type of a scalar with ref or reftype is a bad idea. I don't recall who put the idea forward, or the link. Sorry.

The point was that in Perl there are many mechanisms that make it possible to make a given scalar act like just about anything you want. If you tie a filehandle so that it acts like a hash, the testing with reftype will tell you that you have a filehanle. It won't tell you that you need to use it like a hash.

So, the argument went, it is better to use duck typing to find out what a variable is.

Instead of:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;
    if( $type eq 'HASH' ) {
        $result = $var->{foo};
    }
    elsif( $type eq 'ARRAY' ) {
        $result = $var->[3];
    }
    else {
        $result = 'foo';
    }

    return $result;
}

You should do something like this:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;

    eval {
        $result = $var->{foo};
        1; # guarantee a true result if code works.
    }
    or eval { 
        $result = $var->[3];
        1;
    }
    or do {
        $result = 'foo';
    }

    return $result;
}

For the most part I don't actually do this, but in some cases I have. I'm still making my mind up as to when this approach is appropriate. I thought I'd throw the concept out for further discussion. I'd love to see comments.

Update

I realized I should put forward my thoughts on this approach.

This method has the advantage of handling anything you throw at it.

It has the disadvantage of being cumbersome, and somewhat strange. Stumbling upon this in some code would make me issue a big fat 'WTF'.

I like the idea of testing whether a scalar acts like a hash-ref, rather that whether it is a hash ref.

I don't like this implementation.

JPA eager fetch does not join

The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.

If you set fetchType=EAGER This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.

If you set fetchType=LAZY the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.

You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.

For the second part of the question - how to get hibernate to generate optimised SQL?

Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.

VBA check if file exists

A way that is clean and short:

Public Function IsFile(s)
    IsFile = CreateObject("Scripting.FileSystemObject").FileExists(s)
End Function

Determine function name from within that function (without using traceback)

functionNameAsString = sys._getframe().f_code.co_name

I wanted a very similar thing because I wanted to put the function name in a log string that went in a number of places in my code. Probably not the best way to do that, but here's a way to get the name of the current function.

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

How do I disable orientation change on Android?

Add

android:configChanges="keyboardHidden|orientation|screenSize" 

to your manifest.

How can I define fieldset border color?

If you don't want 3D border use:

border:#f00 1px solid;

Deciding between HttpClient and WebClient

HttpClientFactory

It's important to evaluate the different ways you can create an HttpClient, and part of that is understanding HttpClientFactory.

https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

This is not a direct answer I know - but you're better off starting here than ending up with new HttpClient(...) everywhere.

How to use HttpWebRequest (.NET) asynchronously?

.NET has changed since many of these answers were posted, and I'd like to provide a more up-to-date answer. Use an async method to start a Task that will run on a background thread:

private async Task<String> MakeRequestAsync(String url)
{    
    String responseText = await Task.Run(() =>
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            WebResponse response = request.GetResponse();            
            Stream responseStream = response.GetResponseStream();
            return new StreamReader(responseStream).ReadToEnd();            
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
        return null;
    });

    return responseText;
}

To use the async method:

String response = await MakeRequestAsync("http://example.com/");

Update:

This solution does not work for UWP apps which use WebRequest.GetResponseAsync() instead of WebRequest.GetResponse(), and it does not call the Dispose() methods where appropriate. @dragansr has a good alternative solution that addresses these issues.

Why both no-cache and no-store should be used in HTTP response?

For chrome, no-cache is used to reload the page on a re-visit, but it still caches it if you go back in history (back button). To reload the page for history-back as well, use no-store. IE needs must-revalidate to work in all occasions.

So just to be sure to avoid all bugs and misinterpretations I always use

Cache-Control: no-store, no-cache, must-revalidate

if I want to make sure it reloads.

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

How do I make a splash screen?

Above all answers are really very good. But there are encounter problem of memory leakage. This issue is often known in the Android community as "Leaking an Activity". Now what exactly does that mean?

When configuration change occurs, such as orientation change, Android destroys the Activity and recreates it. Normally, the Garbage Collector will just clear the allocated memory of the old Activity instance and we're all good.

"Leaking an Activity" refers to the situation where the Garbage Collector cannot clear the allocated memory of the old Activity instance since it's being (strong) referenced from an object that out lived the Activity instance. Every Android app has a specific amount of memory allocated for it. When Garbage Collector cannot free up unused memory, the app's performance will decrease gradually and eventually crash with OutOfMemory error.

How to determine whether the app leaks memory or not? The fastest way is to open the Memory tab in Android Studio and pay attention to allocated memory as you change the orientation. If the allocated memory keeps on increasing and never decreases then you have a memory leak.

1.Memory leak when user change the orientation. enter image description here

First you need to define the splash screen in your layout resource splashscreen.xml file

Sample Code for splash screen activity.

public class Splash extends Activity {
 // 1. Create a static nested class that extends Runnable to start the main Activity
    private static class StartMainActivityRunnable implements Runnable {
        // 2. Make sure we keep the source Activity as a WeakReference (more on that later)
        private WeakReference mActivity;

        private StartMainActivityRunnable(Activity activity) {
         mActivity = new WeakReference(activity);
        }

        @Override
        public void run() {
         // 3. Check that the reference is valid and execute the code
            if (mActivity.get() != null) {
             Activity activity = mActivity.get();
             Intent mainIntent = new Intent(activity, MainActivity.class);
             activity.startActivity(mainIntent);
             activity.finish();
            }
        }
    }

    /** Duration of wait **/
    private final int SPLASH_DISPLAY_LENGTH = 1000;

    // 4. Declare the Handler as a member variable
    private Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(icicle);
        setContentView(R.layout.splashscreen);

        // 5. Pass a new instance of StartMainActivityRunnable with reference to 'this'.
        mHandler.postDelayed(new StartMainActivityRunnable(this), SPLASH_DISPLAY_LENGTH);
    }

    // 6. Override onDestroy()
    @Override
    public void onDestroy() {
     // 7. Remove any delayed Runnable(s) and prevent them from executing.
     mHandler.removeCallbacksAndMessages(null);

     // 8. Eagerly clear mHandler allocated memory
     mHandler = null;
    }
}

For more information please go through this link

Meaning of end='' in the statement print("\t",end='')?

See the documentation for the print function: print()

The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

MySQL case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

How to run wget inside Ubuntu Docker image?

You need to install it first. Create a new Dockerfile, and install wget in it:

FROM ubuntu:14.04
RUN  apt-get update \
  && apt-get install -y wget \
  && rm -rf /var/lib/apt/lists/*

Then, build that image:

docker build -t my-ubuntu .

Finally, run it:

docker run my-ubuntu wget https://downloads-packages.s3.amazonaws.com/ubuntu-14.04/gitlab_7.8.2-omnibus.1-1_amd64.deb

Why does my favicon not show up?

  1. Is it really a .ico, or is it just named ".ico"?
  2. What browser are you testing in?

The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.

If you must have it in a subdirectory, use:

<link rel="shortcut icon" href="/img/favicon.ico" />

Note the / before img to ensure it is anchored to the root folder.

PHP send mail to multiple email addresses

Just separate them by comma, like $email_to = "[email protected], [email protected], John Doe <[email protected]>".

Create a batch file to run an .exe with an additional parameter

in batch file abc.bat

cd c:\user\ben_dchost\documents\
executible.exe -flag1 -flag2 -flag3 

I am assuming that your executible.exe is present in c:\user\ben_dchost\documents\ I am also assuming that the parameters it takes are -flag1 -flag2 -flag3

Edited:

For the command you say you want to execute, do:

cd C:\Users\Ben\Desktop\BGInfo\
bginfo.exe dc_bginfo.bgi
pause

Hope this helps

scrollable div inside container

The simplest way is as this example:

<div>
   <div style=' height:300px;'>
     SOME LOGO OR CONTENT HERE
   </div>
   <div style='overflow-x: hidden;overflow-y: scroll;'> 
      THIS IS SOME TEXT
   </DIV>

You can see the test cases on: https://www.w3schools.com/css/css_overflow.asp

Pretty-print an entire Pandas Series / DataFrame

Try using display() function. This would automatically use Horizontal and vertical scroll bars and with this you can display different datasets easily instead of using print().

display(dataframe)

display() supports proper alignment also.

However if you want to make the dataset more beautiful you can check pd.option_context(). It has lot of options to clearly show the dataframe.

Note - I am using Jupyter Notebooks.

Communication between multiple docker-compose projects

version: '2'
services:
  bot:
    build: .
    volumes:
      - '.:/home/node'
      - /home/node/node_modules
    networks:
      - my-rede
    mem_limit: 100m
    memswap_limit: 100m
    cpu_quota: 25000
    container_name: 236948199393329152_585042339404185600_bot
    command: node index.js
    environment:
      NODE_ENV: production
networks:
  my-rede:
    external:
      name: name_rede_externa

Pause in Python

import pdb
pdb.debug()

This is used to debug the script. Should be useful to break also.

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

How can I create an MSI setup?

You can purchase InstallShield, the market leader for creating installation packages. It offers many features beyond what you get with freeware solutions.

Warning: InstallShield is insanely expensive!

Finding whether a point lies inside a rectangle or not

bool pointInRectangle(Point A, Point B, Point C, Point D, Point m ) {
    Point AB = vect2d(A, B);  float C1 = -1 * (AB.y*A.x + AB.x*A.y); float  D1 = (AB.y*m.x + AB.x*m.y) + C1;
    Point AD = vect2d(A, D);  float C2 = -1 * (AD.y*A.x + AD.x*A.y); float D2 = (AD.y*m.x + AD.x*m.y) + C2;
    Point BC = vect2d(B, C);  float C3 = -1 * (BC.y*B.x + BC.x*B.y); float D3 = (BC.y*m.x + BC.x*m.y) + C3;
    Point CD = vect2d(C, D);  float C4 = -1 * (CD.y*C.x + CD.x*C.y); float D4 = (CD.y*m.x + CD.x*m.y) + C4;
    return     0 >= D1 && 0 >= D4 && 0 <= D2 && 0 >= D3;}





Point vect2d(Point p1, Point p2) {
    Point temp;
    temp.x = (p2.x - p1.x);
    temp.y = -1 * (p2.y - p1.y);
    return temp;}

Points inside polygon

I just implemented AnT's Answer using c++. I used this code to check whether the pixel's coordination(X,Y) lies inside the shape or not.

Using pickle.dump - TypeError: must be str, not bytes

Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Rather than using JavaScript perhaps try something like

<a href="#">

  <input type="submit" value="save" style="background: transparent none; border: 0px none; text-decoration: inherit; color: inherit; cursor: inherit" />

</a>

Get decimal portion of a number with JavaScript

Language independent way:

var a = 3.2;
var fract = a * 10 % 10 /10; //0.2
var integr = a - fract; //3

note that it correct only for numbers with one fractioanal lenght )

I can't delete a remote master branch on git

To answer the question literally (since GitHub is not in the question title), also be aware of this post over on superuser. EDIT: Answer copied here in relevant part, slightly modified for clarity in square brackets:

You're getting rejected because you're trying to delete the branch that your origin has currently "checked out".

If you have direct access to the repo, you can just open up a shell [in the bare repo] directory and use good old git branch to see what branch origin is currently on. To change it to another branch, you have to use git symbolic-ref HEAD refs/heads/another-branch.

Delete element in a slice

Rather than thinking of the indices in the [a:]-, [:b]- and [a:b]-notations as element indices, think of them as the indices of the gaps around and between the elements, starting with gap indexed 0 before the element indexed as 0.

enter image description here

Looking at just the blue numbers, it's much easier to see what is going on: [0:3] encloses everything, [3:3] is empty and [1:2] would yield {"B"}. Then [a:] is just the short version of [a:len(arrayOrSlice)], [:b] the short version of [0:b] and [:] the short version of [0:len(arrayOrSlice)]. The latter is commonly used to turn an array into a slice when needed.

What is the Java equivalent of PHP var_dump?

In my experience, var_dump is typically used for debugging PHP in place of a step-though debugger. In Java, you can of course use your IDE's debugger to see a visual representation of an object's contents.

Switch statement fallthrough in C#?

They changed the switch statement (from C/Java/C++) behavior for c#. I guess the reasoning was that people forgot about the fall through and errors were caused. One book I read said to use goto to simulate, but this doesn't sound like a good solution to me.

Git merge with force overwrite

Not really related to this answer, but I'd ditch git pull, which just runs git fetch followed by git merge. You are doing three merges, which is going to make your Git run three fetch operations, when one fetch is all you will need. Hence:

git fetch origin   # update all our origin/* remote-tracking branches

git checkout demo         # if needed -- your example assumes you're on it
git merge origin/demo     # if needed -- see below

git checkout master
git merge origin/master

git merge -X theirs demo   # but see below

git push origin master     # again, see below

Controlling the trickiest merge

The most interesting part here is git merge -X theirs. As root545 noted, the -X options are passed on to the merge strategy, and both the default recursive strategy and the alternative resolve strategy take -X ours or -X theirs (one or the other, but not both). To understand what they do, though, you need to know how Git finds, and treats, merge conflicts.

A merge conflict can occur within some file1 when the base version differs from both the current (also called local, HEAD, or --ours) version and the other (also called remote or --theirs) version of that same file. That is, the merge has identified three revisions (three commits): base, ours, and theirs. The "base" version is from the merge base between our commit and their commit, as found in the commit graph (for much more on this, see other StackOverflow postings). Git has then found two sets of changes: "what we did" and "what they did". These changes are (in general) found on a line-by-line, purely textual basis. Git has no real understanding of file contents; it is merely comparing each line of text.

These changes are what you see in git diff output, and as always, they have context as well. It's possible that things we changed are on different lines from things they changed, so that the changes seem like they would not collide, but the context has also changed (e.g., due to our change being close to the top or bottom of the file, so that the file runs out in our version, but in theirs, they have also added more text at the top or bottom).

If the changes happen on different lines—for instance, we change color to colour on line 17 and they change fred to barney on line 71—then there is no conflict: Git simply takes both changes. If the changes happen on the same lines, but are identical changes, Git takes one copy of the change. Only if the changes are on the same lines, but are different changes, or that special case of interfering context, do you get a modify/modify conflict.

The -X ours and -X theirs options tell Git how to resolve this conflict, by picking just one of the two changes: ours, or theirs. Since you said you are merging demo (theirs) into master (ours) and want the changes from demo, you would want -X theirs.

Blindly applying -X, however, is dangerous. Just because our changes did not conflict on a line-by-line basis does not mean our changes do not actually conflict! One classic example occurs in languages with variable declarations. The base version might declare an unused variable:

int i;

In our version, we delete the unused variable to make a compiler warning go away—and in their version, they add a loop some lines later, using i as the loop counter. If we combine the two changes, the resulting code no longer compiles. The -X option is no help here since the changes are on different lines.

If you have an automated test suite, the most important thing to do is to run the tests after merging. You can do this after committing, and fix things up later if needed; or you can do it before committing, by adding --no-commit to the git merge command. We'll leave the details for all of this to other postings.


1You can also get conflicts with respect to "file-wide" operations, e.g., perhaps we fix the spelling of a word in a file (so that we have a change), and they delete the entire file (so that they have a delete). Git will not resolve these conflicts on its own, regardless of -X arguments.


Doing fewer merges and/or smarter merges and/or using rebase

There are three merges in both of our command sequences. The first is to bring origin/demo into the local demo (yours uses git pull which, if your Git is very old, will fail to update origin/demo but will produce the same end result). The second is to bring origin/master into master.

It's not clear to me who is updating demo and/or master. If you write your own code on your own demo branch, and others are writing code and pushing it to the demo branch on origin, then this first-step merge can have conflicts, or produce a real merge. More often than not, it's better to use rebase, rather than merge, to combine work (admittedly, this is a matter of taste and opinion). If so, you might want to use git rebase instead. On the other hand, if you never do any of your own commits on demo, you don't even need a demo branch. Alternatively, if you want to automate a lot of this, but be able to check carefully when there are commits that both you and others, made, you might want to use git merge --ff-only origin/demo: this will fast-forward your demo to match the updated origin/demo if possible, and simply outright fail if not (at which point you can inspect the two sets of changes, and choose a real merge or a rebase as appropriate).

This same logic applies to master, although you are doing the merge on master, so you definitely do need a master. It is, however, even likelier that you would want the merge to fail if it cannot be done as a fast-forward non-merge, so this probably also should be git merge --ff-only origin/master.

Let's say that you never do your own commits on demo. In this case we can ditch the name demo entirely:

git fetch origin   # update origin/*

git checkout master
git merge --ff-only origin/master || die "cannot fast-forward our master"

git merge -X theirs origin/demo || die "complex merge conflict"

git push origin master

If you are doing your own demo branch commits, this is not helpful; you might as well keep the existing merge (but maybe add --ff-only depending on what behavior you want), or switch it to doing a rebase. Note that all three methods may fail: merge may fail with a conflict, merge with --ff-only may not be able to fast-forward, and rebase may fail with a conflict (rebase works by, in essence, cherry-picking commits, which uses the merge machinery and hence can get a merge conflict).

Htaccess: add/remove trailing slash from URL

Right below the RewriteEngine On line, add:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R] # <- for test, for prod use [L,R=301]

to enforce a no-trailing-slash policy.

To enforce a trailing-slash policy:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R] # <- for test, for prod use [L,R=301]

EDIT: commented the R=301 parts because, as explained in a comment:

Be careful with that R=301! Having it there makes many browsers cache the .htaccess-file indefinitely: It somehow becomes irreversible if you can't clear the browser-cache on all machines that opened it. When testing, better go with simple R or R=302

After you've completed your tests, you can use R=301.

Logout button php

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

session_destroy();

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

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

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

Edit:

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

exit;

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

MySql Inner Join with WHERE clause

You could only write one where clause.

 SELECT table1.f_id  FROM table1
 INNER JOIN table2
 ON table2.f_id = table1.f_id
 where table1.f_com_id = '430' AND      
 table1.f_status = 'Submitted' AND table2.f_type = 'InProcess'

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

I've spend couple of days trying to resolve this frustrating issue. I've tried pretty much everything that can be found on the web. Finally I found that this error could be caused (like in my case) by the different target .Net project versions (4.5 and 4.5.1) in one solution. The steps bellow fixed it for me:

  1. Double check the .Net version of every project that's in your solution. Just right click on project and go to Properties.

enter image description here

  1. If possible set the same .Net version for all projects. If not at least try to change the Startup project one (for me this was the one causing the issues).

  2. Remove all Newtonsoft.Json packs from the solution.

    uninstall-package newtonsoft.json -force

  3. Update all Newtonsoft.Json versions in all packages.config files, like so

    <package id="Newtonsoft.Json" version="7.0.1" targetFramework="net451" />

  4. Reinstall Newtonsoft.Json from "Package Manager Console" with:

    install-package newtonsoft.json

  5. Rebuild the solution

(Optional) 7. If you changed the Startup project, return it again

Values of disabled inputs will not be submitted

They don't get submitted, because that's what it says in the W3C specification.

17.13.2 Successful controls

A successful control is "valid" for submission. [snip]

  • Controls that are disabled cannot be successful.

In other words, the specification says that controls that are disabled are considered invalid and should not be submitted.

How to display a range input slider vertically

Without changing the position to absolute, see below. This supports all recent browsers as well.

_x000D_
_x000D_
.vranger {_x000D_
  margin-top: 50px;_x000D_
   transform: rotate(270deg);_x000D_
  -moz-transform: rotate(270deg); /*do same for other browsers if required*/_x000D_
}
_x000D_
<input type="range" class="vranger"/>
_x000D_
_x000D_
_x000D_

for very old browsers, you can use -sand-transform: rotate(10deg); from CSS sandpaper

or use

prefix selector such as -ms-transform: rotate(270deg); for IE9

Set variable with multiple values and use IN

You need a table variable:

declare @values table
(
    Value varchar(1000)
)

insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')

select blah
from foo
where myField in (select value from @values)

How can we generate getters and setters in Visual Studio?

Enter image description here

On behalf of the Visual Studio tool, we can easily generate C# properties using an online tool called C# property generator.

Bootstrap col-md-offset-* not working

Where's the problem

In your HTML all h2s have the same off-set of 4 columns, so they won't make a diagonal.

How to fix it

A row has 12 columns, so we should put every h2 in it's own row. You should have something like this:

<div class="jumbotron">
    <div class="container">
        <div class="row">
                <h2 class="col-md-4 col-md-offset-1">Browse.</h2>
        </div>
        <div class="row">
                <h2 class="col-md-4 col-md-offset-2">create.</h2>
        </div>
        <div class="row">
                <h2 class="col-md-4 col-md-offset-3">share.</h2>
        </div>
    </div>
</div>

An alternative is to make every h2 width plus offset sum 12 columns, so each one automatically wraps in a new line.

<div class="jumbotron">
    <div class="container">
        <div class="row">
                <h2 class="col-md-11 col-md-offset-1">Browse.</h2>
                <h2 class="col-md-10 col-md-offset-2">create.</h2>
                <h2 class="col-md-9 col-md-offset-3">share.</h2>
        </div>
    </div>
</div>

Possible reasons for timeout when trying to access EC2 instance

For me it was the apache server hosted on a t2.micro linux EC2 instance, not the EC2 instance itself.

I fixed it by doing:

sudo su

service httpd restart

css with background image without repeating the image

Try this

padding:8px;
overflow: hidden;
zoom: 1;
text-align: left;
font-size: 13px;
font-family: "Trebuchet MS",Arial,Sans;
line-height: 24px;
color: black;
border-bottom: solid 1px #BBB;
background:url('images/checked.gif') white no-repeat;

This is full css.. Why you use padding:0 8px, then override it with paddings? This is what you need...

Ordering by specific field value first

do this:

SELECT * FROM table ORDER BY column `name`+0 ASC

Appending the +0 will mean that:

0, 10, 11, 2, 3, 4

becomes :

0, 2, 3, 4, 10, 11

How to delete duplicate rows in SQL Server?

I like CTEs and ROW_NUMBER as the two combined allow us to see which rows are deleted (or updated), therefore just change the DELETE FROM CTE... to SELECT * FROM CTE:

WITH CTE AS(
   SELECT [col1], [col2], [col3], [col4], [col5], [col6], [col7],
       RN = ROW_NUMBER()OVER(PARTITION BY col1 ORDER BY col1)
   FROM dbo.Table1
)
DELETE FROM CTE WHERE RN > 1

DEMO (result is different; I assume that it's due to a typo on your part)

COL1    COL2    COL3    COL4    COL5    COL6    COL7
john    1        1       1       1       1       1
sally   2        2       2       2       2       2

This example determines duplicates by a single column col1 because of the PARTITION BY col1. If you want to include multiple columns simply add them to the PARTITION BY:

ROW_NUMBER()OVER(PARTITION BY Col1, Col2, ... ORDER BY OrderColumn)

Python - Check If Word Is In A String

You could just add a space before and after "word".

x = raw_input("Type your word: ")
if " word " in x:
    print "Yes"
elif " word " not in x:
    print "Nope"

This way it looks for the space before and after "word".

>>> Type your word: Swordsmith
>>> Nope
>>> Type your word:  word 
>>> Yes

How can I switch my git repository to a particular commit

All the above commands create a new branch and with the latest commit being the one specified in the command, but just in case you want your current branch HEAD to move to the specified commit, below is the command:

 git checkout <commit_hash>

It detaches and point the HEAD to specified commit and saves from creating a new branch when the user just wants to view the branch state till that particular commit.


You then might want to go back to the latest commit & fix the detached HEAD:

Fix a Git detached head?

How can I compile my Perl script so it can be executed on systems without perl installed?

Look at PAR (Perl Archiving Toolkit).

PAR is a Cross-Platform Packaging and Deployment tool, dubbed as a cross between Java's JAR and Perl2EXE/PerlApp.

Getting only hour/minute of datetime

I would recommend keeping the object you have, and just utilizing the properties that you want, rather than removing the resolution you already have.

If you want to print it in a certain format you may want to look at this...That way you can preserve your resolution further down the line.

That being said you can create a new DateTime object using only the properties you want as @romkyns has in his answer.

Abstract variables in Java?

Use enums to force values as well to keep bound checks:

enum Speed {
    HIGH, LOW;
}
private abstract  class SuperClass {
    Speed speed;
    SuperClass(Speed speed) {
        this.speed = speed;
    }
}
private class ChildClass extends SuperClass {
    ChildClass(Speed speed) {
        super(speed);
    }
}