Programs & Examples On #Week number

Get the week start date and week end date from week number

Week Start & End Date From Date For Power BI Dax Formula

WeekStartDate = [DateColumn] - (WEEKDAY([DateColumn])-1)
WeekEndDate = [DateColumn] + (7-WEEKDAY([DateColumn]))

How to get week number in Python?

Here's another option:

import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime(d, '%U'))

which prints 24.

See: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior

How to get week numbers from dates?

If you want to get the week number with the year, Grant Shannon's solution using strftime works, but you need to make some corrections for the dates around january 1st. For instance, 2016-01-03 (yyyy-mm-dd) is week 53 of year 2015, not 2016. And 2018-12-31 is week 1 of 2019, not of 2018. This codes provides some examples and a solution. In column "yearweek" the years are sometimes wrong, in "yearweek2" they are corrected (rows 2 and 5).

library(dplyr)
library(lubridate)

# create a testset
test <- data.frame(matrix(data = c("2015-12-31",
                                   "2016-01-03",
                                   "2016-01-04",
                                   "2018-12-30",
                                   "2018-12-31",
                                   "2019-01-01") , ncol=1, nrow = 6 ))
# add a colname
colnames(test) <- "date_txt"

# this codes provides correct year-week numbers
test <- test %>%
        mutate(date = as.Date(date_txt, format = "%Y-%m-%d")) %>%
        mutate(yearweek = as.integer(strftime(date, format = "%Y%V"))) %>%
        mutate(yearweek2 = ifelse(test = day(date) > 7 & substr(yearweek, 5, 6) == '01',
                                 yes  = yearweek + 100,
                                 no   = ifelse(test = month(date) == 1 & as.integer(substr(yearweek, 5, 6)) > 51,
                                               yes  = yearweek - 100,
                                               no   = yearweek)))
# print the result
print(test)

    date_txt       date yearweek yearweek2
1 2015-12-31 2015-12-31   201553    201553
2 2016-01-03 2016-01-03   201653    201553
3 2016-01-04 2016-01-04   201601    201601
4 2018-12-30 2018-12-30   201852    201852
5 2018-12-31 2018-12-31   201801    201901
6 2019-01-01 2019-01-01   201901    201901

Calculate date from week number

The free Time Period Library for .NET includes the ISO 8601 conform class Week:

// ----------------------------------------------------------------------
public static DateTime GetFirstDayOfWeek( int year, int weekOfYear )
{
  return new Week( year, weekOfYear ).FirstDayStart;
} // GetFirstDayOfWeek

jQuery exclude elements with certain class in selector

To add some info that helped me today, a jQuery object/this can also be passed in to the .not() selector.

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $(".navitem").click(function(){_x000D_
        $(".navitem").removeClass("active");_x000D_
        $(".navitem").not($(this)).addClass("active");_x000D_
    });_x000D_
});
_x000D_
.navitem_x000D_
{_x000D_
    width: 100px;_x000D_
    background: red;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    position: relative;_x000D_
    text-align: center;_x000D_
}_x000D_
.navitem.active_x000D_
{_x000D_
    background:green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="navitem">Home</div>_x000D_
<div class="navitem">About</div>_x000D_
<div class="navitem">Pricing</div>
_x000D_
_x000D_
_x000D_

The above example can be simplified, but wanted to show the usage of this in the not() selector.

Extract images from PDF without resampling, in python?

Try below code. it will extract all image from pdf.

    import sys
    import PyPDF2
    from PIL import Image
    pdf=sys.argv[1]
    print(pdf)
    input1 = PyPDF2.PdfFileReader(open(pdf, "rb"))
    for x in range(0,input1.numPages):
        xObject=input1.getPage(x)
        xObject = xObject['/Resources']['/XObject'].getObject()
        for obj in xObject:
            if xObject[obj]['/Subtype'] == '/Image':
                size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
                print(size)
                data = xObject[obj]._data
                #print(data)
                print(xObject[obj]['/Filter'])
                if xObject[obj]['/Filter'][0] == '/DCTDecode':
                    img_name=str(x)+".jpg"
                    print(img_name)
                    img = open(img_name, "wb")
                    img.write(data)
                    img.close()
        print(str(x)+" is done")

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

If you don't want to recompile (as Visual Leak Detector requires) I would recommend WinDbg, which is both powerful and fast (though it's not as easy to use as one could desire).

On the other hand, if you don't want to mess with WinDbg, you can take a look at UMDH, which is also developed by Microsoft and it's easier to learn.

Take a look at these links in order to learn more about WinDbg, memory leaks and memory management in general:

DateTime's representation in milliseconds?

Using the answer of Andoma, this is what I'm doing

You can create a Struct or a Class like this one

struct Date
    {
        public static double GetTime(DateTime dateTime)
        {
            return dateTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
        }

        public static DateTime DateTimeParse(double milliseconds)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds).ToLocalTime();
        }

    }

And you can use this in your code as following

DateTime dateTime = DateTime.Now;

double total = Date.GetTime(dateTime);

dateTime = Date.DateTimeParse(total);

I hope this help you

Order by multiple columns with Doctrine

The comment for orderBy source code notes: Keys are field and values are the order, being either ASC or DESC.. So you can do orderBy->(['field' => Criteria::ASC]).

Cross domain POST request is not sending cookie Ajax Jquery

Please note this doesn't solve the cookie sharing process, as in general this is bad practice.

You need to be using JSONP as your type:

From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

$.ajax(
    { 
      type: "POST",
      url: "http://example.com/api/getlist.json",
      dataType: 'jsonp',
      xhrFields: {
           withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
            xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
      },
      success: function(){
           alert('success');
      },
      error: function (xhr) {
             alert(xhr.responseText);
      }
    }
);

The transaction manager has disabled its support for remote/network transactions

I had a store procedure that call another store Procedure in "linked server".when I execute it in ssms it was ok,but when I call it in application(By Entity Framework),I got this error. This article helped me and I used this script:

EXEC sp_serveroption @server = 'LinkedServer IP or Name',@optname = 'remote proc transaction promotion', @optvalue = 'false' ;

for more detail look at this: Linked server : The partner transaction manager has disabled its support for remote/network transactions

How to create a jQuery plugin with methods?

Too late but maybe it can help someone one day.

I was in the same situation like, creating a jQuery plugin with some methods, and after reading some articles and some tires I create a jQuery plugin boilerplate (https://github.com/acanimal/jQuery-Plugin-Boilerplate).

In addition, I develop with it a plugin to manage tags (https://github.com/acanimal/tagger.js) and wrote a two blog posts explaining step by step the creation of a jQuery plugin (http://acuriousanimal.com/blog/2013/01/15/things-i-learned-creating-a-jquery-plugin-part-i/).

How to copy a selection to the OS X clipboard

For Mac - Holding option key followed by ctrl V while selecting the text did the trick.

Writelines writes lines without newline, Just fills the file

This is actually a pretty common problem for newcomers to Python—especially since, across the standard library and popular third-party libraries, some reading functions strip out newlines, but almost no writing functions (except the log-related stuff) add them.

So, there's a lot of Python code out there that does things like:

fw.write('\n'.join(line_list) + '\n')

or

fw.write(line + '\n' for line in line_list)

Either one is correct, and of course you could even write your own writelinesWithNewlines function that wraps it up…

But you should only do this if you can't avoid it.

It's better if you can create/keep the newlines in the first place—as in Greg Hewgill's suggestions:

line_list.append(new_line + "\n")

And it's even better if you can work at a higher level than raw lines of text, e.g., by using the csv module in the standard library, as esuaro suggests.

For example, right after defining fw, you might do this:

cw = csv.writer(fw, delimiter='|')

Then, instead of this:

new_line = d[looking_for]+'|'+'|'.join(columns[1:])
line_list.append(new_line)

You do this:

row_list.append(d[looking_for] + columns[1:])

And at the end, instead of this:

fw.writelines(line_list)

You do this:

cw.writerows(row_list)

Finally, your design is "open a file, then build up a list of lines to add to the file, then write them all at once". If you're going to open the file up top, why not just write the lines one by one? Whether you're using simple writes or a csv.writer, it'll make your life simpler, and your code easier to read. (Sometimes there can be simplicity, efficiency, or correctness reasons to write a file all at once—but once you've moved the open all the way to the opposite end of the program from the write, you've pretty much lost any benefits of all-at-once.)

How do you underline a text in Android XML?

<resource>
    <string name="your_string_here">This is an <u>underline</u>.</string>
</resources>

If it does not work then

<resource>
<string name="your_string_here">This is an &lt;u>underline&lt;/u>.</string>

Because "<" could be a keyword at some time.

And for Displaying

TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(getString(R.string.your_string_here)));

Javascript - How to extract filename from a file input control

Assuming:

<input type="file" name="file1" id="theFile">

The JavaScript would be:

var fileName = document.getElementById('theFile').files[0].name;

How to utilize date add function in Google spreadsheet?

You can just add the number to the cell with the date.

so if A1: 12/3/2012 and A2: =A1+7 then A2 would display 12/10/2012

Connecting to MySQL from Android with JDBC

You can't access a MySQL DB from Android natively. EDIT: Actually you may be able to use JDBC, but it is not recommended (or may not work?) ... see Android JDBC not working: ClassNotFoundException on driver

See

http://www.helloandroid.com/tutorials/connecting-mysql-database

http://www.basic4ppc.com/forum/basic4android-getting-started-tutorials/8339-connect-android-mysql-database-tutorial.html

Android cannot connect directly to the database server. Therefore we need to create a simple web service that will pass the requests to the database and will return the response.

http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html

For most [good] users this might be fine. But imagine you get a hacker that gets a hold of your program. I've decompiled my own applications and its scary what I've seen. What if they get your username / password to your database and wreak havoc? Bad.

How to install pip for Python 3 on Mac OS X?

Also, it's worth to mention that Max OSX/macOS users can just use Homebrew to install pip3.

$> brew update
$> brew install python3
$> pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

PostgreSQL next value of the sequences?

I stumbled upon this question b/c I was trying to find the next sequence value by table. This didn't answer my question however this is how its done, and it may help those looking for the sequence value not by name but by table:

SELECT nextval(pg_get_serial_sequence('<your_table>', 'id')) AS new_id; 

Hope it helps :)

Character Limit in HTML

For the <input> element there's the maxlength attribute:

<input type="text" id="Textbox" name="Textbox" maxlength="10" />

(by the way, the type is "text", not "textbox" as others are writing), however, you have to use javascript with <textarea>s. Either way the length should be checked on the server anyway.

How an 'if (A && B)' statement is evaluated?

In C and C++, the && and || operators "short-circuit". That means that they only evaluate a parameter if required. If the first parameter to && is false, or the first to || is true, the rest will not be evaluated.

The code you posted is safe, though I question why you'd include an empty else block.

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

What is happening here is that database route does not accept any url methods.

I would try putting the url methods in the app route just like you have in the entry_page function:

@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
    if request.method == 'POST':
        date = request.form['date']
        title = request.form['blog_title']
        post = request.form['blog_main']
        post_entry = models.BlogPost(date = date, title = title, post = post)
        db.session.add(post_entry)
        db.session.commit()
        return redirect(url_for('database'))
    else:
        return render_template('entry.html')

@app.route('/database', methods=['GET', 'POST'])        
def database():
    query = []
    for i in session.query(models.BlogPost):
        query.append((i.title, i.post, i.date))
    return render_template('database.html', query = query)

Bring a window to the front in WPF

I know that this is late answer, maybe helpful for researchers

 if (!WindowName.IsVisible)
 {
     WindowName.Show();
     WindowName.Activate();
 }

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

How do I resolve ClassNotFoundException?

Use ';' as the separator. If your environment variables are set correctly, you should see your settings. If your PATH and CLASSPATH is correct, windows should recognize those commands. You do NOT need to restart your computer when installing Java.

How to jump to top of browser page

You can set the scrollTop, like this:

$('html,body').scrollTop(0);

Or if you want a little animation instead of a snap to the top:

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

How to test an Internet connection with bash?

This works on both MacOSX and Linux:

#!/bin/bash

ping -q -w1 -c1 google.com &>/dev/null && echo online || echo offline

What exactly does += do in python?

Remember when you used to sum, for example 2 & 3, in your old calculator and every time you hit the = you see 3 added to the total, the += does similar job. Example:

>>> orange = 2
>>> orange += 3
>>> print(orange)
5
>>> orange +=3
>>> print(orange)
8

How to convert string to float?

double x;

char *s;

s = " -2309.12E-15";

x = atof(s);     /* x = -2309.12E-15 */

printf("x = %4.4f\n",x);

Merge DLL into EXE?

I answered a similar question for VB.NET. It shouldn't however be too hard to convert. You embedd the DLL's into your Ressource folder and on the first usage, the AppDomain.CurrentDomain.AssemblyResolve event gets fired.

If you want to reference it during development, just add a normal DLL reference to your project.

Embedd a DLL into a project

How can I determine the current CPU utilization from the shell?

You need to sample the load average for several seconds and calculate the CPU utilization from that. If unsure what to you, get the sources of "top" and read it.

Getting the docstring from a function

You can also use inspect.getdoc. It cleans up the __doc__ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.

How to select the nth row in a SQL database table?

PostgreSQL supports windowing functions as defined by the SQL standard, but they're awkward, so most people use (the non-standard) LIMIT / OFFSET:

SELECT
    *
FROM
    mytable
ORDER BY
    somefield
LIMIT 1 OFFSET 20;

This example selects the 21st row. OFFSET 20 is telling Postgres to skip the first 20 records. If you don't specify an ORDER BY clause, there's no guarantee which record you will get back, which is rarely useful.

Send JSON via POST in C# and Receive the JSON returned?

Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

Stopword removal with NLTK

You can use string.punctuation with built-in NLTK stopwords list:

from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from string import punctuation

words = tokenize(text)
wordsWOStopwords = removeStopWords(words)

def tokenize(text):
        sents = sent_tokenize(text)
        return [word_tokenize(sent) for sent in sents]

def removeStopWords(words):
        customStopWords = set(stopwords.words('english')+list(punctuation))
        return [word for word in words if word not in customStopWords]

NLTK stopwords complete list

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

I imported new colors to my project and got the same problem. So I opened styles.xml and re-assigned items to colors using new colors names.

ojdbc14.jar vs. ojdbc6.jar

I have same problem!

Found following in oracle site link text

As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.

If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.

HTML5 form validation pattern alphanumeric with spaces?

It's quite an old question, but in case it could be useful for anyone, starting from a combination of good responses found here, I've ended using this pattern:

pattern="([^\s][A-z0-9À-ž\s]+)"

It will require at least two characters, making sure it does not start with an empty space but allowing spaces between words, and also allowing special characters such as a, ó, ä, ö.

Usage of the backtick character (`) in JavaScript

You can make a template of templates too, and reach private variable.

var a= {e:10, gy:'sfdsad'}; //global object

console.log(`e is ${a.e} and gy is ${a.gy}`); 
//e is 10 and gy is sfdsad

var b = "e is ${a.e} and gy is ${a.gy}" // template string
console.log( `${b}` );
//e is ${a.e} and gy is ${a.gy}

console.log( eval(`\`${b}\``) ); // convert template string to template
//e is 10 and gy is sfdsad

backtick( b );   // use fonction's variable
//e is 20 and gy is fghj

function backtick( temp ) {
  var a= {e:20, gy:'fghj'}; // local object
  console.log( eval(`\`${temp}\``) );
}

Creating a blocking Queue<T> in .NET?

That looks very unsafe (very little synchronization); how about something like:

class SizeQueue<T>
{
    private readonly Queue<T> queue = new Queue<T>();
    private readonly int maxSize;
    public SizeQueue(int maxSize) { this.maxSize = maxSize; }

    public void Enqueue(T item)
    {
        lock (queue)
        {
            while (queue.Count >= maxSize)
            {
                Monitor.Wait(queue);
            }
            queue.Enqueue(item);
            if (queue.Count == 1)
            {
                // wake up any blocked dequeue
                Monitor.PulseAll(queue);
            }
        }
    }
    public T Dequeue()
    {
        lock (queue)
        {
            while (queue.Count == 0)
            {
                Monitor.Wait(queue);
            }
            T item = queue.Dequeue();
            if (queue.Count == maxSize - 1)
            {
                // wake up any blocked enqueue
                Monitor.PulseAll(queue);
            }
            return item;
        }
    }
}

(edit)

In reality, you'd want a way to close the queue so that readers start exiting cleanly - perhaps something like a bool flag - if set, an empty queue just returns (rather than blocking):

bool closing;
public void Close()
{
    lock(queue)
    {
        closing = true;
        Monitor.PulseAll(queue);
    }
}
public bool TryDequeue(out T value)
{
    lock (queue)
    {
        while (queue.Count == 0)
        {
            if (closing)
            {
                value = default(T);
                return false;
            }
            Monitor.Wait(queue);
        }
        value = queue.Dequeue();
        if (queue.Count == maxSize - 1)
        {
            // wake up any blocked enqueue
            Monitor.PulseAll(queue);
        }
        return true;
    }
}

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

Easy, example with txt file

echo $null >> filename.txt

How to autoplay HTML5 mp4 video on Android?

Can add muted tag.

<video autoplay muted>
  <source src="video.webm" type="video/webm" />
  <source src="video.mp4" type="video/mp4" />
</video>

reference https://developers.google.com/web/updates/2016/07/autoplay

PHPMyAdmin Default login password

I just installed Fedora 16 (yea, I know it's old and not supported but, I had the CD burnt :) )

Anyway, coming to the solution, this is what I was required to do:

su -
gedit /etc/phpMyAdmin/config.inc.php

if not found... try phpmyadmin - all small caps.

gedit /etc/phpmyadmin/config.inc.php

Locate

$cfg['Servers'][$i]['AllowNoPassword']

and set it to:

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

Save it.

error: request for member '..' in '..' which is of non-class type

I was having a similar error, it seems that the compiler misunderstand the call to the constructor without arguments. I made it work by removing the parenthesis from the variable declaration, in your code something like this:

class Foo
{
  public:
    Foo() {};
    Foo(int a) {};
    void bar() {};
};

int main()
{
  // this works...
  Foo foo1(1);
  foo1.bar();

  // this does not...
  Foo foo2; // Without "()" 
  foo2.bar();

  return 0;
}

HTML table with fixed headers and a fixed column?

I have created something which has fixed header, fixed footer, fixed left column and also fixed right column. This only works fine in IE. As most of the users are still using IE this can be helpful. Please find the code here in Scrollable Table. Please let me your suggestions.

Meanwhile I am working to fix columns in other browser. I will keep you posted. :-)

Git - Undo pushed commits

You can do something like

git push origin +<short_commit_sha>^:<branch_name>

ASP.NET MVC - Set custom IIdentity or IPrincipal

As an addition to LukeP code for Web Forms users (not MVC) if you want to simplify the access in the code behind of your pages, just add the code below to a base page and derive the base page in all your pages:

Public Overridable Shadows ReadOnly Property User() As CustomPrincipal
    Get
        Return DirectCast(MyBase.User, CustomPrincipal)
    End Get
End Property

So in your code behind you can simply access:

User.FirstName or User.LastName

What I'm missing in a Web Form scenario, is how to obtain the same behaviour in code not tied to the page, for example in httpmodules should I always add a cast in each class or is there a smarter way to obtain this?

Thanks for your answers and thank to LukeP since I used your examples as a base for my custom user (which now has User.Roles, User.Tasks, User.HasPath(int) , User.Settings.Timeout and many other nice things)

Get UserDetails object from Security Context in Spring MVC controller

If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {

    ModelAndView mv = new ModelAndView("index");

    String userName = "not logged in"; // Any default user  name
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        userName = principal.getName();
    }

    mv.addObject("username", userName);

    // By adding a little code (same way) you can check if user has any
    // roles you need, for example:

    boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
    mv.addObject("isAdmin", fAdmin);

    return mv;
}

Note "HttpServletRequest request" parameter added.

Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.

What is the size limit of a post request?

As David pointed out, I would go with KB in most cases.

php_value post_max_size 2K

Note: my form is simple, just a few text boxes, not long text.

(PHP shorthand for KB is K, as outlined here.)

How to get a list of MySQL views?

 select * FROM information_schema.views\G; 

How to iterate through a list of objects in C++

Since C++ 11, you could do the following:

for(const auto& student : data)
{
  std::cout << student.name << std::endl;
}

HTML5 LocalStorage: Checking if a key exists

This method worked for me:

if ("username" in localStorage) {
    alert('yes');
} else {
    alert('no');
}

Best way to check if a Data Table has a null value in it

You can loop throw the rows and columns, checking for nulls, keeping track of whether there's a null with a bool, then check it after looping through the table and handle it.

//your DataTable, replace with table get code
DataTable table = new DataTable();
bool tableHasNull = false;

foreach (DataRow row in table.Rows)
{
    foreach (DataColumn col in table.Columns)
    {
        //test for null here
        if (row[col] == DBNull.Value)
        {
            tableHasNull = true;
        }
    }
}

if (tableHasNull)
{
    //handle null in table
}

You can also come out of the foreach loop with a break statement e.g.

//test for null here
if (row[col] == DBNull.Value)
{
    tableHasNull = true;
    break;
}

To save looping through the rest of the table.

Why would you use String.Equals over ==?

There is one subtle but very important difference between == and the String.Equals methods:

class Program
{
    static void Main(string[] args)
    {
        CheckEquality("a", "a");
        Console.WriteLine("----------");
        CheckEquality("a", "ba".Substring(1));
    }

    static void CheckEquality<T>(T value1, T value2) where T : class
    {
        Console.WriteLine("value1: {0}", value1);
        Console.WriteLine("value2: {0}", value2);

        Console.WriteLine("value1 == value2:      {0}", value1 == value2);
        Console.WriteLine("value1.Equals(value2): {0}", value1.Equals(value2));

        if (typeof(T).IsEquivalentTo(typeof(string)))
        {
            string string1 = (string)(object)value1;
            string string2 = (string)(object)value2;
            Console.WriteLine("string1 == string2:    {0}", string1 == string2);
        }
    }
}

Produces this output:

value1: a
value2: a
value1 == value2:      True
value1.Equals(value2): True
string1 == string2:    True
----------
value1: a
value2: a
value1 == value2:      False
value1.Equals(value2): True
string1 == string2:    True

You can see that the == operator is returning false to two obviously equal strings. Why? Because the == operator in use in the generic method is resolved to be the op_equal method as defined by System.Object (the only guarantee of T the method has at compile time), which means that it's reference equality instead of value equality.

When you have two values typed as System.String explicitly, then == has a value-equality semantic because the compiler resolves the == to System.String.op_equal instead of System.Object.op_equal.

So to play it safe, I almost always use String.Equals instead to that I always get the value equality semantics I want.

And to avoid NullReferenceExceptions if one of the values is null, I always use the static String.Equals method:

bool true = String.Equals("a", "ba".Substring(1));

Git: Find the most recent common ancestor of two branches

You are looking for git merge-base. Usage:

$ git merge-base branch2 branch3
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

How to add new item to hash

Create hash as:

h = Hash.new
=> {}

Now insert into hash as:

h = Hash["one" => 1]

How can I represent an infinite number in Python?

No one seems to have mentioned about the negative infinity explicitly, so I think I should add it.

For negative infinity:

-math.inf

For positive infinity (just for the sake of completeness):

math.inf

onchange event for input type="number"

The oninput event (.bind('input', fn)) covers any changes from keystrokes to arrow clicks and keyboard/mouse paste, but is not supported in IE <9.

_x000D_
_x000D_
jQuery(function($) {_x000D_
  $('#mirror').text($('#alice').val());_x000D_
_x000D_
  $('#alice').on('input', function() {_x000D_
    $('#mirror').text($('#alice').val());_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<input id="alice" type="number" step="any" value="99">_x000D_
_x000D_
<p id="mirror"></p>
_x000D_
_x000D_
_x000D_

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

How to force DNS refresh for a website?

If both of your servers are using WHM, I think we can reduce the time to nil. Create your domain in the new server and set everything ready. Go to the previous server and delete the account corresponding to that domain. Until now I have got no errors by doing this and felt the update instantaneous. FYI I used hostgator hosting (both dedicated servers). And I really dont know why it is so. It's supposed to be not like that until the TTL is over.

Java TreeMap Comparator

you can swipe the key and the value. For example

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());

Difference in Months between two dates in JavaScript

I know this is really late, but posting it anyway just in case it helps others. Here is a function I came up with that seems to do a good job of counting differences in months between two dates. It is admittedly a great deal raunchier than Mr.Crowder's, but provides more accurate results by stepping through the date object. It is in AS3 but you should just be able to drop the strong typing and you'll have JS. Feel free to make it nicer looking anyone out there!

    function countMonths ( startDate:Date, endDate:Date ):int
    {
        var stepDate:Date = new Date;
        stepDate.time = startDate.time;
        var monthCount:int;

        while( stepDate.time <= endDate.time ) { 
            stepDate.month += 1;
            monthCount += 1;
        }           

        if ( stepDate != endDate ) { 
            monthCount -= 1;
        }

        return monthCount;
    }

Split string into tokens and save them in an array

Why strtok() is a bad idea

Do not use strtok() in normal code, strtok() uses static variables which have some problems. There are some use cases on embedded microcontrollers where static variables make sense but avoid them in most other cases. strtok() behaves unexpected when more than 1 thread uses it, when it is used in a interrupt or when there are some other circumstances where more than one input is processed between successive calls to strtok(). Consider this example:

#include <stdio.h>
#include <string.h>

//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
    char *p = strtok(input, "/");
    while(p)
    {
        printf("%s, ",p);
        p = strtok(NULL, "/");
    }
}

int main(void)
{
    char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
    char *p = strtok(buffer, ":");
    while(p)
    {
        printContent(p);
        puts(""); //print newline
        p = strtok(NULL, ":");
    }
    return 0;
}

You may expect the output:

abc, def, ghi,
ABC, DEF, GHI,

But you will get

abc, def, ghi,

This is because you call strtok() in printContent() resting the internal state of strtok() generated in main(). After returning, the content of strtok() is empty and the next call to strtok() returns NULL.

What you should do instead

You could use strtok_r() when you use a POSIX system, this versions does not need static variables. If your library does not provide strtok_r() you can write your own version of it. This should not be hard and Stackoverflow is not a coding service, you can write it on your own.

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

Only Ian's answer was able to make my RecyclerView scroll to a specified position. However, The RecyclerView was not able to scroll afterwards when I used scrollToPosition(). smoothScrollToPosition() worked but the initial animation made it too slow when the list was long. The reason was the listener was not removed. I used the code below to remove the current ViewTreeObserver and it worked as a charm.

    mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mRecyclerView.scrollToPosition(mPosition);
            mRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Find TODO tags in Eclipse

Is there an easy way to view all methods which contain this comment? Some sort of menu option?

Yes, choose one of the following:

  1. Go to Window ? Show View ? Tasks (Not TaskList). The new view will show up where the "Console" and "Problems" tabs are by default.

  2. As mentioned elsewhere, you can see them next to the scroll bar as little blue rectangles if you have the source file in question open.

  3. If you just want the // TODO Auto-generated method stub messages (rather than all // TODO messages) you should use the search function (Ctrl-F for ones in this file Search ? Java Search ? Search string for the ability to specify this workspace, that file, this project, etc.)

Change image source in code behind - Wpf

None of the above solutions worked for me. But this did:

myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));

Two submit buttons in one form

You formaction for multiple submit button in one form example

 <input type="submit" name="" class="btn action_bg btn-sm loadGif" value="Add Address" title="" formaction="/addAddress"> 
 <input type="submit" name="" class="btn action_bg btn-sm loadGif" value="update Address" title="" formaction="/updateAddress"> 

How to append a char to a std::string?

str.append(10u,'d'); //appends character d 10 times

Notice I have written 10u and not 10 for the number of times I'd like to append the character; replace 10 with whatever number.

Can I automatically increment the file build version when using Visual Studio?

There is a visual studio extension Automatic Versions which supports Visual Studio (2012, 2013, 2015) 2017 & 2019.

Screen Shots enter image description here

enter image description here

Android: show/hide a view using an animation

I have used this two function to hide and show view with transition animation smoothly.

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void expand(final View v, int duration, int targetHeight, final int position) {

        int prevHeight = v.getHeight();

        v.setVisibility(View.VISIBLE);
        ValueAnimator valueAnimator = ValueAnimator.ofInt(0, targetHeight);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.getLayoutParams().height = (int) animation.getAnimatedValue();
                v.requestLayout();
            }
        });
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.setDuration(duration);
        valueAnimator.start();
        valueAnimator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                v.clearAnimation();
            }
        });

    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void collapse(final View v, int duration, int targetHeight, final int position) {
        if (position == (data.size() - 1)) {
            return;
        }
        int prevHeight = v.getHeight();
        ValueAnimator valueAnimator = ValueAnimator.ofInt(prevHeight, targetHeight);
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.getLayoutParams().height = (int) animation.getAnimatedValue();
                v.requestLayout();
            }
        });
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.setDuration(duration);
        valueAnimator.start();
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                animBoolArray.put(position, false);
                v.clearAnimation();

            }
        });
    }

AngularJS - Create a directive that uses ng-model

I took a combo of all answers, and now have two ways of doing this with the ng-model attribute:

  • With a new scope which copies ngModel
  • With the same scope which does a compile on link

_x000D_
_x000D_
var app = angular.module('model', []);_x000D_
_x000D_
app.controller('MainCtrl', function($scope) {_x000D_
  $scope.name = "Felipe";_x000D_
  $scope.label = "The Label";_x000D_
});_x000D_
_x000D_
app.directive('myDirectiveWithScope', function() {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: {_x000D_
      ngModel: '=',_x000D_
    },_x000D_
    // Notice how label isn't copied_x000D_
    template: '<div class="some"><label>{{label}}: <input ng-model="ngModel"></label></div>',_x000D_
    replace: true_x000D_
  };_x000D_
});_x000D_
app.directive('myDirectiveWithChildScope', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: true,_x000D_
    // Notice how label is visible in the scope_x000D_
    template: '<div class="some"><label>{{label}}: <input></label></div>',_x000D_
    replace: true,_x000D_
    link: function ($scope, element) {_x000D_
      // element will be the div which gets the ng-model on the original directive_x000D_
      var model = element.attr('ng-model');_x000D_
      $('input',element).attr('ng-model', model);_x000D_
      return $compile(element)($scope);_x000D_
    }_x000D_
  };_x000D_
});_x000D_
app.directive('myDirectiveWithoutScope', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    template: '<div class="some"><label>{{$parent.label}}: <input></label></div>',_x000D_
    replace: true,_x000D_
    link: function ($scope, element) {_x000D_
      // element will be the div which gets the ng-model on the original directive_x000D_
      var model = element.attr('ng-model');_x000D_
      return $compile($('input',element).attr('ng-model', model))($scope);_x000D_
    }_x000D_
  };_x000D_
});_x000D_
app.directive('myReplacedDirectiveIsolate', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: {},_x000D_
    template: '<input class="some">',_x000D_
    replace: true_x000D_
  };_x000D_
});_x000D_
app.directive('myReplacedDirectiveChild', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: true,_x000D_
    template: '<input class="some">',_x000D_
    replace: true_x000D_
  };_x000D_
});_x000D_
app.directive('myReplacedDirective', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    template: '<input class="some">',_x000D_
    replace: true_x000D_
  };_x000D_
});
_x000D_
.some {_x000D_
  border: 1px solid #cacaca;_x000D_
  padding: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>_x000D_
<div ng-app="model" ng-controller="MainCtrl">_x000D_
  This scope value <input ng-model="name">, label: "{{label}}"_x000D_
  <ul>_x000D_
    <li>With new isolate scope (label from parent):_x000D_
      <my-directive-with-scope ng-model="name"></my-directive-with-scope>_x000D_
    </li>_x000D_
    <li>With new child scope:_x000D_
      <my-directive-with-child-scope ng-model="name"></my-directive-with-child-scope>_x000D_
    </li>_x000D_
    <li>Same scope:_x000D_
      <my-directive-without-scope ng-model="name"></my-directive-without-scope>_x000D_
    </li>_x000D_
    <li>Replaced element, isolate scope:_x000D_
      <my-replaced-directive-isolate ng-model="name"></my-replaced-directive-isolate>_x000D_
    </li>_x000D_
    <li>Replaced element, child scope:_x000D_
      <my-replaced-directive-child ng-model="name"></my-replaced-directive-child>_x000D_
    </li>_x000D_
    <li>Replaced element, same scope:_x000D_
      <my-replaced-directive ng-model="name"></my-replaced-directive>_x000D_
    </li>_x000D_
  </ul>_x000D_
  <p>Try typing in the child scope ones, they copy the value into the child scope which breaks the link with the parent scope._x000D_
  <p>Also notice how removing jQuery makes it so only the new-isolate-scope version works._x000D_
  <p>Finally, note that the replace+isolate scope only works in AngularJS >=1.2.0_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'm not sure I like the compiling at link time. However, if you're just replacing the element with another you don't need to do that.

All in all I prefer the first one. Simply set scope to {ngModel:"="} and set ng-model="ngModel" where you want it in your template.

Update: I inlined the code snippet and updated it for Angular v1.2. Turns out that isolate scope is still best, especially when not using jQuery. So it boils down to:

  • Are you replacing a single element: Just replace it, leave the scope alone, but note that replace is deprecated for v2.0:

    app.directive('myReplacedDirective', function($compile) {
      return {
        restrict: 'E',
        template: '<input class="some">',
        replace: true
      };
    });
    
  • Otherwise use this:

    app.directive('myDirectiveWithScope', function() {
      return {
        restrict: 'E',
        scope: {
          ngModel: '=',
        },
        template: '<div class="some"><input ng-model="ngModel"></div>'
      };
    });
    

Set an environment variable in git bash

Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.

How to compile for Windows on Linux with gcc/g++?

Install a cross compiler, like mingw64 from your package manager. Then compile in the following way: instead of simply calling gcc call i686-w64-mingw32-gcc for 32-bit Windows or x86_64-w64-mingw32-gcc" for 64-bit Windows. I would also use the --static option, as the target system may not have all the libraries.

If you want to compile other language, like Fortran, replace -gcc with -gfortran in the previous commands.

What is the difference between new/delete and malloc/free?

also,

the global new and delete can be overridden, malloc/free cannot.

further more new and delete can be overridden per type.

How do I join two lines in vi?

This should do it:

J

final keyword in method parameters

Strings are immutable, so actully you can't change the String afterwards (you can only make the variable that held the String object point to a different String object).

However, that is not the reason why you can bind any variable to a final parameter. All the compiler checks is that the parameter is not reassigned within the method. This is good for documentation purposes, arguably good style, and may even help optimize the byte code for speed (although this seems not to do very much in practice).

But even if you do reassign a parameter within a method, the caller doesn't notice that, because java does all parameter passing by value. After the sequence

  a = someObject();
  process(a);

the fields of a may have changed, but a is still the same object it was before. In pass-by-reference languages this may not be true.

How to pass dictionary items as function arguments in python?

If you want to use them like that, define the function with the variable names as normal:

def my_function(school, standard, city, name):
    schoolName  = school
    cityName = city
    standardName = standard
    studentName = name

Now you can use ** when you call the function:

data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}

my_function(**data)

and it will work as you want.

P.S. Don't use reserved words such as class.(e.g., use klass instead)

How do I use reflection to call a generic method?

You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod:

MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);

For a static method, pass null as the first argument to Invoke. That's nothing to do with generic methods - it's just normal reflection.

As noted, a lot of this is simpler as of C# 4 using dynamic - if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.

Nginx 403 forbidden for all files

I solved this problem by adding user settings.

in nginx.conf

worker_processes 4;
user username;

change the 'username' with linux user name.

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition

e.g.

ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

sass :first-child not working

While @Andre is correct that there are issues with pseudo elements and their support, especially in older (IE) browsers, that support is improving all the time.

As for your question of, are there any issues, I'd say I've not really seen any, although the syntax for the pseudo-element can be a bit tricky, especially when first sussing it out. So:

div#top-level
  declarations: ...
  div.inside
    declarations: ...
    &:first-child
      declarations: ...

which compiles as one would expect:

div#top-level{
  declarations... }
div#top-level div.inside {
  declarations... }
div#top-level div.inside:first-child {
  declarations... }

I haven't seen any documentation on any of this, save for the statement that "sass can do everything that css can do." As always, with Haml and SASS the indentation is everything.

Youtube API Limitations

A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form

Convert integers to strings to create output filenames at run time

To convert an integer to a string:

integer :: i    
character* :: s    
if (i.LE.9) then
     s=char(48+i)    
else if (i.GE.10) then
     s=char(48+(i/10))// char(48-10*(i/10)+i)    
endif

Is there an easy way to strike through text in an app widget?

try this code

textview.setText((Html.fromHtml("<strike>hello world!</strike>")));

CSS, Images, JS not loading in IIS

For me adding this in the web.config resolved the problem

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" >
      <remove name="UrlRoutingModule"/>    
    </modules>
</system.webServer>

Returning binary file from controller in ASP.NET Web API

Try using a simple HttpResponseMessage with its Content property set to a StreamContent:

// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;

public HttpResponseMessage Post(string version, string environment,
    string filetype)
{
    var path = @"C:\Temp\test.exe";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

A few things to note about the stream used:

  • You must not call stream.Dispose(), since Web API still needs to be able to access it when it processes the controller method's result to send data back to the client. Therefore, do not use a using (var stream = …) block. Web API will dispose the stream for you.

  • Make sure that the stream has its current position set to 0 (i.e. the beginning of the stream's data). In the above example, this is a given since you've only just opened the file. However, in other scenarios (such as when you first write some binary data to a MemoryStream), make sure to stream.Seek(0, SeekOrigin.Begin); or set stream.Position = 0;

  • With file streams, explicitly specifying FileAccess.Read permission can help prevent access rights issues on web servers; IIS application pool accounts are often given only read / list / execute access rights to the wwwroot.

How to check if a date is in a given range?

I found this method the easiest:

$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';

$start_date = date_create($start_date);
$date_from_user = date_create($date_from_user);
$end_date = date_create($end_date);

$interval1 = date_diff($start_date, $date_from_user);
$interval2 = date_diff($end_date, $date_from_user);

if($interval1->invert == 0){
  if($interval2->invert == 1){

     // if it lies between start date and end date execute this code

  }
}

jquery - check length of input field?

That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if condition is always true.

The simplest way to make it work, it seems to me, is to account for this case:

    var value = $(this).val();
    if ( value.length > 0 && value != "Default text" ) ...

How to make a website secured with https

I think you are getting confused with your site Authentication and SSL.

If you need to get your site into SSL, then you would need to install a SSL certificate into your web server. You can buy a certificate for yourself from one of the places like Symantec etc. The certificate would contain your public/private key pair, along with other things.

You wont need to do anything in your source code, and you can still continue to use your Form Authntication (or any other) in your site. Its just that, any data communication that takes place between the web server and the client will encrypted and signed using your certificate. People would use secure-HTTP (https://) to access your site.

View this for more info --> http://en.wikipedia.org/wiki/Transport_Layer_Security

Objects inside objects in javascript

You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:

{el1, el2, {el31, el32, el33}, {el41, el42}}

_x000D_
_x000D_
var MainObj = {_x000D_
_x000D_
  prop1: "prop1MainObj",_x000D_
  _x000D_
  Obj1: {_x000D_
    prop1: "prop1Obj1",_x000D_
    prop2: "prop2Obj1",    _x000D_
    Obj2: {_x000D_
      prop1: "hey you",_x000D_
      prop2: "prop2Obj2"_x000D_
    }_x000D_
  },_x000D_
    _x000D_
  Obj3: {_x000D_
    prop1: "prop1Obj3",_x000D_
    prop2: "prop2Obj3"_x000D_
  },_x000D_
  _x000D_
  Obj4: {_x000D_
    prop1: true,_x000D_
    prop2: 3_x000D_
  }  _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
_x000D_
_x000D_

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.

Caution: I have a simple setup and this may not be the best for environments with advanced settings.

I am posting this as a separate answer as previously listed methods did not work for me.

Web Reference vs. Service Reference

Adding a service reference allows you to create a WCF client, which can be used to talk to a regular web service provided you use the appropriate binding. Adding a web reference will allow you to create only a web service (i.e., SOAP) reference.

If you are absolutely certain you are not ready for WCF (really don't know why) then you should create a regular web service reference.

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

Write-Output should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen. The pipeline will eventually write it to out-default if nothing else uses it first.

Write-Host should be used when you want to do the opposite.

[console]::WriteLine is essentially what Write-Host is doing behind the scenes.

Run this demonstration code and examine the result.

function Test-Output {
    Write-Output "Hello World"
}

function Test-Output2 {
    Write-Host "Hello World" -foreground Green
}

function Receive-Output {
    process { Write-Host $_ -foreground Yellow }
}

#Output piped to another function, not displayed in first.
Test-Output | Receive-Output

#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output 

#Pipeline sends to Out-Default at the end.
Test-Output 

You'll need to enclose the concatenation operation in parentheses, so that PowerShell processes the concatenation before tokenizing the parameter list for Write-Host, or use string interpolation

write-host ("count=" + $count)
# or
write-host "count=$count"

BTW - Watch this video of Jeffrey Snover explaining how the pipeline works. Back when I started learning PowerShell I found this to be the most useful explanation of how the pipeline works.

Find an element in a list of tuples

Or takewhile, ( addition to this, example of more values is shown ):

>>> a= [(1,2),(1,4),(3,5),(5,7),(0,2)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,a))
[(1, 2), (1, 4)]
>>> 

if unsorted, like:

>>> a= [(1,2),(3,5),(1,4),(5,7)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,sorted(a,key=lambda x: x[0]==1)))
[(1, 2), (1, 4)]
>>> 

Using an integer as a key in an associative array in JavaScript

Get the value for an associative array property when the property name is an integer:

Starting with an associative array where the property names are integers:

var categories = [
    {"1": "Category 1"},
    {"2": "Category 2"},
    {"3": "Category 3"},
    {"4": "Category 4"}
];

Push items to the array:

categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});

Loop through the array and do something with the property value.

for (var i = 0; i < categories.length; i++) {
    for (var categoryid in categories[i]) {
        var category = categories[i][categoryid];
        // Log progress to the console
        console.log(categoryid + ": " + category);
        //  ... do something
    }
}

Console output should look like this:

1: Category 1
2: Category 2
3: Category 3
4: Category 4
2300: Category 2300
2301: Category 2301

As you can see, you can get around the associative array limitation and have a property name be an integer.

NOTE: The associative array in my example is the JSON content you would have if you serialized a Dictionary<string, string>[] object.

How can I use a batch file to write to a text file?

It's easier to use only one code block, then you only need one redirection.

(
  echo Line1
  echo Line2
  ...
  echo Last Line
) > filename.txt

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

Difference between partition key, composite key and clustering key in Cassandra?

Adding a summary answer as the accepted one is quite long. The terms "row" and "column" are used in the context of CQL, not how Cassandra is actually implemented.

  • A primary key uniquely identifies a row.
  • A composite key is a key formed from multiple columns.
  • A partition key is the primary lookup to find a set of rows, i.e. a partition.
  • A clustering key is the part of the primary key that isn't the partition key (and defines the ordering within a partition).

Examples:

  • PRIMARY KEY (a): The partition key is a.
  • PRIMARY KEY (a, b): The partition key is a, the clustering key is b.
  • PRIMARY KEY ((a, b)): The composite partition key is (a, b).
  • PRIMARY KEY (a, b, c): The partition key is a, the composite clustering key is (b, c).
  • PRIMARY KEY ((a, b), c): The composite partition key is (a, b), the clustering key is c.
  • PRIMARY KEY ((a, b), c, d): The composite partition key is (a, b), the composite clustering key is (c, d).

How to write a full path in a batch file having a folder name with space?

I made a **

automatic-network-drive connector

** using a batch file.

Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!

looks a little bit different but works:

net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES

Thx for the Hint :)

Git commit with no commit message

You don't need git to accomplish this. Creative use of a bash function will do the trick just fine. If you don't care about messages, just set a default one and forget it.

function gitcom() {
  git commit -m "my default commit message"
}

If you were feeling really adventurous you could add, commit and push with one command

function gitzap() {
  git add . && git commit -m "whatevs" && git push $1 $2
}

Which you would then run as

gitzap origin master

You could even get deeper and use parse_git_branch to save yourself some keystrokes there, or set a common default of "origin" and "master".

How can I check if a string only contains letters in Python?

You can leverage regular expressions.

>>> import re
>>> pattern = re.compile("^[a-zA-Z]+$")
>>> pattern.match("hello")
<_sre.SRE_Match object; span=(0, 5), match='hello'>
>>> pattern.match("hel7lo")
>>>

The match() method will return a Match object if a match is found. Otherwise it will return None.


An easier approach is to use the .isalpha() method

>>> "Hello".isalpha()
True
>>> "Hel7lo".isalpha()
False

isalpha() returns true if there is at least 1 character in the string and if all the characters in the string are alphabets.

Export query result to .csv file in SQL Server 2008

  1. Open SQL Server Management Studio
  2. Go to Tools > Options > Query Results > SQL Server > Results To Text
  3. On the far right, there is a drop down box called Output Format
  4. Choose Comma Delimited and click OK

Here's a full screen version of that image, below

enter image description here

This will show your query results as comma-delimited text.

To save the results of a query to a file: Ctrl + Shift + F

iconv - Detected an illegal character in input string

I found one Solution :

echo iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($string));

use utf8_encode()

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

Build Solution - Builds any assemblies which have changed files. If an assembly has no changes, it won't be re-built. Also will not delete any intermediate files.

Used most commonly.

Rebuild Solution - Rebuilds all assemblies regardless of changes but leaves intermediate files.

Used when you notice that Visual Studio didn't incorporate your changes in the latest assembly. Sometimes Visual Studio does make mistakes.

Clean Solution - Delete all intermediate files.

Used when all else fails and you need to clean everything up and start fresh.

Convert String to Float in Swift

You have two options which are quite similar (by the approach and result):

// option 1:
var string_1 : String = "100"
var double_1 : Double = (string_1 as NSString).doubleValue + 99.0

// option 2: 
var string_2 : NSString = "100"
// or:  var string_2 = "100" as NSString
var number_2 : Double = string_2.doubleValue;

Downloading images with node.js

Building on the above, if anyone needs to handle errors in the write/read streams, I used this version. Note the stream.read() in case of a write error, it's required so we can finish reading and trigger close on the read stream.

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    if (err) callback(err, filename);
    else {
        var stream = request(uri);
        stream.pipe(
            fs.createWriteStream(filename)
                .on('error', function(err){
                    callback(error, filename);
                    stream.read();
                })
            )
        .on('close', function() {
            callback(null, filename);
        });
    }
  });
};

How can I change Eclipse theme?

Take a look at rogerdudler/eclipse-ui-themes . In the readme there is a link to a file that you need to extract into your eclipse/dropins folder.

When you have done that go to

Window -> Preferences -> General -> Appearance

And change the theme from GTK (or what ever it is currently) to Dark Juno (or Dark).

That will change the UI to a nice dark theme but to get the complete look and feel you can get the Eclipse Color Theme plugin from eclipsecolorthemes.org. The easiest way is to add this update URI to "Help -> Install New Software" and install it from there.

Eclipse Color Themes

This adds a "Color Theme" menu item under

Window -> Preferences -> Appearance

Where you can select from a large range of editor themes. My preferred one to use with PyDev is Wombat. For Java Solarized Dark

Docker compose, running containers in net:host

Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.

Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none

version: '3.7'
services:
  app:
    image: ramansharma/einwohnertomcat:v0.0.1
    deploy:
      replicas: 1
      ports:
       - '8080:8080'
    volumes:
     - type: bind
       source: /proc
       target: /hostfs/proc
       read_only: true
     - type: bind
       source: /sys/fs/cgroup
       target: /hostfs/sys/fs/cgroup
       read_only: true
     - type: bind
       source: /
       target: /hostfs
       read_only: true
    networks:
     hostnet: {}
    networks:
     - einwohner_net
     - elk_elk_net
networks:
 einwohner_net:
 elk_elk_net:
   external: true
 hostnet:
   external: true
   name: host

How to change the scrollbar color using css

Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.

So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.

Solution:

By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution

See This Demo

Check if a file exists with wildcard in shell script

Using new fancy shmancy features in ksh, bash, and zsh shells (this example doesn't handle spaces in filenames):

# Declare a regular array (-A will declare an associative array. Kewl!)
declare -a myarray=( /mydir/tmp*.txt )
array_length=${#myarray[@]}

# Not found if the 1st element of the array is the unexpanded string
# (ie, if it contains a "*")
if [[ ${myarray[0]} =~ [*] ]] ; then
   echo "No files not found"
elif [ $array_length -eq 1 ] ; then
   echo "File was found"
else
   echo "Files were found"
fi

for myfile in ${myarray[@]}
do
  echo "$myfile"
done

Yes, this does smell like Perl. Glad I didn't step in it ;)

How can I issue a single command from the command line through sql plus?

sqlplus user/password@sid < sqlfile.sql

This will also work from the DOS command line. In this case the file sqlfile.sql contains the SQL you wish to execute.

See full command of running/stopped container in Docker

Use:

docker inspect -f "{{.Name}} {{.Config.Cmd}}" $(docker ps -a -q)

... it does a "docker inspect" for all containers.

Iterate over the lines of a string

Here are three possibilities:

foo = """
this is 
a multi-line string.
"""

def f1(foo=foo): return iter(foo.splitlines())

def f2(foo=foo):
    retval = ''
    for char in foo:
        retval += char if not char == '\n' else ''
        if char == '\n':
            yield retval
            retval = ''
    if retval:
        yield retval

def f3(foo=foo):
    prevnl = -1
    while True:
      nextnl = foo.find('\n', prevnl + 1)
      if nextnl < 0: break
      yield foo[prevnl + 1:nextnl]
      prevnl = nextnl

if __name__ == '__main__':
  for f in f1, f2, f3:
    print list(f())

Running this as the main script confirms the three functions are equivalent. With timeit (and a * 100 for foo to get substantial strings for more precise measurement):

$ python -mtimeit -s'import asp' 'list(asp.f3())'
1000 loops, best of 3: 370 usec per loop
$ python -mtimeit -s'import asp' 'list(asp.f2())'
1000 loops, best of 3: 1.36 msec per loop
$ python -mtimeit -s'import asp' 'list(asp.f1())'
10000 loops, best of 3: 61.5 usec per loop

Note we need the list() call to ensure the iterators are traversed, not just built.

IOW, the naive implementation is so much faster it isn't even funny: 6 times faster than my attempt with find calls, which in turn is 4 times faster than a lower-level approach.

Lessons to retain: measurement is always a good thing (but must be accurate); string methods like splitlines are implemented in very fast ways; putting strings together by programming at a very low level (esp. by loops of += of very small pieces) can be quite slow.

Edit: added @Jacob's proposal, slightly modified to give the same results as the others (trailing blanks on a line are kept), i.e.:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip('\n')
        else:
            raise StopIteration

Measuring gives:

$ python -mtimeit -s'import asp' 'list(asp.f4())'
1000 loops, best of 3: 406 usec per loop

not quite as good as the .find based approach -- still, worth keeping in mind because it might be less prone to small off-by-one bugs (any loop where you see occurrences of +1 and -1, like my f3 above, should automatically trigger off-by-one suspicions -- and so should many loops which lack such tweaks and should have them -- though I believe my code is also right since I was able to check its output with other functions').

But the split-based approach still rules.

An aside: possibly better style for f4 would be:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl == '': break
        yield nl.strip('\n')

at least, it's a bit less verbose. The need to strip trailing \ns unfortunately prohibits the clearer and faster replacement of the while loop with return iter(stri) (the iter part whereof is redundant in modern versions of Python, I believe since 2.3 or 2.4, but it's also innocuous). Maybe worth trying, also:

    return itertools.imap(lambda s: s.strip('\n'), stri)

or variations thereof -- but I'm stopping here since it's pretty much a theoretical exercise wrt the strip based, simplest and fastest, one.

Java Equivalent of C# async/await?

Check out ea-async which does Java bytecode rewriting to simulate async/await pretty nicely. Per their readme: "It is heavily inspired by Async-Await on the .NET CLR"

How to calculate difference between two dates in oracle 11g SQL

You can use this:

SET FEEDBACK OFF;
SET SERVEROUTPUT ON;

DECLARE
  V_START_DATE  CHAR(17) := '28/03/16 17:20:00';
  V_END_DATE    CHAR(17) := '30/03/16 17:50:10';
  V_DATE_DIFF   VARCHAR2(17);

BEGIN

SELECT
  (TO_NUMBER( SUBSTR(NUMTODSINTERVAL(TO_DATE(V_END_DATE , 'DD/MM/YY HH24:MI:SS') - TO_DATE(V_START_DATE, 'DD/MM/YY HH24:MI:SS'), 'DAY'), 02, 9)) * 24) +
  (TO_NUMBER( SUBSTR(NUMTODSINTERVAL(TO_DATE(V_END_DATE , 'DD/MM/YY HH24:MI:SS') - TO_DATE(V_START_DATE, 'DD/MM/YY HH24:MI:SS'), 'DAY'), 12, 2)))  || 
              SUBSTR(NUMTODSINTERVAL(TO_DATE(V_END_DATE , 'DD/MM/YY HH24:MI:SS') - TO_DATE(V_START_DATE, 'DD/MM/YY HH24:MI:SS'), 'DAY'), 14, 6) AS "HH24:MI:SS"
  INTO V_DATE_DIFF
FROM 
  DUAL;

DBMS_OUTPUT.PUT_LINE(V_DATE_DIFF);
END;

Under which circumstances textAlign property works in Flutter?

You can align text anywhere in the scaffold or container except center:-

Its works for me anywhere in my application:-

new Text(

                "Nextperience",

//i have setted in center.

                textAlign: TextAlign.center,

//when i want it left.

 //textAlign: TextAlign.left,

//when i want it right.

 //textAlign: TextAlign.right,

                style: TextStyle(

                    fontSize: 16,

                    color: Colors.blue[900],

                    fontWeight: FontWeight.w500),

              ), 

How to convert milliseconds to seconds with precision

Why don't you simply try

System.out.println(1500/1000.0);
System.out.println(500/1000.0);

How can I retrieve Id of inserted entity using Entity framework?

You can get ID only after saving, instead you can create a new Guid and assign before saving.

"Non-static method cannot be referenced from a static context" error

setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.

You may want to look into some basic object-oriented tutorials to see how static/instance members work.

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

IIS7 defines a defaultDocument section in its configuration files which can be found in the %WinDir%\System32\InetSrv\Config folder. Most likely, the file index.aspx is already defined as a default document in one of IIS7's configuration files and you are adding it again in your web.config.

I suspect that removing the line <add value="index.aspx" />

from the defaultDocument/files section will fix your issue.

The defaultDocument section of your config will look like:

<defaultDocument>
  <files>
    <remove value="default.aspx" />
    <remove value="index.html" />
    <remove value="iisstart.htm" />
    <remove value="index.htm" />
    <remove value="Default.asp" />
    <remove value="Default.htm" />
  </files>
</defaultDocument>

Note that index.aspx will still appear in the list of default documents for your site in the IIS manager.

For more information about IIS7 configuration, click here.

Skip rows during csv import pandas

Also be sure that your file is actually a CSV file. For example, if you had an .xls file, and simply changed the file extension to .csv, the file won't import and will give the error above. To check to see if this is your problem open the file in excel and it will likely say:

"The file format and extension of 'Filename.csv' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?"

To fix the file: open the file in Excel, click "Save As", Choose the file format to save as (use .cvs), then replace the existing file.

This was my problem, and fixed the error for me.

Change WPF window background image in C# code

I have been trying all the answers here with no success. Here is the simplest way to do it with ms-appx

        ImageBrush myBrush = new ImageBrush();
        Image image = new Image();
        image.Source = new BitmapImage(new Uri(@"ms-appx:///Assets/background.jpg"));
        myBrush.ImageSource = image.Source;
        TheGrid.Background = myBrush;

Assets folder is in the first level of my project, so make sure to change the path as convenient.

ImportError: No module named scipy

I recommend you to remove scipy via

apt-get purge scipy

and then to install it by

pip install scipy

If you do both then you might confuse you deb package manager due to possibly differing versions.

WCF service startup error "This collection already contains an address with scheme http"

In my case root cause of this issue was multiple http bindings defined at parent web site i.e. InetMgr->Sites->Mysite->properties->EditBindings. I deleted one http binding which was not required and problem got resolved.

Compile a DLL in C/C++, then call it from another program

Here is how you do it:

In .h

#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif

extern "C" // Only if you are using C++ rather than C
{    
  EXPORT int __stdcall add2(int num);
  EXPORT int __stdcall mult(int num1, int num2);
}

in .cpp

extern "C" // Only if you are using C++ rather than C
{    
EXPORT int __stdcall add2(int num)
{
  return num + 2;
}


EXPORT int __stdcall mult(int num1, int num2)
{
  int product;
  product = num1 * num2;
  return product;
}
}

The macro tells your module (i.e your .cpp files) that they are providing the dll stuff to the outside world. People who incude your .h file want to import the same functions, so they sell EXPORT as telling the linker to import. You need to add BUILD_DLL to the project compile options, and you might want to rename it to something obviously specific to your project (in case a dll uses your dll).

You might also need to create a .def file to rename the functions and de-obfuscate the names (C/C++ mangles those names). This blog entry might be an interesting launching off point about that.

Loading your own custom dlls is just like loading system dlls. Just ensure that the DLL is on your system path. C:\windows\ or the working dir of your application are an easy place to put your dll.

How to order a data frame by one descending and one ascending column?

    library(dplyr)
    library(tidyr)
    #supposing you want to arrange column 'c' in descending order and 'd' in ascending order. name of data frame is df
    ## first doing descending
    df<-arrange(df,desc(c))
    ## then the ascending order of col 'd;
    df <-arrange(df,d)

How to recompile with -fPIC

Before compiling make sure that "rules.mk" file is included properly in Makefile or include it explicitly by:

"source rules.mk"

Return string without trailing slash

Based on @vdegenne 's answer... how to strip:

Single trailing slash:

theString.replace(/\/$/, '');

Single or consecutive trailing slashes:

theString.replace(/\/+$/g, '');

Single leading slash:

theString.replace(/^\//, '');

Single or consecutive leading slashes:

theString.replace(/^\/+/g, '');

Single leading and trailing slashes:

theString.replace(/^\/|\/$/g, '')

Single or consecutive leading and trailing slashes:

theString.replace(/^\/+|\/+$/g, '')

To handle both slashes and backslashes, replace instances of \/ with [\\/]

Add "Are you sure?" to my excel button, how can I?

Create a new sub with the following code and assign it to your button. Change the "DeleteProcess" to the name of your code to do the deletion. This will pop up a box with OK or Cancel and will call your delete sub if you hit ok and not if you hit cancel.

Sub AreYouSure()

Dim Sure As Integer

Sure = MsgBox("Are you sure?", vbOKCancel)
If Sure = 1 Then Call DeleteProcess

End Sub

Jesse

Editing the git commit message in GitHub

For intellij users: If you want to make changes in interactive way for past commits, which are not pushed follow below steps in Intellij:

  • Select Version Control
  • Select Log
  • Right click the commit for which you want to amend comment
  • Click reword
  • Done

Hope it helps

Get specific objects from ArrayList when objects were added anonymously?

I would suggest overriding the equals(Object) of your Party class. It might look something like this:

public boolean equals(Object o){
    if(o == null)
        return false;
    if(o instanceof String)
        return name.equalsIgnoreCase((String)o);
    else if(o instanceof Party)
        return equals(((Party)o).name);
    return false;
}

After you do that, you could use the indexOf(Object) method to retrieve the index of the party specified by its name, as shown below:

int index = cave.parties.indexOf("SecondParty");

Would return the index of the Party with the name SecondParty.

Note: This only works because you are overriding the equals(Object) method.

What is HEAD in Git?

To quote other people:

A head is simply a reference to a commit object. Each head has a name (branch name or tag name, etc). By default, there is a head in every repository called master. A repository can contain any number of heads. At any given time, one head is selected as the “current head.” This head is aliased to HEAD, always in capitals".

Note this difference: a “head” (lowercase) refers to any one of the named heads in the repository; “HEAD” (uppercase) refers exclusively to the currently active head. This distinction is used frequently in Git documentation.

Another good source that quickly covers the inner workings of git (and therefor a better understanding of heads/HEAD) can be found here. References (ref:) or heads or branches can be considered like post-it notes stuck onto commits in the commit history. Usually they point to the tip of series of commits, but they can be moved around with git checkout or git reset etc.

How to use underscore.js as a template engine?

I am giving a very simple example

1)

var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate); 

The result would be

Welcome you are at mysite.This has been created by john whose age is 25.

2) This is a template

   <script type="text/template" id="template_1">
       <% _.each(items,function(item,key,arr) { %>
          <li>
             <span><%= key %></span>
             <span><%= item.name %></span>
             <span><%= item.type %></span>
           </li>
       <% }); %>
   </script>

This is html

<div>
  <ul id="list_2"></ul>
</div>

This is the javascript code which contains json object and putting template into html

   var items = [
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       } 
   ];
  $(document).ready(function(){
      var template = $("#template_1").html();
      $("#list_2").html(_.template(template,{items:items}));
  });

java howto ArrayList push, pop, shift, and unshift

Great Answer by Jon.

I'm lazy though and I hate typing, so I created a simple cut and paste example for all the other people who are like me. Enjoy!

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        List<String> animals = new ArrayList<>();

        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Cat");
        animals.add("Dog");

        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

        // add() -> push(): Add items to the end of an array
        animals.add("Elephant");
        System.out.println(animals);  // [Lion, Tiger, Cat, Dog, Elephant]

        // remove() -> pop(): Remove an item from the end of an array
        animals.remove(animals.size() - 1);
        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

        // add(0,"xyz") -> unshift(): Add items to the beginning of an array
        animals.add(0, "Penguin");
        System.out.println(animals); // [Penguin, Lion, Tiger, Cat, Dog]

        // remove(0) -> shift(): Remove an item from the beginning of an array
        animals.remove(0);
        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

    }

}

Send a SMS via intent

  1. Manifest permission (you can put it after or before "application" )
 uses-permission android:name="android.permission.SEND_SMS"/>
  1. make a button for example and write the below code ( as written before by Prem at this thread ) and replace the below phone_Number by an actual number, it will work:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", "phone_Number", null)));

Redirect HTTP to HTTPS on default virtual host without ServerName

This is the complete way to omit unneeded redirects, too ;)

These rules are intended to be used in .htaccess files, as a RewriteRule in a *:80 VirtualHost entry needs no Conditions.

RewriteEngine on
RewriteCond %{HTTPS} off [OR] 
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

Eplanations:

RewriteEngine on

==> enable the engine at all

RewriteCond %{HTTPS} off [OR]

==> match on non-https connections, or (not setting [OR] would cause an implicit AND !)

RewriteCond %{HTTP:X-Forwarded-Proto} !https

==> match on forwarded connections (proxy, loadbalancer, etc.) without https

RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

==> if one of both Conditions match, do the rewrite of the whole URL, sending a 301 to have this 'learned' by the client (some do, some don't) and the L for the last rule.

Using DISTINCT and COUNT together in a MySQL Query

Isn't it better with a group by? Something like:

SELECT COUNT(*) FROM t1 GROUP BY keywork;

Are there any standard exit status codes in Linux?

Programs return a 16 bit exit code. If the program was killed with a signal then the high order byte contains the signal used, otherwise the low order byte is the exit status returned by the programmer.

How that exit code is assigned to the status variable $? is then up to the shell. Bash keeps the lower 7 bits of the status and then uses 128 + (signal nr) for indicating a signal.

The only "standard" convention for programs is 0 for success, non-zero for error. Another convention used is to return errno on error.

How to run an android app in background?

As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.

Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)

This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.

The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html

https://developer.android.com/reference/android/content/BroadcastReceiver.html

https://developer.android.com/guide/components/bound-services.html

In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:

https://developer.android.com/guide/components/aidl.html

Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip

This project will start an Activity which binds to a service; implementing the AIDL.

This project is also useful to re-factor for the purpose of IPC across different apps.

This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)

When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.

This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.

This project is developed in accordance to the above docs and is subsequently a clean solution.

There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}

Cmake doesn't find Boost

I had the same problem while trying to run make for a project after installing Boost version 1.66.0 on Ubuntu Trusty64. The error message was similar to (not exactly like) this one:

CMake Error at     
/usr/local/Cellar/cmake/3.3.2/share/cmake/Modules/FindBoost.cmake:1245 (message):
Unable to find the requested Boost libraries.
Boost version: 0.0.0
Boost include path: /usr/include
Detected version of Boost is too old.  Requested version was 1.36 (or newer).
Call Stack (most recent call first):
CMakeLists.txt:10 (FIND_PACKAGE)

Boost was definitely installed, but CMake couldn't detect it. After spending plenty of time tinkering with paths and environmental variables, I eventually ended up checking cmake itself for options and found the following:

--check-system-vars        = Find problems with variable usage in system files

So I ran the following in the directory at issue:

sudo cmake --check-system-vars

which returned:

Also check system files when warning about unused and uninitialized variables.
-- Boost version: 1.66.0
-- Found the following Boost libraries:
--   system
--   filesystem
--   thread
--   date_time
--   chrono
--   regex
--   serialization
--   program_options
-- Found Git: /usr/bin/git
-- Configuring done
-- Generating done
-- Build files have been written to: /home/user/myproject

and resolved the issue.

How to get the sizes of the tables of a MySQL database?

SELECT 
    table_name AS "Table",  
    round(((data_length + index_length) / 1024 / 1024), 2) as size   
FROM information_schema.TABLES  
WHERE table_schema = "YOUR_DATABASE_NAME"  
ORDER BY size DESC; 

This sorts the sizes (DB Size in MB).

foreach with index

You can do the following

foreach (var it in someCollection.Select((x, i) => new { Value = x, Index = i }) )
{
   if (it.Index > SomeNumber) //      
}

This will create an anonymous type value for every entry in the collection. It will have two properties

  • Value: with the original value in the collection
  • Index: with the index within the collection

What is the difference between bool and Boolean types in C#

Perhaps bool is a tad "lighter" than Boolean; Interestingly, changing this:

namespace DuckbillServerWebAPI.Models
{
    public class Expense
    {
        . . .
        public bool CanUseOnItems { get; set; }
    }
}

...to this:

namespace DuckbillServerWebAPI.Models
{
    public class Expense
    {
        . . .
        public Boolean CanUseOnItems { get; set; }
    }
}

...caused my cs file to sprout a "using System;" Changing the type back to "bool" caused the using clause's hair to turn grey.

(Visual Studio 2010, WebAPI project)

How can I check if a directory exists in a Bash shell script?

To check more than one directory use this code:

if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
    # Things to do
fi

How to scroll the page when a modal dialog is longer than the screen?

just use

.modal-body {
    max-height: calc(100vh - 210px);
    overflow-y: auto;
}

it will arrange your modal and then give it an vertical scroll

Change background of LinearLayout in Android

 android:background="@drawable/ic_launcher"

should be included inside Layout tab. where ic_launcher is image name that u can put inside project folder/res/drawable . you can copy any number of images and make it as background

CSS animation delay in repeating

Another way you can achieve a pause between animations is to apply a second animation that hides the element for the amount of delay you want. This has the benefit of allowing you to use a CSS easing function like you would normally.

.star {
  animation: shooting-star 1000ms ease-in-out infinite,
    delay-animation 2000ms linear infinite;
}

@keyframes shooting-star {
  0% {
    transform: translate(0, 0) rotate(45deg);
  }

  100% {
    transform: translate(300px, 300px) rotate(45deg);
  }
}

@keyframes delay-animation {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 1;
  }
  50.01% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

This only works if you want the delay to be a multiple of the animation duration. I used this to make a shower of shooting stars appear more random: https://codepen.io/ericdjohnson/pen/GRpOgVO

Time stamp in the C programming language

Use @Arkaitz Jimenez's code to get two timevals:

#include <sys/time.h>
//...
struct timeval tv1, tv2, diff;

// get the first time:
gettimeofday(&tv1, NULL);

// do whatever it is you want to time
// ...

// get the second time:
gettimeofday(&tv2, NULL);

// get the difference:

int result = timeval_subtract(&diff, &tv1, &tv2);

// the difference is storid in diff now.

Sample code for timeval_subtract can be found at this web site:

 /* Subtract the `struct timeval' values X and Y,
    storing the result in RESULT.
    Return 1 if the difference is negative, otherwise 0.  */

 int
 timeval_subtract (result, x, y)
      struct timeval *result, *x, *y;
 {
   /* Perform the carry for the later subtraction by updating y. */
   if (x->tv_usec < y->tv_usec) {
     int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
     y->tv_usec -= 1000000 * nsec;
     y->tv_sec += nsec;
   }
   if (x->tv_usec - y->tv_usec > 1000000) {
     int nsec = (x->tv_usec - y->tv_usec) / 1000000;
     y->tv_usec += 1000000 * nsec;
     y->tv_sec -= nsec;
   }

   /* Compute the time remaining to wait.
      tv_usec is certainly positive. */
   result->tv_sec = x->tv_sec - y->tv_sec;
   result->tv_usec = x->tv_usec - y->tv_usec;

   /* Return 1 if result is negative. */
   return x->tv_sec < y->tv_sec;
 }

In STL maps, is it better to use map::insert than []?

A gotcha with map::insert() is that it won't replace a value if the key already exists in the map. I've seen C++ code written by Java programmers where they have expected insert() to behave the same way as Map.put() in Java where values are replaced.

String.strip() in Python

In this case, you might get some differences. Consider a line like:

"foo\tbar "

In this case, if you strip, then you'll get {"foo":"bar"} as the dictionary entry. If you don't strip, you'll get {"foo":"bar "} (note the extra space at the end)

Note that if you use line.split() instead of line.split('\t'), you'll split on every whitespace character and the "striping" will be done during splitting automatically. In other words:

line.strip().split()

is always identical to:

line.split()

but:

line.strip().split(delimiter)

Is not necessarily equivalent to:

line.split(delimiter)

working with negative numbers in python

Try this on your TA:

# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)

for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
    print numa, numb,
    accum = 0
    negate = False
    if numa < 0:
        negate = True
        numa = -numa
    while numa:
        if numa & 1:
            accum += numb
        numa >>= 1
        numb <<= 1
    if negate:
        accum = -accum
    print accum

output:

3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129

Best way to copy from one array to another

I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];

enumerate() for dictionary in python

Python3:

One solution:

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, k in enumerate(enumm):
    print("{}) d.key={}, d.value={}".format(i, k, enumm[k]))

Output:
0) enumm.key=0, enumm.value=1
1) enumm.key=1, enumm.value=2
2) enumm.key=2, enumm.value=3
3) enumm.key=4, enumm.value=4
4) enumm.key=5, enumm.value=5
5) enumm.key=6, enumm.value=6
6) enumm.key=7, enumm.value=7

An another example:

d = {1 : {'a': 1, 'b' : 2, 'c' : 3},
     2 : {'a': 10, 'b' : 20, 'c' : 30}
    }    
for i, k in enumerate(d):
        print("{}) key={}, value={}".format(i, k, d[k])

Output:    
    0) key=1, value={'a': 1, 'b': 2, 'c': 3}
    1) key=2, value={'a': 10, 'b': 20, 'c': 30}

What is duck typing?

Wikipedia has a fairly detailed explanation:

http://en.wikipedia.org/wiki/Duck_typing

duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.

The important note is likely that with duck typing a developer is concerned more with the parts of the object that are consumed rather than what the actual underlying type is.

How to update one file in a zip archive

From zip(1):

When given the name of an existing zip archive, zip will replace identically named entries in the zip archive or add entries for new names.

So just use the zip command as you normally would to create a new .zip file containing only that one file, except the .zip filename you specify will be the existing archive.

Error message: "'chromedriver' executable needs to be available in the path"

If you are working with robot framework RIDE. Then you can download Chromedriver.exe from its official website and keep this .exe file in C:\Python27\Scripts directory. Now mention this path as your environment variable eg. C:\Python27\Scripts\chromedriver.exe.

Restart your computer and run same test case again. You will not get this problem again.

jquery: get id from class selector

When you add a click event, this returns the element that has been clicked. So you can just use this.id;

$(".test").click(function(){
   alert(this.id); 
});

Example: http://jsfiddle.net/jonathon/rfbrp/

Long vs Integer, long vs int, what to use and when?

When it comes to using a very long number that may exceed 32 bits to represent, you may use long to make sure that you'll not have strange behavior.

From Java 5 you can use in-boxing and out-boxing features to make the use of int and Integer completely the same. It means that you can do :

int myInt = new Integer(11);
Integer myInt2 = myInt;

The in and out boxing allow you to switch between int and Integer without any additional conversion (same for Long,Double,Short too)

You may use int all the time, but Integer contains some helper methods that can help you to do some complex operations with integers (such as Integer.parseInt(String) )

PHP display image BLOB from MySQL

This is what I use to display images from blob:

echo '<img src="data:image/jpeg;base64,'.base64_encode($image->load()) .'" />';

Postgresql tables exists, but getting "relation does not exist" when querying

The error can be caused by access restrictions. Solution:

GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;

CSS image overlay with color and transparency

JSFiddle Demo

HTML:

<div class="image-holder">
    <img src="http://codemancers.com/img/who-we-are-bg.png" />
</div>

CSS:

.image-holder {
    display:inline-block;
    position: relative;
}
.image-holder:after {
    content:'';
    top: 0;
    left: 0;
    z-index: 10;
    width: 100%;
    height: 100%;
    display: block;
    position: absolute;
    background: blue;
    opacity: 0.1;
}
.image-holder:hover:after {
    opacity: 0;
}

What is `related_name` used for in Django?

The related name parameter is actually an option. If we do not set it, Django automatically creates the other side of the relation for us. In the case of the Map model, Django would have created a map_set attribute, allowing access via m.map_set in your example(m being your class instance). The formula Django uses is the name of the model followed by the string _set. The related name parameter thus simply overrides Django’s default rather than providing new behavior.

Regex for string not ending with given suffix

The accepted answer is fine if you can use lookarounds. However, there is also another approach to solve this problem.

If we look at the widely proposed regex for this question:

.*[^a]$

We will find that it almost works. It does not accept an empty string, which might be a little inconvinient. However, this is a minor issue when dealing with just a one character. However, if we want to exclude whole string, e.g. "abc", then:

.*[^a][^b][^c]$

won't do. It won't accept ac, for example.

There is an easy solution for this problem though. We can simply say:

.{,2}$|.*[^a][^b][^c]$

or more generalized version:

.{,n-1}$|.*[^firstchar][^secondchar]$ where n is length of the string you want forbid (for abc it's 3), and firstchar, secondchar, ... are first, second ... nth characters of your string (for abc it would be a, then b, then c).

This comes from a simple observation that a string that is shorter than the text we won't forbid can not contain this text by definition. So we can either accept anything that is shorter("ab" isn't "abc"), or anything long enough for us to accept but without the ending.

Here's an example of find that will delete all files that are not .jpg:

find . -regex '.{,3}$|.*[^.][^j][^p][^g]$' -delete

how to use JSON.stringify and json_decode() properly

When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.

json_decode( html_entity_decode( stripslashes ($jsonString ) ) );

Thanks to @Thisguyhastwothumbs

Check if object is a jQuery object

You can check if the object is produced by JQuery with the jquery property:

myObject.jquery // 3.3.1

=> return the number of the JQuery version if the object produced by JQuery. => otherwise, it returns undefined

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

It appears that you are using the default route which is defined as this:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

The key part of that route is the {id} piece. If you look at your action method, your parameter is k instead of id. You need to change your action method to this so that it matches the route parameter:

// change int k to int id
public ActionResult DetailsData(int id)

If you wanted to leave your parameter as k, then you would change the URL to be:

http://localhost:7317/Employee/DetailsData?k=4

You also appear to have a problem with your connection string. In your web.config, you need to change your connection string to this (provided by haim770 in another answer that he deleted):

<connectionStrings>
  <add name="EmployeeContext"
       connectionString="Server=.;Database=mytry;integrated security=True;"
       providerName="System.Data.SqlClient" />
</connectionStrings>

Fetching data from MySQL database to html dropdown list

To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.

// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}

echo '</select>';// Close your drop down box

How can I add a column that doesn't allow nulls in a Postgresql database?

You have to set a default value.

ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) NOT NULL DEFAULT 'foo';

... some work (set real values as you want)...

ALTER TABLE mytable ALTER COLUMN mycolumn DROP DEFAULT;

Global Git ignore

I am able to ignore a .tmproj file by including either .tmproj or *.tmproj in my /users/me/.gitignore-global file.

Note that the file name is .gitignore-global not .gitignore. It did not work by including .tmproj or *.tmproj in a file called .gitignore in the /users/me directory.

How to merge remote changes at GitHub?

This problem can also occur when you have conflicting tags. If your local version and remote version use same tag name for different commits, you can end up here.

You can solve it my deleting the local tag:

$ git tag --delete foo_tag

What exactly is a Maven Snapshot and why do we need it?

The three others answers provide you a good vision of what a -SNAPSHOT version is. I just wanted to add some information regarding the behavior of Maven when it finds a SNAPSHOT dependency.

When you build an application, Maven will search for dependencies in the local repository. If a stable version is not found there, it will search the remote repositories (defined in settings.xml or pom.xml) to retrieve this dependency. Then, it will copy it into the local repository, to make it available for the next builds.

For example, a foo-1.0.jar library is considered as a stable version, and if Maven finds it in the local repository, it will use this one for the current build.

Now, if you need a foo-1.0-SNAPSHOT.jar library, Maven will know that this version is not stable and is subject to changes. That's why Maven will try to find a newer version in the remote repositories, even if a version of this library is found on the local repository. However, this check is made only once per day. That means that if you have a foo-1.0-20110506.110000-1.jar (i.e. this library has been generated on 2011/05/06 at 11:00:00) in your local repository, and if you run the Maven build again the same day, Maven will not check the repositories for a newer version.

Maven provides you a way to change this update policy in your repository definition:

<repository>
    <id>foo-repository</id>
    <url>...</url>
    <snapshots>
        <enabled>true</enabled>
        <updatePolicy>XXX</updatePolicy>
    </snapshots>
</repository>

where XXX can be:

  • always: Maven will check for a newer version on every build;
  • daily, the default value;
  • interval:XXX: an interval in minutes (XXX)
  • never: Maven will never try to retrieve another version. It will do that only if it doesn't exist locally. With the configuration, SNAPSHOT version will be handled as the stable libraries.

(model of the settings.xml can be found here)

Dismissing a Presented View Controller

try this:

[self dismissViewControllerAnimated:true completion:nil];

php - insert a variable in an echo string

Variable interpolation does not happen in single quotes. You need to use double quotes as:

$i = 1
echo "<p class=\"paragraph$i\"></p>";
++i;

Setting up MySQL and importing dump within Dockerfile

Each RUN instruction in a Dockerfile is executed in a different layer (as explained in the documentation of RUN).

In your Dockerfile, you have three RUN instructions. The problem is that MySQL server is only started in the first. In the others, no MySQL are running, that is why you get your connection error with mysql client.

To solve this problem you have 2 solutions.

Solution 1: use a one-line RUN

RUN /bin/bash -c "/usr/bin/mysqld_safe --skip-grant-tables &" && \
  sleep 5 && \
  mysql -u root -e "CREATE DATABASE mydb" && \
  mysql -u root mydb < /tmp/dump.sql

Solution 2: use a script

Create an executable script init_db.sh:

#!/bin/bash
/usr/bin/mysqld_safe --skip-grant-tables &
sleep 5
mysql -u root -e "CREATE DATABASE mydb"
mysql -u root mydb < /tmp/dump.sql

Add these lines to your Dockerfile:

ADD init_db.sh /tmp/init_db.sh
RUN /tmp/init_db.sh

TOMCAT - HTTP Status 404

You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.

Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.8\webapps, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like your-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or ../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

Source: HTTP Status 404 error in tomcat

How to convert an XML file to nice pandas dataframe?

Here is another way of converting a xml to pandas data frame. For example i have parsing xml from a string but this logic holds good from reading file as well.

import pandas as pd
import xml.etree.ElementTree as ET

xml_str = '<?xml version="1.0" encoding="utf-8"?>\n<response>\n <head>\n  <code>\n   200\n  </code>\n </head>\n <body>\n  <data id="0" name="All Categories" t="2018052600" tg="1" type="category"/>\n  <data id="13" name="RealEstate.com.au [H]" t="2018052600" tg="1" type="publication"/>\n </body>\n</response>'

etree = ET.fromstring(xml_str)
dfcols = ['id', 'name']
df = pd.DataFrame(columns=dfcols)

for i in etree.iter(tag='data'):
    df = df.append(
        pd.Series([i.get('id'), i.get('name')], index=dfcols),
        ignore_index=True)

df.head()

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

Every Driver service in selenium calls the similar code(following is the firefox specific code) while creating the driver object

 @Override
 protected File findDefaultExecutable() {
      return findExecutable(
        "geckodriver", GECKO_DRIVER_EXE_PROPERTY,
        "https://github.com/mozilla/geckodriver",
        "https://github.com/mozilla/geckodriver/releases");
    }

now for the driver that you want to use, you have to set the system property with the value of path to the driver executable.

for firefox GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver" and this can be set before creating the driver object as below

System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe");
WebDriver driver = new FirefoxDriver();

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Tried to install lxml, grab and other extensions, which requires VS 10.0+ and get the same issue. I find own way to solve this problem(Windows 10 x64, Python 3.4+):

  1. Install Visual C++ 2010 Express (download). (Do not install Microsoft Visual Studio 2010 Service Pack 1 )

  2. Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don't do those then the install is going to fail with an obscure "Fatal error during installation" error.

  3. Install offline version of Windows SDK for Visual Studio 2010 (v7.1) (download). This is required for 64bit extensions. Windows has builtin mounting for ISOs. Just mount the ISO and run Setup\SDKSetup.exe instead of setup.exe.

  4. Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 that contains:

    CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64

  5. Find extension on this site, then put them into the python folder, and install .whl extension with pip:

    python -m pip install extensionname.whl

  6. Enjoy

Converting int to string in C

Use snprintf - it is standard an available in every compilator. Query it for the size needed by calling it with NULL, 0 parameters. Allocate one character more for null at the end.

int length = snprintf( NULL, 0, "%d", x );
char* str = malloc( length + 1 );
snprintf( str, length + 1, "%d", x );
...
free(str);

Return a 2d array from a function

The function returns a static 2D array

const int N = 6;
int (*(MakeGridOfCounts)())[N] {
 static int cGrid[N][N] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
 return cGrid;
}

int main() {
int (*arr)[N];
arr = MakeGridOfCounts();
}

You need to make the array static since it will be having a block scope, when the function call ends, the array will be created and destroyed. Static scope variables last till the end of program.

mvn command is not recognized as an internal or external command

Write the entire maven path into the Environment PATH variable.

Example:

C:\Program Files\apache-maven-3.2.3\bin;

My PATH variable wasn't reading %M2% or %M2_HOME%\bin properly, and therefore I wrote the full path into the PATH variable.

Working.

Can I use jQuery with Node.js?

First of all install it

npm install jquery -S

After installing it, you can use it as below

import $ from 'jquery';
window.jQuery = window.$ = $;
$(selector).hide();

You can check out a full tutorial that I wrote here: https://medium.com/fbdevclagos/how-to-use-jquery-on-node-df731bd6abc7

Extracting just Month and Year separately from Pandas Datetime column

You can directly access the year and month attributes, or request a datetime.datetime:

In [15]: t = pandas.tslib.Timestamp.now()

In [16]: t
Out[16]: Timestamp('2014-08-05 14:49:39.643701', tz=None)

In [17]: t.to_pydatetime() #datetime method is deprecated
Out[17]: datetime.datetime(2014, 8, 5, 14, 49, 39, 643701)

In [18]: t.day
Out[18]: 5

In [19]: t.month
Out[19]: 8

In [20]: t.year
Out[20]: 2014

One way to combine year and month is to make an integer encoding them, such as: 201408 for August, 2014. Along a whole column, you could do this as:

df['YearMonth'] = df['ArrivalDate'].map(lambda x: 100*x.year + x.month)

or many variants thereof.

I'm not a big fan of doing this, though, since it makes date alignment and arithmetic painful later and especially painful for others who come upon your code or data without this same convention. A better way is to choose a day-of-month convention, such as final non-US-holiday weekday, or first day, etc., and leave the data in a date/time format with the chosen date convention.

The calendar module is useful for obtaining the number value of certain days such as the final weekday. Then you could do something like:

import calendar
import datetime
df['AdjustedDateToEndOfMonth'] = df['ArrivalDate'].map(
    lambda x: datetime.datetime(
        x.year,
        x.month,
        max(calendar.monthcalendar(x.year, x.month)[-1][:5])
    )
)

If you happen to be looking for a way to solve the simpler problem of just formatting the datetime column into some stringified representation, for that you can just make use of the strftime function from the datetime.datetime class, like this:

In [5]: df
Out[5]: 
            date_time
0 2014-10-17 22:00:03

In [6]: df.date_time
Out[6]: 
0   2014-10-17 22:00:03
Name: date_time, dtype: datetime64[ns]

In [7]: df.date_time.map(lambda x: x.strftime('%Y-%m-%d'))
Out[7]: 
0    2014-10-17
Name: date_time, dtype: object

How do I get a value of datetime.today() in Python that is "timezone aware"?

If you are using Django, you can set dates non-tz aware (only UTC).

Comment the following line in settings.py:

USE_TZ = True

Clear image on picturebox

You need the following:

pictbox.Image = null;
pictbox.update();

How do I flush the PRINT buffer in TSQL?

Another better option is to not depend on PRINT or RAISERROR and just load your "print" statements into a ##Temp table in TempDB or a permanent table in your database which will give you visibility to the data immediately via a SELECT statement from another window. This works the best for me. Using a permanent table then also serves as a log to what happened in the past. The print statements are handy for errors, but using the log table you can also determine the exact point of failure based on the last logged value for that particular execution (assuming you track the overall execution start time in your log table.)

Adding files to java classpath at runtime

You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.

Here is a rather ugly hack that adds to the SystemClassLoader at runtime:

import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;

public class ClassPathHacker {

  private static final Class[] parameters = new Class[]{URL.class};

  public static void addFile(String s) throws IOException {
    File f = new File(s);
    addFile(f);
  }//end method

  public static void addFile(File f) throws IOException {
    addURL(f.toURL());
  }//end method


  public static void addURL(URL u) throws IOException {

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class sysclass = URLClassLoader.class;

    try {
      Method method = sysclass.getDeclaredMethod("addURL", parameters);
      method.setAccessible(true);
      method.invoke(sysloader, new Object[]{u});
    } catch (Throwable t) {
      t.printStackTrace();
      throw new IOException("Error, could not add URL to system classloader");
    }//end try catch

   }//end method

}//end class

The reflection is necessary to access the protected method addURL. This could fail if there is a SecurityManager.

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

I will say It 's just shorthand syntax for get reference of html element during debugging time , normaly these kind of task will perform by these method

document.getElementById , document.getElementsByClassName , document.querySelector

so clicking on an html element and getting a reference variable ($0) in console is a huge time saving during the day

How to check if array element is null to avoid NullPointerException in Java

Fighting whether the code is compiling or not I would say create a array of sixe 5 add 2 values and print them , you will get the two values and others are null. The question is although the size is 5 but there are 2 objects in the array . How to find how many objects are present in the array

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

Bootstrap 3 select input form inline

This is how I made it without extra css or jquery:

<div class="form-group">
    <div class="input-group">
        <label class="sr-only" for="extra3">Extra name 3</label>
        <input type="text" id="extra3" class="form-control" placeholder="Extra name">
        <span class="input-group-addon">
            <label class="checkbox-inline">
               Mandatory? <input type="checkbox" id="inlineCheckbox5" value="option1">
            </label>
        </span>
        <span class="input-group-addon">
             <label class="checkbox-inline">
               Per person? <input type="checkbox" id="inlineCheckbox6" value="option2">
             </label>
        </span>
        <span class="input-group-addon">
            To be paid? 
            <select>
                <option value="online">Online</option>
                <option value="on spot">On Spot</option>
            </select>
        </span>
    </div>
</div>

Properly escape a double quote in CSV

I know this is an old post, but here's how I solved it (along with converting null values to empty string) in C# using an extension method.

Create a static class with something like the following:

    /// <summary>
    /// Wraps value in quotes if necessary and converts nulls to empty string
    /// </summary>
    /// <param name="value"></param>
    /// <returns>String ready for use in CSV output</returns>
    public static string Q(this string value)
    {
        if (value == null)
        {
            return string.Empty;
        }
        if (value.Contains(",") || (value.Contains("\"") || value.Contains("'") || value.Contains("\\"))
        {
            return "\"" + value + "\"";
        }
        return value;
    }

Then for each string you're writing to CSV, instead of:

stringBuilder.Append( WhateverVariable );

You just do:

stringBuilder.Append( WhateverVariable.Q() );

Failed to install *.apk on device 'emulator-5554': EOF

just close the eclipse and avd emulator and restart it. It works fine

react hooks useEffect() cleanup for only componentWillUnmount?

To add to the accepted answer, I had a similar issue and solved it using a similar approach with the contrived example below. In this case I needed to log some parameters on componentWillUnmount and as described in the original question I didn't want it to log every time the params changed.

const componentWillUnmount = useRef(false)

// This is componentWillUnmount
useEffect(() => {
    return () => {
        componentWillUnmount.current = true
    }
}, [])

useEffect(() => {
    return () => {
        // This line only evaluates to true after the componentWillUnmount happens 
        if (componentWillUnmount.current) {
            console.log(params)
        }
    }

}, [params]) // This dependency guarantees that when the componentWillUnmount fires it will log the latest params