Programs & Examples On #Max path

How do I find files with a path length greater than 260 characters in Windows?

you can redirect stderr.

more explanation here, but having a command like:

MyCommand >log.txt 2>errors.txt

should grab the data you are looking for.

Also, as a trick, Windows bypasses that limitation if the path is prefixed with \\?\ (msdn)

Another trick if you have a root or destination that starts with a long path, perhaps SUBST will help:

SUBST Q: "C:\Documents and Settings\MyLoginName\My Documents\MyStuffToBeCopied"
Xcopy Q:\ "d:\Where it needs to go" /s /e
SUBST Q: /D

Getting the last n elements of a vector. Is there a better way than using the length() function?

Here is a function to do it and seems reasonably fast.

endv<-function(vec,val) 
{
if(val>length(vec))
{
stop("Length of value greater than length of vector")
}else
{
vec[((length(vec)-val)+1):length(vec)]
}
}

USAGE:

test<-c(0,1,1,0,0,1,1,NA,1,1)
endv(test,5)
endv(LETTERS,5)

BENCHMARK:

                                                    test replications elapsed relative
1                                 expression(tail(x, 5))       100000    5.24    6.469
2 expression(x[seq.int(to = length(x), length.out = 5)])       100000    0.98    1.210
3                       expression(x[length(x) - (4:0)])       100000    0.81    1.000
4                                 expression(endv(x, 5))       100000    1.37    1.691

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.

I can't figure out exactly what's there, yet ...

edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.

A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.

If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.

How to create a private class method?

Just for the completeness, we can also avoid declaring private_class_method in a separate line. I personally don't like this usage but good to know that it exists.

private_class_method  def self.method_name
 ....
end

How to specify the port an ASP.NET Core application is hosted on?

Alternatively, you can specify port by running app via command line.

Simply run command:

dotnet run --server.urls http://localhost:5001

Note: Where 5001 is the port you want to run on.

Cannot get OpenCV to compile because of undefined references?

For me, this type of error:

mingw-w64-x86_64/lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld: mingw-w64-x86_64/x86_64-w64-mingw32/lib/libTransform360.a(VideoFrameTransform.cpp.obj):VideoFrameTransform.cpp:(.text+0xc7c):
undefined reference to `cv::Mat::Mat(cv::Mat const&, cv::Rect_<int> const&)'

meant load order, I had to do -lTransform360 -lopencv_dnn345 -lopencv... just like that, that order. And putting them right next to each other helped too, don't put -lTransform360 all the way at the beginning...or you'll get, for some freaky reason:

undefined reference to `VideoFrameTransform_new'
undefined reference to `VideoFrameTransform_generateMapForPlane'

...

How do I ignore files in a directory in Git?

Paths which contain slashes are taken to be relative to the directory containing the .gitignore file - usually the top level of your repository, though you can also place them in subdirectories.

So, since in all of the examples you give, the paths contain slashes, the two versions are identical. The only time you need to put a leading slash is when there isn't one in the path already. For example, to ignore foo only at the top level of the repository, use /foo. Simply writing foo would ignore anything called foo anywhere in the repository.

Your wildcards are also redundant. If you want to ignore an entire directory, simply name it:

lib/model/om

The only reason to use wildcards the way you have is if you intend to subsequently un-ignore something in the directory:

lib/model/om/*      # ignore everything in the directory
!lib/model/om/foo   # except foo

How do I pass a variable by reference?

Since your example happens to be object-oriented, you could make the following change to achieve a similar result:

class PassByReference:
    def __init__(self):
        self.variable = 'Original'
        self.change('variable')
        print(self.variable)

    def change(self, var):
        setattr(self, var, 'Changed')

# o.variable will equal 'Changed'
o = PassByReference()
assert o.variable == 'Changed'

Animation fade in and out

we can simply use:

public void animStart(View view) {
    if(count==0){
        Log.d("count", String.valueOf(count));
        i1.animate().alpha(0f).setDuration(2000);
        i2.animate().alpha(1f).setDuration(2000);
        count =1;
    }
    else if(count==1){
        Log.d("count", String.valueOf(count));
        count =0;
        i2.animate().alpha(0f).setDuration(2000);
        i1.animate().alpha(1f).setDuration(2000);
    }
}

where i1 and i2 are defined in the onCreateView() as:

    i1 = (ImageView)findViewById(R.id.firstImage);
    i2 = (ImageView)findViewById(R.id.secondImage);

count is a class variable initilaized to 0.

The XML file is :

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        <ImageView
            android:id="@+id/secondImage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="animStart"
            android:src="@drawable/second" />
      <ImageView
          android:id="@+id/firstImage"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"

          android:onClick="animStart"
          android:src="@drawable/first" />
    </RelativeLayout>

@drawable/first and @drawable/second are the images in the drawable folder in res.

HTTP Basic: Access denied fatal: Authentication failed

The updating of the password in the windows credential manager was not the solution for me.

I had to set a different remote url, by:

git remote set-url origin https://gitlab....git

The url in this case was the one that could be found in Gitlab under Clone -> Clone with HTTPS. It was not the one in the command line instructions.

How to tell if browser/tab is active

If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.

$(window).hover(function() {
  // code here...
});

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

Many ways to do this, you can use DATENAME and check for the actual strings 'Saturday' or 'Sunday'

SELECT DATENAME(DW, GETDATE())

Or use the day of the week and check for 1 (Sunday) or 7 (Saturday)

SELECT DATEPART(DW, GETDATE())

Should __init__() call the parent class's __init__()?

Yes, you should always call base class __init__ explicitly as a good coding practice. Forgetting to do this can cause subtle issues or run time errors. This is true even if __init__ doesn't take any parameters. This is unlike other languages where compiler would implicitly call base class constructor for you. Python doesn't do that!

The main reason for always calling base class _init__ is that base class may typically create member variable and initialize them to defaults. So if you don't call base class init, none of that code would be executed and you would end up with base class that has no member variables.

Example:

class Base:
  def __init__(self):
    print('base init')

class Derived1(Base):
  def __init__(self):
    print('derived1 init')

class Derived2(Base):
  def __init__(self):
    super(Derived2, self).__init__()
    print('derived2 init')

print('Creating Derived1...')
d1 = Derived1()
print('Creating Derived2...')
d2 = Derived2()

This prints..

Creating Derived1...
derived1 init
Creating Derived2...
base init
derived2 init

Run this code.

Detect browser or tab closing

For similar tasks, you can use sessionStorage to store data locally until the browser tab is closed.

The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).(W3Schools)

This is my pen.

<div id="Notice">
    <span title="remove this until browser tab is closed"><u>dismiss</u>.</span>
</div>
<script>
    $("#Notice").click(function() {
     //set sessionStorage on click
        sessionStorage.setItem("dismissNotice", "Hello");
        $("#Notice").remove();
    });
    if (sessionStorage.getItem("dismissNotice"))
    //When sessionStorage is set Do stuff...
        $("#Notice").remove();
</script>

How do I call an Angular.js filter with multiple arguments?

In templates, you can separate filter arguments by colons.

{{ yourExpression | yourFilter: arg1:arg2:... }}

From Javascript, you call it as

$filter('yourFilter')(yourExpression, arg1, arg2, ...)

There is actually an example hidden in the orderBy filter docs.


Example:

Let's say you make a filter that can replace things with regular expressions:

myApp.filter("regexReplace", function() { // register new filter

  return function(input, searchRegex, replaceRegex) { // filter arguments

    return input.replace(RegExp(searchRegex), replaceRegex); // implementation

  };
});

Invocation in a template to censor out all digits:

<p>{{ myText | regexReplace: '[0-9]':'X' }}</p>

php string to int

You can remove the spaces before casting to int:

(int)str_replace(' ', '', $b);

Also, if you want to strip other commonly used digit delimiters (such as ,), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):

(int)str_replace(array(' ', ','), '', $b);

Using array map to filter results with if conditional

You could use flatMap. It can filter and map in one.

$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])

Convert datetime to valid JavaScript date

Just use Date.parse() which returns a Number, then use new Date() to parse it:

var thedate = new Date(Date.parse("2011-07-14 11:23:00"));

How to get href value using jQuery?

If your html link is like this:

<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>

Then you can access the href in jquery as given below (there is no need to use "a" in href for this)

$(".linkClass").on("click",accesshref);

function accesshref()
 {
 var url = $(".linkClass").attr("href");
 //OR
 var url = $(this).attr("href");
}

Get current time in milliseconds using C++ and Boost

// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;

int main()
{
     pt::ptime current_date_microseconds = pt::microsec_clock::local_time();

    long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();

    pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);

    pt::ptime current_date_milliseconds(current_date_microseconds.date(), 
                                        current_time_milliseconds);

    std::cout << "Microseconds: " << current_date_microseconds 
              << " Milliseconds: " << current_date_milliseconds << std::endl;

    // Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}

Getting indices of True values in a boolean list

Using element-wise multiplication and a set:

>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> set(multiply(states,range(1,len(states)+1))-1).difference({-1})

Output: {4, 5, 7}

Is there a list of screen resolutions for all Android based phones and tablets?

Here is a list of almost all resolutions of tablets :

2560*1600
1366*768
1280*800
1280*768
1024*768
1024*600
960*640
960*540
854*480
800*600
800*480
800*400

Of this, the most common resolutions are :

1280*800
1280*768
1024*600
1024*800
1024*768
800*400
800*480

Happy designing .. ! :)

How to use SQL Order By statement to sort results case insensitive?

You can just convert everything to lowercase for the purposes of sorting:

SELECT * FROM NOTES ORDER BY LOWER(title);

If you want to make sure that the uppercase ones still end up ahead of the lowercase ones, just add that as a secondary sort:

SELECT * FROM NOTES ORDER BY LOWER(title), title;

Is there a way to add a gif to a Markdown file?

Giphy Gotcha

After following the 2 requirements listed above (must end in .gif and using the image syntax), if you are having trouble with a gif from giphy:

Be sure you have the correct giphy url! You can't just add .gif to the end of this one and have it work.

If you just copy the url from a browser, you will get something like:

https://giphy.com/gifs/gol-automaton-game-of-life-QfsvYoBSSpfbtFJIVo

You need to instead click on "Copy Link" and then grab the "GIF Link" specifically. Notice the correct one points to media.giphy.com instead of just giphy.com:

https://media.giphy.com/media/QfsvYoBSSpfbtFJIVo/giphy.gif

Ruby: Can I write multi-line string with no concatenation?

conn.exec 'select attr1, attr2, attr3, attr4, attr5, attr6, attr7 ' <<
        'from table1, table2, table3, etc, etc, etc, etc, etc, ' <<
        'where etc etc etc etc etc etc etc etc etc etc etc etc etc'

<< is the concatenation operator for strings

How do I get a file's last modified time in Perl?

You could use stat() or the File::Stat module.

perldoc -f stat

Which comment style should I use in batch files?

This answer attempts a pragmatic summary of the many great answers on this page:

jeb's great answer deserves special mention, because it really goes in-depth and covers many edge cases.
Notably, he points out that a misconstructed variable/parameter reference such as %~ can break any of the solutions below - including REM lines.


Whole-line comments - the only directly supported style:

  • REM (or case variations thereof) is the only official comment construct, and is the safest choice - see Joey's helpful answer.

  • :: is a (widely used) hack, which has pros and cons:

    • Pros:

    • Cons:

      • Inside (...) blocks, :: can break the command, and the rules for safe use are restrictive and not easy to remember - see below.

If you do want to use ::, you have these choices:

  • Either: To be safe, make an exception inside (...) blocks and use REM there, or do not place comments inside (...) altogether.
  • Or: Memorize the painfully restrictive rules for safe use of :: inside (...), which are summarized in the following snippet:
@echo off

for %%i in ("dummy loop") do (

  :: This works: ONE comment line only, followed by a DIFFERENT, NONBLANK line.
  date /t

  REM If you followed a :: line directly with another one, the *2nd* one
  REM would generate a spurious "The system cannot find the drive specified."
  REM error message and potentially execute commands inside the comment.
  REM In the following - commented-out - example, file "out.txt" would be
  REM created (as an empty file), and the ECHO command would execute.
  REM   :: 1st line
  REM   :: 2nd line > out.txt & echo HERE

  REM NOTE: If :: were used in the 2 cases explained below, the FOR statement
  REM would *break altogether*, reporting:
  REM  1st case: "The syntax of the command is incorrect."
  REM  2nd case: ") was unexpected at this time."

  REM Because the next line is *blank*, :: would NOT work here.

  REM Because this is the *last line* in the block, :: would NOT work here.
)

Emulation of other comment styles - inline and multi-line:

Note that none of these styles are directly supported by the batch language, but can be emulated.


Inline comments:

* The code snippets below use ver as a stand-in for an arbitrary command, so as to facilitate experimentation.
* To make SET commands work correctly with inline comments, double-quote the name=value part; e.g., SET "foo=bar".[1]

In this context we can distinguish two subtypes:

  • EOL comments ([to-the-]end-of-line), which can be placed after a command, and invariably extend to the end of the line (again, courtesy of jeb's answer):

    • ver & REM <comment> takes advantage of the fact that REM is a valid command and & can be used to place an additional command after an existing one.
    • ver & :: <comment> works too, but is really only usable outside of (...) blocks, because its safe use there is even more limited than using :: standalone.
  • Intra-line comments, which be placed between multiple commands on a line or ideally even inside of a given command.
    Intra-line comments are the most flexible (single-line) form and can by definition also be used as EOL comments.

    • ver & REM^. ^<comment^> & ver allows inserting a comment between commands (again, courtesy of jeb's answer), but note how < and > needed to be ^-escaped, because the following chars. cannot be used as-is: < > | (whereas unescaped & or && or || start the next command).

    • %= <comment> =%, as detailed in dbenham's great answer, is the most flexible form, because it can be placed inside a command (among the arguments).
      It takes advantage of variable-expansion syntax in a way that ensures that the expression always expands to the empty string - as long as the comment text contains neither % nor :
      Like REM, %= <comment> =% works well both outside and inside (...) blocks, but it is more visually distinctive; the only down-sides are that it is harder to type, easier to get wrong syntactically, and not widely known, which can hinder understanding of source code that uses the technique.


Multi-line (whole-line block) comments:

  • James K's answer shows how to use a goto statement and a label to delimit a multi-line comment of arbitrary length and content (which in his case he uses to store usage information).

  • Zee's answer shows how to use a "null label" to create a multi-line comment, although care must be taken to terminate all interior lines with ^.

  • Rob van der Woude's blog post mentions another somewhat obscure option that allows you to end a file with an arbitrary number of comment lines: An opening ( only causes everything that comes after to be ignored, as long as it doesn't contain a ( non-^-escaped) ), i.e., as long as the block is not closed.


[1] Using SET "foo=bar" to define variables - i.e., putting double quotes around the name and = and the value combined - is necessary in commands such as SET "foo=bar" & REM Set foo to bar., so as to ensure that what follows the intended variable value (up to the next command, in this case a single space) doesn't accidentally become part of it.
(As an aside: SET foo="bar" would not only not avoid the problem, it would make the double quotes part of the value).
Note that this problem is inherent to SET and even applies to accidental trailing whitespace following the value, so it is advisable to always use the SET "foo=bar" approach.

VS 2017 Metadata file '.dll could not be found

After working through a couple of issues in dependent projects, like the accepted answer says, I was still getting this error. I could see the file did indeed exist at the location it was looking in, but for some reason Visual Studio would not recognize it. Rebuilding the solution would clear all dependent projects and then would not rebuild them, but building individually would generate the .dll's. I used msbuild <project-name>.csproj in the developer PowerShell terminal in Visual Studio, meaning to get some more detailed debugging information--but it built for me instead! Try using msbuild against persistant build errors; you can use the --verbosity: option to get more output, as outlined in the docs.

How do you run your own code alongside Tkinter's event loop?

Use the after method on the Tk object:

from tkinter import *

root = Tk()

def task():
    print("hello")
    root.after(2000, task)  # reschedule event in 2 seconds

root.after(2000, task)
root.mainloop()

Here's the declaration and documentation for the after method:

def after(self, ms, func=None, *args):
    """Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel."""

Detect touch press vs long press vs movement?

GestureDetector.SimpleOnGestureListener has methods to help in these 3 cases;

   GestureDetector gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {

        //for single click event.
        @Override
        public boolean onSingleTapUp(MotionEvent motionEvent) {
            return true;
        }

        //for detecting a press event. Code for drag can be added here.
        @Override
        public void onShowPress(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("..", "...");
            clipboardManager.setPrimaryClip(clipData);

            ConceptDragShadowBuilder dragShadowBuilder = new CustomDragShadowBuilder(child);
            // drag child view.
            child.startDrag(clipData, dragShadowBuilder, child, 0);
        }

        //for detecting longpress event
        @Override
        public void onLongPress(MotionEvent e) {
            super.onLongPress(e);
        }
    });

How to change context root of a dynamic web project in Eclipse?

If using eclipse to deploy your application . We can use this maven plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-eclipse-plugin</artifactId>
    <version>2.10</version>
    <configuration>
        <wtpversion>2.0</wtpversion>
        <wtpContextName>newContextroot</wtpContextName>
    </configuration>
</plugin>

now go to your project root folder and open cmd prompt at that location type this command :

mvn eclipse:eclipse -Dwtpversion=2.0

You may need to restart eclipse , or in server view delete server and create agian to see affect. I wonder this exercise make sense in real life but works.

Where to put default parameter value in C++?

the declaration is generally the most 'useful', but that depends on how you want to use the class.

both is not valid.

How to display all elements in an arraylist?

Arraylist uses Iterator interface to traverse the elements Use this

public void display(ArrayList<Integer> v) {
        Iterator vEnum = v.iterator();
        System.out.println("\nElements in vector:");
        while (vEnum.hasNext()) {
            System.out.print(vEnum.next() + " ");
        }
    }

How to print the contents of RDD?

c.take(10)

and Spark newer version will show table nicely.

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

Can't access 127.0.0.1

If it's a DNS problem, you could try:

  • ipconfig /flushdns
  • ipconfig /registerdns

If this doesn't fix it, you could try editing the hosts file located here:

C:\Windows\System32\drivers\etc\hosts

And ensure that this line (and no other line referencing localhost) is in there:

127.0.0.1 localhost

When is it acceptable to call GC.Collect?

One case is when you are trying to unit test code that uses WeakReference.

Simple jQuery, PHP and JSONP example?

More Suggestion

JavaScript:

$.ajax({
        url: "http://FullUrl",
        dataType: 'jsonp',
        success: function (data) {

            //Data from the server in the in the variable "data"
            //In the form of an array

        }

});

PHP CallBack:

<?php

$array = array(
     '0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'),
     '1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'),
);

if(isset ($_GET['callback']))
{
    header("Content-Type: application/json");

    echo $_GET['callback']."(".json_encode($array).")";

}
?>

Random number in range [min - max] using PHP

In a new PHP7 there is a finally a support for a cryptographically secure pseudo-random integers.

int random_int ( int $min , int $max )

random_int — Generates cryptographically secure pseudo-random integers

which basically makes previous answers obsolete.

wait process until all subprocess finish?

A Popen object has a .wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).

If you use this method, you'll prevent that the process zombies are lying around for too long.

(Alternatively, you can use subprocess.call() or subprocess.check_call() for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_)call().)

If you have several subprocesses to wait for, you can do

exit_codes = [p.wait() for p in p1, p2]

which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.

Rails 4 - passing variable to partial

You need the full render partial syntax if you are passing locals

<%= render @users, :locals => {:size => 30} %>

Becomes

<%= render :partial => 'users', :collection => @users, :locals => {:size => 30} %>

Or to use the new hash syntax

<%= render partial: 'users', collection: @users, locals: {size: 30} %>

Which I think is much more readable

MS Access DB Engine (32-bit) with Office 64-bit

Install the 2007 version, it seems that if you install the version opposite to the version of Office you are using you can make it work.

http://www.microsoft.com/en-us/download/details.aspx?id=23734

build failed with: ld: duplicate symbol _OBJC_CLASS_$_Algebra5FirstViewController

also had this problem by declaring a const * NSString in the header file (incorrectly) instead of the implementation file (correctly)

How to fix Invalid AES key length?

I was facing the same issue then i made my key 16 byte and it's working properly now. Create your key exactly 16 byte. It will surely work.

Is it possible to add an HTML link in the body of a MAILTO link

Add the full link, with:

 "http://"

to the beginning of a line, and most decent email clients will auto-link it either before sending, or at the other end when receiving.

For really long urls that will likely wrap due to all the parameters, wrap the link in a less than/greater than symbol. This tells the email client not to wrap the url.

e.g.

  <http://www.example.com/foo.php?this=a&really=long&url=with&lots=and&lots=and&lots=of&prameters=on_it>

How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
    a.Fill(t1);
}
return t1;
}

and now can be used like this:

table = GetDataTable();

What to gitignore from the .idea folder?

Github uses the following .gitignore for their programs

https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore

# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn.  Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

How to set array length in c# dynamically

Typically, arrays require constants to initialize their size. You could sweep over nvPairs once to get the length, then "dynamically" create an array using a variable for length like this.

InputProperty[] ip = (InputProperty[])Array.CreateInstance(typeof(InputProperty), length);

I wouldn't recommend it, though. Just stick with the

List<InputProperty> ip = ...
...
update.Items = ip.ToArray();

solution. It's not that much less performant, and way better looking.

How to generate gcc debug symbol outside the build target?

You need to use objcopy to separate the debug information:

objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"

I use the bash script below to separate the debug information into files with a .debug extension in a .debug directory. This way I can tar the libraries and executables in one tar file and the .debug directories in another. If I want to add the debug info later on I simply extract the debug tar file and voila I have symbolic debug information.

This is the bash script:

#!/bin/bash

scriptdir=`dirname ${0}`
scriptdir=`(cd ${scriptdir}; pwd)`
scriptname=`basename ${0}`

set -e

function errorexit()
{
  errorcode=${1}
  shift
  echo $@
  exit ${errorcode}
}

function usage()
{
  echo "USAGE ${scriptname} <tostrip>"
}

tostripdir=`dirname "$1"`
tostripfile=`basename "$1"`


if [ -z ${tostripfile} ] ; then
  usage
  errorexit 0 "tostrip must be specified"
fi

cd "${tostripdir}"

debugdir=.debug
debugfile="${tostripfile}.debug"

if [ ! -d "${debugdir}" ] ; then
  echo "creating dir ${tostripdir}/${debugdir}"
  mkdir -p "${debugdir}"
fi
echo "stripping ${tostripfile}, putting debug info into ${debugfile}"
objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"
chmod -x "${debugdir}/${debugfile}"

How do I get milliseconds from epoch (1970-01-01) in Java?

java.time

Using the java.time framework built into Java 8 and later.

import java.time.Instant;

Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900

This works in UTC because Instant.now() is really call to Clock.systemUTC().instant()

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html

SQL to LINQ Tool

Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.

[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.

Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

git status shows fatal: bad object HEAD

Your repository is broken. But you can probably fix it AND keep your edits:

  1. Back up first: cp your_repository your_repositry_bak
  2. Clone the broken repository (still works): git clone your_repository your_repository_clone
  3. Replace the broken .git folder with the one from the clone: rm -rf your_repository/.git && cp your_repository_clone/.git your_repository/ -r
  4. Delete clone & backup (if everything is fine): rm -r your_repository_*

Rendering React Components from Array of Objects

There are couple of way which can be used.

const stations = [
  {call:'station one',frequency:'000'},
  {call:'station two',frequency:'001'}
];
const callList = stations.map(({call}) => call)

Solution 1

<p>{callList.join(', ')}</p>

Solution 2

<ol>    
  { callList && callList.map(item => <li>{item}</li>) }
</ol>

Edit kind-antonelli-z8372

Of course there are other ways also available.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I do some quick tests and have the following findings:

1) if using SynchronousQueue:

After the threads reach the maximum size, any new work will be rejected with the exception like below.

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]

at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)

2) if using LinkedBlockingQueue:

The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.

gdb: how to print the current line or find the current line number?

Keep in mind that gdb is a powerful command -capable of low level instructions- so is tied to assembly concepts.

What you are looking for is called de instruction pointer, i.e:

The instruction pointer register points to the memory address which the processor will next attempt to execute. The instruction pointer is called ip in 16-bit mode, eip in 32-bit mode,and rip in 64-bit mode.

more detail here

all registers available on gdb execution can be shown with:

(gdb) info registers

with it you can find which mode your program is running (looking which of these registers exist)

then (here using most common register rip nowadays, replace with eip or very rarely ip if needed):

(gdb)info line *$rip

will show you line number and file source

(gdb) list *$rip

will show you that line with a few before and after

but probably

(gdb) frame

should be enough in many cases.

Download large file in python with requests

With the following streaming code, the Python memory usage is restricted regardless of the size of the downloaded file:

def download_file(url):
    local_filename = url.split('/')[-1]
    # NOTE the stream=True parameter below
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        with open(local_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192): 
                # If you have chunk encoded response uncomment if
                # and set chunk_size parameter to None.
                #if chunk: 
                f.write(chunk)
    return local_filename

Note that the number of bytes returned using iter_content is not exactly the chunk_size; it's expected to be a random number that is often far bigger, and is expected to be different in every iteration.

See body-content-workflow and Response.iter_content for further reference.

How to get the onclick calling object?

The thing with your method is that you clutter your HTML with javascript. If you put your javascript in an external file you can access your HTML unobtrusive and this is much neater.

Lateron you can expand your code with addEventListener/attackEvent(IE) to prevent memory leaks.

This is without jQuery

<a href="123.com" id="elementid">link</a>

window.onload = function () {
  var el = document.getElementById('elementid');
  el.onclick = function (e) {
    var ev = e || window.event;
    // here u can use this or el as the HTML node
  }
}

You say you want to manipulate it with jQuery. So you can use jQuery. Than it is even better to do it like this:

// this is the window.onload startup of your JS as in my previous example. The difference is 
// that you can add multiple onload functions
$(function () {
  $('a#elementid').bind('click', function (e) {
    // "this" points to the <a> element
    // "e" points to the event object
  });
});

Returning value that was passed into a method

Even more useful, if you have multiple parameters you can access any/all of them with:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
     .Returns((string a, string b, string c) => string.Concat(a,b,c));

You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.

Sorting an array in C?

In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
     int int_a = * ( (int*) a );
     int int_b = * ( (int*) b );

     if ( int_a == int_b ) return 0;
     else if ( int_a < int_b ) return -1;
     else return 1;
}

qsort( a, 6, sizeof(int), compare )

see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/


To answer the second part of your question: an optimal (comparison based) sorting algorithm is one that runs with O(n log(n)) comparisons. There are several that have this property (including quick sort, merge sort, heap sort, etc.), but which one to use depends on your use case.

As a side note, you can sometime do better than O(n log(n)) if you know something about your data - see the wikipedia article on Radix Sort

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

No == operator found while comparing structs in C++

Comparison doesn't work on structs in C or C++. Compare by fields instead.

How to read the output from git diff?

The default output format (which originally comes from a program known as diff if you want to look for more info) is known as a “unified diff”. It contains essentially 4 different types of lines:

  • context lines, which start with a single space,
  • insertion lines that show a line that has been inserted, which start with a +,
  • deletion lines, which start with a -, and
  • metadata lines which describe higher level things like which file this is talking about, what options were used to generate the diff, whether the file changed its permissions, etc.

I advise that you practice reading diffs between two versions of a file where you know exactly what you changed. Like that you'll recognize just what is going on when you see it.

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

I realise that WayneM has stated he knows that money is specific to SQL Server. However, he is asking if there are any reasons to use money over decimal or vice versa and I think one obvious reason still ought to be stated and that is using decimal means it's one less thing to worry about if you ever have to change your DBMS - which can happen.

Make your systems as flexible as possible!

vertical-align: middle with Bootstrap 2

Try removing the float attribute from span6:

{ float:none !important; }

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

This worked for me:

Check the current role you are logged into by using: SELECT CURRENT_USER, SESSION_USER;

Note: It must match with Owner of the schema.

Schema | Name | Type | Owner
--------+--------+-------+----------

If the owner is different, then give all the grants to the current user role from the admin role by :

GRANT 'ROLE_OWNER' to 'CURRENT ROLENAME';

Then try to execute the query, it will give the output as it has access to all the relations now.

AngularJS HTTP post to PHP and undefined

It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $http.post, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.

https://docs.angularjs.org/api/ng/service/$httpParamSerializer

Automatically resize images with browser size using CSS

image container

Scaling images using the above trick only works if the container the images are in changes size.

The #icons container uses px values for the width and height. px values don't scale when the browser is resized.

Solutions

Use one of the following approaches:

  1. Define the width and/or height using % values.
  2. Use a series of @media queries to set the width and height to different values based on the current screen size.

Is it possible to set ENV variables for rails development environment in my code?

[Update]

While the solution under "old answer" will work for general problems, this section is to answer your specific question after clarification from your comment.

You should be able to set environment variables exactly like you specify in your question. As an example, I have a Heroku app that uses HTTP basic authentication.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :authenticate

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV['HTTP_USER'] && password == ENV['HTTP_PASS']
    end
  end
end

# config/initializers/dev_environment.rb
unless Rails.env.production?
  ENV['HTTP_USER'] = 'testuser'
  ENV['HTTP_PASS'] = 'testpass'
end

So in your case you would use

unless Rails.env.production?
  ENV['admin_password'] = "secret"
end

Don't forget to restart the server so the configuration is reloaded!

[Old Answer]

For app-wide configuration, you might consider a solution like the following:

Create a file config/application.yml with a hash of options you want to be able to access:

admin_password: something_secret
allow_registration: true
facebook:
  app_id: application_id_here
  app_secret: application_secret_here
  api_key: api_key_here

Now, create the file config/initializers/app_config.rb and include the following:

require 'yaml'

yaml_data = YAML::load(ERB.new(IO.read(File.join(Rails.root, 'config', 'application.yml'))).result)
APP_CONFIG = HashWithIndifferentAccess.new(yaml_data)

Now, anywhere in your application, you can access APP_CONFIG[:admin_password], along with all your other data. (Note that since the initializer includes ERB.new, your YAML file can contain ERB markup.)

Best way of invoking getter by reflection

I think this should point you towards the right direction:

import java.beans.*

for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
  if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
    System.out.println(pd.getReadMethod().invoke(foo));
}

Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for

// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);

However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:

Object value = PropertyUtils.getProperty(person, "name");

BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.

Forward declaring an enum in C++

In my projects, I adopted the Namespace-Bound Enumeration technique to deal with enums from legacy and 3rd-party components. Here is an example:

forward.h:

namespace type
{
    class legacy_type;
    typedef const legacy_type& type;
}

enum.h:

// May be defined here or pulled in via #include.
namespace legacy
{
    enum evil { x , y, z };
}


namespace type
{
    using legacy::evil;

    class legacy_type
    {
    public:
        legacy_type(evil e)
            : e_(e)
        {}

        operator evil() const
        {
            return e_;
        }

    private:
        evil e_;
    };
}

foo.h:

#include "forward.h"

class foo
{
public:
    void f(type::type t);
};

foo.cc:

#include "foo.h"

#include <iostream>
#include "enum.h"

void foo::f(type::type t)
{
    switch (t)
    {
        case legacy::x:
            std::cout << "x" << std::endl;
            break;
        case legacy::y:
            std::cout << "y" << std::endl;
            break;
        case legacy::z:
            std::cout << "z" << std::endl;
            break;
        default:
            std::cout << "default" << std::endl;
    }
}

main.cc:

#include "foo.h"
#include "enum.h"

int main()
{
    foo fu;
    fu.f(legacy::x);

    return 0;
}

Note that the foo.h header does not have to know anything about legacy::evil. Only the files that use the legacy type legacy::evil (here: main.cc) need to include enum.h.

Running sites on "localhost" is extremely slow

This suggestion fixed it for me. Clear out the WebSiteCache in C:\Users\username\AppData\Local\Microsoft\WebSiteCache

http://blog.geocortex.com/2007/12/07/slow-visual-studio-performance-solved/

Databinding an enum property to a ComboBox in WPF

This is a DevExpress specific answer based on the top-voted answer by Gregor S. (currently it has 128 votes).

This means we can keep the styling consistent across the entire application:

enter image description here

Unfortunately, the original answer doesn't work with a ComboBoxEdit from DevExpress without some modifications.

First, the XAML for the ComboBoxEdit:

<dxe:ComboBoxEdit ItemsSource="{Binding Source={xamlExtensions:XamlExtensionEnumDropdown {x:myEnum:EnumFilter}}}"
    SelectedItem="{Binding BrokerOrderBookingFilterSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    DisplayMember="Description"
    MinWidth="144" Margin="5" 
    HorizontalAlignment="Left"
    IsTextEditable="False"
    ValidateOnTextInput="False"
    AutoComplete="False"
    IncrementalFiltering="True"
    FilterCondition="Like"
    ImmediatePopup="True"/>

Needsless to say, you will need to point xamlExtensions at the namespace that contains the XAML extension class (which is defined below):

xmlns:xamlExtensions="clr-namespace:XamlExtensions"

And we have to point myEnum at the namespace that contains the enum:

xmlns:myEnum="clr-namespace:MyNamespace"

Then, the enum:

namespace MyNamespace
{
    public enum EnumFilter
    {
        [Description("Free as a bird")]
        Free = 0,

        [Description("I'm Somewhat Busy")]
        SomewhatBusy = 1,

        [Description("I'm Really Busy")]
        ReallyBusy = 2
    }
}

The problem in with the XAML is that we can't use SelectedItemValue, as this throws an error as the setter is unaccessable (bit of an oversight on your part, DevExpress). So we have to modify our ViewModel to obtain the value directly from the object:

private EnumFilter _filterSelected = EnumFilter.All;
public object FilterSelected
{
    get
    {
        return (EnumFilter)_filterSelected;
    }
    set
    {
        var x = (XamlExtensionEnumDropdown.EnumerationMember)value;
        if (x != null)
        {
            _filterSelected = (EnumFilter)x.Value;
        }
        OnPropertyChanged("FilterSelected");
    }
}

For completeness, here is the XAML extension from the original answer (slightly renamed):

namespace XamlExtensions
{
    /// <summary>
    ///     Intent: XAML markup extension to add support for enums into any dropdown box, see http://bit.ly/1g70oJy. We can name the items in the
    ///     dropdown box by using the [Description] attribute on the enum values.
    /// </summary>
    public class XamlExtensionEnumDropdown : MarkupExtension
    {
        private Type _enumType;


        public XamlExtensionEnumDropdown(Type enumType)
        {
            if (enumType == null)
            {
                throw new ArgumentNullException("enumType");
            }

            EnumType = enumType;
        }

        public Type EnumType
        {
            get { return _enumType; }
            private set
            {
                if (_enumType == value)
                {
                    return;
                }

                var enumType = Nullable.GetUnderlyingType(value) ?? value;

                if (enumType.IsEnum == false)
                {
                    throw new ArgumentException("Type must be an Enum.");
                }

                _enumType = value;
            }
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var enumValues = Enum.GetValues(EnumType);

            return (
                from object enumValue in enumValues
                select new EnumerationMember
                       {
                           Value = enumValue,
                           Description = GetDescription(enumValue)
                       }).ToArray();
        }

        private string GetDescription(object enumValue)
        {
            var descriptionAttribute = EnumType
                .GetField(enumValue.ToString())
                .GetCustomAttributes(typeof (DescriptionAttribute), false)
                .FirstOrDefault() as DescriptionAttribute;


            return descriptionAttribute != null
                ? descriptionAttribute.Description
                : enumValue.ToString();
        }

        #region Nested type: EnumerationMember
        public class EnumerationMember
        {
            public string Description { get; set; }
            public object Value { get; set; }
        }
        #endregion
    }
}

Disclaimer: I have no affiliation with DevExpress. Telerik is also a great library.

SQL Inner join more than two tables

select WucsName as WUCS_Name,Year,Tot_Households,Tot_Households,Tot_Male_Farmers  from tbl_Gender
INNER JOIN tblWUCS
ON tbl_Gender.WUCS_id =tblWUCS .WucsId 
INNER JOIN tblYear
ON tbl_Gender.YearID=tblYear.yearID

There are 3 Tables 1. tbl_Gender 2. tblWUCS 3. tblYear

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

I would mention one more thing that concerns Primefaces's p:commandButton!

When you use a p:commandButton for the action that needs to be done on the server, you can not use type="button" because that is for Push buttons which are used to execute custom javascript without causing an ajax/non-ajax request to the server.

For this purpose, you can dispense the type attribute (default value is "submit") or you can explicitly use type="submit".

Hope this will help someone!

How to break out of multiple loops?

Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:

breaker = False #our mighty loop exiter!
while True:
    while True:
        if conditionMet:
            #insert code here...
            breaker = True 
            break
    if breaker: # the interesting part!
        break   # <--- !

If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!

Encoding conversion in java

You don't need a library beyond the standard one - just use Charset. (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)

EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: new String(bytes, charset) and String.getBytes(charset).

See "URL Encoding (or: 'What are those "%20" codes in URLs?')".

Why is __init__() always called after __new__()?

Referring to this doc:

When subclassing immutable built-in types like numbers and strings, and occasionally in other situations, the static method new comes in handy. new is the first step in instance construction, invoked before init.

The new method is called with the class as its first argument; its responsibility is to return a new instance of that class.

Compare this to init: init is called with an instance as its first argument, and it doesn't return anything; its responsibility is to initialize the instance.

There are situations where a new instance is created without calling init (for example when the instance is loaded from a pickle). There is no way to create a new instance without calling new (although in some cases you can get away with calling a base class's new).

Regarding what you wish to achieve, there also in same doc info about Singleton pattern

class Singleton(object):
        def __new__(cls, *args, **kwds):
            it = cls.__dict__.get("__it__")
            if it is not None:
                return it
            cls.__it__ = it = object.__new__(cls)
            it.init(*args, **kwds)
            return it
        def init(self, *args, **kwds):
            pass

you may also use this implementation from PEP 318, using a decorator

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
...

How to get class object's name as a string in Javascript?

Short answer: No. myObj isn't the name of the object, it's the name of a variable holding a reference to the object - you could have any number of other variables holding a reference to the same object.

Now, if it's your program, then you make the rules: if you want to say that any given object will only be referenced by one variable, ever, and diligently enforce that in your code, then just set a property on the object with the name of the variable.

That said, i doubt what you're asking for is actually what you really want. Maybe describe your problem in a bit more detail...?


Pedantry: JavaScript doesn't have classes. someObject is a constructor function. Given a reference to an object, you can obtain a reference to the function that created it using the constructor property.


In response to the additional details you've provided:

The answer you're looking for can be found here: JavaScript Callback Scope (and in response to numerous other questions on SO - it's a common point of confusion for those new to JS). You just need to wrap the call to the object member in a closure that preserves access to the context object.

How to convert ZonedDateTime to Date?

Here is an example converting current system time to UTC. It involves formatting ZonedDateTime as a String and then the String object will be parsed into a date object using java.text DateFormat.

    ZonedDateTime zdt = ZonedDateTime.now(ZoneOffset.UTC);
    final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss");
    final DateFormat FORMATTER_YYYYMMDD_HH_MM_SS = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
    String dateStr = zdt.format(DATETIME_FORMATTER);

    Date utcDate = null;
    try {
        utcDate = FORMATTER_YYYYMMDD_HH_MM_SS.parse(dateStr);
    }catch (ParseException ex){
        ex.printStackTrace();
    }

Incompatible implicit declaration of built-in function ‘malloc’

The stdlib.h file contains the header information or prototype of the malloc, calloc, realloc and free functions.

So to avoid this warning in ANSI C, you should include the stdlib header file.

Accessing the logged-in user in a template

You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user.

Now, you can access every property of the user. For example, you can access the username like that : app.user.username.

Warning, if the user is not logged, the app.user is null.

If you want to check if the user is logged, you can use the is_granted twig function. For example, if you want to check if the user has ROLE_ADMIN, you just have to do is_granted("ROLE_ADMIN").

So, in every of your pages you can do :

{% if is_granted("ROLE") %}
    Hi {{ app.user.username }}
{% endif %}

Launching Google Maps Directions via an intent on Android

This is a little off-topic because you asked for "directions", but you can also use the Geo URI scheme described in the Android Documentation:

http://developer.android.com/guide/appendix/g-app-intents.html

The problem using "geo:latitude,longitude" is that Google Maps only centers at your point, without any pin or label.

That's quite confusing, especially if you need to point to a precise place or/and ask for directions.

If you use the query parameter "geo:lat,lon?q=name" in order to label your geopoint, it uses the query for search and dismiss the lat/lon parameters.

I found a way to center the map with lat/lon and display a pin with a custom label, very nice to display and useful when asking for directions or any other action:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
Uri.parse("geo:0,0?q=37.423156,-122.084917 (" + name + ")"));
startActivity(intent);

NOTE (by @TheNail): Not working in Maps v.7 (latest version at the time of writing). Will ignore the coordinates and search for an object with the given name between the parentheses. See also Intent for Google Maps 7.0.0 with location

C++ [Error] no matching function for call to

to add to John's answer:

what you want to pass to the shuffle function is a deck of cards from the class deckOfCards that you've declared in main; however, the deck of cards or vector<Card> deck that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:

class deckOfCards
{
    private:
        vector<Card> deck;

    public:
        deckOfCards();
        static int count;
        static int next;
        void shuffle(vector<Card>& deck);
        Card dealCard();
        bool moreCards();
        vector<Card>& getDeck() {   //GETTER
            return deck;
        }
};

this will in turn allow you to call your shuffle function from main like this:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck

however, you have more problems, specifically when calling cout. first, you're calling the dealCard function wrongly; as dealCard is a memeber function of a class, you should be calling it like this cardDeck.dealCard(); instead of this dealCard(cardDeck);.

now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card by using the following instruction:

cout << cardDeck.dealCard();// deal the cards in the deck

yet, the cout doesn't know how to print it, as it's not a standard type. this means you should overload your << operator to print whatever you want it to print when calling with a Card type.

How do I create JavaScript array (JSON format) dynamically?

What I do is something just a little bit different from @Chase answer:

var employees = {};

// ...and then:
employees.accounting = new Array();

for (var i = 0; i < someArray.length; i++) {
    var temp_item = someArray[i];

    // Maybe, here make something like:
    // temp_item.name = 'some value'

    employees.accounting.push({
        "firstName" : temp_item.firstName,
        "lastName"  : temp_item.lastName,
        "age"       : temp_item.age
    });
}

And that work form me!

I hope it could be useful for some body else!

Access event to call preventdefault from custom function originating from onclick attribute of tag

Add a unique class to the links and a javascript that prevents default on links with this class:

<a href="#" class="prevent-default" 
   onclick="$('.comment .hidden').toggle();">Show comments</a>

<script>
  $(document).ready(function(){

    $("a.prevent-default").click(function(event) {
         event.preventDefault(); 
          });
  });
</script>

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

For those who are using brew. Just link you mysql version with "--force" option.

brew link mysql56 --force

How to handle screen orientation change when progress dialog and background thread active?

i have found and easier solution to handle threads when orientation change. You can just keep an static reference to your activity/fragment and verify if its null before acting on the ui. I suggest using a try catch too:

 public class DashListFragment extends Fragment {
     private static DashListFragment ACTIVE_INSTANCE;

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

        ACTIVE_INSTANCE = this;

        new Handler().postDelayed(new Runnable() {
            public void run() {
                try {
                        if (ACTIVE_INSTANCE != null) {
                            setAdapter(); // this method do something on ui or use context
                        }
                }
                catch (Exception e) {}


            }
        }, 1500l);

    }

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

        ACTIVE_INSTANCE = null;
    }


}

Read Variable from Web.Config

I am siteConfiguration class for calling all my appSetting like this way. I share it if it will help anyone.

add the following code at the "web.config"

<configuration>
   <configSections>
     <!-- some stuff omitted here -->
   </configSections>
   <appSettings>
      <add key="appKeyString" value="abc" />
      <add key="appKeyInt" value="123" />  
   </appSettings>
</configuration>

Now you can define a class for getting all your appSetting value. like this

using System; 
using System.Configuration;
namespace Configuration
{
   public static class SiteConfigurationReader
   {
      public static String appKeyString  //for string type value
      {
         get
         {
            return ConfigurationManager.AppSettings.Get("appKeyString");
         }
      }

      public static Int32 appKeyInt  //to get integer value
      {
         get
         {
            return ConfigurationManager.AppSettings.Get("appKeyInt").ToInteger(true);
         }
      }

      // you can also get the app setting by passing the key
      public static Int32 GetAppSettingsInteger(string keyName)
      {
          try
          {
            return Convert.ToInt32(ConfigurationManager.AppSettings.Get(keyName));
        }
        catch
        {
            return 0;
        }
      }
   }
}

Now add the reference of previous class and to access a key call like bellow

string appKeyStringVal= SiteConfigurationReader.appKeyString;
int appKeyIntVal= SiteConfigurationReader.appKeyInt;
int appKeyStringByPassingKey = SiteConfigurationReader.GetAppSettingsInteger("appKeyInt");

Get data from file input in JQuery

Html:

<input type="file" name="input-file" id="input-file">

jQuery:

var fileToUpload = $('#input-file').prop('files')[0];

We want to get first element only, because prop('files') returns array.

How does the 'binding' attribute work in JSF? When and how should it be used?

each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.

  • Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
  • The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
  • For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.

    http:..../somelink?componentId=123 would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123

The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.

Android device chooser - My device seems offline

I can't say for sure but after hours of random disconnections from my device (especially when trying to debug anything), I switched to a USB port that is NOT USB3.0 and that seem to solve the issue.

How do I redirect with JavaScript?

  • If you want to simulate someone clicking on a link, use location.href.
  • If you want to simulate an HTTP redirect, use location.replace.

For example:

// Similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// Similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

Information copied from this answer to a duplicate question

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:

SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName

Log exception with traceback

Use logging.exception from within the except: handler/block to log the current exception along with the trace information, prepended with a message.

import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)

logging.debug('This message should go to the log file')

try:
    run_my_stuff()
except:
    logging.exception('Got exception on main handler')
    raise

Now looking at the log file, /tmp/logging_example.out:

DEBUG:root:This message should go to the log file
ERROR:root:Got exception on main handler
Traceback (most recent call last):
  File "/tmp/teste.py", line 9, in <module>
    run_my_stuff()
NameError: name 'run_my_stuff' is not defined

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

If your databaseName value is correct, then use this: DriverManger.getconnection("jdbc:sqlserver://ServerIp:1433;user=myuser;password=mypassword;databaseName=databaseName;")

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

How do I change the figure size for a seaborn plot?

The top answers by Paul H and J. Li do not work for all types of seaborn figures. For the FacetGrid type (for instance sns.lmplot()), use the size and aspect parameter.

Size changes both the height and width, maintaining the aspect ratio.

Aspect only changes the width, keeping the height constant.

You can always get your desired size by playing with these two parameters.

Credit: https://stackoverflow.com/a/28765059/3901029

Using ffmpeg to change framerate

You may consider using fps filter. It won't change the video playback speed:

ffmpeg -i <input> -filter:v fps=fps=30 <output>

Worked nice for reducing fps from 59.6 to 30.

How to remove duplicates from a list?

Does Customer implement the equals() contract?

If it doesn't implement equals() and hashCode(), then listCustomer.contains(customer) will check to see if the exact same instance already exists in the list (By instance I mean the exact same object--memory address, etc). If what you are looking for is to test whether or not the same Customer( perhaps it's the same customer if they have the same customer name, or customer number) is in the list already, then you would need to override equals() to ensure that it checks whether or not the relevant fields(e.g. customer names) match.

Note: Don't forget to override hashCode() if you are going to override equals()! Otherwise, you might get trouble with your HashMaps and other data structures. For a good coverage of why this is and what pitfalls to avoid, consider having a look at Josh Bloch's Effective Java chapters on equals() and hashCode() (The link only contains iformation about why you must implement hashCode() when you implement equals(), but there is good coverage about how to override equals() too).

By the way, is there an ordering restriction on your set? If there isn't, a slightly easier way to solve this problem is use a Set<Customer> like so:

Set<Customer> noDups = new HashSet<Customer>();
noDups.addAll(tmpListCustomer);
return new ArrayList<Customer>(noDups);

Which will nicely remove duplicates for you, since Sets don't allow duplicates. However, this will lose any ordering that was applied to tmpListCustomer, since HashSet has no explicit ordering (You can get around that by using a TreeSet, but that's not exactly related to your question). This can simplify your code a little bit.

grep without showing path/file:line

Just replace -H with -h. Check man grep for more details on options

find . -name '*.bar' -exec grep -hn FOO {} \;

How to add 10 days to current time in Rails

Try this on Rails

Time.new + 10.days 

Try this on Ruby

require 'date'
DateTime.now.next_day(10).to_time

Where can I download Eclipse Android bundle?

Try www.eclipse.org/downloads/packages/eclipse-android-developers-includes-incubating-components/neonrc3

IO Error: The Network Adapter could not establish the connection

Either:

  1. The database isn't running
  2. You got the URL wrong
  3. There is a firewall in the way.

(This strange error message is produced by Oracle's JDBC driver when it can't connect to the database server. 'Network adapter' appears to refer to some component of their code, which isn't very useful. Real network adapters (NICs) don't establish connections at all: TCP protocol stacks do that. It would have been a lot more useful if they had just let the original ConnectException be thrown, or at least used its error message and let it appear in the stack trace.)

endsWith in JavaScript

UPDATE (Nov 24th, 2015):

This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:

Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple this.substr(-suffix.length) === suffix approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: jsperf.com/endswith-stackoverflow/14 And faster across the board when the result is false: jsperf.com/endswith-stackoverflow-when-false Of course, with ES6 adding endsWith, the point is moot. :-)


ORIGINAL ANSWER:

I know this is a year old question... but I need this too and I need it to work cross-browser so... combining everyone's answer and comments and simplifying it a bit:

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
  • Doesn't create a substring
  • Uses native indexOf function for fastest results
  • Skip unnecessary comparisons using the second parameter of indexOf to skip ahead
  • Works in Internet Explorer
  • NO Regex complications

Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version:

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

EDIT: As noted by @hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a typeof check like so:

if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

addEventListener in Internet Explorer

I'm using this solution and works in IE8 or greater.

if (typeof Element.prototype.addEventListener === 'undefined') {
    Element.prototype.addEventListener = function (e, callback) {
      e = 'on' + e;
      return this.attachEvent(e, callback);
    };
  }

And then:

<button class="click-me">Say Hello</button>

<script>
  document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
    console.log('Hello');
  });
</script>

This will work both IE8 and Chrome, Firefox, etc.

How do you beta test an iphone app?

(As the official guide is still missing in this thread..)

TestFlight, acquired by Apple and now (iOS8+) available for beta testing makes it easy to hand your app to beta testers without the need to collect device UUIDs beforehand (you only need email addresses of your testers). An extensive guide explaining all necessary steps may be found in the iTunes Connect Developer Guide.

How to get week numbers from dates?

if you try with lubridate:

library(lubridate)
lubridate::week(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01'))

[1] 11 11 12  1

The pattern is the same. Try isoweek

lubridate::isoweek(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01'))
[1] 11 12 12  1

Deleting all records in a database table

if you want to completely empty the database and not just delete a model or models attached to it you can do:

rake db:purge

you can also do it on the test database

rake db:test:purge

cleanest way to skip a foreach if array is empty

If variable you need could be boolean false - eg. when no records are returned from database or array - when records are returned, you can do following:

foreach (($result ? $result : array()) as $item)
    echo $item;

Approach with cast((Array)$result) produces an array of count 1 when variable is boolean false which isn't what you probably want.

How can I add a string to the end of each line in Vim?

:%s/$/\*/g

should work and so should :%s/$/*/g.

Difference between application/x-javascript and text/javascript content types

According to RFC 4329 the correct MIME type for JavaScript should be application/javascript. Howerver, older IE versions choke on this since they expect text/javascript.

Linking static libraries to other static libraries

A static library is just an archive of .o object files. Extract them with ar (assuming Unix) and pack them back into one big library.

Splitting a continuous variable into equal sized groups

Without any extra package, 3 being the number of groups:

> findInterval(das$wt, unique(quantile(das$wt, seq(0, 1, length.out = 3 + 1))), rightmost.closed = TRUE)
 [1] 1 1 1 2 2 2 3 1 3 3 3 2 1 3 2

You can speed up the quantile computation by using a representative sample of the values of interest. Double check the documentation of the FindInterval function.

Strange Jackson exception being thrown when serializing Hibernate object

I had a similar problem with lazy loading via the hibernate proxy object. Got around it by annotating the class having lazyloaded private properties with:

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

I assume you can add the properties on your proxy object that breaks the JSON serialization to that annotation.

Avoid Jackson serialization on non fetched lazy objects

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Python "expected an indented block"

There are several issues:

  1. elif option == 2: and the subsequent elif-else should be aligned with the second if option == 1, not with the for.

  2. The for x in range(x, 1, 1): is missing a body.

  3. Since "option 1 (count)" requires a second input, you need to call input() for the second time. However, for sanity's sake I urge you to store the result in a second variable rather than repurposing option.

  4. The comparison in the first line of your code is probably meant to be an assignment.

You'll discover more issues once you're able to run your code (you'll need a couple more input() calls, one of the range() calls will need attention etc).

Lastly, please don't use the same variable as the loop variable and as part of the initial/terminal condition, as in:

            for x in range(1, x, 1):
                print x

It may work, but it is very confusing to read. Give the loop variable a different name:

            for i in range(1, x, 1):
                print i

jQuery: how do I animate a div rotation?

If you're designing for an iOS device or just webkit, you can do it with no JS whatsoever:

CSS:

@-webkit-keyframes spin {  
from {  
    -webkit-transform: rotate(0deg);  
}  
to {  
    -webkit-transform: rotate(360deg);  
    } 
}

.wheel {
    width:40px;
    height:40px;
    background:url(wheel.png);
    -webkit-animation-name: spin; 
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-timing-function: linear;
    -webkit-animation-duration: 3s; 
}

This would trigger the animation on load. If you wanted to trigger it on hover, it might look like this:

.wheel {
    width:40px;
    height:40px;
    background:url(wheel.png);
}

.wheel:hover {
    -webkit-animation-name: spin; 
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-timing-function: ease-in-out;
    -webkit-animation-duration: 3s; 
}

How can I add a custom HTTP header to ajax request with js or jQuery?

Assuming that you mean "When using ajax" and "An HTTP Request header", then use the headers property in the object you pass to ajax()

headers(added 1.5)

Default: {}

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

http://api.jquery.com/jQuery.ajax/

Android Canvas: drawing too large bitmap

This can be an issue with Glide. Use this while you are trying to load to many images and some of them are very large:

Glide.load("your image path")
                       .transform(
                               new MultiTransformation<>(
                                       new CenterCrop(),
                                       new RoundedCorners(
                                               holder.imgCompanyLogo.getResources()
                                                       .getDimensionPixelSize(R.dimen._2sdp)
                                       )
                               )
                       )
                       .error(R.drawable.ic_nfs_default)
                       .into(holder.imgCompanyLogo);
           }

Return outside function error in Python

As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    print(counter)
    break

Difference between java.exe and javaw.exe

java.exe is the console app while javaw.exe is windows app (console-less). You can't have Console with javaw.exe.

Capturing Groups From a Grep RegEx

I realize that an answer was already accepted for this, but from a "strictly *nix purist angle" it seems like the right tool for the job is pcregrep, which doesn't seem to have been mentioned yet. Try changing the lines:

    echo $f | grep -oEi '[0-9]+_([a-z]+)_[0-9a-z]*'
    name=$?

to the following:

    name=$(echo $f | pcregrep -o1 -Ei '[0-9]+_([a-z]+)_[0-9a-z]*')

to get only the contents of the capturing group 1.

The pcregrep tool utilizes all of the same syntax you've already used with grep, but implements the functionality that you need.

The parameter -o works just like the grep version if it is bare, but it also accepts a numeric parameter in pcregrep, which indicates which capturing group you want to show.

With this solution there is a bare minimum of change required in the script. You simply replace one modular utility with another and tweak the parameters.

Interesting Note: You can use multiple -o arguments to return multiple capture groups in the order in which they appear on the line.

What are the ways to make an html link open a folder

You can also copy the link address and paste it in a new window to get around the security. This works in chrome and firefox but you may have to add slashes in firefox.

Overriding fields or properties in subclasses

The example implementation when you want to have an abstract class with implementation. Subclasses must:

  1. Parameterize the implementation of an abstract class.
  2. Fully inherit the implementation of the abstract class;
  3. Have your own implementation.

In this case, the properties that are necessary for the implementation should not be available for use except for the abstract class and its own subclass.

    internal abstract class AbstractClass
    {
        //Properties for parameterization from concrete class
        protected abstract string Param1 { get; }
        protected abstract string Param2 { get; }

        //Internal fields need for manage state of object
        private string var1;
        private string var2;

        internal AbstractClass(string _var1, string _var2)
        {
            this.var1 = _var1;
            this.var2 = _var2;
        }

        internal void CalcResult()
        {
            //The result calculation uses Param1, Param2, var1, var2;
        }
    }

    internal class ConcreteClassFirst : AbstractClass
    {
        private string param1;
        private string param2;
        protected override string Param1 { get { return param1; } }
        protected override string Param2 { get { return param2; } }

        public ConcreteClassFirst(string _var1, string _var2) : base(_var1, _var2) { }

        internal void CalcParams()
        {
            //The calculation param1 and param2
        }
    }

    internal class ConcreteClassSecond : AbstractClass
    {
        private string param1;
        private string param2;

        protected override string Param1 { get { return param1; } }

        protected override string Param2 { get { return param2; } }

        public ConcreteClassSecond(string _var1, string _var2) : base(_var1, _var2) { }

        internal void CalcParams()
        {
            //The calculation param1 and param2
        }
    }

    static void Main(string[] args)
    {
        string var1_1 = "val1_1";
        string var1_2 = "val1_2";

        ConcreteClassFirst concreteClassFirst = new ConcreteClassFirst(var1_1, var1_2);
        concreteClassFirst.CalcParams();
        concreteClassFirst.CalcResult();

        string var2_1 = "val2_1";
        string var2_2 = "val2_2";

        ConcreteClassSecond concreteClassSecond = new ConcreteClassSecond(var2_1, var2_2);
        concreteClassSecond.CalcParams();
        concreteClassSecond.CalcResult();

        //Param1 and Param2 are not visible in main method
    }

How do I print out the contents of an object in Rails for easy debugging?

You need to use debug(@var). It's exactly like "print_r".

There has been an error processing your request, Error log record number

Clear your cache and your website will be work well.

How to change navigation bar color in iOS 7 or 6?

    you can add bellow code in appdelegate.m .if your app is navigation based

    // for background color
   [nav.navigationBar setBarTintColor:[UIColor blueColor]];

    // for change navigation title and button color
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],
    NSForegroundColorAttributeName,               
    [UIFont fontWithName:@"FontNAme" size:20],
    NSFontAttributeName, nil]];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

Laravel blank white screen

Another thing that may cause the WSOD is missing the 'return' keyword, as in:

return View::make('yourview');

as opposed to

View::make('yourview');

How to get mouse position in jQuery without mouse-events?

var CurrentMouseXPostion;
var CurrentMouseYPostion;

$(document).mousemove(function(event) {
    CurrentMouseXPostion = event.pageX;
    CurrentMouseYPostion = event.pageY;
});

Make an eventListener on the main object , in my case the document object, to get the mouse coords every frame and store them in global variables, and like that you can read mouse Y & Z whenever youlike , wherever you like.

How to solve java.lang.OutOfMemoryError trouble in Android

Few hints to handle such error/exception for Android Apps:

  1. Activities & Application have methods like:

    • onLowMemory
    • onTrimMemory Handle these methods to watch on memory usage.
  2. tag in Manifest can have attribute 'largeHeap' set to TRUE, which requests more heap for App sandbox.

  3. Managing in-memory caching & disk caching:

    • Images and other data could have been cached in-memory while app running, (locally in activities/fragment and globally); should be managed or removed.
  4. Use of WeakReference, SoftReference of Java instance creation , specifically to files.

  5. If so many images, use proper library/data structure which can manage memory, use samling of images loaded, handle disk-caching.

  6. Handle OutOfMemory exception

  7. Follow best practices for coding

    • Leaking of memory (Don't hold everything with strong reference)
  8. Minimize activity stack e.g. number of activities in stack (Don't hold everything on context/activty)

    • Context makes sense, those data/instances not required out of scope (activity and fragments), hold them into appropriate context instead global reference-holding.
  9. Minimize the use of statics, many more singletons.

  10. Take care of OS basic memory fundametals

    • Memory fragmentation issues
  11. Involk GC.Collect() manually sometimes when you are sure that in-memory caching no more needed.

This app won't run unless you update Google Play Services (via Bazaar)

UPDATE

The Google maps API v2 is now installed on the latest Google system images (api:19 ARM or x86).
So your application should just work with the new images. There is no need to install these files.

I've been trying to run an Android Google Maps V2 application under an emulator and once I finally got Google Play Services running, I updated my SDK to Google Play Services revision 4, and my emulator wouldn't run my application any more.

I have now worked out how to update my emulator from my transformer tablet. (You won't need a tablet as you can download the files below.)

I used Titanium Backup to backup my Asus Eee Pad Transformer (TF101) and then grabbed the com.android.vending and the com.google.android.gms APK files from the backup.

I installed these on an emulator configured with platform: 4.1.2, API Level: 16, CPU Intel/Atom x86) and my Google Maps V2 application works again.

That was all .. none of the other steps regarding /system/app were required.

My application only uses the Google Maps API, no doubt, more steps are required if you use other Google Play services.

New files for latest Google Play services:

Same instructions as before: Create a new emulator with any CPU/ABI, a non-Google API target (versions 10-19 work) and GPU emulation on or off, and then install the files:

adb install com.android.vending-20140218.apk
adb install com.google.android.gms-20140218.apk

If you are upgrading an existing emulator then you might need to uninstall previous versions by:

adb uninstall com.android.vending
adb uninstall com.google.android.gms

That's all.

What are the JavaScript KeyCodes?

Here are some useful links:

The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.

How to read file using NPOI

Since you've asked to read and modify the xls file I have changed @mj82's answer to correspond your needs.

HSSFWorkbook does not have Save method, but it does have Write to a stream.

static void Main(string[] args)
        {
            string filepath = @"C:\test.xls";

            HSSFWorkbook hssfwb;

            using (FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Read))
            {
                hssfwb = new HSSFWorkbook(file);
            }

            ISheet sheet = hssfwb.GetSheetAt(0);

            for (int row = 0; row <= sheet.LastRowNum; row++)
            {
                if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
                {
                    // Set new cell value
                    sheet.GetRow(row).GetCell(0).SetCellValue("foo");
                    Console.WriteLine("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue);
                }
            }

            // Save the file
            using (FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Write))
            {
                hssfwb.Write(file);
            }

            Console.ReadLine();
        }

Remove Blank option from Select Option with AngularJS

If you just want to remove the blank space use ng-show and you are done! No need to initialize value in JS.

<select ng-model="SelectedStatus" ng-options="x.caption for x in statusList">
    <option value="" ng-show="false"></option>
</select>`

Switch case with fallthrough?

If the values are integer then you can use [2-3] or you can use [5,7,8] for non continuous values.

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    1)
        echo "one"
        ;;
    [2-3])
        echo "two or three"
        ;;
    [4-6])
        echo "four to six"
        ;;
    [7,9])
        echo "seven or nine"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

If the values are string then you can use |.

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    "one")
        echo "one"
        ;;
    "two" | "three")
        echo "two or three"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

select unique rows based on single distinct column

Since you don't care which id to return I stick with MAX id for each email to simplify SQL query, give it a try

;WITH ue(id)
 AS
 (
   SELECT MAX(id)
   FROM table
   GROUP BY email
 )
 SELECT * FROM table t
 INNER JOIN ue ON ue.id = t.id

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

For identifying a windows machine uniquely. Make sure when you use wmic to have a strategy of alternative methods. Since "wmic bios get serialnumber" might not work on all machines, you might need to have additional methods:

# Get serial number from bios
wmic bios get serialnumber
# If previous fails, get UUID
wmic csproduct get UUID
# If previous fails, get diskdrive serialnumber
wmic DISKDRIVE get SerialNumber

Resources: The Best Way To Uniquely Identify A Windows Machine http://www.nextofwindows.com/the-best-way-to-uniquely-identify-a-windows-machine/

How can I rename a conda environment?

I'm using Conda on Windows and this answer did not work for me. But I can suggest another solution:

  • rename enviroment folder (old_name to new_name)

  • open shell and activate env with custom folder:

    conda.bat activate "C:\Users\USER_NAME\Miniconda3\envs\new_name"

  • now you can use this enviroment, but it's not on the enviroment list. Update\install\remove any package to fix it. For example, update numpy:

    conda update numpy

  • after applying any action to package, the environment will show in env list. To check this, type:

    conda env list

error: expected primary-expression before ')' token (C)

A function call needs to be performed with objects. You are doing the equivalent of this:

// function declaration/definition
void foo(int) {}

// function call
foo(int); // wat!??

i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing

int i = 42;
foo(i);

or

foo(42);

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

I've recently found a lib called ion that brings a little extra to the table.

ion has built-in support for image download integrated with ImageView, JSON (with the help of GSON), files and a very handy UI threading support.

I'm using it on a new project and so far the results have been good. Its use is much simpler than Volley or Retrofit.

Error: package or namespace load failed for ggplot2 and for data.table

This solved the issue:

remove.packages(c("ggplot2", "data.table"))
install.packages('Rcpp', dependencies = TRUE)
install.packages('ggplot2', dependencies = TRUE)
install.packages('data.table', dependencies = TRUE)

Python - 'ascii' codec can't decode byte

You use u"??".encode('utf8') to encode an unicode string. But if you want to represent "??", you should decode it. Just like:

"??".decode("utf8")

You will get what you want. Maybe you should learn more about encode & decode.

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

This is the problem about Multidex . You can try to remove some jar, or you can try like this : http://developer.android.com/tools/building/multidex.html#mdex-gradle in app build.gradle :

    defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

In your manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

Docker is installed but Docker Compose is not ? why?

just use brew:

brew install docker-compose

Storing an object in state of a React component?

In addition to kiran's post, there's the update helper (formerly a react addon). This can be installed with npm using npm install immutability-helper

import update from 'immutability-helper';

var abc = update(this.state.abc, {
   xyz: {$set: 'foo'}
});

this.setState({abc: abc});

This creates a new object with the updated value, and other properties stay the same. This is more useful when you need to do things like push onto an array, and set some other value at the same time. Some people use it everywhere because it provides immutability.

If you do this, you can have the following to make up for the performance of

shouldComponentUpdate: function(nextProps, nextState){
   return this.state.abc !== nextState.abc; 
   // and compare any props that might cause an update
}

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

I use apache version 2.4.27, also have this problem, solved it through modify

the conf/extra/httpdahssl.conf,comment the 18 line content(Listen 443 https),it works fine.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Use data type 'MultilineText':

[DataType(DataType.MultilineText)]
public string Text { get; set; }

See ASP.NET MVC3 - textarea with @Html.EditorFor

Get current NSDate in timestamp format

Swift:

I have a UILabel which shows TimeStamp over a Camera Preview.

    var timeStampTimer : NSTimer?
    var dateEnabled:  Bool?
    var timeEnabled: Bool?
   @IBOutlet weak var timeStampLabel: UILabel!

override func viewDidLoad() {
        super.viewDidLoad()
//Setting Initial Values to be false.
        dateEnabled =  false
        timeEnabled =  false
}

override func viewWillAppear(animated: Bool) {

        //Current Date and Time on Preview View
        timeStampLabel.text = timeStamp
        self.timeStampTimer = NSTimer.scheduledTimerWithTimeInterval(1.0,target: self, selector: Selector("updateCurrentDateAndTimeOnTimeStamperLabel"),userInfo: nil,repeats: true)
}

func updateCurrentDateAndTimeOnTimeStamperLabel()
    {
//Every Second, it updates time.

        switch (dateEnabled, timeEnabled) {
        case (true?, true?):
            timeStampLabel.text =  NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .MediumStyle)
            break;
        case (true?, false?):
            timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .NoStyle)
            break;

        case (false?, true?):
            timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .MediumStyle)
            break;
        case (false?, false?):
            timeStampLabel.text =  NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .NoStyle)
            break;
        default:
            break;

        }
    }

I am setting up a setting Button to trigger a alertView.

@IBAction func settingsButton(sender : AnyObject) {


let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet)

let timeStampOnAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in

    self.dateEnabled = true
    self.timeEnabled =  true

}
let timeStampOffAction = UIAlertAction(title: NSLocalizedString("TimeStamp Off", comment: ""), style: .Default) { action in

    self.dateEnabled = false
    self.timeEnabled =  false

}
let dateOnlyAction = UIAlertAction(title: NSLocalizedString("Date Only", comment: ""), style: .Default) { action in

    self.dateEnabled = true
    self.timeEnabled =  false


}
let timeOnlyAction = UIAlertAction(title: NSLocalizedString("Time Only", comment: ""), style: .Default) { action in

    self.dateEnabled = false
    self.timeEnabled =  true
}

let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in

}
cameraSettingsAlert.addAction(cancel)
cameraSettingsAlert.addAction(timeStampOnAction)
cameraSettingsAlert.addAction(timeStampOffAction)
cameraSettingsAlert.addAction(dateOnlyAction)
cameraSettingsAlert.addAction(timeOnlyAction)

self.presentViewController(cameraSettingsAlert, animated: true, completion: nil)

}

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

how to delete all cookies of my website in php

$past = time() - 3600;
foreach ( $_COOKIE as $key => $value )
{
    setcookie( $key, $value, $past, '/' );
}

Even better is however to remember (or store it somewhere) which cookies are set with your application on a domain and delete all those directly.
That way you can be sure to delete all values correctly.

What is the difference between char array and char pointer in C?

What is the difference between char array vs char pointer in C?

C99 N1256 draft

There are two different uses of character string literals:

  1. Initialize char[]:

    char c[] = "abc";      
    

    This is "more magic", and described at 6.7.8/14 "Initialization":

    An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

    So this is just a shortcut for:

    char c[] = {'a', 'b', 'c', '\0'};
    

    Like any other regular array, c can be modified.

  2. Everywhere else: it generates an:

    So when you write:

    char *c = "abc";
    

    This is similar to:

    /* __unnamed is magic because modifying it gives UB. */
    static char __unnamed[] = "abc";
    char *c = __unnamed;
    

    Note the implicit cast from char[] to char *, which is always legal.

    Then if you modify c[0], you also modify __unnamed, which is UB.

    This is documented at 6.4.5 "String literals":

    5 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence [...]

    6 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

6.7.8/32 "Initialization" gives a direct example:

EXAMPLE 8: The declaration

char s[] = "abc", t[3] = "abc";

defines "plain" char array objects s and t whose elements are initialized with character string literals.

This declaration is identical to

char s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

char *p = "abc";

defines p with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

GCC 4.8 x86-64 ELF implementation

Program:

#include <stdio.h>

int main(void) {
    char *s = "abc";
    printf("%s\n", s);
    return 0;
}

Compile and decompile:

gcc -ggdb -std=c99 -c main.c
objdump -Sr main.o

Output contains:

 char *s = "abc";
8:  48 c7 45 f8 00 00 00    movq   $0x0,-0x8(%rbp)
f:  00 
        c: R_X86_64_32S .rodata

Conclusion: GCC stores char* it in .rodata section, not in .text.

If we do the same for char[]:

 char s[] = "abc";

we obtain:

17:   c7 45 f0 61 62 63 00    movl   $0x636261,-0x10(%rbp)

so it gets stored in the stack (relative to %rbp).

Note however that the default linker script puts .rodata and .text in the same segment, which has execute but no write permission. This can be observed with:

readelf -l a.out

which contains:

 Section to Segment mapping:
  Segment Sections...
   02     .text .rodata

What is the difference between Set and List?

1.List allows duplicate values and set does'nt allow duplicates

2.List maintains the order in which you inserted elements in to the list Set does'nt maintain order. 3.List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered.

How to automatically convert strongly typed enum into int?

As others have said, you can't have an implicit conversion, and that's by-design.

If you want you can avoid the need to specify the underlying type in the cast.

template <typename E>
constexpr typename std::underlying_type<E>::type to_underlying(E e) noexcept {
    return static_cast<typename std::underlying_type<E>::type>(e);
}

std::cout << foo(to_underlying(b::B2)) << std::endl;

Git push rejected after feature branch rebase

I would use instead "checkout -b" and it is easier to understand.

git checkout myFeature
git rebase master
git push origin --delete myFeature
git push origin myFeature

when you delete you prevent to push in an exiting branch that contains different SHA ID. I am deleting only the remote branch in this case.

how to convert object into string in php

You can tailor how your object is represented as a string by implementing a __toString() method in your class, so that when your object is type cast as a string (explicit type cast $str = (string) $myObject;, or automatic echo $myObject) you can control what is included and the string format.

If you only want to display your object's data, the method above would work. If you want to store your object in a session or database, you need to serialize it, so PHP knows how to reconstruct your instance.

Some code to demonstrate the difference:

class MyObject {

  protected $name = 'JJ';

  public function __toString() {
    return "My name is: {$this->name}\n";
  }

}

$obj = new MyObject;

echo $obj;
echo serialize($obj);

Output:

My name is: JJ

O:8:"MyObject":1:{s:7:"*name";s:2:"JJ";}

How can I load webpage content into a div on page load?

With jQuery, it is possible, however not using ajax.

function LoadPage(){
  $.get('http://a_site.com/a_page.html', function(data) {
    $('#siteloader').html(data);
  });
}

And then place onload="LoadPage()" in the body tag.

Although if you follow this route, a php version might be better:

echo htmlspecialchars(file_get_contents("some URL"));

Array of arrays (Python/NumPy)

You'll have problems creating lists without commas. It shouldn't be too hard to transform your data so that it uses commas as separating character.

Once you have commas in there, it's a relatively simple list creation operations:

array1 = [1,2,3]
array2 = [4,5,6]

array3 = [array1, array2]

array4 = [7,8,9]
array5 = [10,11,12]

array3 = [array3, [array4, array5]]

When testing we get:

print(array3)

[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:

array3[0][1]
[4, 5, 6]

array3[1][1]
[10, 11, 12]

Hope that helps.

Apply CSS Style to child elements

This code can do the trick as well, using the SCSS syntax

.parent {
  & > * {
    margin-right: 15px;
    &:last-child {
      margin-right: 0;
    }
  }
}

How Do I Convert an Integer to a String in Excel VBA?

Another way to do it is to splice two parsed sections of the numerical value together:

Cells(RowNum, ColumnNum).Value = Mid(varNumber,1,1) & Mid(varNumber,2,Len(varNumber))

I have found better success with this than CStr() because CStr() doesn't seem to convert decimal numbers that came from variants in my experience.

Determine version of Entity Framework I am using?

if you are using EF core this command below could help

dotnet ef --version

Javascript Get Element by Id and set the value

I think the problem is the way you call your javascript function. Your code is like so:

<input type="button" onclick="javascript: myFunc(myID)" value="button"/>

myID should be wrapped in quotes.

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

Replace words in the body text

I had the same problem. I wrote my own function using replace on innerHTML, but it would screw up anchor links and such.

To make it work correctly I used a library to get this done.

The library has an awesome API. After including the script I called it like this:

findAndReplaceDOMText(document.body, {
  find: 'texttofind',
  replace: 'texttoreplace'
  }
);

How to merge a specific commit in Git

You can use git cherry-pick to apply a single commit by itself to your current branch.

Example: git cherry-pick d42c389f

how to find my angular version in my project?

try this command :

ng --version

It prints out Angular, Angular CLI, Node, Typescript versions etc.

Change Select List Option background colour on hover

In FF also CSS filter works fine. E.g. hue-rotate:

option {
    filter: hue-rotate(90deg);
}

https://jsfiddle.net/w3a740jq/4/

What is an 'undeclared identifier' error and how do I fix it?

These error meassages

1.For the Visual Studio compiler: error C2065: 'printf' : undeclared identifier
2.For the GCC compiler: `printf' undeclared (first use in this function)

mean that you use name printf but the compiler does not see where the name was declared and accordingly does not know what it means.

Any name used in a program shall be declared before its using. The compiler has to know what the name denotes.

In this particular case the compiler does not see the declaration of name printf . As we know (but not the compiler) it is the name of standard C function declared in header <stdio.h> in C or in header <cstdio> in C++ and placed in standard (std::) and global (::) (not necessarily) name spaces.

So before using this function we have to provide its name declaration to the compiler by including corresponding headers.

For example C:

#include <stdio.h>

int main( void )
{
   printf( "Hello World\n" );
}

C++:

#include <cstdio>

int main()
{
   std::printf( "Hello World\n" );
   // or printf( "Hello World\n" );
   // or ::printf( "Hello World\n" );
}

Sometimes the reason of such an error is a simple typo. For example let's assume that you defined function PrintHello

void PrintHello()
{
    std::printf( "Hello World\n" );
}

but in main you made a typo and instead of PrintHello you typed printHello with lower case letter 'p'.

#include <cstdio>

void PrintHello()
{
    std::printf( "Hello World\n" );
}

int main()
{
   printHello();
}

In this case the compiler will issue such an error because it does not see the declaration of name printHello. PrintHello and printHello are two different names one of which was declared and other was not declared but used in the body of main

mysql update query with sub query

The main issue is that the inner query cannot be related to your where clause on the outer update statement, because the where filter applies first to the table being updated before the inner subquery even executes. The typical way to handle a situation like this is a multi-table update.

Update
  Competition as C
  inner join (
    select CompetitionId, count(*) as NumberOfTeams
    from PicksPoints as p
    where UserCompetitionID is not NULL
    group by CompetitionID
  ) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = A.NumberOfTeams

Demo: http://www.sqlfiddle.com/#!2/a74f3/1

Is there a way to detach matplotlib plots so that the computation can continue?

IMPORTANT: Just to make something clear. I assume that the commands are inside a .py script and the script is called using e.g. python script.py from the console.

A simple way that works for me is:

  1. Use the block = False inside show : plt.show(block = False)
  2. Use another show() at the end of the .py script.

Example of script.py file:

plt.imshow(*something*)                                                               
plt.colorbar()                                                                             
plt.xlabel("true ")                                                                   
plt.ylabel("predicted ")                                                              
plt.title(" the matrix")  

# Add block = False                                           
plt.show(block = False)

################################
# OTHER CALCULATIONS AND CODE HERE ! ! !
################################

# the next command is the last line of my script
plt.show()

What are Runtime.getRuntime().totalMemory() and freeMemory()?

According to the API

totalMemory()

Returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment. Note that the amount of memory required to hold an object of any given type may be implementation-dependent.

maxMemory()

Returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned.

freeMemory()

Returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory.

In reference to your question, maxMemory() returns the -Xmx value.

You may be wondering why there is a totalMemory() AND a maxMemory(). The answer is that the JVM allocates memory lazily. Lets say you start your Java process as such:

java -Xms64m -Xmx1024m Foo

Your process starts with 64mb of memory, and if and when it needs more (up to 1024m), it will allocate memory. totalMemory() corresponds to the amount of memory currently available to the JVM for Foo. If the JVM needs more memory, it will lazily allocate it up to the maximum memory. If you run with -Xms1024m -Xmx1024m, the value you get from totalMemory() and maxMemory() will be equal.

Also, if you want to accurately calculate the amount of used memory, you do so with the following calculation :

final long usedMem = totalMemory() - freeMemory();

CustomErrors mode="Off"

If you're using the MVC preview 4, you could be experiencing this because you're using the HandleErrorAttribute. The behavior changed in 5 so that it doesn't handle exceptions if you turn off custom errors.

Using an array from Observable Object with ngFor and Async Pipe Angular 2

Who ever also stumbles over this post.

I belive is the correct way:

  <div *ngFor="let appointment of (_nextFourAppointments | async).availabilities;"> 
    <div>{{ appointment }}</div>
  </div>

How to find the last field using 'cut'

If your input string doesn't contain forward slashes then you can use basename and a subshell:

$ basename "$(echo 'maps.google.com' | tr '.' '/')"

This doesn't use sed or awk but it also doesn't use cut either, so I'm not quite sure if it qualifies as an answer to the question as its worded.

This doesn't work well if processing input strings that can contain forward slashes. A workaround for that situation would be to replace forward slash with some other character that you know isn't part of a valid input string. For example, the pipe (|) character is also not allowed in filenames, so this would work:

$ basename "$(echo 'maps.google.com/some/url/things' | tr '/' '|' | tr '.' '/')" | tr '|' '/'

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

If embed no longer works for you, try with /v instead:

<iframe width="420" height="315" src="https://www.youtube.com/v/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>

How can I get the last character in a string?

You should look at charAt function and take length of the string.

var b = 'I am a JavaScript hacker.';
console.log(b.charAt(b.length-1));

Subtract 1 day with PHP

Not sure why your current code isn't working but if you don't specifically need a date object this will work:

$first_date = strtotime($date_raw);
$second_date = strtotime('-1 day', $first_date);

print 'First Date ' . date('Y-m-d', $first_date);
print 'Next Date ' . date('Y-m-d', $second_date);

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

The above answers are incorrect in that most over-ride the 'is this connection HTTPS' test to allow serving the pages over http irrespective of connection security.

The secure answer using an error-page on an NGINX specific http 4xx error code to redirect the client to retry the same request to https. (as outlined here https://serverfault.com/questions/338700/redirect-http-mydomain-com12345-to-https-mydomain-com12345-in-nginx )

The OP should use:

server {
  listen        12345;
  server_name   php.myadmin.com;

  root         /var/www/php;

  ssl           on;

  # If they come here using HTTP, bounce them to the correct scheme
  error_page 497 https://$server_name:$server_port$request_uri;

  [....]
}

how to run the command mvn eclipse:eclipse

The m2e plugin uses it's own distribution of Maven, packaged with the plugin.

In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows

Once Maven is properly installed (i.e. be sure that MAVEN_HOME, JAVA_HOME and PATH variables are set correctly): you must run mvn eclipse:eclipse from the directory containing the pom.xml.

Filtering lists using LINQ

I couldn't figure out how to do this in pure MS LINQ, so I wrote my own extension method to do it:

public static bool In<T>(this T objToCheck, params T[] values)
{
    if (values == null || values.Length == 0) 
    {
        return false; //early out
    }
    else
    {
        foreach (T t in values)
        {
            if (t.Equals(objToCheck))
                return true;   //RETURN found!
        }

        return false; //nothing found
    }
}

Using jQuery to center a DIV on the screen

It can be done with only CSS. But they asked with jQuery or JavaScript

Here, use CSS Flex box property to align the div center.

body.center{
  display:flex;
  align-items:center; // Vertical alignment
  justify-content:center; // Horizontal alignment
}

align-items:center; - used to align vertically.

justify-content:center; - used to align horizontally.

_x000D_
_x000D_
document.querySelector("body").classList.add("center");
_x000D_
body {
  margin : 0;
  height:100vh;
  width:100%;
  background: #ccc;
}
#main{
  background:#00cc00;
  width:100px;
  height:100px;
}
body.center{
  display:flex;
  align-items:center;
  justify-content:center;
}
_x000D_
<body>
  <div id="main"></div>
</body>
_x000D_
_x000D_
_x000D_

How to prove that a problem is NP complete?

To show a problem is NP complete, you need to:

Show it is in NP

In other words, given some information C, you can create a polynomial time algorithm V that will verify for every possible input X whether X is in your domain or not.

Example

Prove that the problem of vertex covers (that is, for some graph G, does it have a vertex cover set of size k such that every edge in G has at least one vertex in the cover set?) is in NP:

  • our input X is some graph G and some number k (this is from the problem definition)

  • Take our information C to be "any possible subset of vertices in graph G of size k"

  • Then we can write an algorithm V that, given G, k and C, will return whether that set of vertices is a vertex cover for G or not, in polynomial time.

Then for every graph G, if there exists some "possible subset of vertices in G of size k" which is a vertex cover, then G is in NP.

Note that we do not need to find C in polynomial time. If we could, the problem would be in `P.

Note that algorithm V should work for every G, for some C. For every input there should exist information that could help us verify whether the input is in the problem domain or not. That is, there should not be an input where the information doesn't exist.

Prove it is NP Hard

This involves getting a known NP-complete problem like SAT, the set of boolean expressions in the form:

(A or B or C) and (D or E or F) and ...

where the expression is satisfiable, that is there exists some setting for these booleans, which makes the expression true.

Then reduce the NP-complete problem to your problem in polynomial time.

That is, given some input X for SAT (or whatever NP-complete problem you are using), create some input Y for your problem, such that X is in SAT if and only if Y is in your problem. The function f : X -> Y must run in polynomial time.

In the example above, the input Y would be the graph G and the size of the vertex cover k.

For a full proof, you'd have to prove both:

  • that X is in SAT => Y in your problem

  • and Y in your problem => X in SAT.

marcog's answer has a link with several other NP-complete problems you could reduce to your problem.

Footnote: In step 2 (Prove it is NP-hard), reducing another NP-hard (not necessarily NP-complete) problem to the current problem will do, since NP-complete problems are a subset of NP-hard problems (that are also in NP).

How to set shadows in React Native for android?

In short, you can't do that in android, because if you see the docs about shadow only Support IOS see doc

The best option you can install 3rd party react-native-shadow

How to delete files older than X hours

If you do not have "-mmin" in your version of "find", then "-mtime -0.041667" gets pretty close to "within the last hour", so in your case, use:

-mtime +(X * 0.041667)

so, if X means 6 hours, then:

find . -mtime +0.25 -ls

works because 24 hours * 0.25 = 6 hours

Eclipse error: R cannot be resolved to a variable

I'm not posting this as an answer but a confirmation to Paresh's accepted answer. I recently updated SDK tools to Revision 22 and I noticed my code changes was not being affective on the device i'm testing at all. Such as the url I was using, I was getting errors for connection time out regarding the url I was "previously" using. Therefore I cleaned the project and built again only to find out that autogenerated R.java file is missing.

After reading Paresh's answer and checking what's going on with my sdk manager this is what I saw: enter image description here

SDK Build-tools 17 was not installed and there was already a new update to SDK tools even though it does not mention any change related to this problem in the changelog, this update brought back my R.java file and the related problems were gone after an eclipse restart and final clean/rebuild on the project.

WAMP server, localhost is not working

Wamp Server localhost not working. problems port 80 is closed. Icon Color Yellow

Solution:

wamp icon click > Apache > Service > Service Install

wamp icon click > All Services Restart

Icon Green its Work

dyld: Library not loaded: @rpath/libswiftCore.dylib

I'm using Xcode 8.3.3 and Xcode 9.2. The solution for me was to switch my default Xcode from 8 to 9 using Xcode Select:

$ xcode-select --print-path

$ sudo xcode-select -switch /Applications/Xcode-9.2.app

Edit: Actually what seemed to help here was that Xcode 9.2 used the derived data from Xcode 8.3.3. Not a solution but at least it allows me to move forward with my work.

How to split a dos path into its components in Python

Adapted the solution of @Mike Robins avoiding empty path elements at the beginning:

def parts(path):
    p,f = os.path.split(os.path.normpath(path))
    return parts(p) + [f] if f and p else [p] if p else []

os.path.normpath() is actually required only once and could be done in a separate entry function to the recursion.

How to get body of a POST in php?

return value in array

 $data = json_decode(file_get_contents('php://input'), true);

How to Validate on Max File Size in Laravel?

Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.

I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up

My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:

in resources/lang/en/validaton.php:

'uploaded' => 'The :attribute failed to upload.',

And this is the message displayed when the file is larger than the limit set by PHP.

I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.

However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.

So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.

Here is what works if the file to smaller than the PHP file size limit:

In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:

This is how I set a custom error message and maximum file size:

I have an input field <input type="file" name="upload">. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
  ...
  ...
  public function rules() {
    return [
      'upload' => 'required|file|max:8192',
    ];
  }
  public function messages()
  {
    return [            
      'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
      'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
    ];
  }
}

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

The JDK does not install a JVM in the default path.

Unless you need external tools to run like ant, the non-JDK is enough for Eclipse to run. The easiest way to install such a JVM is to go to http://java.com and let it install whatever it want to install.

Then double-click the Eclipse binary again.

How do I prevent mails sent through PHP mail() from going to spam?

<?php 
$to1 = '[email protected]';
$subject = 'Tester subject'; 

    // To send HTML mail, the Content-type header must be set

    $headers .= "Reply-To: The Sender <[email protected]>\r\n"; 
    $headers .= "Return-Path: The Sender <[email protected]>\r\n"; 
    $headers .= "From: [email protected]" ."\r\n" .
    $headers .= "Organization: Sender Organization\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
?>

ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.

How do I change the default schema in sql developer?

When a new user is created in ORACLE, an empty work area for tables and views is also automatically created. That work area is called a 'Schema'. Because of the tightly coupled relationship between users and schemas, the terms are often used synonymously. SQL Developer will, by default, show the empty schema that belongs to the user you connected with if it is indeed empty.

However, if you click to expand the part of the tree titled 'Other Users', you'll see other users/schemas that your user has access to. In there, you may find the tables and views you are seeking if you select the correct user/schema. An object only lives in the schema that owns it.

Still, it would be nice if the application allowed us to pick our desired schema closer to the root of the tree instead of forcing us to go searching for it. Other answers have offered workarounds such as:

  1. Logging in as the desired user/schema to begin with.
  2. Using a different Tool.
  3. Ignoring the tree and just executing: alter session set current_schema = otheruser;
  4. Creating a startup script to set the schema every time the application loads.

In the end, I searched and found another free tool that seems to solve this particular usability issue called DBeaver.

It's all a bit confusing because the word schema is overloaded. Schema could also be used to describe the database of your application. To get more clarity, read more about the term schema as it is used in the ORACLE context.

How to set cursor position in EditText?

I'm so late to answer this problem, so I figure it out. Just use,

android:gravity="center_horizontal"

How to use phpexcel to read data and insert into database?

      if($query)
       {
        // try to export to excel the whole data ---
        //initialize php excel first  
        ob_end_clean();
        //--- create php excel object ---
        $objPHPExcel = new PHPExcel();
        //define cachemethod
        ini_set('memory_limit', '3500M');
        $cacheMethod   = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array('memoryCacheSize' => '800MB');
        //set php excel settings
        PHPExcel_Settings::setCacheStorageMethod(
                $cacheMethod,$cacheSettings
              );


        $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");

        $objPHPExcel->setActiveSheetIndex(0);

        // Field names in the first row
        $fields = $query->list_fields();
        $col = 0;
        foreach ($fields as $field)
        {
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
            $col++;
        }

        // Fetching the table data
        $row = 2;
        foreach($query->result() as $data)
        {
            $col = 0;
            foreach ($fields as $field)
            {
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
                $col++;
            }

            $row++;
        }

        $objPHPExcel->setActiveSheetIndex(0);
        //redirect to cleint browser
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=Provinces.xlsx');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
     }