Programs & Examples On #Django tagging

How to find out which processes are using swap space in Linux?

On MacOSX, you run top command as well but need to type "o" then "vsize" then ENTER.

Python - abs vs fabs

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In [2]: from math import fabs

In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop

In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop

So it seems abs() only has slight speed advantage over fabs() for integers. For floats, abs() and fabs() demonstrate similar speed.


In addition to what @aix has said, one more thing to consider is the speed difference:

In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop

In [2]: import math

In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop

So abs() is faster than math.fabs().

min and max value of data type in C

The header file limits.h defines macros that expand to various limits and parameters of the standard integer types.

Fetch API with Cookie

Just adding to the correct answers here for .net webapi2 users.

If you are using cors because your client site is served from a different address as your webapi then you need to also include SupportsCredentials=true on the server side configuration.

        // Access-Control-Allow-Origin
        // https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
        var cors = new EnableCorsAttribute(Settings.CORSSites,"*", "*");
        cors.SupportsCredentials = true;
        config.EnableCors(cors);

How to cherry pick a range of commits and merge into another branch?

I wrapped VonC's code into a short bash script, git-multi-cherry-pick, for easy running:

#!/bin/bash

if [ -z $1 ]; then
    echo "Equivalent to running git-cherry-pick on each of the commits in the range specified.";
    echo "";
    echo "Usage:  $0 start^..end";
    echo "";
    exit 1;
fi

git rev-list --reverse --topo-order $1 | while read rev 
do 
  git cherry-pick $rev || break 
done 

I'm currently using this as I rebuild the history of a project that had both 3rd-party code and customizations mixed together in the same svn trunk. I'm now splitting apart core 3rd party code, 3rd party modules, and customizations onto their own git branches for better understanding of customizations going forward. git-cherry-pick is helpful in this situation since I have two trees in the same repository, but without a shared ancestor.

Autoplay audio files on an iPad with HTML5

As of iOS 4.2.1, neither the fake click nor the .load() trick will work to autoplay audio on any iOS device. The only option I know of is to have the user actually perform a click action and begin playback in the click event handler without wrapping the .play() call in anything asynchronous (ajax, setTimeout, etc).

Someone please tell me if I'm mistaken. I had working loopholes for both iPad and iPhone before the most recent update, and all of them look like they've been closed.

How do I parse command line arguments in Bash?

I'd like to offer my version of option parsing, that allows for the following:

-s p1
--stage p1
-w somefolder
--workfolder somefolder
-sw p1 somefolder
-e=hello

Also allows for this (could be unwanted):

-s--workfolder p1 somefolder
-se=hello p1
-swe=hello p1 somefolder

You have to decide before use if = is to be used on an option or not. This is to keep the code clean(ish).

while [[ $# > 0 ]]
do
    key="$1"
    while [[ ${key+x} ]]
    do
        case $key in
            -s*|--stage)
                STAGE="$2"
                shift # option has parameter
                ;;
            -w*|--workfolder)
                workfolder="$2"
                shift # option has parameter
                ;;
            -e=*)
                EXAMPLE="${key#*=}"
                break # option has been fully handled
                ;;
            *)
                # unknown option
                echo Unknown option: $key #1>&2
                exit 10 # either this: my preferred way to handle unknown options
                break # or this: do this to signal the option has been handled (if exit isn't used)
                ;;
        esac
        # prepare for next option in this key, if any
        [[ "$key" = -? || "$key" == --* ]] && unset key || key="${key/#-?/-}"
    done
    shift # option(s) fully processed, proceed to next input argument
done

Redefine tab as 4 spaces

Permanent for all users (when you alone on server):

# echo "set tabstop=4" >> /etc/vim/vimrc

Appends the setting in the config file. Normally on new server apt-get purge nano mc and all other to save your time. Otherwise, you will redefine editor in git, crontab etc.

How can I select records ONLY from yesterday?

If you want the timestamp for yesterday try something like:

(CURRENT_TIMESTAMP - INTERVAL '1' DAY)

PyLint "Unable to import" error - how to set PYTHONPATH?

Maybe by manually appending the dir inside the PYTHONPATH?

sys.path.append(dirname)

alternative to "!is.null()" in R

Ian put this in the comment, but I think it's a good answer:

if (exists("aVariable"))
{
  do whatever
}

note that the variable name is quoted.

XSL if: test with multiple test conditions

Just for completeness and those unaware XSL 1 has choose for multiple conditions.

<xsl:choose>
 <xsl:when test="expression">
  ... some output ...
 </xsl:when>
 <xsl:when test="another-expression">
  ... some output ...
 </xsl:when>
 <xsl:otherwise>
   ... some output ....
 </xsl:otherwise>
</xsl:choose>

How to define a circle shape in an Android XML drawable file?

You can try to use this

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item>
    <shape
        android:innerRadius="0dp"
        android:shape="ring"
        android:thicknessRatio="2"
        android:useLevel="false" >
        <solid android:color="@color/button_blue_two" />
    </shape>
</item>

and you don't have to bother the width and height aspect ratio if you are using this for a textview

JavaScript open in a new window, not tab

The key is the parameters :

If you provide Parameters [ Height="" , Width="" ] , then it will open in new windows.

If you DON'T provide Parameters , then it will open in new tab.

Tested in Chrome and Firefox

how to do bitwise exclusive or of two strings in python?

Below illustrates XORing string s with m, and then again to reverse the process:

>>> s='hello, world'
>>> m='markmarkmark'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'\x05\x04\x1e\x07\x02MR\x1c\x02\x13\x1e\x0f'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'hello, world'
>>>

Max length UITextField

I posted a solution using IBInspectable, so you can change the max length value both in interface builder or programmatically. Check it out here

How can I hide select options with JavaScript? (Cross browser)

Try this:

$(".hide").css("display","none");

But I think it doesn't make sense to hide it. if you wanna remove it, just:

$(".hide").remove();

How to wait for 2 seconds?

How about this?

WAITFOR DELAY '00:00:02';

If you have "00:02" it's interpreting that as Hours:Minutes.

Does Git Add have a verbose switch

You can use git add -i to get an interactive version of git add, although that's not exactly what you're after. The simplest thing to do is, after having git added, use git status to see what is staged or not.

Using git add . isn't really recommended unless it's your first commit. It's usually better to explicitly list the files you want staged, so that you don't start tracking unwanted files accidentally (temp files and such).

MySQL SELECT DISTINCT multiple columns

Both your queries are correct and should give you the right answer.

I would suggest the following query to troubleshoot your problem.

SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc

That is add count(*) field. This will give you idea how many rows were eliminated using the group command.

How do write IF ELSE statement in a MySQL query

You probably want to use a CASE expression.

They look like this:

SELECT col1, col2, (case when (action = 2 and state = 0) 
 THEN
      1 
 ELSE
      0 
 END)
 as state from tbl1;

Facebook how to check if user has liked page and show content?

With Javascript SDK, you can change the code as below, this should be added after FB.init call.

     // Additional initialization code such as adding Event Listeners goes here
FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {
        // the user is logged in and has authenticated your
        // app, and response.authResponse supplies
        // the user's ID, a valid access token, a signed
        // request, and the time the access token 
        // and signed request each expire
        var uid = response.authResponse.userID;
        var accessToken = response.authResponse.accessToken;
        alert('we are fine');
      } else if (response.status === 'not_authorized') {
        // the user is logged in to Facebook, 
        // but has not authenticated your app
        alert('please like us');
         $("#container_notlike").show();
      } else {
        // the user isn't logged in to Facebook.
        alert('please login');
      }
     });

FB.Event.subscribe('edge.create',
function(response) {
    alert('You liked the URL: ' + response);
      $("#container_like").show();
}

Can one do a for each loop in java in reverse order?

The List (unlike the Set) is an ordered collection and iterating over it does preserve the order by contract. I would have expected a Stack to iterate in the reverse order but unfortunately it doesn't. So the simplest solution I can think of is this:

for (int i = stack.size() - 1; i >= 0; i--) {
    System.out.println(stack.get(i));
}

I realize that this is not a "for each" loop solution. I'd rather use the for loop than introducing a new library like the Google Collections.

Collections.reverse() also does the job but it updates the list as opposed to returning a copy in reverse order.

NameError: uninitialized constant (rails)

I had this problem because I changed the name of the class in a model, and it did not match the name of the file.

"Model class names use CamelCase. These are singular, and will map automatically to the plural database table name.

Model files go in app/models/#{singular_model_name}.rb."

https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e#model

Looping over elements in jQuery

Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...

$("#formID").serialize()

It creates a string for you with all of the values automatically.

As for looping through objects, you can also do this.

$.each($("input, select, textarea"), function(i,v) {
    var theTag = v.tagName;
    var theElement = $(v);
    var theValue = theElement.val();
});

SelectSingleNode returning null for known good xml node path using XPath

Just to build upon solving the namespace issues, in my case I've been running into documents with multiple namespaces and needed to handle namespaces properly. I wrote the function below to get a namespace manager to deal with any namespace in the document:

private XmlNamespaceManager GetNameSpaceManager(XmlDocument xDoc)
    {
        XmlNamespaceManager nsm = new XmlNamespaceManager(xDoc.NameTable);
        XPathNavigator RootNode = xDoc.CreateNavigator();
        RootNode.MoveToFollowing(XPathNodeType.Element);
        IDictionary<string, string> NameSpaces = RootNode.GetNamespacesInScope(XmlNamespaceScope.All);

        foreach (KeyValuePair<string, string> kvp in NameSpaces)
        {
            nsm.AddNamespace(kvp.Key, kvp.Value);
        }

        return nsm;
    }

How to keep console window open

You can handle this without requiring a user input.

Step 1. Create a ManualRestEvent at the start of Main thread

ManualResetEvent manualResetEvent = new ManualResetEvent(false);

Step 2 . Wait ManualResetEvent

manualResetEvent.WaitOne();

Step 3.To Stop

manualResetEvent.Set();

Remove all whitespace from C# string with regex

Instead of a RegEx use Replace for something that simple:

LastName = LastName.Replace(" ", String.Empty);

Is it possible to program iPhone in C++

You have to use Objective C to interface with the Cocoa API, so there is no choice. Of course, you can use as much C++ as you like behind the scenes (Objective C++ makes this easy).

It is an insane language indeed, but it's also... kind of fun to use once you're a bit used to it. :-)

Can Selenium interact with an existing browser session?

It is possible. But you have to hack it a little, there is a code What you have to do is to run stand alone server and "patch" RemoteWebDriver

public class CustomRemoteWebDriver : RemoteWebDriver
{
    public static bool newSession;
    public static string capPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "tmp", "sessionCap");
    public static string sessiodIdPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "tmp", "sessionid");

    public CustomRemoteWebDriver(Uri remoteAddress) 
        : base(remoteAddress, new DesiredCapabilities())
    {
    }

    protected override Response Execute(DriverCommand driverCommandToExecute, Dictionary<string, object> parameters)
    {
        if (driverCommandToExecute == DriverCommand.NewSession)
        {
            if (!newSession)
            {
                var capText = File.ReadAllText(capPath);
                var sidText = File.ReadAllText(sessiodIdPath);

                var cap = JsonConvert.DeserializeObject<Dictionary<string, object>>(capText);
                return new Response
                {
                    SessionId = sidText,
                    Value = cap
                };
            }
            else
            {
                var response = base.Execute(driverCommandToExecute, parameters);
                var dictionary = (Dictionary<string, object>) response.Value;
                File.WriteAllText(capPath, JsonConvert.SerializeObject(dictionary));
                File.WriteAllText(sessiodIdPath, response.SessionId);
                return response;
            }
        }
        else
        {
            var response = base.Execute(driverCommandToExecute, parameters);
            return response;
        }
    }
}

How to print star pattern in JavaScript in a very simple manner?

It's very simple, Try this code as below:

for(var i = 1; i <= 5; i++) {

      for(var j = 1; j<= i; j++) {

        document.write("*");  

      }

      document.write("<br/>");
}

Define make variable at rule execution time

In your example, the TMP variable is set (and the temporary directory created) whenever the rules for out.tar are evaluated. In order to create the directory only when out.tar is actually fired, you need to move the directory creation down into the steps:

out.tar : 
    $(eval TMP := $(shell mktemp -d))
    @echo hi $(TMP)/hi.txt
    tar -C $(TMP) cf $@ .
    rm -rf $(TMP)

The eval function evaluates a string as if it had been typed into the makefile manually. In this case, it sets the TMP variable to the result of the shell function call.

edit (in response to comments):

To create a unique variable, you could do the following:

out.tar : 
    $(eval $@_TMP := $(shell mktemp -d))
    @echo hi $($@_TMP)/hi.txt
    tar -C $($@_TMP) cf $@ .
    rm -rf $($@_TMP)

This would prepend the name of the target (out.tar, in this case) to the variable, producing a variable with the name out.tar_TMP. Hopefully, that is enough to prevent conflicts.

Plot width settings in ipython notebook

If you use %pylab inline you can (on a new line) insert the following command:

%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)

This will set all figures in your document (unless otherwise specified) to be of the size (10, 6), where the first entry is the width and the second is the height.

See this SO post for more details. https://stackoverflow.com/a/17231361/1419668

how can I enable scrollbars on the WPF Datagrid?

Put the DataGrid in a Grid, DockPanel, ContentControl or directly in the Window. A vertically-oriented StackPanel will give its children whatever vertical space they ask for - even if that means it is rendered out of view.

How do you Programmatically Download a Webpage in Java

Here's some tested code using Java's URL class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.

public static void main(String[] args) {
    URL url;
    InputStream is = null;
    BufferedReader br;
    String line;

    try {
        url = new URL("http://stackoverflow.com/");
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException mue) {
         mue.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
}

get dictionary key by value

maybe something like this:

foreach (var keyvaluepair in dict)
{
    if(Object.ReferenceEquals(keyvaluepair.Value, searchedObject))
    {
        //dict.Remove(keyvaluepair.Key);
        break;
    }
}

AngularJS sorting by property

Here is what i did and it works.
I just used a stringified object.

$scope.thread = [ 
  {
    mostRecent:{text:'hello world',timeStamp:12345678 } 
    allMessages:[]
  }
  {MoreThreads...}
  {etc....}
]

<div ng-repeat="message in thread | orderBy : '-mostRecent.timeStamp'" >

if i wanted to sort by text i would do

orderBy : 'mostRecent.text'

How to identify unused CSS definitions from multiple CSS files in a project

Chrome Developer Tools has an Audits tab which can show unused CSS selectors.

Run an audit, then, under Web Page Performance see Remove unused CSS rules

enter image description here

How to check if all elements of a list matches a condition?

If you want to check if any item in the list violates a condition use all:

if all([x[2] == 0 for x in lista]):
    # Will run if all elements in the list has x[2] = 0 (use not to invert if necessary)

To remove all elements not matching, use filter

# Will remove all elements where x[2] is 0
listb = filter(lambda x: x[2] != 0, listb)

Datepicker: How to popup datepicker when click on edittext

I thought it better to override the EditText class...

public class EditTextDP extends android.support.v7.widget.AppCompatEditText implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
    public EditTextDP(Context context) {
        super(context);
        setOnClickListener(this);
        setFocusable(false);
    }

    public EditTextDP(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(this);
        setFocusable(false);
    }

    public EditTextDP(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOnClickListener(this);
        setFocusable(false);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        setText(new StringBuilder().append(dayOfMonth).append("/").append(monthOfYear + 1).append("/").append(year));
    }

    @Override
    public void onClick(View v) {
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        DatePickerDialog dialog = new DatePickerDialog(getContext(), this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }
}

And use that in the XML instead...

            <*.*.*.EditTextDP
                android:id="@+id/c1_dob_hm"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/round_edittext_white"
                android:ems="10"
                android:padding="8dp">

            </*.*.*.EditTextDP>

How to check if "Radiobutton" is checked?

You can also maintain a flag value based on listener,

 radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

                //handle the boolean flag here. 
                  if(arg1==true)
                         //Do something

                else 
                    //do something else

            }
        });

Or simply isChecked() can also be used to check the state of your RadioButton.

Here is a link to a sample,

http://www.mkyong.com/android/android-radio-buttons-example/

And then based on the flag you can execute your function.

How to check whether a string is Base64 encoded or not

Try like this for PHP5

//where $json is some data that can be base64 encoded
$json=some_data;

//this will check whether data is base64 encoded or not
if (base64_decode($json, true) == true)
{          
   echo "base64 encoded";          
}
else 
{
   echo "not base64 encoded"; 
}

Use this for PHP7

 //$string parameter can be base64 encoded or not

function is_base64_encoded($string){
 //this will check if $string is base64 encoded and return true, if it is.
 if (base64_decode($string, true) !== false){          
   return true;        
 }else{
   return false;
 }
}

Trigger validation of all fields in Angular Form submit

You can use Angular-Validator to do what you want. It's stupid simple to use.

It will:

  • Only validate the fields on $dirty or on submit
  • Prevent the form from being submitted if it is invalid
  • Show custom error message after the field is $dirty or the form is submitted

See the demo

Example

<form angular-validator 
       angular-validator-submit="myFunction(myBeautifulForm)"
       name="myBeautifulForm">
       <!-- form fields here -->
    <button type="submit">Submit</button>
</form>

If the field does not pass the validator then the user will not be able to submit the form.

Check out angular-validator use cases and examples for more information.

Disclaimer: I am the author of Angular-Validator

Mapping a JDBC ResultSet to an object

Use Statement Fetch Size , if you are retrieving more number of records. like this.

Statement statement = connection.createStatement();
statement.setFetchSize(1000); 

Apart from that i dont see an issue with the way you are doing in terms of performance

In terms of Neat. Always use seperate method delegate to map the resultset to POJO object. which can be reused later in the same class

like

private User mapResultSet(ResultSet rs){
     User user = new User();
     // Map Results
     return user;
}

If you have the same name for both columnName and object's fieldName , you could also write reflection utility to load the records back to POJO. and use MetaData to read the columnNames . but for small scale projects using reflection is not an problem. but as i said before there is nothing wrong with the way you are doing.

How can I change the language (to english) in Oracle SQL Developer?

You can also set language at runtime

sqldeveloper.exe --AddVMOption=-Duser.language=en

to avoid editing sqldeveloper.conf every time you install new version.

Java ArrayList of Doubles

Using guava

Doubles.asList(1.2, 5.6, 10.1);

or immutable list

ImmutableList.of(1.2, 5.6, 10.1);

How to declare an array inside MS SQL Server Stored Procedure?

Great question and great idea, but in SQL you'll need to do this:

For data type datetime, something like this-

declare @BeginDate    datetime = '1/1/2016',
        @EndDate      datetime = '12/1/2016'
create table #months (dates datetime)
declare @var datetime = @BeginDate
   while @var < dateadd(MONTH, +1, @EndDate)
   Begin
          insert into #months Values(@var)
          set @var = Dateadd(MONTH, +1, @var)
   end

If all you really want is numbers, do this-

create table #numbas (digit int)
declare @var int = 1        --your starting digit
    while @var <= 12        --your ending digit
    begin
        insert into #numbas Values(@var)
        set @var = @var +1
    end

fatal: could not create work tree dir 'kivy'

Your current directory does not has the write/create permission to create kivy directory, thats why occuring this problem.

Your current directory give 777 rights and try it.

sudo chmod 777 DIR_NAME
cd DIR_NAME
git clone https://github.com/mygitusername/kivy.git

New warnings in iOS 9: "all bitcode will be dropped"

Your library was compiled without bitcode, but the bitcode option is enabled in your project settings. Say NO to Enable Bitcode in your target Build Settings and the Library Build Settings to remove the warnings.

For those wondering if enabling bitcode is required:

For iOS apps, bitcode is the default, but optional. For watchOS and tvOS apps, bitcode is required. If you provide bitcode, all apps and frameworks in the app bundle (all targets in the project) need to include bitcode.

https://help.apple.com/xcode/mac/current/#/devbbdc5ce4f

Is Tomcat running?

Are you trying to set up an alert system? For a simple "heartbeat", do a HTTP request to the Tomcat port.

For more elaborate monitoring, you can set up JMX and/or SNMP to view JVM stats. We run Nagios with the SNMP plugin (bridges to JMX) to check Tomcat memory usage and request thread pool size every 10-15 minutes.

http://tomcat.apache.org/tomcat-6.0-doc/monitoring.html

Update (2012):

We have upgraded our systems to use "monit" to check the tomcat process. I really like it. With very little configuration it automatically verifies the service is running, and automatically restarts if it is not. (sending an email alert). It can integrate with the /etc/init.d scripts or check by process name.

form_for with nested resources

Be sure to have both objects created in controller: @post and @comment for the post, eg:

@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)

Then in view:

<%= form_for([@post, @comment]) do |f| %>

Be sure to explicitly define the array in the form_for, not just comma separated like you have above.

PHP form send email to multiple recipients

You can add your receipients to $email_to variable separating them with comma (,). Or you can add new fields to headers, namely CC: or BCC: and put your receipients there. BCC is most recommended

git is not installed or not in the PATH

Install git and tortoise git for windows and make sure it is on your path, (the installer for Tortoise Git includes options for the command line tools and ensuring that it is on the path - select them).

You will need to close and re-open any existing command line sessions for the changes to take effect.

Then you should be able to run npm install successfully or move on to the next problem!

jquery .live('click') vs .click()

There might be times when you explicitly want to only assign the click handler to objects which already exist, and handle new objects differently. But more commonly, live doesn't always work. It doesn't work with chained jQuery statements such as:

$(this).children().live('click',doSomething);

It needs a selector to work properly because of the way events bubble up the DOM tree.

Edit: Someone just upvoted this, so obviously people are still looking at it. I should point out that live and bind are both deprecated. You can perform both with .on(), which IMO is a much clearer syntax. To replace bind:

$(selector).on('click', function () {
    ...
});

and to replace live:

$(document).on('click', selector, function () {
    ...
});

Instead of using $(document), you can use any jQuery object which contains all the elements you're monitoring the clicks on, but the corresponding element must exist when you call it.

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

Make sure you've set your target API (different from the target SDK) in the Project Properties (not the manifest) to be at least 4.0/API 14.

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.

After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.

indexOf Case Sensitive?

There is an ignore case method in StringUtils class of Apache Commons Lang library

indexOfIgnoreCase(CharSequence str, CharSequence searchStr)

What is the result of % in Python?

I have found that the easiest way to grasp the modulus operator (%) is through long division. It is the remainder and can be useful in determining a number to be even or odd:

4%2 = 0

  2
2|4
 -4
  0


11%3 = 2

  3
3|11
 -9
  2

Get current URL with jQuery?

If there is someone who wants to concatenate the URL and hash tag, combine two functions:

var pathname = window.location.pathname + document.location.hash;

Access PHP variable in JavaScript

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>

Failed to add the host to the list of know hosts

Okay so ideal permissions look like this
For ssh directory (You can get this by typing ls -ld ~/.ssh/)
drwx------ 2 oroborus oroborus 4096 Nov 28 12:05 /home/oroborus/.ssh/

d means directory, rwx means the user oroborus has read write and execute permission. Here oroborus is my computer name, you can find yours by echoing $USER. The second oroborus is actually the group. You can read more about what does each field mean here. It is very important to learn this because if you are working on ubuntu/osx or any Linux distro chances are you will encounter it again.

Now to make your permission look like this, you need to type
sudo chmod 700 ~/.ssh

7 in binary is 111 which means read 1 write 1 and execute 1, you can decode 6 by similar logic means only read-write permissions

You have given your user read write and execute permissions. Make sure your file permissions look like this.

total 20
-rw------- 1 oroborus oroborus  418 Nov  8  2014 authorized_keys
-rw------- 1 oroborus oroborus   34 Oct 19 14:25 config
-rw------- 1 oroborus oroborus 1679 Nov 15  2015 id_rsa
-rw------- 1 oroborus oroborus  418 Nov 15  2015 id_rsa.pub
-rw-r--r-- 1 oroborus root      222 Nov 28 12:12 known_hosts

You have given here read-write permission to your user here for all files. You can see this by typing ls -l ~/.ssh/

This issue occurs because ssh is a program is trying to write to a file called known_hosts in its folder. While writing if it knows that it doesn't have sufficient permissions it will not write in that file and hence fail. This is my understanding of the issue, more knowledgeable people can throw more light in this. Hope it helps

c - warning: implicit declaration of function ‘printf’

You need to include a declaration of the printf() function.

#include <stdio.h>

How to customize a Spinner in Android

I have build a small demo project on this you could have a look to it Link to project

how to make a full screen div, and prevent size to be changed by content?

Here is my Solution, I think will better to use vh (viewport height) and vw for (viewport width), units regarding to the height and width of the current viewport

_x000D_
_x000D_
function myFunction() {
  var element = document.getElementById("main");
  element.classList.add("container");
}
_x000D_
.container{
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: #333;
  margin: 0; 
  padding: 0; 
}
_x000D_
<div id="main"></div>
<button onclick="myFunction()">Try it</button>
_x000D_
_x000D_
_x000D_

Python Dictionary Comprehension

There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a new dictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you like.

>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

If you want to set them all to True:

>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}

What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. There's no direct shortcut for that. You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict) to merge the new values into the old dict.

How to combine two lists in R

We can use append

append(l1, l2)

It also has arguments to insert element at a particular location.

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

First, the possible values for the hbm2ddl configuration property are the following ones:

  • none - No action is performed. The schema will not be generated.
  • create-only - The database schema will be generated.
  • drop - The database schema will be dropped.
  • create - The database schema will be dropped and created afterward.
  • create-drop - The database schema will be dropped and created afterward. Upon closing the SessionFactory, the database schema will be dropped.
  • validate - The database schema will be validated using the entity mappings.
  • update - The database schema will be updated by comparing the existing database schema with the entity mappings.

The hibernate.hbm2ddl.auto="update" is convenient but less flexible if you plan on adding functions or executing some custom scripts.

So, The most flexible approach is to use Flyway.

However, even if you use Flyway, you can still generate the initial migration script using hbm2ddl.

HTML display result in text (input) field?

innerHTML sets the text (including html elements) inside an element. Normally we use it for elements like div, span etc to insert other html elements inside it.

For your case you want to set the value of an input element. So you should use the value attribute.

Change innerHTML to value

document.getElementById('add').value = sum;

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

This just happened to me in a foreach loop. I had inadvertently typed ($array as $key as $value) and PHP objected to the first as.

How to make Firefox headless programmatically in Selenium with Python?

To the OP or anyone currently interested, here's the section of code that's worked for me with firefox currently:

opt = webdriver.FirefoxOptions()
opt.add_argument('-headless')
ffox_driver = webdriver.Firefox(executable_path='\path\to\geckodriver', options=opt)

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Adding this to build.gradle (Module app) worked for me:
compile 'com.android.support:support-annotations:27.1.1'

Differences between MySQL and SQL Server

Spending some time working with MySQL from the MSSQL to MySQL syntax POV I kept finding myself limited in what I could do.

There are bizzare limits on updating a table while refrencing the same table during an update.

Additionally UPDATE FROM does not work and last time I checked they don't support the Oracle MERGE INTO syntax either. This was a show stopper for me and I stopped thinking I would get anywhere with MySQL after that.

Why is JsonRequestBehavior needed?

You do not need it.

If your action has the HttpPost attribute, then you do not need to bother with setting the JsonRequestBehavior and use the overload without it. There is an overload for each method without the JsonRequestBehavior enum. Here they are:

Without JsonRequestBehavior

protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);

With JsonRequestBehavior

protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType, 
                                   JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType, 
    Encoding contentEncoding, JsonRequestBehavior behavior);

VBA equivalent to Excel's mod function

Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.

In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0

They are certainly not equivalent!

Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123

SQL Server 2008 can't login with newly created user

If you haven't restarted your SQL database Server after you make login changes, then make sure you do that. Start->Programs->Microsoft SQL Server -> Configuration tools -> SQL Server configuration manager -> Restart Server.

It looks like you only added the user to the server. You need to add them to the database too. Either open the database/Security/User/Add New User or open the server/Security/Logins/Properties/User Mapping.

MacOSX homebrew mysql root password

Running these lines in the terminal did the trick for me and several others who had the same problem. These instructions are listed in the terminal after brew installs mysql sucessfully.

mkdir -p ~/Library/LaunchAgents

cp /usr/local/Cellar/mysql/5.5.25a/homebrew.mxcl.mysql.plist ~/Library/LaunchAgents/

launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

/usr/local/Cellar/mysql/5.5.25a/bin/mysqladmin -u root password 'YOURPASSWORD'

where YOURPASSWORD is the password for root.

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

I tried every possible solution on this web site and nothing worked for me. I ended up doing in the design mode. Right click on the table name and then click design. Then I changed the name and saved here. Worked simply.

How do you get the cursor position in a textarea?

Here is code to get line number and column position

function getLineNumber(tArea) {

    return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}

function getCursorPos() {
    var me = $("textarea[name='documenttext']")[0];
    var el = $(me).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    var ret = pos - prevLine(me);
    alert(ret);

    return ret; 
}

function prevLine(me) {
    var lineArr = me.value.substr(0, me.selectionStart).split("\n");

    var numChars = 0;

    for (var i = 0; i < lineArr.length-1; i++) {
        numChars += lineArr[i].length+1;
    }

    return numChars;
}

tArea is the text area DOM element

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

This is often caused by an attempt to process a null object. An example, trying to empty a Bindable list that is null will trigger the exception:

public class MyViewModel {
    [BindableProperty]
    public virtual IList<Products> ProductsList{ get; set; }

    public MyViewModel ()
    {
        ProductsList.Clear(); // here is the problem
    }
}

This could easily be fixed by checking for null:

if (ProductsList!= null) ProductsList.Clear();

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

iOS for VirtualBox

Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator

Controller not a function, got undefined, while defining controllers globally

This error might also occur when you have a large project with many modules. Make sure that the app (module) used in you angular file is the same that you use in your template, in this example "thisApp".

app.js

angular
.module('thisApp', [])
    .controller('ContactController', ['$scope', function ContactController($scope) {
        $scope.contacts = ["[email protected]", "[email protected]"];

        $scope.add = function() {
            $scope.contacts.push($scope.newcontact);
            $scope.newcontact = "";

        };
    }]);

index.html

  <html>
    <body ng-app='thisApp' ng-controller='ContactController>
         ...
        <script type="text/javascript" src="assets/js/angular.js"></script>
        <script src="app.js"></script>
    </body>
    </html>

CSS "and" and "or"

A word of caution. Stringing together several not selectors increases the specificity of the resulting selector, which makes it harder to override: you'll basically need to find the selector with all the nots and copy-paste it into your new selector.

A not(X or Y) selector would be great to avoid inflating specificity, but I guess we'll have to stick to combining the opposites, like in this answer.

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

Angular - Set headers for every request

There were some changes for angular 2.0.1 and higher:

    import {RequestOptions, RequestMethod, Headers} from '@angular/http';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpModule }     from '@angular/http';
    import { AppRoutingModule } from './app.routing.module';   
    import { AppComponent }  from './app.component';

    //you can move this class to a better place
    class GlobalHttpOptions extends RequestOptions {
        constructor() { 
          super({ 
            method: RequestMethod.Get,
            headers: new Headers({
              'MyHeader': 'MyHeaderValue',
            })
          });
        }
      }

    @NgModule({

      imports:      [ BrowserModule, HttpModule, AppRoutingModule ],
      declarations: [ AppComponent],
      bootstrap:    [ AppComponent ],
      providers:    [ { provide: RequestOptions, useClass: GlobalHttpOptions} ]
    })

    export class AppModule { }

How to colorize diff on the command line?

With bat command:

diff file1 file2 | bat -l diff

python multithreading wait till all threads finished

You can have class something like below from which you can add 'n' number of functions or console_scripts you want to execute in parallel passion and start the execution and wait for all jobs to complete..

from multiprocessing import Process

class ProcessParallel(object):
    """
    To Process the  functions parallely

    """    
    def __init__(self, *jobs):
        """
        """
        self.jobs = jobs
        self.processes = []

    def fork_processes(self):
        """
        Creates the process objects for given function deligates
        """
        for job in self.jobs:
            proc  = Process(target=job)
            self.processes.append(proc)

    def start_all(self):
        """
        Starts the functions process all together.
        """
        for proc in self.processes:
            proc.start()

    def join_all(self):
        """
        Waits untill all the functions executed.
        """
        for proc in self.processes:
            proc.join()


def two_sum(a=2, b=2):
    return a + b

def multiply(a=2, b=2):
    return a * b


#How to run:
if __name__ == '__main__':
    #note: two_sum, multiply can be replace with any python console scripts which
    #you wanted to run parallel..
    procs =  ProcessParallel(two_sum, multiply)
    #Add all the process in list
    procs.fork_processes()
    #starts  process execution 
    procs.start_all()
    #wait until all the process got executed
    procs.join_all()

How can I get Git to follow symlinks?

Use hard links instead. This differs from a soft (symbolic) link. All programs, including git will treat the file as a regular file. Note that the contents can be modified by changing either the source or the destination.

On macOS (before 10.13 High Sierra)

If you already have git and Xcode installed, install hardlink. It's a microscopic tool to create hard links.

To create the hard link, simply:

hln source destination

macOS High Sierra update

Does Apple File System support directory hard links?

Directory hard links are not supported by Apple File System. All directory hard links are converted to symbolic links or aliases when you convert from HFS+ to APFS volume formats on macOS.

From APFS FAQ on developer.apple.com

Follow https://github.com/selkhateeb/hardlink/issues/31 for future alternatives.

On Linux and other Unix flavors

The ln command can make hard links:

ln source destination

On Windows (Vista, 7, 8, …)

Use mklink to create a junction on Windows:

mklink /j "source" "destination"

PHP str_replace replace spaces with underscores

For one matched character replace, use str_replace:

$string = str_replace(' ', '_', $string);

For all matched character replace, use preg_replace:

$string = preg_replace('/\s+/', '_', $string);

How can I run a directive after the dom has finished rendering?

I had the a similar problem and want to share my solution here.

I have the following HTML:

<div data-my-directive>
  <div id='sub' ng-include='includedFile.htm'></div>
</div>

Problem: In the link-function of directive of the parent div I wanted to jquery'ing the child div#sub. But it just gave me an empty object because ng-include hadn't finished when link function of directive ran. So first I made a dirty workaround with $timeout, which worked but the delay-parameter depended on client speed (nobody likes that).

Works but dirty:

app.directive('myDirective', [function () {
    var directive = {};
    directive.link = function (scope, element, attrs) {
        $timeout(function() {
            //very dirty cause of client-depending varying delay time 
            $('#sub').css(/*whatever*/);
        }, 350);
    };
    return directive;
}]);

Here's the clean solution:

app.directive('myDirective', [function () {
    var directive = {};
    directive.link = function (scope, element, attrs) {
        scope.$on('$includeContentLoaded', function() {
            //just happens in the moment when ng-included finished
            $('#sub').css(/*whatever*/);
        };
    };
    return directive;
}]);

Maybe it helps somebody.

How can I check if a key exists in a dictionary?

If you want to retrieve the key's value if it exists, you can also use

try:
    value = a[key]
except KeyError:
    # Key is not present
    pass

If you want to retrieve a default value when the key does not exist, use value = a.get(key, default_value). If you want to set the default value at the same time in case the key does not exist, use value = a.setdefault(key, default_value).

No visible cause for "Unexpected token ILLEGAL"

Here is my reason:

before:

var path = "D:\xxx\util.s"

which \u is a escape, I figured it out by using Codepen's analyze JS.

after:

var path = "D:\\xxx\\util.s"

and the error fixed

JBoss debugging in Eclipse

Here, if you want to directly debug the server then you can use:

1.)Windows ->

2.)Show View -> Server: Right click on server then run In debug mode.

PHP Date Time Current Time Add Minutes

$time = strtotime(date('2016-02-03 12:00:00'));
        echo date("H:i:s",strtotime("-30 minutes", $time));

JavaScript style.display="none" or jQuery .hide() is more efficient?

Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.

In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden') which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.

What is the preferred Bash shebang?

#!/bin/sh

as most scripts do not need specific bash feature and should be written for sh.

Also, this makes scripts work on the BSDs, which do not have bash per default.

Insert a background image in CSS (Twitter Bootstrap)

Is your image on the same folder/directory as your css file? If so, your image url is correct. Otherwise, it's not.

If by any chance your folder structure is like so...

webpage
-index.html
-css
- - style.css
- images
- - background.png

then to reference the image on your css file you should use the following path:

../images/background.png

So that would be background: url('../images/background.png');

The logic is simple: Go up one folder by typing "../" (as many times as you need). Go down one folder by specifying the folder you wish to go down to.

Flutter: Setting the height of the AppBar

Cinn's answer is great, but there's one thing wrong with it.

The PreferredSize widget will start immediately at the top of the screen, without accounting for the status bar, so some of its height will be shadowed by the status bar's height. This also accounts for the side notches.

The solution: Wrap the preferredSize's child with a SafeArea

appBar: PreferredSize(
  //Here is the preferred height.
  preferredSize: Size.fromHeight(50.0),
  child: SafeArea(
    child: AppBar(
      flexibleSpace: ...
    ),
  ),
),

If you don't wanna use the flexibleSpace property, then there's no need for all that, because the other properties of the AppBar will account for the status bar automatically.

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

before start make sure of installation:

yum install -y xorg-x11-server-Xorg xorg-x11-xauth xorg-x11-apps
  1. start xming or cygwin
  2. make connection with X11 forwarding (in putty don't forget to set localhost:0.0 for X display location)
  3. edit sshd.cong and restart
     cat /etc/ssh/sshd_config | grep X
                             X11Forwarding yes
                             X11DisplayOffset 10
AddressFamily inet
  1. Without the X11 forwarding, you are subjected to the X11 SECURITY and then you must: authorize the remote server to make a connection with the local X Server using a method (for instance, the xhost command) set the display environment variable to redirect the output to the X server of your local computer. In this example: 192.168.2.223 is the IP of the server 192.168.2.2 is the IP of the local computer where the x server is installed. localhost can also be used.
blablaco@blablaco01 ~
$ xhost 192.168.2.223
192.168.2.223 being added to access control list

blablaco@blablaco01 ~
$ ssh -l root 192.168.2.223
[email protected] password:
Last login: Sat May 22 18:59:04 2010 from etcetc
[root@oel5u5 ~]# export DISPLAY=192.168.2.2:0.0
[root@oel5u5 ~]# echo $DISPLAY
192.168.2.2:0.0
[root@oel5u5 ~]# xclock&

Then the xclock application must launch.

Check it on putty or mobaxterm and don't check in remote desktop Manager software. Be careful for user that sudo in.

CMD command to check connected USB devices

You can use the wmic command:

wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

yourimg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}

and make sure there is no parent tags with position: relative in it

Custom UITableViewCell from nib in Swift

Swift 4

Register Nib

override func viewDidLoad() {
    super.viewDidLoad()
    tblMissions.register(UINib(nibName: "MissionCell", bundle: nil), forCellReuseIdentifier: "MissionCell")
}

In TableView DataSource

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          guard let cell = tableView.dequeueReusableCell(withIdentifier: "MissionCell", for: indexPath) as? MissionCell else { return UITableViewCell() }
          return cell
    }

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

How to get Git to clone into current directory

The following is probably not fully equivalent to a clone in all cases but did the trick for me:

git init .
git remote add -t \* -f origin <repository-url>
git checkout master

In my case, this produces a .git/config file which is equivalent to the one I get when doing a clone.

How to implement onBackPressed() in Fragments?

In activity life cycle, always android back button deals with FragmentManager transactions when we used FragmentActivity or AppCompatActivity.

To handle the backstack we don't need to handle its backstack count or tag anything but we should keep focus while adding or replacing a fragment. Please find the following snippets to handle the back button cases,

    public void replaceFragment(Fragment fragment) {

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!(fragment instanceof HomeFragment)) {
            transaction.addToBackStack(null);
        }
        transaction.replace(R.id.activity_menu_fragment_container, fragment).commit();
    }

Here, I won't add back stack for my home fragment because it's home page of my application. If add addToBackStack to HomeFragment then app will wait to remove all the frament in acitivity then we'll get blank screen so I'm keeping the following condition,

if (!(fragment instanceof HomeFragment)) {
            transaction.addToBackStack(null);
}

Now, you can see the previously added fragment on acitvity and app will exit when reaching HomeFragment. you can also look on the following snippets.

@Override
public void onBackPressed() {

    if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
        closeDrawer();
    } else {
        super.onBackPressed();
    }
}

Is there a GUI design app for the Tkinter / grid geometry?

Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu.

This is the first description by the author taken from the github repository:

Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.

The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.


Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu.

The following in an image of interface of the last version of pygubu designer on a OS X Yosemite 10.10.2:

enter image description here

I would definitely give it a try, and contribute to its development.

UITableview: How to Disable Selection for Some Rows but Not Others

For Swift 4.0 for example:

cell.isUserInteractionEnabled = false
cell.contentView.alpha = 0.5

Sorting std::map using value

I needed something similar, but the flipped map wouldn't work for me. I just copied out my map (freq below) into a vector of pairs, then sorted the pairs however I wanted.

std::vector<std::pair<int, int>> pairs;
for (auto itr = freq.begin(); itr != freq.end(); ++itr)
    pairs.push_back(*itr);

sort(pairs.begin(), pairs.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b)
{
    return a.second < b.second;
}
);

Attempt to write a readonly database - Django w/ SELinux error

You have to add writing rights to the directory in which your sqlite database is stored. So running chmod 664 /srv/mysite should help.

This is a security risk, so better solution is to change the owner of your database to www-data:

chown www-data:www-data /srv/mysite
chown www-data:www-data /srv/mysite/DATABASE.sqlite

How to check if a std::thread is still running?

An easy solution is to have a boolean variable that the thread sets to true on regular intervals, and that is checked and set to false by the thread wanting to know the status. If the variable is false for to long then the thread is no longer considered active.

A more thread-safe way is to have a counter that is increased by the child thread, and the main thread compares the counter to a stored value and if the same after too long time then the child thread is considered not active.

Note however, there is no way in C++11 to actually kill or remove a thread that has hanged.

Edit How to check if a thread has cleanly exited or not: Basically the same technique as described in the first paragraph; Have a boolean variable initialized to false. The last thing the child thread does is set it to true. The main thread can then check that variable, and if true do a join on the child thread without much (if any) blocking.

Edit2 If the thread exits due to an exception, then have two thread "main" functions: The first one have a try-catch inside which it calls the second "real" main thread function. This first main function sets the "have_exited" variable. Something like this:

bool thread_done = false;

void *thread_function(void *arg)
{
    void *res = nullptr;

    try
    {
        res = real_thread_function(arg);
    }
    catch (...)
    {
    }

    thread_done = true;

    return res;
}

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

  1. I agree with yossi's example, stretch the image to fit the div but in a slightly different way (without background-image as this is a little inflexible in css 2.1). Show full image:

    <div id="yourdiv">
        <img id="theimage" src="image.jpg" alt="" />
    </div>
    
    #yourdiv img {
        width:100%;
      /*height will be automatic to remain aspect ratio*/
    }
    
  2. Show part of the image using background-position:

    #yourdiv 
    {
        background-image: url(image.jpg);
        background-repeat: no-repeat;
        background-position: 10px 25px;
    }
    
  3. Same as the first part of (1) the image will scale to the div so bigger or smaller will both work

  4. Same as yossi's.

How to avoid using Select in Excel VBA

IMHO use of .select comes from people, who like me started learning VBA by necessity through recording macros and then modifying the code without realizing that .select and subsequent selection is just an unnecessary middle-men.

.select can be avoided, as many posted already, by directly working with the already existing objects, which allows various indirect referencing like calculating i and j in a complex way and then editing cell(i,j), etc.

Otherwise, there is nothing implicitly wrong with .select itself and you can find uses for this easily, e.g. I have a spreadsheet that I populate with date, activate macro that does some magic with it and exports it in an acceptable format on a separate sheet, which, however, requires some final manual (unpredictable) inputs into an adjacent cell. So here comes the moment for .select that saves me that additional mouse movement and click.

Accessing nested JavaScript objects and arrays by string path

Building off of Alnitak's answer:

if(!Object.prototype.byString){
  //NEW byString which can update values
Object.prototype.byString = function(s, v, o) {
  var _o = o || this;
      s = s.replace(/\[(\w+)\]/g, '.$1'); // CONVERT INDEXES TO PROPERTIES
      s = s.replace(/^\./, ''); // STRIP A LEADING DOT
      var a = s.split('.'); //ARRAY OF STRINGS SPLIT BY '.'
      for (var i = 0; i < a.length; ++i) {//LOOP OVER ARRAY OF STRINGS
          var k = a[i];
          if (k in _o) {//LOOP THROUGH OBJECT KEYS
              if(_o.hasOwnProperty(k)){//USE ONLY KEYS WE CREATED
                if(v !== undefined){//IF WE HAVE A NEW VALUE PARAM
                  if(i === a.length -1){//IF IT'S THE LAST IN THE ARRAY
                    _o[k] = v;
                  }
                }
                _o = _o[k];//NO NEW VALUE SO JUST RETURN THE CURRENT VALUE
              }
          } else {
              return;
          }
      }
      return _o;
  };

}

This allows you to set a value as well!

I've created an npm package and github with this as well

jQuery textbox change event

$('#input').on("input",function () {alert('changed');});

works for me.

What is the correct way to check for string equality in JavaScript?

Just one addition to answers: If all these methods return false, even if strings seem to be equal, it is possible that there is a whitespace to the left and or right of one string. So, just put a .trim() at the end of strings before comparing:

if(s1.trim() === s2.trim())
{
    // your code
}

I have lost hours trying to figure out what is wrong. Hope this will help to someone!

Does Python's time.time() return the local or UTC timestamp?

There is no such thing as an "epoch" in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is Jan 1 1970 00:00:00 UTC. So time.time() returns the number of seconds since the epoch.

How can I tell which button was clicked in a PHP form submit?

All you need to give the name attribute to the each button. And you need to address each button press from the PHP script. But be careful to give each button a unique name. Because the PHP script only take care of the name most of the time

<input type="submit" name="Submit_this" id="This" />

Apply jQuery datepicker to multiple instances

I had the same problem, but finally discovered that it was an issue with the way I was invoking the script from an ASP web user control. I was using ClientScript.RegisterStartupScript(), but forgot to give the script a unique key (the second argument). With both scripts being assigned the same key, only the first box was actually being converted into a datepicker. So I decided to append the textbox's ID to the key to make it unique:

Page.ClientScript.RegisterStartupScript(this.GetType(), "DPSetup" + DPTextbox.ClientID, dpScript);

Inline onclick JavaScript variable

There's an entire practice that says it's a bad idea to have inline functions/styles. Taking into account you already have an ID for your button, consider

JS

var myvar=15;
function init(){
    document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
}
window.onload=init;

HTML

<input id="EditBanner" type="button"  value="Edit Image" />

How to hide reference counts in VS2013?

The other features of CodeLens like: Show Bugs, Show Test Status, etc (other than Show Reference) might be useful.

However, if the only way to disable Show References is to disable CodeLens altogether.

Then, I guess I could do just that.

Furthermore, I would do like I always have, 'right-click on a member and choose Find all References or Ctrl+K, R'

If I wanted to know what references the member -- I too like not having any extra information crammed into my code, like extra white-space.

In short, uncheck Codelens...

SQL Server Operating system error 5: "5(Access is denied.)"

This is Windows related issue where SQL Server does not have the appropriate permission to the folder that contains .bak file and hence this error.

The easiest work around is to copy your .bak file to default SQL backup location which has all the necessary permissions. You do not need to fiddle with anything else. In SQL SERVER 2012, this location is

D:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup (SQL 2012)
C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup (SQL 2014)
C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\Backup (SQL 2016)

How do I convert a single character into it's hex ascii value in python

This might help

import binascii

x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')

print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'

x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test

This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').

Eclipse error ... cannot be resolved to a type

I was importing the source into the wrong folder. I'm so used to using Visual Studio, that I expect all IDE's to be so accommodating.

Remove whitespaces inside a string in javascript

You can use Strings replace method with a regular expression.

"Hello World ".replace(/ /g, "");

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp

RegExp

  • / / - Regular expression matching spaces

  • g - Global flag; find all matches rather than stopping after the first match

_x000D_
_x000D_
const str = "H    e            l l       o  World! ".replace(/ /g, "");_x000D_
document.getElementById("greeting").innerText = str;
_x000D_
<p id="greeting"><p>
_x000D_
_x000D_
_x000D_

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

MERGE INTO target
USING
(
    --Source data
    SELECT id, some_value, 0 deleteMe FROM source
    --And anything that has been deleted from the source
    UNION ALL
    SELECT id, null some_value, 1 deleteMe
    FROM
    (
        SELECT id FROM target
        MINUS
        SELECT id FROM source
    )
) source
   ON (target.ID = source.ID)
WHEN MATCHED THEN
    --Requires a lot of ugly CASE statements, to prevent updating deleted data
    UPDATE SET target.some_value =
        CASE WHEN deleteMe=1 THEN target.some_value ELSE source.some_value end
    ,isDeleted = deleteMe
WHEN NOT MATCHED THEN
    INSERT (id, some_value, isDeleted) VALUES (source.id, source.some_value, 0)

--Test data
create table target as
select 1 ID, 'old value 1' some_value, 0 isDeleted from dual union all
select 2 ID, 'old value 2' some_value, 0 isDeleted from dual;

create table source as
select 1 ID, 'new value 1' some_value, 0 isDeleted from dual union all
select 3 ID, 'new value 3' some_value, 0 isDeleted from dual;


--Results:
select * from target;

ID  SOME_VALUE   ISDELETED
1   new value 1  0
2   old value 2  1
3   new value 3  0

How to crop a CvMat in OpenCV?

To create a copy of the crop we want, we can do the following,

// Read img
cv::Mat img = cv::imread("imgFileName");
cv::Mat croppedImg;

// This line picks out the rectangle from the image
// and copies to a new Mat
img(cv::Rect(xMin,yMin,xMax-xMin,yMax-yMin)).copyTo(croppedImg);

// Display diff
cv::imshow( "Original Image",  img );
cv::imshow( "Cropped Image",  croppedImg);
cv::waitKey();

SSL "Peer Not Authenticated" error with HttpClient 4.1

Im not a java developer but was using a java app to test a RESTful API. In order for me to fix the error I had to install the intermediate certificates in the webserver in order to make the error go away. I was using lighttpd, the original certificate was installed on an IIS server. Hope it helps. These were the certificates I had missing on the server.

  • CA.crt
  • UTNAddTrustServer_CA.crt
  • AddTrustExternalCARoot.crt

How can I get the ID of an element using jQuery?

This can be element id , class , or automatically using even

------------------------
$(this).attr('id');
=========================
------------------------
$("a.remove[data-id='2']").attr('id');
=========================
------------------------
$("#abc1'").attr('id');
=========================

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

response.sendRedirect() from Servlet to JSP does not seem to work

Instead of using

response.sendRedirect("/demo.jsp");

Which does a permanent redirect to an absolute URL path,

Rather use RequestDispatcher. Example:

RequestDispatcher dispatcher = request.getRequestDispatcher("demo.jsp");
dispatcher.forward(request, response);

Write HTML to string

If you're looking to create an HTML document similar to how you would create an XML document in C#, you could try Microsoft's open source library, the Html Agility Pack.

It provides an HtmlDocument object that has a very similar API to the System.Xml.XmlDocument class.

How to find my php-fpm.sock?

When you look up your php-fpm.conf

example location:
cat /usr/src/php/sapi/fpm/php-fpm.conf

you will see, that you need to configure the PHP FastCGI Process Manager to actually use Unix sockets. Per default, the listen directive` is set up to listen on a TCP socket on one port. If there's no Unix socket defined, you won't find a Unix socket file.

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all IPv4 addresses on a
;                            specific port;
;   '[::]:port'            - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

Colorized grep -- viewing the entire file with highlighted matches

Alternatively you can use The Silver Searcher and do

ag <search> --passthrough

How to view file diff in git before commit

If you want to see what you haven't git added yet:

git diff myfile.txt

or if you want to see already added changes

git diff --cached myfile.txt

Changes in import statement python3

To support both Python 2 and Python 3, use explicit relative imports as below. They are relative to the current module. They have been supported starting from 2.5.

from .sister import foo
from . import brother
from ..aunt import bar
from .. import uncle

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

find the path to imdb.py then just add the flag to np.load(path,...flag...)

    def load_data(.......):
    .......................................
    .......................................
    - with np.load(path) as f:
    + with np.load(path,allow_pickle=True) as f:

fastest MD5 Implementation in JavaScript

I've heard Joseph's Myers implementation is quite fast. Additionally, he has a lengthy article on Javascript optimization describing what he learned while writing his implementation. It's a good read for anyone interested in performant javascript.

http://www.webreference.com/programming/javascript/jkm3/

His MD5 implementation can be found here

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

ssl.SSLError: tlsv1 alert protocol version

None of the accepted answers pointed me in the right direction, and this is still the question that comes up when searching the topic, so here's my (partially) successful saga.

Background: I run a Python script on a Beaglebone Black that polls the cryptocurrency exchange Poloniex using the python-poloniex library. It suddenly stopped working with the TLSV1_ALERT_PROTOCOL_VERSION error.

Turns out that OpenSSL was fine, and trying to force a v1.2 connection was a huge wild goose chase - the library will use the latest version as necessary. The weak link in the chain was actually Python, which only defined ssl.PROTOCOL_TLSv1_2, and therefore started supporting TLS v1.2, since version 3.4.

Meanwhile, the version of Debian on the Beaglebone considers Python 3.3 the latest. The workaround I used was to install Python 3.5 from source (3.4 might have eventually worked too, but after hours of trial and error I'm done):

sudo apt-get install build-essential checkinstall
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
wget https://www.python.org/ftp/python/3.5.4/Python-3.5.4.tgz
sudo tar xzf Python-3.5.4.tgz
cd Python-3.5.4
./configure
sudo make altinstall

Maybe not all those packages are strictly necessary, but installing them all at once saves a bunch of retries. The altinstall prevents the install from clobbering existing python binaries, installing as python3.5 instead, though that does mean you have to re-install additional libraries. The ./configure took a good five or ten minutes. The make took a couple of hours.

Now this still didn't work until I finally ran

sudo -H pip3.5 install requests[security]

Which also installs pyOpenSSL, cryptography and idna. I suspect pyOpenSSL was the key, so maybe pip3.5 install -U pyopenssl would have been sufficient but I've spent far too long on this already to make sure.

So in summary, if you get TLSV1_ALERT_PROTOCOL_VERSION error in Python, it's probably because you can't support TLS v1.2. To add support, you need at least the following:

  • OpenSSL 1.0.1
  • Python 3.4
  • requests[security]

This has got me past TLSV1_ALERT_PROTOCOL_VERSION, and now I get to battle with SSL23_GET_SERVER_HELLO instead.

Turns out this is back to the original issue of Python selecting the wrong SSL version. This can be confirmed by using this trick to mount a requests session with ssl_version=ssl.PROTOCOL_TLSv1_2. Without it, SSLv23 is used and the SSL23_GET_SERVER_HELLO error appears. With it, the request succeeds.

The final battle was to force TLSv1_2 to be picked when the request is made deep within a third party library. Both this method and this method ought to have done the trick, but neither made any difference. My final solution is horrible, but effective. I edited /usr/local/lib/python3.5/site-packages/urllib3/util/ssl_.py and changed

def resolve_ssl_version(candidate):
    """
    like resolve_cert_reqs
    """
    if candidate is None:
        return PROTOCOL_SSLv23

    if isinstance(candidate, str):
        res = getattr(ssl, candidate, None)
        if res is None:
            res = getattr(ssl, 'PROTOCOL_' + candidate)
        return res

    return candidate

to

def resolve_ssl_version(candidate):
    """
    like resolve_cert_reqs
    """
    if candidate is None:
        return ssl.PROTOCOL_TLSv1_2

    if isinstance(candidate, str):
        res = getattr(ssl, candidate, None)
        if res is None:
            res = getattr(ssl, 'PROTOCOL_' + candidate)
        return res

    return candidate

and voila, my script can finally contact the server again.

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

Remove credentials from Git

The Git credential cache runs a daemon process which caches your credentials in memory and hands them out on demand. So killing your git-credential-cache--daemon process throws all these away and results in re-prompting you for your password if you continue to use this as the cache.helper option.

You could also disable use of the Git credential cache using git config --global --unset credential.helper. Then reset this, and you would continue to have the cached credentials available for other repositories (if any). You may also need to do git config --system --unset credential.helper if this has been set in the system configuration file (for example, Git for Windows 2).

On Windows you might be better off using the manager helper (git config --global credential.helper manager). This stores your credentials in the Windows credential store which has a Control Panel interface where you can delete or edit your stored credentials. With this store, your details are secured by your Windows login and can persist over multiple sessions. The manager helper included in Git for Windows 2.x has replaced the earlier wincred helper that was added in Git for Windows 1.8.1.1. A similar helper called winstore is also available online and was used with GitExtensions as it offers a more GUI driven interface. The manager helper offers the same GUI interface as winstore.

Extract from the Windows 10 support page detailing the Windows credential manager:

To open Credential Manager, type "credential manager" in the search box on the taskbar and select Credential Manager Control panel.

And then select Windows Credentials to edit (=remove or modify) the stored git credentials for a given URL.

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

If I can throw my hat into the ring, I think there is a cleaner way than the existing answers to reuse the radio button functionality.

Let's say you have the following property in your ViewModel:

Public Class ViewModel
    <Display(Name:="Do you like Cats?")>
    Public Property LikesCats As Boolean
End Class

You can expose that property through a reusable editor template:

First, create the file Views/Shared/EditorTemplates/YesNoRadio.vbhtml

Then add the following code to YesNoRadio.vbhtml:

@ModelType Boolean?

<fieldset>
    <legend>
        @Html.LabelFor(Function(model) model)
    </legend>

    <label>
        @Html.RadioButtonFor(Function(model) model, True) Yes
    </label>
    <label>
        @Html.RadioButtonFor(Function(model) model, False) No
    </label>
</fieldset>

You can call the editor for the property by manually specifying the template name in your View:

@Html.EditorFor(Function(model) model.LikesCats, "YesNoRadio")

Pros:

  • Get to write HTML in an HTML editor instead of appending strings in code behind.
  • Preserves the DisplayName DataAnnotation
  • Allows clicks on Label to toggle radio button
  • Least possible code to maintain in form (1 line). If something is wrong with the way it is rending, take it up with the template.

Adding hours to JavaScript Date object?

SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.

Here's how you do that:

var milliseconds = 0;          //amount of time from current date/time
var sec = 0;                   //(+): future
var min = 0;                   //(-): past
var hours = 2;
var days = 0;

var startDate = new Date();     //start date in local time (we'll use current time as an example)

var time = startDate.getTime(); //convert to milliseconds since epoch

//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);

var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now

or do it in one line (where variable names are the same as above:
var newDate = 
    new Date(startDate.getTime() + millisecond + 
        1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));

SQL datetime format to date only

With SQL server you can use this

SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY];

with mysql server you can do the following

SELECT * FROM my_table WHERE YEAR(date_field) = '2006' AND MONTH(date_field) = '9' AND DAY(date_field) = '11'

CSS center display inline block?

If you have a <div> with text-align:center;, then any text inside it will be centered with respect to the width of that container element. inline-block elements are treated as text for this purpose, so they will also be centered.

Use Font Awesome Icons in CSS

For this you just need to add content attribute and font-family attribute to the required element via :before or :after wherever applicable.

For example: I wanted to attach an attachment icon after all the a element inside my post. So, first I need to search if such icon exists in fontawesome. Like in the case I found it here, i.e. fa fa-paperclip. Then I would right click the icon there, and go the ::before pseudo property to fetch out the content tag it is using, which in my case I found to be \f0c6. Then I would use that in my css like this:

   .post a:after {
     font-family: FontAwesome,
     content: " \f0c6" /* I added a space before \ for better UI */
    }

rsync error: failed to set times on "/foo/bar": Operation not permitted

As @racl101 has commented on an answer, this problem might be related to the folder owner. The rsync command should be done by the same user as the folder owner's one. If it's not the same, you can change it.

chown -R userCorrect /remote/path/to/foo/bar

How to verify that a specific method was not called using Mockito?

As a more general pattern to follow, I tend to use an @After block in the test:

@After
public void after() {
    verifyNoMoreInteractions(<your mock1>, <your mock2>...);
}

Then the test is free to verify only what should be called.

Also, I found that I often forgot to check for "no interactions", only to later discover that things were being called that shouldn't have been.

So I find this pattern useful for catching all unexpected calls that haven't specifically been verified.

error: package com.android.annotations does not exist

For Ionic, try this:

ionic cordova plugin add cordova-plugin-androidx
ionic cordova plugin add cordova-plugin-androidx-adapter

The error comes because this app is not using androidX but these plugins solve errors.

What is the difference between Amazon SNS and Amazon SQS?

Here's a comparison of the two:

Entity Type

  • SQS: Queue (Similar to JMS)
  • SNS: Topic (Pub/Sub system)

Message consumption

  • SQS: Pull Mechanism - Consumers poll and pull messages from SQS
  • SNS: Push Mechanism - SNS Pushes messages to consumers

Use Case

  • SQS: Decoupling two applications and allowing parallel asynchronous processing
  • SNS: Fanout - Processing the same message in multiple ways

Persistence

  • SQS: Messages are persisted for some (configurable) duration if no consumer is available (maximum two weeks), so the consumer does not have to be up when messages are added to queue.
  • SNS: No persistence. Whichever consumer is present at the time of message arrival gets the message and the message is deleted. If no consumers are available then the message is lost after a few retries.

Consumer Type

  • SQS: All the consumers are typically identical and hence process the messages in the exact same way (each message is processed once by one consumer, though in rare cases messages may be resent)
  • SNS: The consumers might process the messages in different ways

Sample applications

  • SQS: Jobs framework: The Jobs are submitted to SQS and the consumers at the other end can process the jobs asynchronously. If the job frequency increases, the number of consumers can simply be increased to achieve better throughput.
  • SNS: Image processing. If someone uploads an image to S3 then watermark that image, create a thumbnail and also send a Thank You email. In that case S3 can publish notifications to an SNS topic with three consumers listening to it. The first one watermarks the image, the second one creates a thumbnail and the third one sends a Thank You email. All of them receive the same message (image URL) and do their processing in parallel.

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

I'd do

for i in `seq 0 2 10`; do echo $i; done

(though of course seq 0 2 10 will produce the same output on its own).

Note that seq allows floating-point numbers (e.g., seq .5 .25 3.5) but bash's brace expansion only allows integers.

How to pass form input value to php function

You can write your php file to the action attr of form element.
At the php side you can get the form value by $_POST['element_name'].

What does PHP keyword 'var' do?

So basically it is an old style and do not use it for newer version of PHP. Better to use Public keyword instead;if you are not in love with var keyword. So instead of using

class Test {
    var $name;
}

Use

class Test {
   public $name;
}

How to check if a number is a power of 2

bool isPow2 = ((x & ~(x-1))==x)? !!x : 0;

int to unsigned int conversion

This conversion is well defined and will yield the value UINT_MAX - 61. On a platform where unsigned int is a 32-bit type (most common platforms, these days), this is precisely the value that others are reporting. Other values are possible, however.

The actual language in the standard is

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type).

Getting Access Denied when calling the PutObject operation with bucket-level permission

In case this help out anyone else, in my case, I was using a CMK (it worked fine using the default aws/s3 key)

I had to go into my encryption key definition in IAM and add the programmatic user logged into boto3 to the list of users that "can use this key to encrypt and decrypt data from within applications and when using AWS services integrated with KMS.".

What is the difference between Normalize.css and Reset CSS?

The major difference is that:

  • CSS resets aim to remove all built-in browser styling. Standard elements like H1-6, p, strong, em, et cetera end up looking exactly alike, having no decoration at all. You're then supposed to add all decoration yourself.

  • Normalize CSS aims to make built-in browser styling consistent across browsers. Elements like H1-6 will appear bold, larger et cetera in a consistent way across browsers. You're then supposed to add only the difference in decoration your design needs.

If your design a) follows common conventions for typography et cetera, and b) Normalize.css works for your target audience, then using Normalize.CSS instead of a CSS reset will make your own CSS smaller and faster to write.

What is monkey patching?

Monkey patching is reopening the existing classes or methods in class at runtime and changing the behavior, which should be used cautiously, or you should use it only when you really need to.

As Python is a dynamic programming language, Classes are mutable so you can reopen them and modify or even replace them.

What is an MvcHtmlString and when should I use it?

ASP.NET 4 introduces a new code nugget syntax <%: %>. Essentially, <%: foo %> translates to <%= HttpUtility.HtmlEncode(foo) %>. The team is trying to get developers to use <%: %> instead of <%= %> wherever possible to prevent XSS.

However, this introduces the problem that if a code nugget already encodes its result, the <%: %> syntax will re-encode it. This is solved by the introduction of the IHtmlString interface (new in .NET 4). If the foo() in <%: foo() %> returns an IHtmlString, the <%: %> syntax will not re-encode it.

MVC 2's helpers return MvcHtmlString, which on ASP.NET 4 implements the interface IHtmlString. Therefore when developers use <%: Html.*() %> in ASP.NET 4, the result won't be double-encoded.

Edit:

An immediate benefit of this new syntax is that your views are a little cleaner. For example, you can write <%: ViewData["anything"] %> instead of <%= Html.Encode(ViewData["anything"]) %>.

Where is SQL Profiler in my SQL Server 2008?

Management Studio->Tools->SQL Server Profiler.

If it is not installed see this link

Concatenating two one-dimensional NumPy arrays

An alternative ist to use the short form of "concatenate" which is either "r_[...]" or "c_[...]" as shown in the example code beneath (see http://wiki.scipy.org/NumPy_for_Matlab_Users for additional information):

%pylab
vector_a = r_[0.:10.] #short form of "arange"
vector_b = array([1,1,1,1])
vector_c = r_[vector_a,vector_b]
print vector_a
print vector_b
print vector_c, '\n\n'

a = ones((3,4))*4
print a, '\n'
c = array([1,1,1])
b = c_[a,c]
print b, '\n\n'

a = ones((4,3))*4
print a, '\n'
c = array([[1,1,1]])
b = r_[a,c]
print b

print type(vector_b)

Which results in:

[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
[1 1 1 1]
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.  1.  1.  1.  1.] 


[[ 4.  4.  4.  4.]
 [ 4.  4.  4.  4.]
 [ 4.  4.  4.  4.]] 

[[ 4.  4.  4.  4.  1.]
 [ 4.  4.  4.  4.  1.]
 [ 4.  4.  4.  4.  1.]] 


[[ 4.  4.  4.]
 [ 4.  4.  4.]
 [ 4.  4.  4.]
 [ 4.  4.  4.]] 

[[ 4.  4.  4.]
 [ 4.  4.  4.]
 [ 4.  4.  4.]
 [ 4.  4.  4.]
 [ 1.  1.  1.]]

How to save a bitmap on internal storage

private static void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().getAbsolutePath();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();

    String fname = "Image-"+ o +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete ();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

Git: How to remove remote origin from Git repo

first will change push remote url

git remote set-url --push origin https://newurl

second will change fetch remote url

git remote set-url origin https://newurl

Pass multiple parameters to rest API - Spring

you can pass multiple params in url like

http://localhost:2000/custom?brand=dell&limit=20&price=20000&sort=asc

and in order to get this query fields , you can use map like

    @RequestMapping(method = RequestMethod.GET, value = "/custom")
    public String controllerMethod(@RequestParam Map<String, String> customQuery) {

        System.out.println("customQuery = brand " + customQuery.containsKey("brand"));
        System.out.println("customQuery = limit " + customQuery.containsKey("limit"));
        System.out.println("customQuery = price " + customQuery.containsKey("price"));
        System.out.println("customQuery = other " + customQuery.containsKey("other"));
        System.out.println("customQuery = sort " + customQuery.containsKey("sort"));

        return customQuery.toString();
    }

Spring - @Transactional - What happens in background?

This is a big topic. The Spring reference doc devotes multiple chapters to it. I recommend reading the ones on Aspect-Oriented Programming and Transactions, as Spring's declarative transaction support uses AOP at its foundation.

But at a very high level, Spring creates proxies for classes that declare @Transactional on the class itself or on members. The proxy is mostly invisible at runtime. It provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied. Transaction management is just one example of the behaviors that can be hooked in. Security checks are another. And you can provide your own, too, for things like logging. So when you annotate a method with @Transactional, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.

Transactions in EJB work similarly, by the way.

As you observed, through, the proxy mechanism only works when calls come in from some external object. When you make an internal call within the object, you're really making a call through the "this" reference, which bypasses the proxy. There are ways of working around that problem, however. I explain one approach in this forum post in which I use a BeanFactoryPostProcessor to inject an instance of the proxy into "self-referencing" classes at runtime. I save this reference to a member variable called "me". Then if I need to make internal calls that require a change in the transaction status of the thread, I direct the call through the proxy (e.g. "me.someMethod()".) The forum post explains in more detail. Note that the BeanFactoryPostProcessor code would be a little different now, as it was written back in the Spring 1.x timeframe. But hopefully it gives you an idea. I have an updated version that I could probably make available.

Get local href value from anchor (a) tag

The below code gets the full path, where the anchor points:

document.getElementById("aaa").href; // http://example.com/sec/IF00.html

while the one below gets the value of the href attribute:

document.getElementById("aaa").getAttribute("href"); // sec/IF00.html

Displaying the Error Messages in Laravel after being Redirected from controller

Laravel 4

When the validation fails return back with the validation errors.

if($validator->fails()) {
    return Redirect::back()->withErrors($validator);
}

You can catch the error on your view using

@if($errors->any())
    {{ implode('', $errors->all('<div>:message</div>')) }}
@endif

UPDATE

To display error under each field you can do like this.

<input type="text" name="firstname">
@if($errors->has('firstname'))
    <div class="error">{{ $errors->first('firstname') }}</div>
@endif

For better display style with css.

You can refer to the docs here.

UPDATE 2

To display all errors at once

@if($errors->any())
    {!! implode('', $errors->all('<div>:message</div>')) !!}
@endif

To display error under each field.

@error('firstname')
    <div class="error">{{ $message }}</div>
@enderror

How does DISTINCT work when using JPA and Hibernate

You are close.

select DISTINCT(c.name) from Customer c

SQL Server: Get data for only the past year

The following adds -1 years to the current date:

SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())

Perl - Multiple condition if statement without duplicating code?

if (   ($name eq "tom" and $password eq "123!")
    or ($name eq "frank" and $password eq "321!")) {

    print "You have gained access.";
}
else {
    print "Access denied!";
}

Height of an HTML select box (dropdown)

NO. It's not possible to change height of a select dropdown because that property is browser specific.

However if you want that functionality, then there are many options. You can use bootstrap dropdown-menu and define it's max-height property. Something like this.

_x000D_
_x000D_
$('.dropdown-menu').on( 'click', 'a', function() {_x000D_
    var text = $(this).html();_x000D_
    var htmlText = text + ' <span class="caret"></span>';_x000D_
    $(this).closest('.dropdown').find('.dropdown-toggle').html(htmlText);_x000D_
});
_x000D_
.dropdown-menu {_x000D_
    max-height: 146px;_x000D_
    overflow: scroll;_x000D_
    overflow-x: hidden;_x000D_
    margin-top: 0px;_x000D_
}_x000D_
_x000D_
.caret {_x000D_
   float: right;_x000D_
    margin-top: 5%;_x000D_
}_x000D_
_x000D_
#menu1 {_x000D_
    width: 160px; _x000D_
    text-align: left;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
   _x000D_
<div class="container" style="margin:10px">_x000D_
  <div class="dropdown">_x000D_
    <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Tutorials_x000D_
    <span class="caret"></span></button>_x000D_
    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
      <li><a href="#">HTML</a></li>_x000D_
      <li><a href="#">CSS</a></li>_x000D_
      <li><a href="#">JavaScript</a></li>_x000D_
      <li><a href="#">About Us</a></li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

VBA Macro to compare all cells of two Excel files

A very simple check you can do with Cell formulas:

Sheet 1 (new - old)

=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")

Sheet 2 (old - new)

=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")

This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)

You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".

Doe the same for Sheet two.

Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.

But two cases are not covered here:

  1. In the compared cell of New and Old is the same data (Resulting Cell will be empty)
  2. In the compared cell of New and Old is diffe data (Resulting Cell will be empty)

To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com

How to get the 'height' of the screen using jquery

$(window).height();

To set anything in the middle you can use CSS.

<style>
#divCentre 
{ 
    position: absolute;
    left: 50%;
    top: 50%;
    width: 300px;
    height: 400px;
    margin-left: -150px;
    margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>

How do I generate random integers within a specific range in Java?

Another option is just using Apache Commons:

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

public void method() {
    RandomData randomData = new RandomDataImpl();
    int number = randomData.nextInt(5, 10);
    // ...
 }

Two column div layout with fluid left and fixed right column

CSS:

#sidebar {float: right; width: 200px; background: #eee;}
#content {overflow: hidden; background: #dad;}

HTML:

<div id="sidebar">I'm 200px wide</div>
<div id="content"> I take up the remaining space <br> and I don't wrap under the right column</div>

The above should work, you can put that code in wrapper if you want the give it width and center it too, overflow:hidden on the column without a width is the key to getting it to contain, vertically, as in not wrap around the side columns (can be left or right)

IE6 might need zoom:1 set on the #content div too if you need it's support

Getting input values from text box

Javascript document.getElementById("<%=contrilid.ClientID%>").value; or using jquery

$("#<%= txt_iplength.ClientID %>").val();

Left align and right align within div in Bootstrap

bootstrap 5.0

_x000D_
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

<div class="row">
  <div class="col-sm-6"><p class="float-start">left</p></div>  
  <div class="col-sm-6"><p class="float-end">right</p></div>  
</div>
_x000D_
_x000D_
_x000D_

A whole column can accommodate 12, 6 (col-sm-6) is exactly half, and in this half, one to the left(float-start) and one to the right(float-end).

more example

  • fontawesome-button

    _x000D_
    _x000D_
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />
    
    <div class="row">
      <div class=col-sm-6>
        <p class="float-start text-center">  <!-- text-center can help you put the icon at the center -->
          <a class="text-decoration-none" href="https://www.google.com/"
          ><i class="fas fa-arrow-circle-left fa-3x"></i><br>Left
          </a>
        </p>
      </div>
      <div class=col-sm-6>
        <p class="float-end text-center">
          <a class="text-decoration-none" href="https://www.google.com/"
          ><i class="fas fa-arrow-circle-right fa-3x"></i><br>Right
          </a>
        </p>
      </div>  
    _x000D_
    _x000D_
    _x000D_

Java - get index of key in HashMap?

Posting this as an equally viable alternative to @Binil Thomas's answer - tried to add it as a comment, but was not convinced of the readability of it all.

int index = 0;

for (Object key : map.keySet()) {
   Object value = map.get(key);
   ++index;
}

Probably doesn't help the original question poster since this is the literal situation they were trying to avoid, but may aid others searching for an easy answer.

Rails 4 LIKE query - ActiveRecord adds quotes

While string interpolation will work, as your question specifies rails 4, you could be using Arel for this and keeping your app database agnostic.

def self.search(query, page=1)
  query = "%#{query}%"
  name_match = arel_table[:name].matches(query)
  postal_match = arel_table[:postal_code].matches(query)
  where(name_match.or(postal_match)).page(page).per_page(5)
end

Very simple log4j2 XML configuration file using Console and File appender

There are excellent answers, but if you want to color your console logs you can use the pattern :

<PatternLayout pattern="%style{%date{DEFAULT}}{yellow}
            [%t] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green} %logger{36} - %message\n"/>

The full log4j2 file is:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="APP_LOG_ROOT">/opt/test/log</Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT">
            <PatternLayout pattern="%style{%date{DEFAULT}}{yellow}
                [%t] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green} %logger{36} - %message\n"/>
        </Console>
        <RollingFile name="XML_ROLLING_FILE_APPENDER"
                     fileName="${APP_LOG_ROOT}/appName.log"
                     filePattern="${APP_LOG_ROOT}/appName-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="%d{DEFAULT} [%t] %-5level %logger{36} - %msg%n"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="19500KB"/>
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="error">
            <AppenderRef ref="ConsoleAppender"/>
        </Root>
        <Logger name="com.compName.projectName" level="debug">
            <AppenderRef ref="XML_ROLLING_FILE_APPENDER"/>
        </Logger>
    </Loggers>
</Configuration>

And the logs will look like this: enter image description here

How to check if a value is not null and not empty string in JS

When we code empty in essence could mean any one of the following given the circumstances;

  • 0 as in number value
  • 0.0 as in float value
  • '0' as in string value
  • '0.0' as in string value
  • null as in Null value, as per chance it could also capture undefined or it may not
  • undefined as in undefined value
  • false as in false truthy value, as per chance 0 also as truthy but what if we want to capture false as it is
  • '' empty sting value with no white space or tab
  • ' ' string with white space or tab only

In real life situation as OP stated we may wish to test them all or at times we may only wish to test for limited set of conditions.

Generally if(!a){return true;} serves its purpose most of the time however it will not cover wider set of conditions.

Another hack that has made its round is return (!value || value == undefined || value == "" || value.length == 0);

But what if we need control on whole process?

There is no simple whiplash solution in native core JavaScript it has to be adopted. Considering we drop support for legacy IE11 (to be honest even windows has so should we) below solution born out of frustration works in all modern browsers;

 function empty (a,b=[])
 {if(!Array.isArray(b)) return; 
 var conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
 if(conditions.includes(a)|| (typeof a === 'string' && conditions.includes(a.toString().trim())))
 {return true;};
 return false;};`

Logic behind the solution is function has two parameters a and b, a is value we need to check, b is a array with set conditions we need to exclude from predefined conditions as listed above. Default value of b is set to an empty array [].

First run of function is to check if b is an array or not, if not then early exit the function.

next step is to compute array difference from [null,'0','0.0',false,undefined,''] and from array b. if b is an empty array predefined conditions will stand else it will remove matching values.

conditions = [predefined set] - [to be excluded set] filter function does exactly that make use of it. Now that we have conditions in array set all we need to do is check if value is in conditions array. includes function does exactly that no need to write nasty loops of your own let JS engine do the heavy lifting.

Gotcha if we are to convert a into string for comparison then 0 and 0.0 would run fine however Null and Undefined would through error blocking whole script. We need edge case solution. Below simple || covers the edge case if first condition is not satisfied. Running another early check through include makes early exit if not met.

if(conditions.includes(a)||  (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim())))

trim() function will cover for wider white spaces and tabs only value and will only come into play in edge case scenario.

Play ground

_x000D_
_x000D_
function empty (a,b=[]){
if(!Array.isArray(b)) return;
conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)|| 
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
 return true;
} 
return false;
}

console.log('1 '+empty());
console.log('2 '+empty(''));
console.log('3 '+empty('      '));
console.log('4 '+empty(0));
console.log('5 '+empty('0'));
console.log('6 '+empty(0.0));
console.log('7 '+empty('0.0'));
console.log('8 '+empty(false));
console.log('9 '+empty(null));
console.log('10 '+empty(null,[null]));
console.log('11 dont check 0 as number '+empty(0,['0']));
console.log('12 dont check 0 as string '+empty('0',['0']));
console.log('13 as number for false as value'+empty(false,[false]));
_x000D_
_x000D_
_x000D_

Lets make it complex - what if our value to compare is array its self and can be as deeply nested it can be. what if we are to check if any value in array is empty, it can be an edge business case.

_x000D_
_x000D_
function empty (a,b=[]){
    if(!Array.isArray(b)) return;

    conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
    if(Array.isArray(a) && a.length > 0){
    for (i = 0; i < a.length; i++) { if (empty(a[i],b))return true;} 
    } 
    
    if(conditions.includes(a)|| 
    (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
     return true;
    } 
    return false;
    }

console.log('checking for all values '+empty([1,[0]]));
console.log('excluding for 0 from condition '+empty([1,[0]], ['0']));
_x000D_
_x000D_
_x000D_

it simple and wider use case function that I have adopted in my framework;

  • Gives control over as to what exactly is the definition of empty in a given situation
  • Gives control over to redefine conditions of empty
  • Can compare for almost for every thing from string, number, float, truthy, null, undefined and deep arrays
  • Solution is drawn keeping in mind the resuability and flexibility. All other answers are suited in case if simple one or two cases are to be dealt with. However, there is always a case when definition of empty changes while coding above snippets make work flawlessly in that case.

Importing modules from parent folder

You can use OS depending path in "module search path" which is listed in sys.path . So you can easily add parent directory like following

import sys
sys.path.insert(0,'..')

If you want to add parent-parent directory,

sys.path.insert(0,'../..')

This works both in python 2 and 3.

How do you add an image?

Shouldn't that be:

<xsl:value-of select="/root/Image/img/@src"/>

? It looks like you are trying to copy the entire Image/img node to the attribute @src

How to download a branch with git?

For any Git newbies like me, here are some steps you could follow to download a remote repository, and then switch to the branch that you want to view. They probably abuse Git in some way, but it did the job for me! :-)

Clone the repository you want to download the code for (in this example I've picked the LRResty project on Github):

$ git clone https://github.com/lukeredpath/LRResty.git
$ cd LRResty

Check what branch you are using at this point (it should be the master branch):

$ git branch    
* master

Check out the branch you want, in my case it is called 'arcified':

 $ git checkout -b arcified origin/arcified
 Branch arcified set up to track remote branch arcified from origin.
 Switched to a new branch 'arcified'

Confirm you are now using the branch you wanted:

$ git branch    
* arcified
  master

If you want to update the code again later, run git pull:

$ git pull
Already up-to-date.

printf formatting (%d versus %u)

The difference is simple: they cause different warning messages to be emitted when compiling:

1156942.c:7:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %d\n", &a); // prints "memory add=-12"
                               ^
1156942.c:8:31: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %u\n", &a); // prints "memory add=65456"
                               ^

If you pass your pointer as a void* and use %p as the conversion specifier, then you get no error message:

#include <stdio.h>

int main()
{
    int a = 5;
    // check the memory address
    printf("memory address = %d\n", &a); /* wrong */
    printf("memory address = %u\n", &a); /* wrong */
    printf("memory address = %p\n", (void*)&a); /* right */
}

importing a CSV into phpmyadmin

In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :

enter image description here

how to create a list of lists

You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:

>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]

crop text too long inside div

.crop { 
  overflow:hidden; 
  white-space:nowrap; 
  text-overflow:ellipsis; 
  width:100px; 
}?

http://jsfiddle.net/hT3YA/

Any way to clear python's IDLE window?

It seems it is impossible to do it without any external library.

An alternative way if you are using windows and don't want to open and close the shell everytime you want to clear it is by using windows command prompt.

  • Type python and hit enter to turn windows command prompt to python idle (make sure python is installed).

  • Type quit() and hit enter to turn it back to windows command prompt.

  • Type cls and hit enter to clear the command prompt/ windows shell.

Javascript Regular Expression Remove Spaces

I would recommend you use the literal notation, and the \s character class:

//..
return str.replace(/\s/g, '');
//..

There's a difference between using the character class \s and just ' ', this will match a lot more white-space characters, for example '\t\r\n' etc.., looking for ' ' will replace only the ASCII 32 blank space.

The RegExp constructor is useful when you want to build a dynamic pattern, in this case you don't need it.

Moreover, as you said, "[\s]+" didn't work with the RegExp constructor, that's because you are passing a string, and you should "double escape" the back-slashes, otherwise they will be interpreted as character escapes inside the string (e.g.: "\s" === "s" (unknown escape)).

How do I find the length/number of items present for an array?

If the array is statically allocated, use sizeof(array) / sizeof(array[0])

If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0]) (which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.

Check if a String is in an ArrayList of Strings

The List interface already has this solved.

int temp = 2;
if(bankAccNos.contains(bakAccNo)) temp=1;

More can be found in the documentation about List.

download file using an ajax request

It is possible. You can have the download started from inside an ajax function, for example, just after the .csv file is created.

I have an ajax function that exports a database of contacts to a .csv file, and just after it finishes, it automatically starts the .csv file download. So, after I get the responseText and everything is Ok, I redirect browser like this:

window.location="download.php?filename=export.csv";

My download.php file looks like this:

<?php

    $file = $_GET['filename'];

    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=".$file."");
    header("Content-Transfer-Encoding: binary");
    header("Content-Type: binary/octet-stream");
    readfile($file);

?>

There is no page refresh whatsoever and the file automatically starts downloading.

NOTE - Tested in the following browsers:

Chrome v37.0.2062.120 
Firefox v32.0.1
Opera v12.17
Internet Explorer v11

Force the origin to start at 0

Simply add these to your ggplot:

+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

Example

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for


p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

enter image description here

Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge' could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules