Programs & Examples On #Pyflakes

Pyflakes analyzes Python source code non-intrusively to check for errors.

Pylint, PyChecker or PyFlakes?

pep8 was recently added to PyPi.

  • pep8 - Python style guide checker
  • pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

It is now super easy to check your code against pep8.

See http://pypi.python.org/pypi/pep8

In .NET, which loop runs faster, 'for' or 'foreach'?

It is what you do inside the loop that affects perfomance, not the actual looping construct (assuming your case is non-trivial).

Server configuration is missing in Eclipse

As Yoni already mentioned, you probably deleted the project named "Servers" from your Project Explorer. If config files for the server still present on a file system, the quickest way to restore it will be Right Click in Project Explorer->Import->General->Existing Projects into Workspace, then select the root dir where Servers dir located, set checkbox near "Servers" and finally click Finish. If everything works as expected, you should see the 'Servers' project added to the Project Explorer view and your old config files will be there. Finally, save the tomcat configuration which you had open. You can startup your Tomcat server without errors now.

How to redirect in a servlet filter?

I'm trying to find a method to redirect my request from filter to login page

Don't

You just invoke

chain.doFilter(request, response);

from filter and the normal flow will go ahead.

I don't know how to redirect from servlet

You can use

response.sendRedirect(url);

to redirect from servlet

ActiveRecord find and only return selected columns

pluck(column_name)

This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.

Examples:

Person.pluck(:id) # SELECT people.id FROM people
Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
Person.where(:confirmed => true).limit(5).pluck(:id)

see http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck

Its introduced rails 3.2 onwards and accepts only single column. In rails 4, it accepts multiple columns

Use and meaning of "in" in an if statement?

You are used to using the javascript if, and I assume you know how it works.

in is a Pythonic way of implementing iteration. It's supposed to be easier for non-programmatic thinkers to adopt, but that can sometimes make it harder for programmatic thinkers, ironically.

When you say if x in y, you are literally saying:

"if x is in y", which assumes that y has an index. In that if statement then, each object at each index in y is checked against the condition.

Similarly,

for x in y

iterates through x's in y, where y is that indexable set of items.

Think of the if situation this way (pseudo-code):

for i in next:
    if i == "0" || i == "1":
        how_much = int(next)

It takes care of the iteration over next for you.

Happy coding!

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

I got this when building a project via Visual Studio Online (VSTS) Build using Visual Studio Build Steps.

The solution was:

  • Delete the existing source folder
  • Explicitly set 'Any CPU' in the platform for all Visual Studio Builds including dependencies (see screenshot below).
  • Re-run the build

VSO Screenshot

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

SQL Query to find missing rows between two related tables

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

Send email by using codeigniter library via localhost

Please check my working code.

function sendMail()
{
    $config = Array(
  'protocol' => 'smtp',
  'smtp_host' => 'ssl://smtp.googlemail.com',
  'smtp_port' => 465,
  'smtp_user' => '[email protected]', // change it to yours
  'smtp_pass' => 'xxx', // change it to yours
  'mailtype' => 'html',
  'charset' => 'iso-8859-1',
  'wordwrap' => TRUE
);

        $message = '';
        $this->load->library('email', $config);
      $this->email->set_newline("\r\n");
      $this->email->from('[email protected]'); // change it to yours
      $this->email->to('[email protected]');// change it to yours
      $this->email->subject('Resume from JobsBuddy for your Job posting');
      $this->email->message($message);
      if($this->email->send())
     {
      echo 'Email sent.';
     }
     else
    {
     show_error($this->email->print_debugger());
    }

}

How to programmatically add controls to a form in VB.NET

Public Class Form1
    Private boxes(5) As TextBox

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim newbox As TextBox
        For i As Integer = 1 To 5 'Create a new textbox and set its properties26.27.
        newbox = New TextBox
        newbox.Size = New Drawing.Size(100, 20)
        newbox.Location = New Point(10, 10 + 25 * (i - 1))
        newbox.Name = "TextBox" & i
        newbox.Text = newbox.Name   'Connect it to a handler, save a reference to the array & add it to the form control.
        AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
        boxes(i) = newbox
        Me.Controls.Add(newbox)
        Next
    End Sub

    Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs)
        'When you modify the contents of any textbox, the name of that textbox
        'and its current contents will be displayed in the title bar

        Dim box As TextBox = DirectCast(sender, TextBox)
        Me.Text = box.Name & ": " & box.Text
    End Sub
End Class

PHP date yesterday

strtotime(), as in date("F j, Y", strtotime("yesterday"));

Check input value length

<input type='text' minlength=3 /><br />

if browser supports html5,

it will automatical be validate attributes(minlength) in tag

but Safari(iOS) doesn't working

How to create a POJO?

  1. File-setting-plugins-Browse repositories
  2. Search RoboPOJOGenerator and install, Restart Android studio
  3. Open Project and right click on package select on Generate POJO from JSON
  4. Paste JSON in dialogbox and select option according your requirements
  5. Click on Generate button

jquery clone div and append it after specific div

You can do it using clone() function of jQuery, Accepted answer is ok but i am providing alternative to it, you can use append(), but it works only if you can change html slightly as below:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $('#clone_btn').click(function(){_x000D_
      $("#car_parent").append($("#car2").clone());_x000D_
    });_x000D_
});
_x000D_
.car-well{_x000D_
  border:1px solid #ccc;_x000D_
  text-align: center;_x000D_
  margin: 5px;_x000D_
  padding:3px;_x000D_
  font-weight:bold;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div id="car_parent">_x000D_
  <div id="car1" class="car-well">Normal div</div>_x000D_
  <div id="car2" class="car-well" style="background-color:lightpink;color:blue">Clone div</div>_x000D_
  <div id="car3" class="car-well">Normal div</div>_x000D_
  <div id="car4" class="car-well">Normal div</div>_x000D_
  <div id="car5" class="car-well">Normal div</div>_x000D_
</div>_x000D_
<button type="button" id="clone_btn" class="btn btn-primary">Clone</button>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

SQL Server 2005 How Create a Unique Constraint?

In SQL Server Management Studio Express:

  • Right-click table, choose Modify or Design(For Later Versions)
  • Right-click field, choose Indexes/Keys...
  • Click Add
  • For Columns, select the field name you want to be unique.
  • For Type, choose Unique Key.
  • Click Close, Save the table.

How to recover deleted rows from SQL server table?

You have Full data + Transaction log backups, right? You can restore to another Database from backups and then sync the deleted rows back. Lots of work though...

(Have you looked at Redgate's SQL Log Rescue? Update: it's SQL Server 2000 only)

There is Log Explorer

comparing strings in vb

I think this String.Equals is what you need.

Dim aaa = "12/31"
            Dim a = String.Equals(aaa, "06/30")

a will return false.

Call an overridden method from super class in typescript

If you want a super class to call a function from a subclass, the cleanest way is to define an abstract pattern, in this manner you explicitly know the method exists somewhere and must be overridden by a subclass.

This is as an example, normally you do not call a sub method within the constructor as the sub instance is not initialized yet… (reason why you have an "undefined" in your question's example)

abstract class A {
    // The abstract method the subclass will have to call
    protected abstract doStuff():void;

    constructor(){
     alert("Super class A constructed, calling now 'doStuff'")
     this.doStuff();
    }
}

class B extends A{

    // Define here the abstract method
    protected doStuff()
    {
        alert("Submethod called");
    }
}

var b = new B();

Test it Here

And if like @Max you really want to avoid implementing the abstract method everywhere, just get rid of it. I don't recommend this approach because you might forget you are overriding the method.

abstract class A {
    constructor() {
        alert("Super class A constructed, calling now 'doStuff'")
        this.doStuff();
    }

    // The fallback method the subclass will call if not overridden
    protected doStuff(): void {
        alert("Default doStuff");
    };
}

class B extends A {
    // Override doStuff()
    protected doStuff() {
        alert("Submethod called");
    }
}

class C extends A {
    // No doStuff() overriding, fallback on A.doStuff()
}

var b = new B();
var c = new C();

Try it Here

jQuery: Check if special characters exists in string

var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
var check = function(string){
    for(i = 0; i < specialChars.length;i++){
        if(string.indexOf(specialChars[i]) > -1){
            return true
        }
    }
    return false;
}

if(check($('#Search').val()) == false){
    // Code that needs to execute when none of the above is in the string
}else{
    alert('Your search string contains illegal characters.');
}

Background images: how to fill whole div if image is small and vice versa

Rather than giving background-size:100%;
We can give background-size:contain;
Check out this for different options avaliable: http://www.css3.info/preview/background-size/

DateTimePicker: pick both date and time

You can get it to display time. From that you will probably have to have two controls (one date, one time) the accomplish what you want.

how to get file path from sd card in android

As some people indicated, the officially accepted answer does not quite return the external removable SD card. And i ran upon the following thread that proposes a method I've tested on some Android devices and seems to work reliably, so i thought of re-sharing here as i don't see it in the other responses:

http://forums.androidcentral.com/samsung-galaxy-s7/668364-whats-external-sdcard-path.html

Kudos to paresh996 for coming up with the answer itself, and i can attest I've tried on Samsung S7 and S7edge and seems to work.

Now, i needed a method that returned a valid path where to read files, and that considered the fact that there might not be an external SD, in which case the internal storage should be returned, so i modified the code from paresh996 to this :

File getStoragePath() {
    String removableStoragePath;
    File fileList[] = new File("/storage/").listFiles();
    for (File file : fileList) {
       if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) {
            return file;
        }
    }
    return Environment.getExternalStorageDirectory();
}

Make a dictionary in Python from input values

Assuming you have the text in variable s:

dict(map(lambda l: l.split(), s.splitlines()))

How can I generate an ObjectId with mongoose?

With ES6 syntax

import mongoose from "mongoose";

// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');

What is the bit size of long on 64-bit Windows?

This article on MSDN references a number of type aliases (available on Windows) that are a bit more explicit with respect to their width:

http://msdn.microsoft.com/en-us/library/aa505945.aspx

For instance, although you can use ULONGLONG to reference a 64-bit unsigned integral value, you can also use UINT64. (The same goes for ULONG and UINT32.) Perhaps these will be a bit clearer?

Formatting ISODate from Mongodb

JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:

> foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
> foo.toTimeString()
'17:00:00 GMT-0700 (MST)'

If you want the time string without the seconds and the time zone then you can call the getHours() and getMinutes() methods on the Date object and format the time yourself.

Why doesn't Dijkstra's algorithm work for negative weight edges?

Try Dijkstra's algorithm on the following graph, assuming A is the source node and D is the destination, to see what is happening:

Graph

Note that you have to follow strictly the algorithm definition and you should not follow your intuition (which tells you the upper path is shorter).

The main insight here is that the algorithm only looks at all directly connected edges and it takes the smallest of these edge. The algorithm does not look ahead. You can modify this behavior , but then it is not the Dijkstra algorithm anymore.

Send Email to multiple Recipients with MailMessage?

Easy!

Just split the incoming address list on the ";" character, and add them to the mail message:

foreach (var address in addresses.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
    mailMessage.To.Add(address);    
}

In this example, addresses contains "[email protected];[email protected]".

Clicking the back button twice to exit an activity

After having had to implement the same things many times, decided its about time someone built a simple to use library. And that is DoubleBackPress Android library. The README explains all the APIs provided along with Examples (like ToastDisplay + Exit Activity), but a short rundown of the steps here.


To get going, start by adding the dependency to your application :

dependencies {
    implementation 'com.github.kaushikthedeveloper:double-back-press:0.0.1'
} 

Next, create a DoubleBackPress object in your Activity which provides the required behaviour.

DoubleBackPress doubleBackPress = new DoubleBackPress();
doubleBackPress.setDoublePressDuration(3000);           // msec

Then create a Toast that needs to be shown upon the First Back Press. Here, you can create your own Toast, or go with Standard Toast provided in the library. Doing so here by the later option.

FirstBackPressAction firstBackPressAction = new ToastDisplay().standard(this);
doubleBackPress.setFirstBackPressAction(firstBackPressAction);   // set the action

Now, define what should happen when your Second Back Press happens. Here, we are closing the Activity.

DoubleBackPressAction doubleBackPressAction = new DoubleBackPressAction() {
    @Override
    public void actionCall() {
        finish();
        System.exit(0);
    }
};

Finally, override your back press behaviour with the DoubleBackPress behaviour.

@Override
public void onBackPressed() {
    doubleBackPress.onBackPressed();
}

Example GIF of similar behavioural requirements

Creating a batch file, for simple javac and java command execution

Create a plain text file (using notepad) and type the exact line you would use to run your Java file with the command prompt. Then change the extension to .bat and you're done.

Double clicking on this file would run your java program.

I reccommend one file for javac, one for java so you can troubleshoot if anything is wrong.

  • Make sure java is in your path, too.. IE typing java in a Dos windows when in your java workspace should bring up the java version message. If java is not in your path the batch file won't work unless you use absolut path to the java binary.

How do you kill all current connections to a SQL Server 2005 database?

I usually run into that error when I am trying to restore a database I usually just go to the top of the tree in Management Studio and right click and restart the database server (because it's on a development machine, this might not be ideal in production). This is close all database connections.

Remove innerHTML from div

divToUpdate.innerHTML =     "";   

Server.Mappath in C# classlibrary

By calling it?

var path = System.Web.HttpContext.Current.Server.MapPath("default.aspx");

Make sure you add a reference to the System.Web assembly.

Differences between unique_ptr and shared_ptr

When wrapping a pointer in a unique_ptr you cannot have multiple copies of unique_ptr. The shared_ptr holds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptr is copied, this counter is incremented. Each time a shared_ptr is destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.

Java substring: 'string index out of range'

You get this if itemdescription is shorter than 38 characters

You can look which exceptions are thrown and when in the JAVA API in you case for String#substring(int,int): https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#substring-int-int-

substring
public String substring(int beginIndex, int endIndex)
   . . .

Throws:
 IndexOutOfBoundsException
 if the beginIndex is negative,
 or endIndex is larger than the length of this String object, 
 or beginIndex is larger than endIndex.



(same applies to previous java versions as well)

What's the best way to select the minimum value from several columns?

This is brute force but works

 select case when col1 <= col2 and col1 <= col3 then col1
           case when col2 <= col1 and col2 <= col3 then col2
           case when col3 <= col1 and col3 <= col2 then col3
    as 'TheMin'
           end

from Table T

... because min() works only on one column and not across columns.

How can I do a line break (line continuation) in Python?

It may not be the Pythonic way, but I generally use a list with the join function for writing a long string, like SQL queries:

query = " ".join([
    'SELECT * FROM "TableName"',
    'WHERE "SomeColumn1"=VALUE',
    'ORDER BY "SomeColumn2"',
    'LIMIT 5;'
])

How does a Breadth-First Search work when looking for Shortest Path?

I have wasted 3 days
ultimately solved a graph question
used for
finding shortest distance
using BFS

Want to share the experience.

When the (undirected for me) graph has
fixed distance (1, 6, etc.) for edges

#1
We can use BFS to find shortest path simply by traversing it
then, if required, multiply with fixed distance (1, 6, etc.)

#2
As noted above
with BFS
the very 1st time an adjacent node is reached, it is shortest path

#3
It does not matter what queue you use
   deque/queue(c++) or
   your own queue implementation (in c language)
   A circular queue is unnecessary

#4
Number of elements required for queue is N+1 at most, which I used
(dint check if N works)
here, N is V, number of vertices.

#5
Wikipedia BFS will work, and is sufficient.
    https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode

I have lost 3 days trying all above alternatives, verifying & re-verifying again and again above
they are not the issue.
(Try to spend time looking for other issues, if you dint find any issues with above 5).


More explanation from the comment below:

      A
     /  \
  B       C
 /\       /\
D  E     F  G

Assume above is your graph
graph goes downwards
For A, the adjacents are B & C
For B, the adjacents are D & E
For C, the adjacents are F & G

say, start node is A

  1. when you reach A, to, B & C the shortest distance to B & C from A is 1

  2. when you reach D or E, thru B, the shortest distance to A & D is 2 (A->B->D)

similarly, A->E is 2 (A->B->E)

also, A->F & A->G is 2

So, now instead of 1 distance between nodes, if it is 6, then just multiply the answer by 6
example,
if distance between each is 1, then A->E is 2 (A->B->E = 1+1)
if distance between each is 6, then A->E is 12 (A->B->E = 6+6)

yes, bfs may take any path
but we are calculating for all paths

if you have to go from A to Z, then we travel all paths from A to an intermediate I, and since there will be many paths we discard all but shortest path till I, then continue with shortest path ahead to next node J
again if there are multiple paths from I to J, we only take shortest one
example,
assume,
A -> I we have distance 5
(STEP) assume, I -> J we have multiple paths, of distances 7 & 8, since 7 is shortest
we take A -> J as 5 (A->I shortest) + 8 (shortest now) = 13
so A->J is now 13
we repeat now above (STEP) for J -> K and so on, till we get to Z

Read this part, 2 or 3 times, and draw on paper, you will surely get what i am saying, best of luck


Accessing Redux state in an action creator?

There are differing opinions on whether accessing state in action creators is a good idea:

  • Redux creator Dan Abramov feels that it should be limited: "The few use cases where I think it’s acceptable is for checking cached data before you make a request, or for checking whether you are authenticated (in other words, doing a conditional dispatch). I think that passing data such as state.something.items in an action creator is definitely an anti-pattern and is discouraged because it obscured the change history: if there is a bug and items are incorrect, it is hard to trace where those incorrect values come from because they are already part of the action, rather than directly computed by a reducer in response to an action. So do this with care."
  • Current Redux maintainer Mark Erikson says it's fine and even encouraged to use getState in thunks - that's why it exists. He discusses the pros and cons of accessing state in action creators in his blog post Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability.

If you find that you need this, both approaches you suggested are fine. The first approach does not require any middleware:

import store from '../store';

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return {
    type: SOME_ACTION,
    items: store.getState().otherReducer.items,
  }
}

However you can see that it relies on store being a singleton exported from some module. We don’t recommend that because it makes it much harder to add server rendering to your app because in most cases on the server you’ll want to have a separate store per request. So while technically this approach works, we don’t recommend exporting a store from a module.

This is why we recommend the second approach:

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return (dispatch, getState) => {
    const {items} = getState().otherReducer;

    dispatch(anotherAction(items));
  }
}

It would require you to use Redux Thunk middleware but it works fine both on the client and on the server. You can read more about Redux Thunk and why it’s necessary in this case here.

Ideally, your actions should not be “fat” and should contain as little information as possible, but you should feel free to do what works best for you in your own application. The Redux FAQ has information on splitting logic between action creators and reducers and times when it may be useful to use getState in an action creator.

Java using enum with switch statement

I like a few usages of Java enum:

  1. .name() allows you to fetch the enum name in String.
  2. .ordinal() allow you to get the integer value, 0-based.
  3. You can attach other value parameters with each enum.
  4. and, of course, switch enabled.

enum with value parameters:

    enum StateEnum {
        UNDEFINED_POLL  ( 1 * 1000L,       4 * 1000L),
        SUPPORT_POLL    ( 1 * 1000L,       5 * 1000L),
        FAST_POLL       ( 2 * 1000L,  4 * 60 * 1000L),
        NO_POLL         ( 1 * 1000L,       6 * 1000L); 
        ...
    }

switch example:

private void queuePoll(StateEnum se) {
    // debug print se.name() if needed
    switch (se) {
        case UNDEFINED_POLL:
            ...
            break;
        case SUPPORT_POLL:
            ...
            break;

Pass values of checkBox to controller action in asp.net mvc4

For some reason Andrew method of creating the checkbox by hand didn't work for me using Mvc 5. Instead I used this

@Html.CheckBox("checkResp")

to create a checkbox that would play nice with the controller.

AJAX Mailchimp signup form integration

In the other hand, there is some packages in AngularJS which are helpful (in AJAX WEB):

https://github.com/cgarnier/angular-mailchimp-subscribe

Tools for making latex tables in R

Thanks Joris for creating this question. Hopefully, it will be made into a community wiki.

The booktabs packages in latex produces nice looking tables. Here is a blog post on how to use xtable to create latex tables that use booktabs

I would also add the apsrtable package to the mix as it produces nice looking regression tables.

Another Idea: Some of these packages (esp. memisc and apsrtable) allow easy extensions of the code to produce tables for different regression objects. One such example is the lme4 memisc code shown in the question. It might make sense to start a github repository to collect such code snippets, and over time maybe even add it to the memisc package. Any takers?

What's the best way to share data between activities?

What you can use:

  1. passing data between activities (like Cristian said)
  2. using a class with a lot of static variables (so you can call them without an instance of the class and without using getter/setter)
  3. Using a database
  4. Shared Preferences

What you choose depends on your needs. Probably you will use more than one way when you have "a lot of"

Configure Log4Net in web application

often this is due to missing permissions. The windows account the local IIS Application Pool is running with may not have the permission to write to the applications directory. You could create a directory somewhere, give everyone permission to write in it and point your log4net config to that directory. If then a log file is created there, you can modify the permissions for your desired log directory so that the app pool can write to it.

Another reason could be an uninitialized log4net. In a winforms app, you usually configure log4net upon application start. In a web app, you can do this either dynamically (in your logging component, check if you can create a specific Ilog logger using its name, if not -> call configure()) or again upon application start in global.asax.cs.

Iterating over Typescript Map

This worked for me.

Object.keys(myMap).map( key => {
    console.log("key: " + key);
    console.log("value: " + myMap[key]);
});

remove attribute display:none; so the item will be visible

You should remove "style" attribute instead of "display" property :

$("span").removeAttr("style");

How to get a product's image in Magento?

First You need to verify the base, small and thumbnail image are selected in Magento admin.

admin->catalog->manage product->product->image

Then select your image roles(base,small,thumbnail)enter image description here

Then you call the image using

echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(163, 100);

Hope this helps you.

DataColumn Name from DataRow (not DataTable)

You would still need to go through the DataTable class. But you can do so using your DataRow instance by using the Table property.

foreach (DataColumn c in dr.Table.Columns)  //loop through the columns. 
{
    MessageBox.Show(c.ColumnName);
}

How to run a Runnable thread in Android at defined intervals?

new Handler().postDelayed(new Runnable() {
    public void run() {
        // do something...              
    }
}, 100);

how to check if object already exists in a list

If it's maintainable to use those 2 properties, you could:

bool alreadyExists = myList.Any(x=> x.Foo=="ooo" && x.Bar == "bat");

BeanFactory vs ApplicationContext

I think it is worth mentioning that since Spring 3, if you want to create a factory, you can also use the @configuration annotation combined with the proper @scope

@Configuration
public class MyFactory {

    @Bean
    @Scope("prototype")
    public MyClass create() {
        return new MyClass();
    }
}

Your factory should be visible by Spring container using the @ComponentScan annotation or xml configuration

Spring bean scopes article from baeldung site

Find the closest ancestor element that has a specific class

Based on the the8472 answer and https://developer.mozilla.org/en-US/docs/Web/API/Element/matches here is cross-platform 2017 solution:

if (!Element.prototype.matches) {
    Element.prototype.matches =
        Element.prototype.matchesSelector ||
        Element.prototype.mozMatchesSelector ||
        Element.prototype.msMatchesSelector ||
        Element.prototype.oMatchesSelector ||
        Element.prototype.webkitMatchesSelector ||
        function(s) {
            var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                i = matches.length;
            while (--i >= 0 && matches.item(i) !== this) {}
            return i > -1;
        };
}

function findAncestor(el, sel) {
    if (typeof el.closest === 'function') {
        return el.closest(sel) || null;
    }
    while (el) {
        if (el.matches(sel)) {
            return el;
        }
        el = el.parentElement;
    }
    return null;
}

Eloquent - where not equal to

Fetching data with either null and value on where conditions are very tricky. Even if you are using straight Where and OrWhereNotNull condition then for every rows you will fetch both items ignoring other where conditions if applied. For example if you have more where conditions it will mask out those and still return with either null or value items because you used orWhere condition

The best way so far I found is as follows. This works as where (whereIn Or WhereNotNull)

Code::where(function ($query) {
            $query->where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id');                  
        })->get();

Find stored procedure by name

Very neat trick I stumble upon trying some SQL injection, in object explorer in the search box just use your percentage characters, and this will search EVERYTHING stored procedures, functions, views, tables, schema, indexes...I tired of thinking of more :)

Search Pattern

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

If your class dependency is managing by Spring then this issue may occur if we forgot to add default/empty arg constructor inside our POJO class.

How to change already compiled .class file without decompile?

I added some codes and save .class file.

What you see in JD EClipse Decompiler is decompiled representation of byte code in the .class file. Even though you change the text it won't affect the byte code.

Invalid column name sql error

Your issue seems to be the Name keyword. Rather use FullName or firstName and lastName, always try and remember to use CamelCase too.

Gridview row editing - dynamic binding to a DropDownList

The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.

I used it to change the value of two label controls - lblEditModifiedBy and lblEditModifiedOn - when I was editing a row, so that the correct ModifiedBy and ModifiedOn would be saved to the db on 'Update'.

When I clicked the 'Update' button, in the RowUpdating event it showed the new values I entered in the OldValues list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource attached to the GridView.)

The fix to this is using balexandre's code, but in a modified form in the gv_DataBound event:

protected void gv_DataBound(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in gv.Rows)
    {
        if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            // Here you will get the Control you need like:
            ((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
            ((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
        }
    }
}

How to output loop.counter in python jinja template?

change this {% if loop.counter == 1 %} to {% if forloop.counter == 1 %} {#your code here#} {%endfor%}

and this from {{ user }} {{loop.counter}} to {{ user }} {{forloop.counter}}

how to delete default values in text field using selenium?

You can use the code below. It selects the pre-existing value in the field and overwrites it with the new value.

driver.findElement(By.xpath("*enter your xpath here*")).sendKeys(Keys.chord(Keys.CONTROL, "a"),*enter the new value here*);

How to break out of nested loops?

i = 0;

do
{
  for (int j = 0; j < 1000; j++) // by the way, your code uses i++ here!
  {
     if (condition)
     {
       break;
     }
  }

  ++i;

} while ((i < 1000) && !condition);

How to convert an address into a Google Maps Link (NOT MAP)

The best way is to use this line:

var mapUrl = "http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=16900+North+Bay+Road,+Sunny+Isles+Beach,+FL+33160&amp;aq=0&amp;sll=37.0625,-95.677068&amp;sspn=61.282355,146.513672&amp;ie=UTF8&amp;hq=&amp;hnear=16900+North+Bay+Road,+Sunny+Isles+Beach,+FL+33160&amp;spn=0.01628,0.025663&amp;z=14&amp;iwloc=A&amp;output=embed"

Remember to replace the first and second addresses when necessary.

You can look at work sample

Laravel blank white screen

Try this, in the public/index.php page

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

Property 'catch' does not exist on type 'Observable<any>'

Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below

=====================

Yes, you need to import the operator:

import 'rxjs/add/operator/catch';

Or import Observable this way:

import {Observable} from 'rxjs/Rx';

But in this case, you import all operators.

See this question for more details:

how to wait for first command to finish?

Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh after the last command of st_new.sh has finished.

Now there is a special command which messes this up: &

cmd &

means: "Start a new background process and execute cmd in it. After starting the background process, immediately continue with the next command in the script."

That means & doesn't wait for cmd to do it's work. My guess is that st_new.sh contains such a command. If that is the case, then you need to modify the script:

cmd &
BACK_PID=$!

This puts the process ID (PID) of the new background process in the variable BACK_PID. You can then wait for it to end:

while kill -0 $BACK_PID ; do
    echo "Process is still active..."
    sleep 1
    # You can add a timeout here if you want
done

or, if you don't want any special handling/output simply

wait $BACK_PID

Note that some programs automatically start a background process when you run them, even if you omit the &. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's & command instead to get the PID.

Git update submodules recursively

The way I use is:

git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Calling async code from synchronous code can be quite tricky.

I explain the full reasons for this deadlock on my blog. In short, there's a "context" that is saved by default at the beginning of each await and used to resume the method.

So if this is called in an UI context, when the await completes, the async method tries to re-enter that context to continue executing. Unfortunately, code using Wait (or Result) will block a thread in that context, so the async method cannot complete.

The guidelines to avoid this are:

  1. Use ConfigureAwait(continueOnCapturedContext: false) as much as possible. This enables your async methods to continue executing without having to re-enter the context.
  2. Use async all the way. Use await instead of Result or Wait.

If your method is naturally asynchronous, then you (probably) shouldn't expose a synchronous wrapper.

How do I initialize a byte array in Java?

You can use the Java UUID class to store these values, instead of byte arrays:

UUID

public UUID(long mostSigBits,
            long leastSigBits)

Constructs a new UUID using the specified data. mostSigBits is used for the most significant 64 bits of the UUID and leastSigBits becomes the least significant 64 bits of the UUID.

Shell script to capture Process ID and kill it if exist

A lot of *NIX systems also have either or both pkill(1) and killall(1) which, allows you to kill processes by name. Using them, you can avoid the whole parsing ps problem.

Using Service to run background and create notification

Your error is in UpdaterServiceManager in onCreate and showNotification method.

You are trying to show notification from Service using Activity Context. Whereas Every Service has its own Context, just use the that. You don't need to pass a Service an Activity's Context.I don't see why you need a specific Activity's Context to show Notification.

Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.

You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

I create a new key, I had to search the csproj for the old one and refactor it.

In PowerShell, how do I test whether or not a specific variable exists in global scope?

EDIT: Use stej's answer below. My own (partially incorrect) one is still reproduced here for reference:


You can use

Get-Variable foo -Scope Global

and trap the error that is raised when the variable doesn't exist.

Replace part of a string in Python?

You can easily use .replace() as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change. Let me explain by;

    >>stuff = "bin and small"
    >>stuff.replace('and', ',')
    >>print(stuff)
    "big and small" #no change

To observe the change you want to apply, you can assign same or another variable;

    >>stuff = "big and small"
    >>stuff = stuff.replace("and", ",")   
    >>print(stuff)
    'big, small'

Android SQLite Example

The following Links my help you

1. Android Sqlite Database

2. Tutorial 1

Database Helper Class:

A helper class to manage database creation and version management.

You create a subclass implementing onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the database is always in a sensible state.

This class makes it easy for ContentProvider implementations to defer opening and upgrading the database until first use, to avoid blocking application startup with long-running database upgrades.

You need more refer this link Sqlite Helper

What is the best way to know if all the variables in a Class are null?

I think this is a solution that solves your problem easily: (return true if any of the parameters is not null)

  public boolean isUserEmpty(){ 
boolean isEmpty;
isEmpty =  isEmpty = Stream.of(id,
            name)
        .anyMatch(userParameter -> userParameter != null);

return isEmpty;}

Another solution to the same task is:(you can change it to if(isEmpty==0) checks if all the parameters are null.

public boolean isUserEmpty(){  
       long isEmpty;
            isEmpty = Stream.of(id,
                    name)
                    .filter(userParameter -> userParameter != null).count();

            if (isEmpty > 0) {
                return true;
            } else {
                return false;
            }
    }

Code for best fit straight line of a scatter plot in python

Have implemented @Micah 's solution to generate a trendline with a few changes and thought I'd share:

  • Coded as a function
  • Option for a polynomial trendline (input order=2)
  • Function can also just return the coefficient of determination (R^2, input Rval=True)
  • More Numpy array optimisations

Code:

def trendline(xd, yd, order=1, c='r', alpha=1, Rval=False):
    """Make a line of best fit"""

    #Calculate trendline
    coeffs = np.polyfit(xd, yd, order)

    intercept = coeffs[-1]
    slope = coeffs[-2]
    power = coeffs[0] if order == 2 else 0

    minxd = np.min(xd)
    maxxd = np.max(xd)

    xl = np.array([minxd, maxxd])
    yl = power * xl ** 2 + slope * xl + intercept

    #Plot trendline
    plt.plot(xl, yl, c, alpha=alpha)

    #Calculate R Squared
    p = np.poly1d(coeffs)

    ybar = np.sum(yd) / len(yd)
    ssreg = np.sum((p(xd) - ybar) ** 2)
    sstot = np.sum((yd - ybar) ** 2)
    Rsqr = ssreg / sstot

    if not Rval:
        #Plot R^2 value
        plt.text(0.8 * maxxd + 0.2 * minxd, 0.8 * np.max(yd) + 0.2 * np.min(yd),
                 '$R^2 = %0.2f$' % Rsqr)
    else:
        #Return the R^2 value:
        return Rsqr

Setting a max character length in CSS

Pure CSS solution to truncating multi line characters

I had a similar problem and found this excellent css only solution from Hackingui.com. You can read the article for information but below is the main code.

I tested it and it works perfectly. Hopefully someone finds it useful before opting for JS or server side options

  /* styles for '...' */ 
.block-with-text {
  /* hide text if it more than N lines  */
  overflow: hidden;
  /* for set '...' in absolute position */
  position: relative; 
  /* use this value to count block height */
  line-height: 1.2em;
  /* max-height = line-height (1.2) * lines max number (3) */
  max-height: 3.6em; 
  /* fix problem when last visible word doesn't adjoin right side  */
  text-align: justify;  
  /* place for '...' */
  margin-right: -1em;
  padding-right: 1em;
}

/* create the ... */
.block-with-text:before {
  /* points in the end */
  content: '...';
  /* absolute position */
  position: absolute;
  /* set position to right bottom corner of block */
  right: 0;
  bottom: 0;
}

/* hide ... if we have text, which is less than or equal to max lines */
.block-with-text:after {
  /* points in the end */
  content: '';
  /* absolute position */
  position: absolute;
  /* set position to right bottom corner of text */
  right: 0;
  /* set width and height */
  width: 1em;
  height: 1em;
  margin-top: 0.2em;
  /* bg color = bg color under block */
  background: white;
}

Multiple controllers with AngularJS in single page app

I just put one simple declaration of the app

var app = angular.module("app", ["xeditable"]);

Then I built one service and two controllers

For each controller I had a line in the JS

app.controller('EditableRowCtrl', function ($scope, CRUD_OperService) {

And in the HTML I declared the app scope in a surrounding div

<div ng-app="app">

and each controller scope separately in their own surrounding div (within the app div)

<div ng-controller="EditableRowCtrl">

This worked fine

How can I URL encode a string in Excel VBA?

None of the solutions here worked for me out of the box, but it was most likely due my lack of experience with VBA. It might also be because I simply copied and pasted some of the functions above, not knowing details that maybe are necessary to make them work on a VBA for applications environment.

My needs were simply to send xmlhttp requests using urls that contained some special characters of the Norwegian language. Some of the solutions above encode even colons, which made the urls unsuitable for what I needed.

I then decided to write my own URLEncode function. It does not use more clever programming such as the one from @ndd and @Tom. I am not a very experienced programmer, but I had to make this done sooner.

I realized that the problem was that my server didn't accept UTF-16 encodings, so I had to write a function that would convert UTF-16 to UTF-8. A good source of information was found here and here.

I haven't tested it extensively to check if it works with url with characters that have higher unicode values and which would produce more than 2 bytes of utf-8 characters. I am not saying it will decode everything that needs to be decoded (but it is easy to modify to include/exclude characters on the select case statement) nor that it will work with higher characters, as I haven't fully tested. But I am sharing the code because it might help someone who is trying to understand the issue.

Any comments are welcome.

Public Function URL_Encode(ByVal st As String) As String

    Dim eachbyte() As Byte
    Dim i, j As Integer 
    Dim encodeurl As String
    encodeurl = "" 

    eachbyte() = StrConv(st, vbFromUnicode)

    For i = 0 To UBound(eachbyte)

        Select Case eachbyte(i)
        Case 0
        Case 32
            encodeurl = encodeurl & "%20"

        ' I am not encoding the lower parts, not necessary for me
        Case 1 To 127
            encodeurl = encodeurl & Chr(eachbyte(i))
        Case Else

            Dim myarr() As Byte
            myarr = utf16toutf8(eachbyte(i))
            For j = LBound(myarr) To UBound(myarr) - 1
                encodeurl = encodeurl & "%" & Hex(myarr(j))
            Next j
        End Select
    Next i
    URL_Encode = encodeurl 
End Function

Public Function utf16toutf8(ByVal thechars As Variant) As Variant
    Dim numbytes As Integer
    Dim byte1 As Byte
    Dim byte2 As Byte
    Dim byte3 As Byte
    Dim byte4 As Byte
    Dim byte5 As Byte 
    Dim i As Integer  
    Dim temp As Variant
    Dim stri As String

    byte1 = 0
    byte2 = byte3 = byte4 = byte5 = 128

    ' Test to see how many bytes the utf-8 char will need
    Select Case thechars
        Case 0 To 127
            numbytes = 1
        Case 128 To 2047
            numbytes = 2
        Case 2048 To 65535
            numbytes = 3
        Case 65536 To 2097152
            numbytes = 4
        Case Else
            numbytes = 5
    End Select

    Dim returnbytes() As Byte
    ReDim returnbytes(numbytes)


    If numbytes = 1 Then
        returnbytes(0) = thechars
        GoTo finish
    End If


    ' prepare the first byte
    byte1 = 192

    If numbytes > 2 Then
        For i = 3 To numbytes
            byte1 = byte1 / 2
            byte1 = byte1 + 128
        Next i
    End If
    temp = 0
    stri = ""
    If numbytes = 5 Then
        temp = thechars And 63

        byte5 = temp + 128
        returnbytes(4) = byte5
        thechars = thechars / 12
        stri = byte5
    End If

    If numbytes >= 4 Then

        temp = 0
        temp = thechars And 63
        byte4 = temp + 128
        returnbytes(3) = byte4
        thechars = thechars / 12
        stri = byte4 & stri
    End If

    If numbytes >= 3 Then

        temp = 0
        temp = thechars And 63
        byte3 = temp + 128
        returnbytes(2) = byte3
        thechars = thechars / 12
        stri = byte3 & stri
    End If

    If numbytes >= 2 Then

        temp = 0
        temp = thechars And 63
        byte2 = temp Or 128
        returnbytes(1) = byte2
        thechars = Int(thechars / (2 ^ 6))
        stri = byte2 & stri
    End If

    byte1 = thechars Or byte1
    returnbytes(0) = byte1

    stri = byte1 & stri

    finish:
       utf16toutf8 = returnbytes()
End Function

setTimeout in React Native

You can bind this to your function by adding .bind(this) directly to the end of your function definition. You would rewrite your code block as:

setTimeout(function () {
  this.setState({ timePassed: true });
}.bind(this), 1000);

Using subprocess to run Python script on Windows

You are using a pathname separator which is platform dependent. Windows uses "\" and Unix uses "/".

What's the difference between fill_parent and wrap_content?

fill_parent (deprecated) = match_parent
The border of the child view expands to match the border of the parent view.

wrap_content
The border of the child view wraps snugly around its own content.

Here are some images to make things more clear. The green and red are TextViews. The white is a LinearLayout showing through.

enter image description here

Every View (a TextView, an ImageView, a Button, etc.) needs to set the width and the height of the view. In the xml layout file, that might look like this:

android:layout_width="wrap_content"
android:layout_height="match_parent"

Besides setting the width and height to match_parent or wrap_content, you could also set them to some absolute value:

android:layout_width="100dp"
android:layout_height="200dp"

Generally that is not as good, though, because it is not as flexible for different sized devices. After you have understood wrap_content and match_parent, the next thing to learn is layout_weight.

See also

XML for above images

Vertical LinearLayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="width=wrap height=wrap"
        android:background="#c5e1b0"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="width=match height=wrap"
        android:background="#f6c0c0"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="width=match height=match"
        android:background="#c5e1b0"/>

</LinearLayout>

Horizontal LinearLayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="WrapWrap"
        android:background="#c5e1b0"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="WrapMatch"
        android:background="#f6c0c0"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="MatchMatch"
        android:background="#c5e1b0"/>

</LinearLayout>

Note

The explanation in this answer assumes there is no margin or padding. But even if there is, the basic concept is still the same. The view border/spacing is just adjusted by the value of the margin or padding.

JPA OneToMany not deleting child

@Entity 
class Employee {
     @OneToOne(orphanRemoval=true)
     private Address address;
}

See here.

Is there a Google Voice API?

I looked for a C/C++ API for Google Voice for quite a while and never found anything close (the closest was a C# API). Since I really needed it, I decided to just write one myself:

http://github.com/mastermind202/GoogleVoice

I hope others find it useful. Feedback and suggestions welcome.

Extracting double-digit months and days from a Python date

Look at the types of those properties:

In [1]: import datetime

In [2]: d = datetime.date.today()

In [3]: type(d.month)
Out[3]: <type 'int'>

In [4]: type(d.day)
Out[4]: <type 'int'>

Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.

If you want leading zeroes, you'll have to format them one way or another. For that you have several options:

In [5]: '{:02d}'.format(d.month)
Out[5]: '03'

In [6]: '%02d' % d.month
Out[6]: '03'

In [7]: d.strftime('%m')
Out[7]: '03'

In [8]: f'{d.month:02d}'
Out[8]: '03'

How to get the xml node value in string

The problem in your code is xml.LoadXml(filePath);

LoadXml method take parameter as xml data not the xml file path

Try this code

   string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xmlFile);
                XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
                string Short_Fall=string.Empty;
                foreach (XmlNode node in nodeList)
                {
                    Short_Fall = node.InnerText;
                }

Edit

Seeing the last edit of your question i found the solution,

Just replace the below 2 lines

XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")

with

string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

It should solve your problem or you can use the solution i provided earlier.

"The system cannot find the file specified"

If you encounter this error in GoDaddy after deploying a .Net MVC web application..And your web.config is absolutely correct... Right click your data project select settings and make sure that the correct connection strings to the GoDaddy server is in use

Convert JsonObject to String

You can use reliable library GSON

private static final Type DATA_TYPE_JSON = 
        new TypeToken<JSONObject>() {}.getType();           
JSONObject orderJSON = new JSONObject();
orderJSON.put("noOfLayers", "2");
orderJSON.put("baseMaterial", "mat");
System.out.println("JSON == "+orderJSON.toString());
String dataAsJson = new Gson().toJson(orderJSON, DATA_TYPE_JSON);
System.out.println("Value of dataAsJson == "+dataAsJson.toString());
String data = new Gson().toJson(dataAsJson);
System.out.println("Value of jsonString == "+data.toString());

Can I serve multiple clients using just Flask app.run() as standalone?

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

Sound alarm when code finishes

On Windows

import winsound
duration = 1000  # milliseconds
freq = 440  # Hz
winsound.Beep(freq, duration)

Where freq is the frequency in Hz and the duration is in milliseconds.

On Linux and Mac

import os
duration = 1  # seconds
freq = 440  # Hz
os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))

In order to use this example, you must install sox.

On Debian / Ubuntu / Linux Mint, run this in your terminal:

sudo apt install sox

On Mac, run this in your terminal (using macports):

sudo port install sox

Speech on Mac

import os
os.system('say "your program has finished"')

Speech on Linux

import os
os.system('spd-say "your program has finished"')

You need to install the speech-dispatcher package in Ubuntu (or the corresponding package on other distributions):

sudo apt install speech-dispatcher

How does the Java 'for each' loop work?

The Java "for-each" loop construct will allow iteration over two types of objects:

  • T[] (arrays of any type)
  • java.lang.Iterable<T>

The Iterable<T> interface has only one method: Iterator<T> iterator(). This works on objects of type Collection<T> because the Collection<T> interface extends Iterable<T>.

Creating email templates with Django

Boys and Girls!

Since Django's 1.7 in send_email method the html_message parameter was added.

html_message: If html_message is provided, the resulting email will be a multipart/alternative email with message as the text/plain content type and html_message as the text/html content type.

So you can just:

from django.core.mail import send_mail
from django.template.loader import render_to_string


msg_plain = render_to_string('templates/email.txt', {'some_params': some_params})
msg_html = render_to_string('templates/email.html', {'some_params': some_params})

send_mail(
    'email title',
    msg_plain,
    '[email protected]',
    ['[email protected]'],
    html_message=msg_html,
)

How can I recover the return value of a function passed to multiprocessing.Process?

I modified vartec's answer a bit since I needed to get the error codes from the function. (Thanks vertec!!! its an awesome trick)

This can also be done with a manager.list but I think is better to have it in a dict and store a list within it. That way, way we keep the function and the results since we can't be sure of the order in which the list will be populated.

from multiprocessing import Process
import time
import datetime
import multiprocessing


def func1(fn, m_list):
    print 'func1: starting'
    time.sleep(1)
    m_list[fn] = "this is the first function"
    print 'func1: finishing'
    # return "func1"  # no need for return since Multiprocess doesnt return it =(

def func2(fn, m_list):
    print 'func2: starting'
    time.sleep(3)
    m_list[fn] = "this is function 2"
    print 'func2: finishing'
    # return "func2"

def func3(fn, m_list):
    print 'func3: starting'
    time.sleep(9)
    # if fail wont join the rest because it never populate the dict
    # or do a try/except to get something in return.
    raise ValueError("failed here")
    # if we want to get the error in the manager dict we can catch the error
    try:
        raise ValueError("failed here")
        m_list[fn] = "this is third"
    except:
        m_list[fn] = "this is third and it fail horrible"
        # print 'func3: finishing'
        # return "func3"


def runInParallel(*fns):  # * is to accept any input in list
    start_time = datetime.datetime.now()
    proc = []
    manager = multiprocessing.Manager()
    m_list = manager.dict()
    for fn in fns:
        # print fn
        # print dir(fn)
        p = Process(target=fn, name=fn.func_name, args=(fn, m_list))
        p.start()
        proc.append(p)
    for p in proc:
        p.join()  # 5 is the time out

    print datetime.datetime.now() - start_time
    return m_list, proc

if __name__ == '__main__':
    manager, proc = runInParallel(func1, func2, func3)
    # print dir(proc[0])
    # print proc[0]._name
    # print proc[0].name
    # print proc[0].exitcode

    # here you can check what did fail
    for i in proc:
        print i.name, i.exitcode  # name was set up in the Process line 53

    # here will only show the function that worked and where able to populate the 
    # manager dict
    for i, j in manager.items():
        print dir(i)  # things you can do to the function
        print i, j

multiple figure in latex with captions

Look at the Subfloats section of http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions.

\begin{figure}[htp]
  \centering
  \label{figur}\caption{equation...}

  \subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
  \subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
  \\
  \subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
  \subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
  \\
  \subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
  \subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}

\end{figure}

What is the difference between . (dot) and $ (dollar sign)?

One application that is useful and took me some time to figure out from the very short description at learn you a haskell: Since:

f $ x = f x

and parenthesizing the right hand side of an expression containing an infix operator converts it to a prefix function, one can write ($ 3) (4+) analogous to (++", world") "hello".

Why would anyone do this? For lists of functions, for example. Both:

map (++", world") ["hello","goodbye"]`

and:

map ($ 3) [(4+),(3*)]

are shorter than map (\x -> x ++ ", world") ... or map (\f -> f 3) .... Obviously, the latter variants would be more readable for most people.

'Incomplete final line' warning when trying to read a .csv file into R

I realized that several answers have been provided but no real fix yet.

The reason, as mentioned above, is a "End of line" missing at the end of the CSV file.

While the real Fix should come from Microsoft, the walk around is to open the CSV file with a Text-editor and add a line at the end of the file (aka press return key). I use ATOM software as a text/code editor but virtually all basic text editor would do.

In the meanwhile, please report the bug to Microsoft.

Question: It seems to me that it is a office 2016 problem. Does anyone have the issue on a PC?

How do I unload (reload) a Python module?

For Python 2 use built-in function reload():

reload(module)

For Python 2 and 3.2–3.3 use reload from module imp:

import imp
imp.reload(module)

But imp is deprecated since version 3.4 in favor of importlib, so use:

import importlib
importlib.reload(module)

or

from importlib import reload
reload(module)

Using global variables in a function

In addition to already existing answers and to make this more confusing:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Source: What are the rules for local and global variables in Python?.

How to delete multiple files at once in Bash on Linux?

Bash supports all sorts of wildcards and expansions.

Your exact case would be handled by brace expansion, like so:

$ rm -rf abc.log.2012-03-{14,27,28}

The above would expand to a single command with all three arguments, and be equivalent to typing:

$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28

It's important to note that this expansion is done by the shell, before rm is even loaded.

How to create a Java cron job

You can use TimerTask for Cronjobs.

Main.java

public class Main{
   public static void main(String[] args){

     Timer t = new Timer();
     MyTask mTask = new MyTask();
     // This task is scheduled to run every 10 seconds

     t.scheduleAtFixedRate(mTask, 0, 10000);
   }

}

MyTask.java

class MyTask extends TimerTask{

   public MyTask(){
     //Some stuffs
   }

   @Override
   public void run() {
     System.out.println("Hi see you after 10 seconds");
   }

}

Alternative You can also use ScheduledExecutorService.

Remove all git files from a directory?

In case someone else stumbles onto this topic - here's a more "one size fits all" solution.

If you are using .git or .svn, you can use the --exclude-vcs option for tar. This will ignore many different files/folders required by different version control systems.

If you want to read more about it, check out: http://www.gnu.org/software/tar/manual/html_section/exclude.html

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

In my case, this happens when I try to save an object in hibernate or other orm-mapping with null property which can not be null in database table. This happens when you try to save an object, but the save action doesn't comply with the contraints of the table.

Specify a Root Path of your HTML directory for script links?

Use two periods before /, example:

../style.css

convert string into array of integers

us the split function:

var splitresult = "14 2".split(" ");

How do you read CSS rule values with JavaScript?

Based on @dude answer this should return relevant styles in a object, for instance:

.recurly-input {                                                                                                                                                                             
  display: block;                                                                                                                                                                            
  border-radius: 2px;                                                                                                                                                                        
  -webkit-border-radius: 2px;                                                                                                                                                                
  outline: 0;                                                                                                                                                                                
  box-shadow: none;                                                                                                                                                                          
  border: 1px solid #beb7b3;                                                                                                                                                                 
  padding: 0.6em;                                                                                                                                                                            
  background-color: #f7f7f7;                                                                                                                                                                 
  width:100%;                                                                                                                                                                                
}

This will return:

backgroundColor:
"rgb(247, 247, 247)"
border
:
"1px solid rgb(190, 183, 179)"
borderBottom
:
"1px solid rgb(190, 183, 179)"
borderBottomColor
:
"rgb(190, 183, 179)"
borderBottomLeftRadius
:
"2px"
borderBottomRightRadius
:
"2px"
borderBottomStyle
:
"solid"
borderBottomWidth
:
"1px"
borderColor
:
"rgb(190, 183, 179)"
borderLeft
:
"1px solid rgb(190, 183, 179)"
borderLeftColor
:
"rgb(190, 183, 179)"
borderLeftStyle
:
"solid"
borderLeftWidth
:
"1px"
borderRadius
:
"2px"
borderRight
:
"1px solid rgb(190, 183, 179)"
borderRightColor
:
"rgb(190, 183, 179)"
borderRightStyle
:
"solid"
borderRightWidth
:
"1px"
borderStyle
:
"solid"
borderTop
:
"1px solid rgb(190, 183, 179)"
borderTopColor
:
"rgb(190, 183, 179)"
borderTopLeftRadius
:
"2px"
borderTopRightRadius
:
"2px"
borderTopStyle
:
"solid"
borderTopWidth
:
"1px"
borderWidth
:
"1px"
boxShadow
:
"none"
display
:
"block"
outline
:
"0px"
outlineWidth
:
"0px"
padding
:
"0.6em"
paddingBottom
:
"0.6em"
paddingLeft
:
"0.6em"
paddingRight
:
"0.6em"
paddingTop
:
"0.6em"
width
:
"100%"

Code:

function getStyle(className_) {

    var styleSheets = window.document.styleSheets;
    var styleSheetsLength = styleSheets.length;
    for(var i = 0; i < styleSheetsLength; i++){
        var classes = styleSheets[i].rules || styleSheets[i].cssRules;
        if (!classes)
            continue;
        var classesLength = classes.length;
        for (var x = 0; x < classesLength; x++) {
            if (classes[x].selectorText == className_) {
                return _.pickBy(classes[x].style, (v, k) => isNaN(parseInt(k)) && typeof(v) == 'string' && v && v != 'initial' && k != 'cssText' )
            }
        }
    }

}

DLL load failed error when importing cv2

After spending too much time on this issue and trying out all different answers, here is what found:

  • The accepted answer by @thewaywewere is no longer applicable. I think this was applicable when opencv-python module still wasn't available.

  • This is indeed a bug in Anaconda 4.2 because they forgot to ship python3.dll. They have fixed this in next releases but unfortunately 4.2 is the last release with Python 3.5 as default. If you are stuck with Python 3.5 (for example VS2015 is only aware of versions up to 3.5) then you must manually download python3.dll as described in answer by @Ramesh-X.

  • If you can move on to Python 3.6 (which at present bit difficult if you are using OpenCV and VS2015) then just install latest Anaconda version and you don't have to deal with any of these.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

One liner to check if element is in the list

I would use:

if (Stream.of("a","b","c").anyMatch("a"::equals)) {
    //Code to execute
};

or:

Stream.of("a","b","c")
    .filter("a"::equals)
    .findAny()
    .ifPresent(ignore -> /*Code to execute*/);

PostgreSQL Exception Handling

To catch the error message and its code:

do $$       
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

    raise notice '% %', SQLERRM, SQLSTATE;

end; $$ 
language 'plpgsql';

Haven't found the line number yet

UPDATE April, 16, 2019

As suggested by Diego Scaravaggi, for Postgres 9.2 and up, use GET STACKED DIAGNOSTICS:

do language plpgsql $$
declare
    v_state   TEXT;
    v_msg     TEXT;
    v_detail  TEXT;
    v_hint    TEXT;
    v_context TEXT;
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    get stacked diagnostics
        v_state   = returned_sqlstate,
        v_msg     = message_text,
        v_detail  = pg_exception_detail,
        v_hint    = pg_exception_hint,
        v_context = pg_exception_context;

    raise notice E'Got exception:
        state  : %
        message: %
        detail : %
        hint   : %
        context: %', v_state, v_msg, v_detail, v_hint, v_context;

    raise notice E'Got exception:
        SQLSTATE: % 
        SQLERRM: %', SQLSTATE, SQLERRM;     

    raise notice '%', message_text; -- invalid. message_text is contextual to GET STACKED DIAGNOSTICS only

end; $$;

Result:

NOTICE:  Got exception:
        state  : 42P07
        message: relation "yyy" already exists
        detail : 
        hint   : 
        context: SQL statement "create table yyy(a int)"
PL/pgSQL function inline_code_block line 11 at SQL statement
NOTICE:  Got exception:
        SQLSTATE: 42P07 
        SQLERRM: relation "yyy" already exists

ERROR:  column "message_text" does not exist
LINE 1: SELECT message_text
               ^
QUERY:  SELECT message_text
CONTEXT:  PL/pgSQL function inline_code_block line 33 at RAISE
SQL state: 42703

Aside from GET STACKED DIAGNOSTICS is SQL standard-compliant, its diagnostics variables (e.g., message_text) are contextual to GSD only. So if you have a field named message_text in your table, there's no chance that GSD can interfere with your field's value.

Still no line number though.

CSS transition fade on hover

I recommend you to use an unordered list for your image gallery.

You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.

#photos li {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;
}

#photos li:hover {
    opacity: 1;
}

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

This is the proper way to access data in laravel :

@foreach($data-> ac as $link) 

   {{$link->url}}

@endforeach

What's the best/easiest GUI Library for Ruby?

Try shoes. Unfortunately, I have not had a chance to work with it yet, but I have an upcoming project where I plan to use it. It is cross-platform. Also the API looks very Rubyish so I would give it a try.

get name of a variable or parameter

Pre C# 6.0 solution

You can use this to get a name of any provided member:

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

To get name of a variable:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}

C# 6.0 and higher solution

You can use the nameof operator for parameters, variables and properties alike:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

Detecting which UIButton was pressed in a UITableView

In Apple's Accessory sample the following method is used:

[button addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

Then in touch handler touch coordinate retrieved and index path is calculated from that coordinate:

- (void)checkButtonTapped:(id)sender
{
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)
    {
     ...
    }
}

How do I use Join-Path to combine more than two strings into a file path?

The following approach is more concise than piping Join-Path statements:

$p = "a"; "b", "c", "d" | ForEach-Object -Process { $p = Join-Path $p $_ }

$p then holds the concatenated path 'a\b\c\d'.

(I just noticed that this is the exact same approach as Mike Fair's, sorry.)

Sleep function in C++

On Unix, include #include <unistd.h>.

The call you're interested in is usleep(). Which takes microseconds, so you should multiply your millisecond value by 1000 and pass the result to usleep().

How to convert CSV file to multiline JSON?

You can use Pandas DataFrame to achieve this, with the following Example:

import pandas as pd
csv_file = pd.DataFrame(pd.read_csv("path/to/file.csv", sep = ",", header = 0, index_col = False))
csv_file.to_json("/path/to/new/file.json", orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)

Regular expression to match any character being repeated more than 10 times

On some apps you need to remove the slashes to make it work.

/(.)\1{9,}/

or this:

(.)\1{9,}

How can I assign the output of a function to a variable using bash?

VAR=$(scan)

Exactly the same way as for programs.

MVC 3 file upload and model binding

1st download jquery.form.js file from below url

http://plugins.jquery.com/form/

Write below code in cshtml

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmTemplateUpload" }))
{
    <div id="uploadTemplate">

        <input type="text" value="Asif" id="txtname" name="txtName" />


        <div id="dvAddTemplate">
            Add Template
            <br />
            <input type="file" name="file" id="file" tabindex="2" />
            <br />
            <input type="submit" value="Submit" />
            <input type="button" id="btnAttachFileCancel" tabindex="3" value="Cancel" />
        </div>

        <div id="TemplateTree" style="overflow-x: auto;"></div>
    </div>

    <div id="progressBarDiv" style="display: none;">
        <img id="loading-image" src="~/Images/progress-loader.gif" />
    </div>

}


<script type="text/javascript">

    $(document).ready(function () {
        debugger;
        alert('sample');
        var status = $('#status');
        $('#frmTemplateUpload').ajaxForm({
            beforeSend: function () {
                if ($("#file").val() != "") {
                    //$("#uploadTemplate").hide();
                    $("#btnAction").hide();
                    $("#progressBarDiv").show();
                    //progress_run_id = setInterval(progress, 300);
                }
                status.empty();
            },
            success: function () {
                showTemplateManager();
            },
            complete: function (xhr) {
                if ($("#file").val() != "") {
                    var millisecondsToWait = 500;
                    setTimeout(function () {
                        //clearInterval(progress_run_id);
                        $("#uploadTemplate").show();
                        $("#btnAction").show();
                        $("#progressBarDiv").hide();
                    }, millisecondsToWait);
                }
                status.html(xhr.responseText);
            }
        });

    });


</script>

Action method :-

 public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

 public void Upload(HttpPostedFileBase file, string txtname )
        {

            try
            {
                string attachmentFilePath = file.FileName;
                string fileName = attachmentFilePath.Substring(attachmentFilePath.LastIndexOf("\\") + 1);

           }
            catch (Exception ex)
            {

            }
        }

How to set column header text for specific column in Datagridview C#

Dg_View.Columns.Add("userid","User Id");
Dg_View.Columns[0].Width = 100;

Dg_View.Columns.Add("username", "User name");
Dg_View.Columns[0].Width = 100;

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

Look for any DDL operation in the script. Maybe the user does not have access rights to run changes.

In my case it was SET IDENTITY_INSERT tblTableName ON

You can either add db_ddladmin for the whole database or for just the table to solve this issue (or change the script)

-- give the non-ddladmin user INSERT/SELECT as well as ALTER:
GRANT ALTER, INSERT, SELECT ON dbo.tblTableName TO user_name;

Test if numpy array contains only zeros

This will work.

def check(arr):
    if np.all(arr == 0):
        return True
    return False

PHP passing $_GET in linux command prompt

Typically, for passing arguments to a command line script, you will use either argv global variable or getopt:

// bash command:
//   php -e myscript.php hello
echo $argv[1]; // prints hello

// bash command:
//   php -e myscript.php -f=world
$opts = getopt('f:');
echo $opts['f']; // prints world

$_GET refers to the HTTP GET method parameters, which are unavailable in command line, since they require a web server to populate.

If you really want to populate $_GET anyway, you can do this:

// bash command:
//   export QUERY_STRING="var=value&arg=value" ; php -e myscript.php
parse_str($_SERVER['QUERY_STRING'], $_GET);
print_r($_GET);
/* outputs:
     Array(
        [var] => value
        [arg] => value
     )
*/

You can also execute a given script, populate $_GET from the command line, without having to modify said script:

export QUERY_STRING="var=value&arg=value" ; \
php -e -r 'parse_str($_SERVER["QUERY_STRING"], $_GET); include "index.php";'

Note that you can do the same with $_POST and $_COOKIE as well.

Create a temporary table in a SELECT statement without a separate CREATE TABLE

CREATE TEMPORARY TABLE IF NOT EXISTS to_table_name AS (SELECT * FROM from_table_name)

SSL peer shut down incorrectly in Java

I had mutual SSL enabled on my Spring Boot app and my Jenkins pipeline was re-building the dockers, bringing the compose up and then running integration tests which failed every time with this error. I was able to test the running dockers without this SSL error every time in a standalone test on the same Jenkins machine. It turned out that server was not completely up when the tests started executing. Putting a sleep of few seconds in my bash script to allow Spring boot application to be up and running completely resolved the issue.

Unexpected token }

Try running the entire script through jslint. This may help point you at the cause of the error.

Edit Ok, it's not quite the syntax of the script that's the problem. At least not in a way that jslint can detect.

Having played with your live code at http://ft2.hostei.com/ft.v1/, it looks like there are syntax errors in the generated code that your script puts into an onclick attribute in the DOM. Most browsers don't do a very good job of reporting errors in JavaScript run via such things (what is the file and line number of a piece of script in the onclick attribute of a dynamically inserted element?). This is probably why you get a confusing error message in Chrome. The FireFox error message is different, and also doesn't have a useful line number, although FireBug does show the code which causes the problem.

This snippet of code is taken from your edit function which is in the inline script block of your HTML:

var sub = document.getElementById('submit');
...
sub.setAttribute("onclick", "save(\""+file+"\", document.getElementById('name').value, document.getElementById('text').value");

Note that this sets the onclick attribute of an element to invalid JavaScript code:

<input type="submit" id="submit" onclick="save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value">

The JS is:

save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value

Note the missing close paren to finish the call to save.

As an aside, inserting onclick attributes is not a very modern or clean way of adding event handlers in JavaScript. Why are you not using the DOM's addEventListener to simply hook up a function to the element? If you were using something like jQuery, this would be simpler still.

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

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

Multiple commands on a single line in a Windows batch file

Use:

echo %time% & dir & echo %time%

This is, from memory, equivalent to the semi-colon separator in bash and other UNIXy shells.

There's also && (or ||) which only executes the second command if the first succeeded (or failed), but the single ampersand & is what you're looking for here.


That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.

You can get round this by turning on delayed expansion:

pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85

That's needed from the command line. If you're doing this inside a script, you can just use setlocal:

@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal

How to clear/delete the contents of a Tkinter Text widget?

A lot of answers ask you to use END, but if that's not working for you, try:

text.delete("1.0", "end-1c")

How to send parameters with jquery $.get()

Try this:

$.ajax({
    type: 'get',
    url: 'manageproducts.do',
    data: 'option=1',
    success: function(data) {

        availableProductNames = data.split(",");

        alert(availableProductNames);

    }
});

Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.

Body set to overflow-y:hidden but page is still scrollable in Chrome

Try this when you want to "fix" your body's scroll:

jQuery('body').css('height', '100vh').css('overflow-y', 'hidden');

and this when you want to turn it normal again:

jQuery('body').css('height', '').css('overflow-y', '');

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

An extension to what GenericTypeTea says - Here is a concrete example:

<form onsubmit="return false">

The above form will not submit, whereas...

<form onsubmit="false">

...does nothing, i.e. the form will submit.

Without the return, onsubmit doesn't receive a value and the event is executed just like without any handler at all.

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

unlinkr function recursively deletes all the folders and files in given path by making sure it doesn't delete the script itself.

function unlinkr($dir, $pattern = "*") {
    // find all files and folders matching pattern
    $files = glob($dir . "/$pattern"); 

    //interate thorugh the files and folders
    foreach($files as $file){ 
    //if it is a directory then re-call unlinkr function to delete files inside this directory     
        if (is_dir($file) and !in_array($file, array('..', '.')))  {
            echo "<p>opening directory $file </p>";
            unlinkr($file, $pattern);
            //remove the directory itself
            echo "<p> deleting directory $file </p>";
            rmdir($file);
        } else if(is_file($file) and ($file != __FILE__)) {
            // make sure you don't delete the current script
            echo "<p>deleting file $file </p>";
            unlink($file); 
        }
    }
}

if you want to delete all files and folders where you place this script then call it as following

//get current working directory
$dir = getcwd();
unlinkr($dir);

if you want to just delete just php files then call it as following

unlinkr($dir, "*.php");

you can use any other path to delete the files as well

unlinkr("/home/user/temp");

This will delete all files in home/user/temp directory.

How do you check if a selector matches something in jQuery?

firstly create a function:

$.fn.is_exists = function(){ return document.getElementById(selector) }

then

if($(selector).is_exists()){ ... }

Change status bar color with AppCompat ActionBarActivity

I don't think the status bar color has been implemented in AppCompat yet. These are the attributes which are available:

    <!-- ============= -->
    <!-- Color palette -->
    <!-- ============= -->

    <!-- The primary branding color for the app. By default, this is the color applied to the
         action bar background. -->
    <attr name="colorPrimary" format="color" />

    <!-- Dark variant of the primary branding color. By default, this is the color applied to
         the status bar (via statusBarColor) and navigation bar (via navigationBarColor). -->
    <attr name="colorPrimaryDark" format="color" />

    <!-- Bright complement to the primary branding color. By default, this is the color applied
         to framework controls (via colorControlActivated). -->
    <attr name="colorAccent" format="color" />

    <!-- The color applied to framework controls in their normal state. -->
    <attr name="colorControlNormal" format="color" />

    <!-- The color applied to framework controls in their activated (ex. checked) state. -->
    <attr name="colorControlActivated" format="color" />

    <!-- The color applied to framework control highlights (ex. ripples, list selectors). -->
    <attr name="colorControlHighlight" format="color" />

    <!-- The color applied to framework buttons in their normal state. -->
    <attr name="colorButtonNormal" format="color" />

    <!-- The color applied to framework switch thumbs in their normal state. -->
    <attr name="colorSwitchThumbNormal" format="color" />

(From \sdk\extras\android\support\v7\appcompat\res\values\attrs.xml)

Set System.Drawing.Color values

using System;
using System.Drawing;
public struct MyColor
    {
        private byte a, r, g, b;        
        public byte A
        {
            get
            {
                return this.a;
            }
        }
        public byte R
        {
            get
            {
                return this.r;
            }
        }
        public byte G
        {
            get
            {
                return this.g;
            }
        }
        public byte B
        {
            get
            {
                return this.b;
            }
        }       
        public MyColor SetAlpha(byte value)
        {
            this.a = value;
            return this;
        }
        public MyColor SetRed(byte value)
        {
            this.r = value;
            return this;
        }
        public MyColor SetGreen(byte value)
        {
            this.g = value;
            return this;
        }
        public MyColor SetBlue(byte value)
        {
            this.b = value;
            return this;
        }
        public int ToArgb()
        {
            return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
        }
        public override string ToString ()
        {
            return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
        }

        public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
        {
            return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
        }
        public static MyColor FromArgb(byte red, byte green, byte blue)
        {
            return MyColor.FromArgb(255, red, green, blue);
        }
        public static MyColor FromArgb(byte alpha, MyColor baseColor)
        {
            return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
        }
        public static MyColor FromArgb(int argb)
        {
            return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
        }   
        public static implicit operator Color(MyColor myColor)
        {           
            return Color.FromArgb(myColor.ToArgb());
        }
        public static implicit operator MyColor(Color color)
        {
            return MyColor.FromArgb(color.ToArgb());
        }
    }

How to Retrieve value from JTextField in Java Swing?

You can use the getText() method anywhere in your code it is instancely called by your object, So you can use the method anywhere within a calass

jQuery: serialize() form and other parameters

serialize() effectively turns the form values into a valid querystring, as such you can simply append to the string:

$.ajax({
    type : 'POST',
    url : 'url',
    data : $('#form').serialize() + "&par1=1&par2=2&par3=232"
}

How to find the kth largest element in an unsorted array of length n in O(n)?

i would like to suggest one answer

if we take the first k elements and sort them into a linked list of k values

now for every other value even for the worst case if we do insertion sort for rest n-k values even in the worst case number of comparisons will be k*(n-k) and for prev k values to be sorted let it be k*(k-1) so it comes out to be (nk-k) which is o(n)

cheers

How to check if a file exists in a folder?

This way we can check for an existing file in a particular folder:

 string curFile = @"c:\temp\test.txt";  //Your path
 Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");

Can media queries resize based on a div element instead of the screen?

I ran into the same problem a couple of years ago and funded the development of a plugin to help me in my work. I've released the plugin as open-source so others can benefit from it as well, and you can grab it on Github: https://github.com/eqcss/eqcss

There are a few ways we could apply different responsive styles based on what we can know about an element on the page. Here are a few element queries that the EQCSS plugin will let you write in CSS:

@element 'div' and (condition) {
  $this {
    /* Do something to the 'div' that meets the condition */
  }
  .other {
    /* Also apply this CSS to .other when 'div' meets this condition */
  }
}

So what conditions are supported for responsive styles with EQCSS?

Weight Queries

  • min-width in px
  • min-width in %
  • max-width in px
  • max-width in %

Height Queries

  • min-height in px
  • min-height in %
  • max-height in px
  • max-height in %

Count Queries

  • min-characters
  • max-characters
  • min-lines
  • max-lines
  • min-children
  • max-children

Special Selectors

Inside EQCSS element queries you can also use three special selectors that allow you to more specifically apply your styles:

  • $this (the element(s) matching the query)
  • $parent (the parent element(s) of the element(s) matching the query)
  • $root (the root element of the document, <html>)

Element queries allow you to compose your layout out of individually responsive design modules, each with a bit of 'self-awareness' of how they are being displayed on the page.

With EQCSS you can design one widget to look good from 150px wide all the way up to 1000px wide, then you can confidently drop that widget into any sidebar in any page using any template (on any site) and

How do I convert from stringstream to string in C++?

Use the .str()-method:

Manages the contents of the underlying string object.

1) Returns a copy of the underlying string as if by calling rdbuf()->str().

2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)...

Notes

The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer...

How to truncate a foreign key constrained table?

Just use CASCADE

TRUNCATE "products" RESTART IDENTITY CASCADE;

But be ready for cascade deletes )

jQuery: how do I animate a div rotation?

Make use of WebkitTransform / -moz-transform: rotate(Xdeg). This will not work in IE, but Matt's zachstronaut solution doesn't work in IE either.

If you want to support IE too, you'll have to look into using a canvas like I believe Raphael does.

Here is a simple jQuery snippet that rotates the elements in a jQuery object. Rotation can be started and stopped:

_x000D_
_x000D_
$(function() {_x000D_
    var $elie = $("img"), degree = 0, timer;_x000D_
    rotate();_x000D_
    function rotate() {_x000D_
        _x000D_
        $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});  _x000D_
        $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});                      _x000D_
        timer = setTimeout(function() {_x000D_
            ++degree; rotate();_x000D_
        },5);_x000D_
    }_x000D_
    _x000D_
    $("input").toggle(function() {_x000D_
        clearTimeout(timer);_x000D_
    }, function() {_x000D_
        rotate();_x000D_
    });_x000D_
}); 
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>_x000D_
<input type="button" value=" Toggle Spin " />_x000D_
<br/><br/><br/><br/>_x000D_
<img src="http://i.imgur.com/ABktns.jpg" />
_x000D_
_x000D_
_x000D_

GridView sorting: SortDirection always Ascending

I got tired of dealing with this issue and put the sort direction and sort column in the ViewState....

Python handling socket.error: [Errno 104] Connection reset by peer

There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error. This example also catches the timeout.

from urllib.request import urlopen 
from socket import timeout

url = "http://......"
try: 
    string = urlopen(url, timeout=5).read()
except ConnectionResetError:
    print("==> ConnectionResetError")
    pass
except timeout: 
    print("==> Timeout")
    pass

rsync: difference between --size-only and --ignore-times

On a Scientific Linux 6.7 system, the man page on rsync says:

--ignore-times          don't skip files that match size and time

I have two files with identical contents, but with different creation dates:

[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron

[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/new/usercron

With --size-only, the two files are regarded the same:

[root@windstorm ~]# rsync -v --size-only -n  /tmp/new/usercron /tmp/master/usercron

sent 29 bytes  received 12 bytes  82.00 bytes/sec
total size is 1595  speedup is 38.90 (DRY RUN)

With --ignore-times, the two files are regarded different:

[root@windstorm ~]# rsync -v --ignore-times -n  /tmp/new/usercron /tmp/master/usercron
usercron

sent 32 bytes  received 15 bytes  94.00 bytes/sec
total size is 1595  speedup is 33.94 (DRY RUN)

So it does not looks like --ignore-times has any effect at all.

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

Because a 32-bit floating-point number - such as 1.024 - is not 1.024. In a computer, 1.024 is an interval: from (1.024-e) to (1.024+e), where "e" represents an error. Some people fail to realize this and also believe that * in a*a stands for multiplication of arbitrary-precision numbers without there being any errors attached to those numbers. The reason why some people fail to realize this is perhaps the math computations they exercised in elementary schools: working only with ideal numbers without errors attached, and believing that it is OK to simply ignore "e" while performing multiplication. They do not see the "e" implicit in "float a=1.2", "a*a*a" and similar C codes.

Should majority of programmers recognize (and be able to execute on) the idea that C expression a*a*a*a*a*a is not actually working with ideal numbers, the GCC compiler would then be FREE to optimize "a*a*a*a*a*a" into say "t=(a*a); t*t*t" which requires a smaller number of multiplications. But unfortunately, the GCC compiler does not know whether the programmer writing the code thinks that "a" is a number with or without an error. And so GCC will only do what the source code looks like - because that is what GCC sees with its "naked eye".

... once you know what kind of programmer you are, you can use the "-ffast-math" switch to tell GCC that "Hey, GCC, I know what I am doing!". This will allow GCC to convert a*a*a*a*a*a into a different piece of text - it looks different from a*a*a*a*a*a - but still computes a number within the error interval of a*a*a*a*a*a. This is OK, since you already know you are working with intervals, not ideal numbers.

delete image from folder PHP

<?php

    require 'database.php';

    $id = $_GET['id'];

    $image = "SELECT * FROM slider WHERE id = '$id'";
    $query = mysqli_query($connect, $image);
    $after = mysqli_fetch_assoc($query);

    if ($after['image'] != 'default.png') {
        unlink('../slider/'.$after['image']);
    }

    $delete = "DELETE FROM slider WHERE id = $id";
    $query = mysqli_query($connect, $delete);

    if ($query) {
        header('location: slider.php');
    }

?>

How to resize html canvas element?

You didn't publish your code, and I suspect you do something wrong. it is possible to change the size by assigning width and height attributes using numbers:

canvasNode.width  = 200; // in pixels
canvasNode.height = 100; // in pixels

At least it works for me. Make sure you don't assign strings (e.g., "2cm", "3in", or "2.5px"), and don't mess with styles.

Actually this is a publicly available knowledge — you can read all about it in the HTML canvas spec — it is very small and unusually informative. This is the whole DOM interface:

interface HTMLCanvasElement : HTMLElement {
           attribute unsigned long width;
           attribute unsigned long height;

  DOMString toDataURL();
  DOMString toDataURL(in DOMString type, [Variadic] in any args);

  DOMObject getContext(in DOMString contextId);
};

As you can see it defines 2 attributes width and height, and both of them are unsigned long.

Show div when radio button selected

 $('input[type="radio"]').change(function(){
      if($("input[name='group']:checked")){
      $(div).show();
    }
  });

Saving ssh key fails

For windows use enter button 3 times

Enter file in which to save the key (/c/Users/Rupesh/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again:

its work for me...

not:first-child selector

As I used ul:not(:first-child) is a perfect solution.

div ul:not(:first-child) {
    background-color: #900;
}

Why is this a perfect because by using ul:not(:first-child), we can apply CSS on inner elements. Like li, img, span, a tags etc.

But when used others solutions:

div ul + ul {
  background-color: #900;
}

and

div li~li {
    color: red;
}

and

ul:not(:first-of-type) {}

and

div ul:nth-child(n+2) {
    background-color: #900;
}

These restrict only ul level CSS. Suppose we cannot apply CSS on li as `div ul + ul li'.

For inner level elements the first Solution works perfectly.

div ul:not(:first-child) li{
        background-color: #900;
    }

and so on ...

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

insert data from one table to another in mysql

INSERT INTO mt_magazine_subscription ( 
      magazine_subscription_id, 
      subscription_name, 
      magazine_id, 
      status ) 
VALUES ( 
      (SELECT magazine_subscription_id, 
              subscription_name, 
              magazine_id,'1' as status
       FROM tbl_magazine_subscription 
       ORDER BY magazine_subscription_id ASC));

XPath to fetch SQL XML value

I think the xpath query you want goes something like this:

/xml/box[@stepId="$stepId"]/components/component[@id="$componentId"]/variables/variable[@nom="Enabled" and @valeur="Yes"]

This should get you the variables that are named "Enabled" with a value of "Yes" for the specified $stepId and $componentId. This is assuming that your xml starts with an tag like you show, and not

If the SQL Server 2005 XPath stuff is pretty straightforward (I've never used it), then the above query should work. Otherwise, someone else may have to help you with that.

How to delete the top 1000 rows from a table using Sql Server 2008?

SET ROWCOUNT 1000;

DELETE FROM [MyTable] WHERE .....

How to define Singleton in TypeScript

Not a pure singleton (initialization may be not lazy), but similar pattern with help of namespaces.

namespace MyClass
{
    class _MyClass
    {
    ...
    }
    export const instance: _MyClass = new _MyClass();
}

Access to object of Singleton:

MyClass.instance

Run C++ in command prompt - Windows

  1. Download MinGW form : https://sourceforge.net/projects/mingw-w64/
  2. use notepad++ to write the C++ source code.
  3. using command line change the directory/folder where the source code is saved(using notepad++)
  4. compile: g++ file_name.cpp -o file_name.exe
  5. run the executable: file_name.exe

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

Output an Image in PHP

header('Content-type: image/jpeg');
readfile($image);

Mac SQLite editor

That FireFox extension looks pretty nice. I've used SQLite Browser in the past and it did the job.

What's the difference between an element and a node in XML?

A node is defined as:

the smallest unit of a valid, complete structure in a document.

or as:

An object in the tree view that serves as a container to hold related objects.

Now their are many different kinds of nodes as an elements node, an attribute node etc.

How to clear browser cache with php?

With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');

How to POST form data with Spring RestTemplate?

Your url String needs variable markers for the map you pass to work, like:

String url = "https://app.example.com/hr/email?{email}";

Or you could explicitly code the query params into the String to begin with and not have to pass the map at all, like:

String url = "https://app.example.com/hr/[email protected]";

See also https://stackoverflow.com/a/47045624/1357094

Return back to MainActivity from another activity

Here's why you saw the menu with the code you listed in your onClick method:

You were creating an Intent with the constructor that takes a string for the action parameter of the Intent's IntentFilter. You passed "android.intent.action.MAIN" as the argument to that constructor, which specifies that the Intent can be satisfied by any Activity with an IntentFilter including <action="android.intent.action.MAIN">.

When you called startActivity with that Intent, you effectively told the Android OS to go find an Activity (in any app installed on the system) that specifies the android.intent.action.MAIN action. When there are multiple Activities that qualify (and there are in this case since every app will have a main Activity with an IntentFilter including the "android.intent.action.MAIN" action), the OS presents a menu to let the user choose which app to use.

As to the question of how to get back to your main activity, as with most things, it depends on the specifics of your app. While the accepted answer probably worked in your case, I don't think it's the best solution, and it's probably encouraging you to use a non-idiomatic UI in your Android app. If your Button's onClick() method contains only a call to finish() then you should most likely remove the Button from the UI and just let the user push the hardware/software back button, which has the same functionality and is idiomatic for Android. (You'll often see back Buttons used to emulate the behavior of an iOS UINavigationController navigationBar which is discouraged in Android apps).

If your main activity launches a stack of Activities and you want to provide an easy way to get back to the main activity without repeatedly pressing the back button, then you want to call startActivity after setting the flag Intent.FLAG_ACTIVITY_CLEAR_TOP which will close all the Activities in the call stack which are above your main activity and bring your main activity to the top of the call stack. See below (assuming your main activity subclass is called MainActivity:

btnReturn1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent i=new Intent(this, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
    }
)};

ArrayList - How to modify a member of an object?

I wrote you 2 classes to show you how it's done; Main and Customer. If you run the Main class you see what's going on:

import java.util.*;

public class Customer {

    private String name;
    private String email;

    public Customer(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return name + " | " + email;
    }

    public static String toString(Collection<Customer> customers) {
        String s = "";
        for(Customer customer : customers) {
            s += customer + "\n";
        }
        return s;
    }

}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer("Bert", "[email protected]"));
        customers.add(new Customer("Ernie", "[email protected]"));
        System.out.println("customers before email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
        customers.get(1).setEmail("[email protected]");
        System.out.println("customers after email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
    }

}

to get this running, make 2 classes, Main and Customer and copy paste the contents from both classes to the correct class; then run the Main class.

Does mobile Google Chrome support browser extensions?

Just use a different browser. Follow the steps given below to install Chrome extensions on your Android device.

Step 1: Open Google Play Store and download Yandex Browser. Install the browser on your phone.

Step 2: In the URL box of your new browser, open 'chrome.google.com/webstore’ by entering the same in the URL address.

Step 3: Look for the Chrome extension that you want and once you have it, tap on 'Add to Chrome.’

The added Chrome extension will now be automatically added to the Yandex browser.

How to check if an element exists in the xml using xpath?

If boolean() is not available (the tool I'm using does not) one way to achieve it is:

//SELECT[@id='xpto']/OPTION[not(not(@selected))]

In this case, within the /OPTION, one of the options is the selected one. The "selected" does not have a value... it just exists, while the other OPTION do not have "selected". This achieves the objective.

Creating a JavaScript cookie on a domain and reading it across sub domains

You can also use the Cookies API and do:

browser.cookies.set({
  url: 'example.com',
  name: 'HelloWorld',
  value: 'HelloWorld',
  expirationDate: myDate
}

MDN Set() Method Documentation

auto refresh for every 5 mins

Refresh document every 300 seconds using HTML Meta tag add this inside the head tag of the page

 <meta http-equiv="refresh" content="300">

Using Script:

            setInterval(function() {
                  window.location.reload();
                }, 300000); 

What is the correct way to read a serial port using .NET framework?

    using System;
    using System.IO.Ports;
    using System.Threading;

    namespace SerialReadTest
    {
        class SerialRead
        {
            static void Main(string[] args)
            {
        Console.WriteLine("Serial read init");
        SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
        port.Open();
        while(true){
          Console.WriteLine(port.ReadLine());
        }

    }
}
}

Webdriver Screenshot

I understand you are looking for an answer in python, but here is how one would do it in ruby..

http://watirwebdriver.com/screenshots/

If that only works by saving in current directory only.. I would first assign the image to a variable and then save that variable to disk as a PNG file.

eg:

 image = b.screenshot.png

 File.open("testfile.png", "w") do |file|
  file.puts "#{image}"
 end

where b is the browser variable used by webdriver. i have the flexibility to provide an absolute or relative path in "File.open" so I can save the image anywhere.

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Usually the problem is not closing brackets (}) or missing semicolon (;)

Read the package name of an Android APK

You can extract AndroidManifest.xml from the APK, remove all NULL bytes, skip everything until after the string 'manifest', and then you are at a length byte followed by the package name (and what comes after it). For the difficult task I use the great GEMA tool, so the command looks like this:

7z e -so MyApp.apk AndroidManifest.xml | gema '\x00=' | gema -match 'manifest<U1><U>=@substring{0;@char-int{$1};$2}'

Of course, you can use any other tool to do the filtering.

Formula px to dp, dp to px android

Note: The widely used solution above is based on displayMetrics.density. However, the docs explain that this value is a rounded value, used with the screen 'buckets'. Eg. on my Nexus 10 it returns 2, where the real value would be 298dpi (real) / 160dpi (default) = 1.8625.

Depending on your requirements, you might need the exact transformation, which can be achieved like this:

[Edit] This is not meant to be mixed with Android's internal dp unit, as this is of course still based on the screen buckets. Use this where you want a unit that should render the same real size on different devices.

Convert dp to pixel:

public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));     
}

Convert pixel to dp:

public int pxToDp(int px) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}

Note that there are xdpi and ydpi properties, you might want to distinguish, but I can't imagine a sane display where these values differ greatly.

Format number to always show 2 decimal places

If you're already using jQuery, you could look at using the jQuery Number Format plugin.

The plugin can return formatted numbers as a string, you can set decimal, and thousands separators, and you can choose the number of decimals to show.

$.number( 123, 2 ); // Returns '123.00'

You can also get jQuery Number Format from GitHub.

link_to method and click event in Rails

You can use link_to_function (removed in Rails 4.1):

link_to_function 'My link with obtrusive JavaScript', 'alert("Oh no!")'

Or, if you absolutely need to use link_to:

link_to 'Another link with obtrusive JavaScript', '#',
        :onclick => 'alert("Please no!")'

However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.

Instead, your Rails code should simply be something like this:

link_to 'Link with unobtrusive JavaScript',
        '/actual/url/in/case/javascript/is/broken',
        :id => 'my-link'

And assuming you're using the Prototype JS framework, JS like this in your application.js:

$('my-link').observe('click', function (event) {
  alert('Hooray!');
  event.stop(); // Prevent link from following through to its given href
});

Or if you're using jQuery:

$('#my-link').click(function (event) {
  alert('Hooray!');
  event.preventDefault(); // Prevent link from following its href
});

By using this third technique, you guarantee that the link will follow through to some other page—not just fail silently—if JavaScript is unavailable for the user. Remember, JS could be unavailable because the user has a poor internet connection (e.g., mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (i.e., developer error).

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

Many things changed since 2009, but I can only find answers saying you need to use NamedParametersJDBCTemplate.

For me it works if I just do a

db.query(sql, new MyRowMapper(), StringUtils.join(listeParamsForInClause, ","));

using SimpleJDBCTemplate or JDBCTemplate

Eclipse error: R cannot be resolved to a variable

I assume you have updated ADT with version 22 and R.java file is not getting generated.

If this is the case, then here is the solution:

Hope you know Android studio has gradle building tool. Same as in eclipse they have given new component in the Tools folder called Android SDK Build-tools that needs to be installed. Open the Android SDK Manager, select the newly added build tools, install it, restart the SDK Manager after the update.

enter image description here

How to downgrade Node version

Try using the following commands

//For make issues 
sudo apt-get install build-essential

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.4/install.sh | bash

//To uninstall a node version 
nvm uninstall <current version>

nvm install 6.10.3

nvm use 6.10.3

//check with 
node -v

How is Docker different from a virtual machine?

Through this post we are going to draw some lines of differences between VMs and LXCs. Let's first define them.

VM:

A virtual machine emulates a physical computing environment, but requests for CPU, memory, hard disk, network and other hardware resources are managed by a virtualization layer which translates these requests to the underlying physical hardware.

In this context the VM is called as the Guest while the environment it runs on is called the host.

LXCs:

Linux Containers (LXC) are operating system-level capabilities that make it possible to run multiple isolated Linux containers, on one control host (the LXC host). Linux Containers serve as a lightweight alternative to VMs as they don’t require the hypervisors viz. Virtualbox, KVM, Xen, etc.

Now unless you were drugged by Alan (Zach Galifianakis- from the Hangover series) and have been in Vegas for the last year, you will be pretty aware about the tremendous spurt of interest for Linux containers technology, and if I will be specific one container project which has created a buzz around the world in last few months is – Docker leading to some echoing opinions that cloud computing environments should abandon virtual machines (VMs) and replace them with containers due to their lower overhead and potentially better performance.

But the big question is, is it feasible?, will it be sensible?

a. LXCs are scoped to an instance of Linux. It might be different flavors of Linux (e.g. a Ubuntu container on a CentOS host but it’s still Linux.) Similarly, Windows-based containers are scoped to an instance of Windows now if we look at VMs they have a pretty broader scope and using the hypervisors you are not limited to operating systems Linux or Windows.

b. LXCs have low overheads and have better performance as compared to VMs. Tools viz. Docker which are built on the shoulders of LXC technology have provided developers with a platform to run their applications and at the same time have empowered operations people with a tool that will allow them to deploy the same container on production servers or data centers. It tries to make the experience between a developer running an application, booting and testing an application and an operations person deploying that application seamless, because this is where all the friction lies in and purpose of DevOps is to break down those silos.

So the best approach is the cloud infrastructure providers should advocate an appropriate use of the VMs and LXC, as they are each suited to handle specific workloads and scenarios.

Abandoning VMs is not practical as of now. So both VMs and LXCs have their own individual existence and importance.

How do I generate a random int number?

You could use Jon Skeet's StaticRandom method inside the MiscUtil class library that he built for a pseudo-random number.

using MiscUtil;
...

for (int i = 0; i < 100; 
    Console.WriteLine(StaticRandom.Next());

How do I make the return type of a method generic?

Create a function and pass out put parameter as of generic type.

 public static T some_function<T>(T out_put_object /*declare as Output object*/)
    {
        return out_put_object;
    }

ListBox with ItemTemplate (and ScrollBar!)

I have never had any luck with any scrollable content placed inside a stackpanel (anything derived from ScrollableContainer. The stackpanel has an odd layout mechanism that confuses child controls when the measure operation is completed and I found the vertical size ends up infinite, therefore not constrained - so it goes beyond the boundaries of the container and ends up clipped. The scrollbar doesn't show because the control thinks it has all the space in the world when it doesn't.

You should always place scrollable content inside a container that can resolve to a known height during its layout operation at runtime so that the scrollbars size appropriately. The parent container up in the visual tree must be able to resolve to an actual height, and this happens in the grid if you set the height of the RowDefinition o to auto or fixed.

This also happens in Silverlight.

-em-

Can you use Microsoft Entity Framework with Oracle?

Update:

Oracle now fully supports the Entity Framework. Oracle Data Provider for .NET Release 11.2.0.3 (ODAC 11.2) Release Notes: http://docs.oracle.com/cd/E20434_01/doc/win.112/e23174/whatsnew.htm#BGGJIEIC

More documentation on Linq to Entities and ADO.NET Entity Framework: http://docs.oracle.com/cd/E20434_01/doc/win.112/e23174/featLINQ.htm#CJACEDJG

Note: ODP.NET also supports Entity SQL.

Static constant string (class member)

The current standard only allows such initialization for static constant integral types. So you need to do as AndreyT explained. However, that will be available in the next standard through the new member initialization syntax.

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

Another bug in Java. I seldom find them, only my second in my 10 year career. This is my solution, as others have mentioned. I have nether used System.gc(). But here, in my case, it is absolutely crucial. Weird? YES!

finally
{
    try
    {
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
        System.gc();
    }
    catch (IOException e)
    {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}

Concatenate columns in Apache Spark DataFrame

val newDf =
  df.withColumn(
    "NEW_COLUMN",
    concat(
      when(col("COL1").isNotNull, col("COL1")).otherwise(lit("null")),
      when(col("COL2").isNotNull, col("COL2")).otherwise(lit("null"))))

Note: For this code to work you need to put the parentheses "()" in the "isNotNull" function. -> The correct one is "isNotNull()".

val newDf =
  df.withColumn(
    "NEW_COLUMN",
    concat(
      when(col("COL1").isNotNull(), col("COL1")).otherwise(lit("null")),
      when(col("COL2").isNotNull(), col("COL2")).otherwise(lit("null"))))

Check if element is in the list (contains)

you must #include <algorithm>, then you can use std::find

Can I use Homebrew on Ubuntu?

You can just follow instructions from the Homebrew on Linux docs, but I think it is better to understand what the instructions are trying to achieve.

Understanding the installation steps can save some time


Step 1: Choose location

First of all, it is important to understand that linuxbrew will be installed on the /home directory and not inside /home/your-user (the ~ directory).
(See the reason for that at the end of answer).
Keep this in mind when you run the other steps below.

Step 2: Add linuxbrew binaries to /home :

The installation script will do it for us:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Step 3: Check that /linuxbrew was added to the relevant location

This can be done by simply navigating to /home.
Notice that the docs are showing it as a one-liner by adding test -d <linuxbrew location> before each command.

(Read more about the test command in here).

Step 4: Export relevant environment variables to terminal

We need to add linuxbrew to PATH and add some more environment variables to the current terminal.

We can just add the following exports to terminal (wait don't do it..):

export PATH="/home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin${PATH+:$PATH}";

export HOMEBREW_PREFIX="/home/linuxbrew/.linuxbrew";
export HOMEBREW_CELLAR="/home/linuxbrew/.linuxbrew/Cellar";
export HOMEBREW_REPOSITORY="/home/linuxbrew/.linuxbrew/Homebrew";
export MANPATH="/home/linuxbrew/.linuxbrew/share/man${MANPATH+:$MANPATH}:";
export INFOPATH="/home/linuxbrew/.linuxbrew/share/info:${INFOPATH:-}";

Or simply run (If your linuxbrew folder is on other location then /home - change the path):

eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)

(*) Because brew command is not yet identified by the current terminal (this is what we're solving right now) we'll have to specify the full path to the brew binary: /home/linuxbrew/.linuxbrew/bin/brew shellenv

Test this step by:

1 ) Run brew from current terminal to see if it identifies the command.

2 ) Run printenv and check if all environment variables were exported and that you see /home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin on PATH.

Step 5: Ensure step 4 is running on each terminal

We need to add step 4 to ~/.profile (in case of Debian/Ubuntu):

echo "eval \$($(brew --prefix)/bin/brew shellenv)" >> ~/.profile

For CentOS/Fedora/Red Hat - replace ~/.profile with ~/.bash_profile.

Step 6: Ensure that ~/.profile or ~/.bash_profile are being executed when new terminal is opened

If you executed step 5 and failed to run brew from new terminal - add a test command like echo "Hi!" to ~/.profile or ~/.bash_profile.
If you don't see Hi! when you open a new terminal - go to the terminal preferences and ensure that the attribute of 'run command as login shell' is set.
Read more in here.


Why the installation script installs Homebrew to /home/linuxbrew/.linuxbrew - from here:

The installation script installs Homebrew to /home/linuxbrew/.linuxbrew using sudo if possible and in your home directory at ~/.linuxbrew otherwise. Homebrew does not use sudo after installation.
Using /home/linuxbrew/.linuxbrew allows the use of more binary packages (bottles) than installing in your personal home directory.

The prefix /home/linuxbrew/.linuxbrew was chosen so that users without admin access can ask an admin to create a linuxbrew role account and still benefit from precompiled binaries.

If you do not yourself have admin privileges, consider asking your admin staff to create a linuxbrew role account for you with home directory /home/linuxbrew.

How to debug an apache virtual host configuration?

I recently had some issues with a VirtualHost. I used a2ensite to enable a host but before running a restart (which would kill the server on fail) I ran

apache2ctl -S

Which gives you some info about what's going on with your virtual hosts. It's not perfect, but it helps.

Rails: Check output of path helper from console

You can show them with rake routes directly.

In a Rails console, you can call app.post_path. This will work in Rails ~= 2.3 and >= 3.1.0.

How to clear an ImageView in Android?

This works for me.

emoji.setBackground(null);

This crashes in runtime.

viewToUse.setImageResource(android.R.color.transparent);