Programs & Examples On #Dday

DDay.iCal is an iCalendar class library written in C# and based on the RFC 2445 standard. It parses files in the iCalendar format and provides an object-oriented interface to iCalendar components: Event, Todo, TimeZone, Journal, FreeBusy, and Alarm.

Finding modified date of a file/folder

If you run the Get-Item or Get-ChildItem commands these will output System.IO.FileInfo and System.IO.DirectoryInfo objects that contain this information e.g.:

Get-Item c:\folder | Format-List  

Or you can access the property directly like so:

Get-Item c:\folder | Foreach {$_.LastWriteTime}

To start to filter folders & files based on last write time you can do this:

Get-ChildItem c:\folder | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

You can use the .tostring() method with datetime format specifiers to format to whatever you need:

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

(Get-Date).AddDays(-1).ToString('MM-dd-yyyy')
11-01-2013

Using Cookie in Asp.Net Mvc 4

Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

PHP array() to javascript array()

This may be a easy solution.

var mydate = '<?php implode("##",$youdateArray); ?>';
var ret = mydate.split("##");

TimePicker Dialog from clicking EditText

You have not put the last argument in the TimePickerDialog.

{
public TimePickerDialog(Context context, OnTimeSetListener listener, int hourOfDay, int minute,
            boolean is24HourView) {
        this(context, 0, listener, hourOfDay, minute, is24HourView);
    }
}

this is the code of the TimePickerclass. it requires a boolean argument is24HourView

Using Get-childitem to get a list of files modified in the last 3 days

Very similar to previous responses, but the is from the current directory, looks at any file and only for ones that are 4 days old. This is what I needed for my research and the above answers were all very helpful. Thanks.

Get-ChildItem -Path . -Recurse| ? {$_.LastWriteTime -gt (Get-Date).AddDays(-4)}

Combining the results of two SQL queries as separate columns

You could also use a CTE to grab groups of information you want and join them together, if you wanted them in the same row. Example, depending on which SQL syntax you use, here:

WITH group1 AS (
  SELECT testA
    FROM tableA
),
group2 AS (
  SELECT testB
    FROM tableB 
)
SELECT *
  FROM group1
  JOIN group2 ON group1.testA = group2.testB --your choice of join
;

You decide what kind of JOIN you want based on the data you are pulling, and make sure to have the same fields in the groups you are getting information from in order to put it all into a single row. If you have multiple columns, make sure to name them all properly so you know which is which. Also, for performance sake, CTE's are the way to go, instead of inline SELECT's and such. Hope this helps.

Datetime in C# add days

Assign the enddate to some date variable because AddDays method returns new Datetime as the result..

Datetime somedate=endDate.AddDays(2);

how to pass list as parameter in function

You can pass it as a List<DateTime>

public void somefunction(List<DateTime> dates)
{
}

However, it's better to use the most generic (as in general, base) interface possible, so I would use

public void somefunction(IEnumerable<DateTime> dates)
{
}

or

public void somefunction(ICollection<DateTime> dates)
{
}

You might also want to call .AsReadOnly() before passing the list to the method if you don't want the method to modify the list - add or remove elements.

Get the correct week number of a given date

Here is an extension version and nullable version of il_guru's answer.

Extension:

public static int GetIso8601WeekOfYear(this DateTime time)
{
    var day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
    {
        time = time.AddDays(3);
    }

    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

Nullable:

public static int? GetIso8601WeekOfYear(this DateTime? time)
{
    return time?.GetIso8601WeekOfYear();
}

Usages:

new DateTime(2019, 03, 15).GetIso8601WeekOfYear(); //returns 11
((DateTime?) new DateTime(2019, 03, 15)).GetIso8601WeekOfYear(); //returns 11
((DateTime?) null).GetIso8601WeekOfYear(); //returns null

Subtract days from a DateTime

The object (i.e. destination variable) for the AddDays method can't be the same as the source.

Instead of:

DateTime today = DateTime.Today;
today.AddDays(-7);

Try this instead:

DateTime today = DateTime.Today;
DateTime sevenDaysEarlier = today.AddDays(-7);

Using GregorianCalendar with SimpleDateFormat

  1. You are putting there a two-digits year. The first century. And the Gregorian calendar started in the 16th century. I think you should add 2000 to the year.

  2. Month in the function new GregorianCalendar(year, month, days) is 0-based. Subtract 1 from the month there.

  3. Change the body of the second function as follows:

        String dateFormatted = null;
        SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
        try {
            dateFormatted = fmt.format(date);
        }
        catch ( IllegalArgumentException e){
            System.out.println(e.getMessage());
        }
        return dateFormatted;
    

After debugging, you'll see that simply GregorianCalendar can't be an argument of the fmt.format();.

Really, nobody needs GregorianCalendar as output, even you are told to return "a string".

Change the header of your format function to

public static String format(final Date date) 

and make the appropriate changes. fmt.format() will take the Date object gladly.

  1. Always after an unexpected exception arises, catch it yourself, don't allow the Java machine to do it. This way, you'll understand the problem.

Powershell Get-ChildItem most recent file in directory

Yes I think this would be quicker.

Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1 

Convert a string to a datetime

Try converting date like this:

    Dim expenddt as Date = Date.ParseExact(edate, "dd/mm/yyyy", 
System.Globalization.DateTimeFormatInfo.InvariantInfo);

Hope this helps.

What does void do in java?

void means it returns nothing. It does not return a string, you write a string to System.out but you're not returning one.

You must specify what a method returns, even if you're just saying that it returns nothing.

Technically speaking they could have designed the language such that if you don't write a return type then it's assumed to return nothing, however making you explicitly write out void helps to ensure that the lack of a returned value is intentional and not accidental.

Check date with todays date

Using Joda Time this can be simplified to:

DateMidnight startDate = new DateMidnight(startYear, startMonth, startDay);
if (startDate.isBeforeNow())
{
    // startDate is before now
    // do something...
}

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

LINQ orderby on date field in descending order

env.OrderByDescending(x => x.ReportDate)

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

Javascript - get array of dates between 2 dates

Function:

  var dates = [],
      currentDate = startDate,
      addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
      };
  while (currentDate <= endDate) {
    dates.push(currentDate);
    currentDate = addDays.call(currentDate, 1);
  }
  return dates;
};

Usage:

var dates = getDatesRange(new Date(2019,01,01), new Date(2019,01,25));                                                                                                           
dates.forEach(function(date) {
  console.log(date);
});

Hope it helps you

Assign variable in if condition statement, good practice or not?

I would consider this more of an old-school C style; it is not really good practice in JavaScript so you should avoid it.

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

Use DateTime.Today as opposed to DateTime.Now (which is what Get-Date returns) because Today is just the date with 00:00 as the time, and now is the moment in time down to the millisecond. (from masenkablast)

> [DateTime]::Today.AddDays(-1).AddHours(22)
Thursday, March 11, 2010 10:00:00 PM

Add days to JavaScript Date

Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.

If you want to just simply add n days to the date you have you are best to just go:

myDate.setDate(myDate.getDate() + n);

or the longwinded version

var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);

This today/tomorrow stuff is confusing. By setting the current date into your new date variable you will mess up the year value. if you work from the original date you won't.

Getting last month's date in php

It's simple to get last month date

echo date("Y-n-j", strtotime("first day of previous month"));
echo date("Y-n-j", strtotime("last day of previous month"));

at November 3 returns

2014-10-1
2014-10-31

How to enable C# 6.0 feature in Visual Studio 2013?

It worth mentioning that the build time will be increased for VS 2015 users after:

Install-Package Microsoft.Net.Compilers

Those who are using VS 2015 and have to keep this package in their projects can fix increased build time.

Edit file packages\Microsoft.Net.Compilers.1.2.2\build\Microsoft.Net.Compilers.props and clean it up. The file should look like:

<Project DefaultTargets="Build" 
         xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>

Doing so forces a project to be built as it was before adding Microsoft.Net.Compilers package

What is the difference between exit(0) and exit(1) in C?

exit(0) means Program(Process) terminate normally successfully..

exit(1) means program(process) terminate normally unsuccessfully..

If you want to observe this thing you must know signal handling and process management in Unix ...

know about sigaction, watipid()..for()...such....API...........

how to change default python version?

Old question, but alternatively:

virtualenv --python=python3.5 .venv
source .venv/bin/activate

What is the instanceof operator in JavaScript?

//Vehicle is a function. But by naming conventions
//(first letter is uppercase), it is also an object
//constructor function ("class").
function Vehicle(numWheels) {
    this.numWheels = numWheels;
}

//We can create new instances and check their types.
myRoadster = new Vehicle(4);
alert(myRoadster instanceof Vehicle);

How can I check file size in Python?

You can use the stat() method from the os module. You can provide it with a path in the form of a string, bytes or even a PathLike object. It works with file descriptors as well.

import os

res = os.stat(filename)

res.st_size # this variable contains the size of the file in bytes

Capture iframe load complete event

There is another consistent way (only for IE9+) in vanilla JavaScript for this:

const iframe = document.getElementById('iframe');
const handleLoad = () => console.log('loaded');

iframe.addEventListener('load', handleLoad, true)

And if you're interested in Observables this does the trick:

return Observable.fromEventPattern(
  handler => iframe.addEventListener('load', handler, true),
  handler => iframe.removeEventListener('load', handler)
);

Disable click outside of bootstrap modal area to close modal

Use this CSS for Modal and modal-dialog

.modal{
    pointer-events: none;
}

.modal-dialog{
    pointer-events: all;
 }

This can resolve your problem in Modal

The order of keys in dictionaries

Just sort the list when you want to use it.

l = sorted(d.keys())

How do I "Add Existing Item" an entire directory structure in Visual Studio?

Enable "Show All Files" for the specific project (you might need to hit "Refresh" to see them)**.

The folders/files that are not part of your project appear slightly "lighter" in the project tree.

Right click the folders/files you want to add and click "Include In Project". It will recursively add folders/files to the project.

** These buttons are located on the mini Solution Explorer toolbar.

** Make sure you are NOT in debug mode.

Oracle select most recent date record

select *
from (select
  staff_id, site_id, pay_level, date, 
  rank() over (partition by staff_id order by date desc) r
  from owner.table
  where end_enrollment_date is null
)
where r = 1

How to convert string to string[]?

A string is one string, a string[] is a string array. It means it's a variable with multiple strings in it.

Although you can convert a string to a string[] (create a string array with one element in it), it's probably a sign that you're trying to do something which you shouldn't do.

Get element inside element by class and ID - JavaScript

If this needs to work in IE 7 or lower you need to remember that getElementsByClassName does not exist in all browsers. Because of this you can create your own getElementsByClassName or you can try this.

var fooDiv = document.getElementById("foo");

for (var i = 0, childNode; i <= fooDiv.childNodes.length; i ++) {
    childNode = fooDiv.childNodes[i];
    if (/bar/.test(childNode.className)) {
        childNode.innerHTML = "Goodbye world!";
    }
}

How can I convert IPV6 address to IPV4 address?

Here is the code you are looking for in javascript. Well you know you can't convert all of the ipv6 addresses

<script>
function parseIp6(str)
{
  //init
  var ar=new Array;
  for(var i=0;i<8;i++)ar[i]=0;
  //check for trivial IPs
  if(str=="::")return ar;
  //parse
  var sar=str.split(':');
  var slen=sar.length;
  if(slen>8)slen=8;
  var j=0;
  for(var i=0;i<slen;i++){
    //this is a "::", switch to end-run mode
    if(i && sar[i]==""){j=9-slen+i;continue;}
    ar[j]=parseInt("0x0"+sar[i]);
    j++;
  }

  return ar;
}
function ipcnvfrom6(ip6)
{
  var ip6=parseIp6(ip6);
  var ip4=(ip6[6]>>8)+"."+(ip6[6]&0xff)+"."+(ip6[7]>>8)+"."+(ip6[7]&0xff);
  return ip4;
}
alert(ipcnvfrom6("::C0A8:4A07"));
</script>

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

This is due to espresso. You can add the following to your apps build.grade to mitigate this.

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
  exclude group: 'com.google.code.findbugs'
}

Regular Expressions: Is there an AND operator?

You can do that with a regular expression but probably you'll want to some else. For example use several regexp and combine them in a if clause.

You can enumerate all possible permutations with a standard regexp, like this (matches a, b and c in any order):

(abc)|(bca)|(acb)|(bac)|(cab)|(cba)

However, this makes a very long and probably inefficient regexp, if you have more than couple terms.

If you are using some extended regexp version, like Perl's or Java's, they have better ways to do this. Other answers have suggested using positive lookahead operation.

using OR and NOT in solr query

Just to add another unexpected case, here is query that wasn't returning expected results:

*:* AND ( ( field_a:foo AND field_b:bar ) OR !field_b:bar )

field_b in my case is something I perform faceting on, and needed to target the query term "foo" only on that type (bar)

I had to insert another *:* after the or condition to get this to work, like so:

*:* AND ( ( field_a:foo AND field_b:bar ) OR ( *:* AND !field_b:bar ) )

edit: this is in solr 6.6.3

How to test if JSON object is empty in Java

Try:

if (record.has("problemkey") && !record.isNull("problemkey")) {
    // Do something with object.
}

Best way to pass parameters to jQuery's .load()

In the first case, the data are passed to the script via GET, in the second via POST.

http://docs.jquery.com/Ajax/load#urldatacallback

I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

How to print to console when using Qt

If you are printing to stderr using the stdio library, a call to fflush(stderr) should flush the buffer and get you real-time logging.

How do I get my Python program to sleep for 50 milliseconds?

You can also use pyautogui as:

import pyautogui
pyautogui._autoPause(0.05, False)

If the first argument is not None, then it will pause for first argument's seconds, in this example: 0.05 seconds

If the first argument is None, and the second argument is True, then it will sleep for the global pause setting which is set with:

pyautogui.PAUSE = int

If you are wondering about the reason, see the source code:

def _autoPause(pause, _pause):
    """If `pause` is not `None`, then sleep for `pause` seconds.
    If `_pause` is `True`, then sleep for `PAUSE` seconds (the global pause setting).

    This function is called at the end of all of PyAutoGUI's mouse and keyboard functions. Normally, `_pause`
    is set to `True` to add a short sleep so that the user can engage the failsafe. By default, this sleep
    is as long as `PAUSE` settings. However, this can be override by setting `pause`, in which case the sleep
    is as long as `pause` seconds.
    """
    if pause is not None:
        time.sleep(pause)
    elif _pause:
        assert isinstance(PAUSE, int) or isinstance(PAUSE, float)
        time.sleep(PAUSE)

Popup Message boxes

JOptionPane.showMessageDialog(btn1, "you are clicked save button","title of dialog",2);

btn1 is a JButton variable and its used in this dialog to dialog open position btn1 or textfield etc, by default use null position of the frame.next your message and next is the title of dialog. 2 numbers of alert type icon 3 is the information 1,2,3,4. Ok I hope you understand it

How do I format XML in Notepad++?

Try Plugins -> XML Tools -> Pretty Print (libXML) or (XML only - with line breaks Ctrl + Alt + Shift + B)

You may need to install XML Tools using your plugin manager in order to get this option in your menu.

In my experience, libXML gives nice output but only if the file is 100% correctly formed.

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

If you came across this error while using the command line its because you must be using php 7 to execute whatever it is you are trying to execute. What happened is that the code is trying to use an operator thats only available in php7+ and is causing a syntax error.

If you already have php 7+ on your computer try pointing the command line to the higher version of php you want to use.

export PATH=/usr/local/[php-7-folder]/bin/:$PATH

Here is the exact location that worked based off of my setup for reference:

export PATH=/usr/local/php5-7.1.4-20170506-100436/bin/:$PATH

The operator thats actually caused the break is the "null coalesce operator" you can read more about it here:

php7 New Operators

Flask-SQLAlchemy how to delete all rows in a single table

Try delete:

models.User.query.delete()

From the docs: Returns the number of rows deleted, excluding any cascades.

How do I create a pause/wait function using Qt?

Since you're trying to "test some class code," I'd really recommend learning to use QTestLib. It provides a QTest namespace and a QtTest module that contain a number of useful functions and objects, including QSignalSpy that you can use to verify that certain signals are emitted.

Since you will eventually be integrating with a full GUI, using QTestLib and testing without sleeping or waiting will give you a more accurate test -- one that better represents the true usage patterns. But, should you choose not to go that route, you could use QTestLib::qSleep to do what you've requested.

Since you just need a pause between starting your pump and shutting it down, you could easily use a single shot timer:

class PumpTest: public QObject {
    Q_OBJECT
    Pump &pump;
public:
    PumpTest(Pump &pump):pump(pump) {};
public slots:
    void start() { pump.startpump(); }
    void stop() { pump.stoppump(); }
    void stopAndShutdown() {
        stop();
        QCoreApplication::exit(0);
    }
    void test() {
        start();
        QTimer::singleShot(1000, this, SLOT(stopAndShutdown));
    }
};

int main(int argc, char* argv[]) {
    QCoreApplication app(argc, argv);
    Pump p;
    PumpTest t(p);
    t.test();
    return app.exec();
}

But qSleep() would definitely be easier if all you're interested in is verifying a couple of things on the command line.

EDIT: Based on the comment, here's the required usage patterns.

First, you need to edit your .pro file to include qtestlib:

CONFIG += qtestlib

Second, you need to include the necessary files:

  • For the QTest namespace (which includes qSleep): #include <QTest>
  • For all the items in the QtTest module: #include <QtTest>. This is functionally equivalent to adding an include for each item that exists within the namespace.

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

How to get a json string from url?

Use the WebClient class in System.Net:

var json = new WebClient().DownloadString("url");

Keep in mind that WebClient is IDisposable, so you would probably add a using statement to this in production code. This would look like:

using (WebClient wc = new WebClient())
{
   var json = wc.DownloadString("url");
}

I am not able launch JNLP applications using "Java Web Start"?

This can also be due to environment variable CATALINA_HOME in your system. In our organization there were several cases where JNLP applications just refused to start without logging anything and emptying CATALINA_HOME solved the issue.

I had the environment variable set in the command prompt and it didn't appear in GUI. I'm not sure if setx command or register removal commands did the trick. Restart seems to be necessary after removing the variable.

HTTP 404 when accessing .svc file in IIS

What worked for me, On Windows 2012 Server R2:

WCF HTTP 404

Thanks goes to "Aaron D"

How to get the Google Map based on Latitude on Longitude?

Have you gone through google's geocoding api. The following link shall help you get started: http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests

How to parse JSON to receive a Date object in JavaScript?

You can convert JSON Date to normal date format in JavaScript.

var date = new Date(parseInt(jsonDate.substr(6)));

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

How to merge two json string in Python?

What do you mean by merging? JSON objects are key-value data structure. What would be a key and a value in this case? I think you need to create new directory and populate it with old data:

d = {}
d["new_key"] = jsonStringA[<key_that_you_did_not_mention_here>] + \ 
               jsonStringB["timestamp_in_ms"]

Merging method is obviously up to you.

Git Push ERROR: Repository not found

git remote rm origin
git remote add origin <remote url>

What is the advantage of using heredoc in PHP?

The heredoc syntax is much cleaner to me and it is really useful for multi-line strings and avoiding quoting issues. Back in the day I used to use them to construct SQL queries:

$sql = <<<SQL
select *
  from $tablename
 where id in [$order_ids_list]
   and product_name = "widgets"
SQL;

To me this has a lower probability of introducing a syntax error than using quotes:

$sql = "
select *
  from $tablename
 where id in [$order_ids_list]
   and product_name = \"widgets\"
";

Another point is to avoid escaping double quotes in your string:

$x = "The point of the \"argument" was to illustrate the use of here documents";

The problem with the above is the syntax error (the missing escaped quote) I just introduced as opposed to here document syntax:

$x = <<<EOF
The point of the "argument" was to illustrate the use of here documents
EOF;

It is a bit of style, but I use the following as rules for single, double and here documents for defining strings:

  • Single quotes are used when the string is a constant like 'no variables here'
  • Double quotes when I can put the string on a single line and require variable interpolation or an embedded single quote "Today is ${user}'s birthday"
  • Here documents for multi-line strings that require formatting and variable interpolation.

How to add jQuery to an HTML page?

Include javascript using script tags just before your ending body tag. Preferably you will want to put it in a separate file and link to it to keep things a little more organized and easier to read. Theres a simple article here that will show you how http://www.selftaughtweb.com/how-to-include-javascript/

Replace only text inside a div using jquery

If you actually know the text you are going to replace you could use

$('#one').contents(':contains("Hi I am text")')[0].nodeValue = '"Hi I am replace"';

http://jsfiddle.net/5rWwh/

Or

$('#one').contents(':not(*)')[1].nodeValue = '"Hi I am replace"';

$('#one').contents(':not(*)') selects non-element child nodes in this case text nodes and the second node is the one we want to replace.

http://jsfiddle.net/5rWwh/1/

MySql Inner Join with WHERE clause


1. Change the INNER JOIN before the WHERE clause.
2. You have two WHEREs which is not allowed.

Try this:

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

Select info from table where row has max date

SELECT group, date, checks
  FROM table 
  WHERE checks > 0
  GROUP BY group HAVING date = max(date) 

should work.

How to add a button dynamically using jquery

Your append line must be in your test() function

EDIT:

Here are two versions:

Version 1: jQuery listener

$(function(){
    $('button').on('click',function(){
        var r= $('<input type="button" value="new button"/>');
        $("body").append(r);
    });
});

DEMO HERE

Version 2: With a function (like your example)

function createInput(){
    var $input = $('<input type="button" value="new button" />');
    $input.appendTo($("body"));
}

DEMO HERE

Note: This one can be done with either .appendTo or with .append.

Can I disable a CSS :hover effect via JavaScript?

There isn’t a pure JavaScript generic solution, I’m afraid. JavaScript isn’t able to turn off the CSS :hover state itself.

You could try the following alternative workaround though. If you don’t mind mucking about in your HTML and CSS a little bit, it saves you having to reset every CSS property manually via JavaScript.

HTML

<body class="nojQuery">

CSS

/* Limit the hover styles in your CSS so that they only apply when the nojQuery 
class is present */

body.nojQuery ul#mainFilter a:hover {
    /* CSS-only hover styles go here */
}

JavaScript

// When jQuery kicks in, remove the nojQuery class from the <body> element, thus
// making the CSS hover styles disappear.

$(function(){}
    $('body').removeClass('nojQuery');
)

PHP - define constant inside a class

This is a pretty old question, but perhaps this answer can still help someone else.

You can emulate a public constant that is restricted within a class scope by applying the final keyword to a method that returns a pre-defined value, like this:

class Foo {

    // This is a private constant
    final public MYCONSTANT()
    {
        return 'MYCONSTANT_VALUE';
    }
}

The final keyword on a method prevents an extending class from re-defining the method. You can also place the final keyword in front of the class declaration, in which case the keyword prevents class Inheritance.

To get nearly exactly what Alex was looking for the following code can be used:

final class Constants {

    public MYCONSTANT()
    {
        return 'MYCONSTANT_VALUE';
    }
}

class Foo {

    static public app()
    {
        return new Constants();
    }
}

The emulated constant value would be accessible like this:

Foo::app()->MYCONSTANT();

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

First of all, never use a for in loop to enumerate over an array. Never. Use good old for(var i = 0; i<arr.length; i++).

The reason behind this is the following: each object in JavaScript has a special field called prototype. Everything you add to that field is going to be accessible on every object of that type. Suppose you want all arrays to have a cool new function called filter_0 that will filter zeroes out.

Array.prototype.filter_0 = function() {
    var res = [];
    for (var i = 0; i < this.length; i++) {
        if (this[i] != 0) {
            res.push(this[i]);
        }
    }
    return res;
};

console.log([0, 5, 0, 3, 0, 1, 0].filter_0());
//prints [5,3,1]

This is a standard way to extend objects and add new methods. Lots of libraries do this. However, let's look at how for in works now:

var listeners = ["a", "b", "c"];
for (o in listeners) {
    console.log(o);
}
//prints:
//  0
//  1
//  2
//  filter_0

Do you see? It suddenly thinks filter_0 is another array index. Of course, it is not really a numeric index, but for in enumerates through object fields, not just numeric indexes. So we're now enumerating through every numeric index and filter_0. But filter_0 is not a field of any particular array object, every array object has this property now.

Luckily, all objects have a hasOwnProperty method, which checks if this field really belongs to the object itself or if it is simply inherited from the prototype chain and thus belongs to all the objects of that type.

for (o in listeners) {
    if (listeners.hasOwnProperty(o)) {
       console.log(o);
    }
}
 //prints:
 //  0
 //  1
 //  2

Note, that although this code works as expected for arrays, you should never, never, use for in and for each in for arrays. Remember that for in enumerates the fields of an object, not array indexes or values.

var listeners = ["a", "b", "c"];
listeners.happy = "Happy debugging";

for (o in listeners) {
    if (listeners.hasOwnProperty(o)) {
       console.log(o);
    }
}

 //prints:
 //  0
 //  1
 //  2
 //  happy

Unsupported method: BaseConfig.getApplicationIdSuffix()

For Android Studio 3 I need to update two files to fix the error:--

1. app/build.gradle

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

2. app/gradle/wrapper/gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

Checkbox value true/false

Try this

_x000D_
_x000D_
$("#checkbox1").is(':checked', function(){_x000D_
  $("#checkbox1").prop('checked', true);_x000D_
});_x000D_
      
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false">
_x000D_
_x000D_
_x000D_

How do I check if a string is valid JSON in Python?

I would say parsing it is the only way you can really entirely tell. Exception will be raised by python's json.loads() function (almost certainly) if not the correct format. However, the the purposes of your example you can probably just check the first couple of non-whitespace characters...

I'm not familiar with the JSON that facebook sends back, but most JSON strings from web apps will start with a open square [ or curly { bracket. No images formats I know of start with those characters.

Conversely if you know what image formats might show up, you can check the start of the string for their signatures to identify images, and assume you have JSON if it's not an image.

Another simple hack to identify a graphic, rather than a text string, in the case you're looking for a graphic, is just to test for non-ASCII characters in the first couple of dozen characters of the string (assuming the JSON is ASCII).

Excel VBA - Sum up a column

Here is what you can do if you want to add a column of numbers in Excel. ( I am using Excel 2010 but should not make a difference.)

Example: Lets say you want to add the cells in Column B form B10 to B100 & want the answer to be in cell X or be Variable X ( X can be any cell or any variable you create such as Dim X as integer, etc). Here is the code:

Range("B5") = "=SUM(B10:B100)"

or

X = "=SUM(B10:B100)

There are no quotation marks inside the parentheses in "=Sum(B10:B100) but there are quotation marks inside the parentheses in Range("B5"). Also there is a space between the equals sign and the quotation to the right of it.

It will not matter if some cells are empty, it will simply see them as containing zeros!

This should do it for you!

declaring a priority_queue in c++ with a custom comparator

In case this helps anyone :

static bool myFunction(Node& p1, Node& p2) {}
priority_queue <Node, vector<Node>, function<bool(Node&, Node&)>> pq1(myFunction);

How to catch an Exception from a thread

Currently you are catching only RuntimeException, a sub class of Exception. But your application may throw other sub-classes of Exception. Catch generic Exception in addition to RuntimeException

Since many of things have been changed on Threading front, use advanced java API.

Prefer advance java.util.concurrent API for multi-threading like ExecutorService or ThreadPoolExecutor.

You can customize your ThreadPoolExecutor to handle exceptions.

Example from oracle documentation page:

Override

protected void afterExecute(Runnable r,
                            Throwable t)

Method invoked upon completion of execution of the given Runnable. This method is invoked by the thread that executed the task. If non-null, the Throwable is the uncaught RuntimeException or Error that caused execution to terminate abruptly.

Example code:

class ExtendedExecutor extends ThreadPoolExecutor {
   // ...
   protected void afterExecute(Runnable r, Throwable t) {
     super.afterExecute(r, t);
     if (t == null && r instanceof Future<?>) {
       try {
         Object result = ((Future<?>) r).get();
       } catch (CancellationException ce) {
           t = ce;
       } catch (ExecutionException ee) {
           t = ee.getCause();
       } catch (InterruptedException ie) {
           Thread.currentThread().interrupt(); // ignore/reset
       }
     }
     if (t != null)
       System.out.println(t);
   }
 }

Usage:

ExtendedExecutor service = new ExtendedExecutor();

I have added one constructor on top of above code as:

 public ExtendedExecutor() { 
       super(1,5,60,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(100));
   }

You can change this constructor to suit your requirement on number of threads.

ExtendedExecutor service = new ExtendedExecutor();
service.submit(<your Callable or Runnable implementation>);

Find multiple files and rename them in Linux

For renaming recursively I use the following commands:

find -iname \*.* | rename -v "s/ /-/g"

Convert string to variable name in JavaScript

let me make it more clear

function changeStringToVariable(variable, value){
window[variable]=value
}
changeStringToVariable("name", "john doe");
console.log(name);
//this outputs: john doe
let file="newFile";
changeStringToVariable(file, "text file");
console.log(newFile);
//this outputs: text file

What is the best (and safest) way to merge a Git branch into master?

Old thread, but I haven't found my way of doing it. It might be valuable for someone who works with rebase and wants to merge all the commits from a (feature) branch on top of master. If there is a conflict on the way, you can resolve them for every commit. You keep full control during the process and can abort any time.

Get Master and Branch up-to-date:

git checkout master
git pull --rebase origin master
git checkout <branch_name>
git pull --rebase origin <branch_name>

Merge Branch on top of Master:

git checkout <branch_name>
git rebase master

Optional: If you run into Conflicts during the Rebase:

First, resolve conflict in file. Then:

git add .
git rebase --continue

Push your rebased Branch:

git push origin <branch_name>

Now you've got two options:

  • A) Create a PR (e.g. on GitHub) and merge it there via the UI
  • B) Go back on the command line and merge the branch into master
git checkout master
git merge --no-ff <branch_name>
git push origin master

Done.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

In Python 3, the reduce has been removed: Release notes. Nevertheless you can use the functools module

import operator, functools
def product(xs):
    return functools.reduce(operator.mul, xs, 1)

On the other hand, the documentation expresses preference towards for-loop instead of reduce, hence:

def product(xs):
    result = 1
    for i in xs:
        result *= i
    return result

Python copy files to a new directory and rename if file name already exists

Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.

movdir = r"C:\Scans"
basedir = r"C:\Links"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
    for filename in files:
        # I use absolute path, case you want to move several dirs.
        old_name = os.path.join( os.path.abspath(root), filename )

        # Separate base from extension
        base, extension = os.path.splitext(filename)

        # Initial new name
        new_name = os.path.join(basedir, base, filename)

        # If folder basedir/base does not exist... You don't want to create it?
        if not os.path.exists(os.path.join(basedir, base)):
            print os.path.join(basedir,base), "not found" 
            continue    # Next filename
        elif not os.path.exists(new_name):  # folder exists, file does not
            shutil.copy(old_name, new_name)
        else:  # folder exists, file exists as well
            ii = 1
            while True:
                new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
                if not os.path.exists(new_name):
                   shutil.copy(old_name, new_name)
                   print "Copied", old_name, "as", new_name
                   break 
                ii += 1

Room persistance library. Delete all

Combining what Dick Lucas says and adding a reset autoincremental from other StackOverFlow posts, i think this can work:

fun clearAndResetAllTables(): Boolean {
    val db = db ?: return false

    // reset all auto-incrementalValues
    val query = SimpleSQLiteQuery("DELETE FROM sqlite_sequence")

    db.beginTransaction()
    return try {
        db.clearAllTables()
        db.query(query)
        db.setTransactionSuccessful()
        true
    } catch (e: Exception){
        false
    } finally {
        db.endTransaction()
    }
}

How do I set bold and italic on UILabel of iPhone/iPad?

Example Bold text:

UILabel *titleBold = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 30)];
UIFont* myBoldFont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
[titleBold setFont:myBoldFont];

Example Italic text:

UILabel *subTitleItalic = [[UILabel alloc] initWithFrame:CGRectMake(10, 35, 200, 30)];
UIFont* myItalicFont = [UIFont italicSystemFontOfSize:[UIFont systemFontSize]];
[subTitleItalic setFont:myItalicFont];

I lose my data when the container exits

the similar problem (and no way Dockerfile alone could fix it) brought me to this page.

stage 0: for all, hoping Dockerfile could fix it: until --dns and --dns-search will appear in Dockerfile support - there is no way to integrate intranet based resources into.

stage 1: after building image using Dockerfile (by the way it's a serious glitch Dockerfile must be in the current folder), having an image to deploy what's intranet based, by running docker run script. example: docker run -d \ --dns=${DNSLOCAL} \ --dns=${DNSGLOBAL} \ --dns-search=intranet \ -t pack/bsp \ --name packbsp-cont \ bash -c " \ wget -r --no-parent http://intranet/intranet-content.tar.gz \ tar -xvf intranet-content.tar.gz \ sudo -u ${USERNAME} bash --norc"

stage 2: applying docker run script in daemon mode providing local dns records to have ability to download and deploy local stuff.

important point: run script should be ending with something like /usr/bin/sudo -u ${USERNAME} bash --norc to keep container running even after the installation scripts finishes.

no, it's not possible to run container in interactive mode for the full automation matter as it will remain inside internal shall command prompt until CTRL-p CTRL-q being pressed.

no, if interacting bash will not be executed at the end of the installation script, the container will terminate immediately after finishes script execution, loosing all installation results.

stage 3: container is still running in background but it's unclear whether container has ended installation procedure or not yet. using following block to determine execution procedure finishes: while ! docker container top ${CONTNAME} | grep "00[[:space:]]\{12\}bash \--norc" - do echo "." sleep 5 done the script will proceed further only after completed installation. and this is the right moment to call: commit, providing current container id as well as destination image name (it may be the same as on the build/run procedure but appended with the local installation purposes tag. example: docker commit containerID pack/bsp:toolchained. see this link on how to get proper containerID

stage 4: container has been updated with the local installs as well as it has been committed into newly assigned image (the one having purposes tag added). it's safe now to stop container running. example: docker stop packbsp-cont

stage5: any moment the container with local installs require to run, start it with the image previously saved. example: docker run -d -t pack/bsp:toolchained

git ignore exception

!foo.dll in .gitignore, or (every time!) git add -f foo.dll

What is the purpose of the HTML "no-js" class?

The no-js class is used by the Modernizr feature detection library. When Modernizr loads, it replaces no-js with js. If JavaScript is disabled, the class remains. This allows you to write CSS which easily targets either condition.

From Modernizrs' Anotated Source (no longer maintained):

Remove "no-js" class from element, if it exists: docElement.className=docElement.className.replace(/\bno-js\b/,'') + ' js';

Here is a blog post by Paul Irish describing this approach: http://www.paulirish.com/2009/avoiding-the-fouc-v3/


I like to do this same thing, but without Modernizr. I put the following <script> in the <head> to change the class to js if JavaScript is enabled. I prefer to use .replace("no-js","js") over the regex version because its a bit less cryptic and suits my needs.

<script>
    document.documentElement.className = 
       document.documentElement.className.replace("no-js","js");
</script>

Prior to this technique, I would generally just apply js-dependant styles directly with JavaScript. For example:

$('#someSelector').hide();
$('.otherStuff').css({'color' : 'blue'});

With the no-js trick, this can Now be done with css:

.js #someSelector {display: none;}
.otherStuff { color: blue; }
.no-js .otherStuff { color: green }

This is preferable because:

  • It loads faster with no FOUC (flash of unstyled content)
  • Separation of concerns, etc...

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

How to find rows in one table that have no corresponding row in another table

select parentTable.id from parentTable
left outer join childTable on (parentTable.id = childTable.parentTableID) 
where childTable.id is null

How to Access Hive via Python?

I believe the easiest way is to use PyHive.

To install you'll need these libraries:

pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive

Please note that although you install the library as PyHive, you import the module as pyhive, all lower-case.

If you're on Linux, you may need to install SASL separately before running the above. Install the package libsasl2-dev using apt-get or yum or whatever package manager for your distribution. For Windows there are some options on GNU.org, you can download a binary installer. On a Mac SASL should be available if you've installed xcode developer tools (xcode-select --install in Terminal)

After installation, you can connect to Hive like this:

from pyhive import hive
conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU")

Now that you have the hive connection, you have options how to use it. You can just straight-up query:

cursor = conn.cursor()
cursor.execute("SELECT cool_stuff FROM hive_table")
for result in cursor.fetchall():
  use_result(result)

...or to use the connection to make a Pandas dataframe:

import pandas as pd
df = pd.read_sql("SELECT cool_stuff FROM hive_table", conn)

How to split a string into an array of characters in Python?

You can also do it in this very simple way without list():

>>> [c for c in "foobar"]
['f', 'o', 'o', 'b', 'a', 'r']

nginx error connect to php5-fpm.sock failed (13: Permission denied)

If you have declarations

pid = /run/php-fpm.pid

and

listen = /run/php-fpm.pid

in different configuration files, then root will owner of this file.

How to get param from url in angular 4?

import {Router, ActivatedRoute, Params} from '@angular/router';

constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.paramMap
    .subscribe( params => {
    let id = +params.get('id');
    console.log('id' + id);
    console.log(params);


id12
ParamsAsMap {params: {…}}
keys: Array(1)
0: "id"
length: 1
__proto__: Array(0)
params:
id: "12"
__proto__: Object
__proto__: Object
        }
        )

      }

Adding days to a date in Java

Calendar cal = Calendar.getInstance();    
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 2012);
cal.add(Calendar.DAY_OF_MONTH, 5);

You can also substract days like Calendar.add(Calendar.DAY_OF_MONTH, -5);

How to comment in Vim's config files: ".vimrc"?

A double quote to the left of the text you want to comment.

Example: " this is how a comment looks like in ~/.vimrc

How to run shell script on host from docker container?

My laziness led me to find the easiest solution that wasn't published as an answer here.

It is based on the great article by luc juggery.

All you need to do in order to gain a full shell to your linux host from within your docker container is:

docker run --privileged --pid=host -it alpine:3.8 \
nsenter -t 1 -m -u -n -i sh

Explanation:

--privileged : grants additional permissions to the container, it allows the container to gain access to the devices of the host (/dev)

--pid=host : allows the containers to use the processes tree of the Docker host (the VM in which the Docker daemon is running) nsenter utility: allows to run a process in existing namespaces (the building blocks that provide isolation to containers)

nsenter (-t 1 -m -u -n -i sh) allows to run the process sh in the same isolation context as the process with PID 1. The whole command will then provide an interactive sh shell in the VM

This setup has major security implications and should be used with cautions (if any).

How to convert char to int?

The most secure way to accomplish this is using Int32.TryParse method. See here: http://dotnetperls.com/int-tryparse

Use PHP composer to clone git repo

At the time of writing in 2013, this was one way to do it. Composer has added support for better ways: See @igorw 's answer

DO YOU HAVE A REPOSITORY?

Git, Mercurial and SVN is supported by Composer.

DO YOU HAVE WRITE ACCESS TO THE REPOSITORY?

Yes?

DOES THE REPOSITORY HAVE A composer.json FILE

If you have a repository you can write to: Add a composer.json file, or fix the existing one, and DON'T use the solution below.

Go to @igorw 's answer

ONLY USE THIS IF YOU DON'T HAVE A REPOSITORY
OR IF THE REPOSITORY DOES NOT HAVE A composer.json AND YOU CANNOT ADD IT

This will override everything that Composer may be able to read from the original repository's composer.json, including the dependencies of the package and the autoloading.

Using the package type will transfer the burden of correctly defining everything onto you. The easier way is to have a composer.json file in the repository, and just use it.

This solution really only is for the rare cases where you have an abandoned ZIP download that you cannot alter, or a repository you can only read, but it isn't maintained anymore.

"repositories": [
    {
        "type":"package",
        "package": {
          "name": "l3pp4rd/doctrine-extensions",
          "version":"master",
          "source": {
              "url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
              "type": "git",
              "reference":"master"
            }
        }
    }
],
"require": {
    "l3pp4rd/doctrine-extensions": "master"
}

How to print colored text to the terminal?

There is also the Python termcolor module. Usage is pretty simple:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

Or in Python 3:

print(colored('hello', 'red'), colored('world', 'green'))

It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...

Has anyone ever got a remote JMX JConsole to work?

Adding -Djava.rmi.server.hostname='<host ip>' resolved this problem for me.

Get the position of a spinner in Android

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = findViewById(R.id.button);
        spinner = findViewById(R.id.sp_item);
        setInfo();
        spinnerAdapter = new SpinnerAdapter(this, arrayList);
        spinner.setAdapter(spinnerAdapter);



        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //first,  we have to retrieve the item position as a string
                // then, we can change string value into integer
                String item_position = String.valueOf(position);

                int positonInt = Integer.valueOf(item_position);

                Toast.makeText(MainActivity.this, "value is "+ positonInt, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });







note: the position of items is counted from 0.

How can I make content appear beneath a fixed DIV element?

Here's a responsive way of doing it with jQuery.

 $(window).resize(function () {
      $('#YourRelativeDiv').css('margin-top', $('#YourFixedDiv').height());
 });

Spark - SELECT WHERE or filtering?

According to spark documentation "where() is an alias for filter()"

filter(condition) Filters rows using the given condition. where() is an alias for filter().

Parameters: condition – a Column of types.BooleanType or a string of SQL expression.

>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]

>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]

How to filter a data frame

You are missing a comma in your statement.

Try this:

data[data[, "Var1"]>10, ]

Or:

data[data$Var1>10, ]

Or:

subset(data, Var1>10)

As an example, try it on the built-in dataset, mtcars

data(mtcars)

mtcars[mtcars[, "mpg"]>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2


mtcars[mtcars$mpg>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

subset(mtcars, mpg>25)

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

Choosing line type and color in Gnuplot 4.0

I've ran into this topic, because i was struggling with dashed lines too (gnuplot 4.6 patchlevel 0)

If you use:

set termoption dashed

Your posted code will work accordingly.

Related question:
However, if I want to export a png with: set terminal png, this isn't working anymore. Anyone got a clue why?

Turns out, out, gnuplots png export library doesnt support this.
Possbile solutions:

  • one can simply export to ps, then convert it with pstopng
  • according to @christoph, if you use pngcairo as your terminal (set terminal pngcairo) it will work

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

How to subscribe to an event on a service in Angular2?

Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945

Also, the Angular docs now have a cookbook example that uses a Subject.


Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.

Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.

nav.service.ts

import {EventEmitter} from 'angular2/core';
export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emitNavChangeEvent(number) {
    this.navchange.emit(number);
  }
  getNavChangeEmitter() {
    return this.navchange;
  }
}

components.ts

import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number = 0;
  subscription: any;
  constructor(private navService:NavService) {}
  ngOnInit() {
    this.subscription = this.navService.getNavChangeEmitter()
      .subscribe(item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item = 1;
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emitNavChangeEvent(item);
  }
}

Plunker

Loop structure inside gnuplot?

I wanted to use wildcards to plot multiple files often placed in different directories, while working from any directory. The solution i found was to create the following function in ~/.bashrc

plo () {
local arg="w l"
local str="set term wxt size 900,500 title 'wild plotting'
set format y '%g'
set logs
plot"
while [ $# -gt 0 ]
        do str="$str '$1' $arg,"
        shift
done
echo "$str" | gnuplot -persist
}

and use it e.g. like plo *.dat ../../dir2/*.out, to plot all .dat files in the current directory and all .out files in a directory that happens to be a level up and is called dir2.

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

Understanding slice notation

Index:
      ------------>
  0   1   2   3   4
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
  0  -4  -3  -2  -1
      <------------

Slice:
    <---------------|
|--------------->
:   1   2   3   4   :
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
:  -4  -3  -2  -1   :
|--------------->
    <---------------|

I hope this will help you to model the list in Python.

Reference: http://wiki.python.org/moin/MovingToPythonFromOtherLanguages

How do I declare and use variables in PL/SQL like I do in T-SQL?

Revised Answer

If you're not calling this code from another program, an option is to skip PL/SQL and do it strictly in SQL using bind variables:

var myname varchar2(20);

exec :myname := 'Tom';

SELECT *
FROM   Customers
WHERE  Name = :myname;

In many tools (such as Toad and SQL Developer), omitting the var and exec statements will cause the program to prompt you for the value.


Original Answer

A big difference between T-SQL and PL/SQL is that Oracle doesn't let you implicitly return the result of a query. The result always has to be explicitly returned in some fashion. The simplest way is to use DBMS_OUTPUT (roughly equivalent to print) to output the variable:

DECLARE
   myname varchar2(20);
BEGIN
     myname := 'Tom';

     dbms_output.print_line(myname);
END;

This isn't terribly helpful if you're trying to return a result set, however. In that case, you'll either want to return a collection or a refcursor. However, using either of those solutions would require wrapping your code in a function or procedure and running the function/procedure from something that's capable of consuming the results. A function that worked in this way might look something like this:

CREATE FUNCTION my_function (myname in varchar2)
     my_refcursor out sys_refcursor
BEGIN
     open my_refcursor for
     SELECT *
     FROM   Customers
     WHERE  Name = myname;

     return my_refcursor;
END my_function;

How to convert a number to string and vice versa in C++

Update for C++11

As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string> (as per paragraph 21.5).

string to numeric

float              stof(const string& str, size_t *idx = 0);
double             stod(const string& str, size_t *idx = 0);
long double        stold(const string& str, size_t *idx = 0);
int                stoi(const string& str, size_t *idx = 0, int base = 10);
long               stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long      stoul(const string& str, size_t *idx = 0, int base = 10);
long long          stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);

Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (std::invalid_argument or std::out_of_range).

If conversion succeeded and idx is not 0, idx will contain the index of the first character that was not used for decoding. This could be an index behind the last character.

Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10 until z=35). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.

Finally, for each function there is also an overload that accepts a std::wstring as it's first parameter.

numeric to string

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.

As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.

There are also similar functions defined that are named to_wstring, these will return a std::wstring.

Visual Studio 2017 does not have Business Intelligence Integration Services/Projects

VS2017 supports ssis or ssrs projects if you install SSDT for VS2017 here.

Click on the newly downloaded file and check SSIS or SSRS components that you required, as show in diagram :-

enter image description here

Once you have installed this, try opening ssis / ssrs project. I managed to open ssis developed on vs2010.

You should see these component installed. (reboot if you don't see them).

enter image description here

Try open your project again. If you get 'incompatible project' - right click on your project, select "reload project" (not reopen the solution)

SQL Server: Database stuck in "Restoring" state

Ran into a similar issue while restoring the database using SQL server management studio and it got stuck into restoring mode. After several hours of issue tracking, the following query worked for me. The following query restores the database from an existing backup to a previous state. I believe, the catch is the to have the .mdf and .log file in the same directory.

RESTORE DATABASE aqua_lc_availability
FROM DISK = 'path to .bak file'
WITH RECOVERY

CSS Border Not Working

Do this:

border: solid #000;
border-width: 0 1px;

Live demo: http://jsfiddle.net/aFzKy/

How should I load files into my Java application?

I haven't had a problem just using Unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).

The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)

Single line sftp from terminal

sftp supports batch files.

From the man page:

-b batchfile

Batch mode reads a series of commands from an input batchfile instead of stdin.  
Since it lacks user interaction it should be used in conjunction with non-interactive
authentication.  A batchfile of `-' may be used to indicate standard input.  sftp 
will abort if any of the following commands fail: get, put, rename, ln, rm, mkdir, 
chdir, ls, lchdir, chmod, chown, chgrp, lpwd, df, symlink, and lmkdir.  Termination 
on error can be suppressed on a command by command basis by prefixing the command 
with a `-' character (for example, -rm /tmp/blah*).

Setting a width and height on an A tag

Below working for me

display: block;
width: 100%;

How can I check if a directory exists?

You might use stat() and pass it the address of a struct stat, then check its member st_mode for having S_IFDIR set.

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

...

char d[] = "mydir";

struct stat s = {0};

if (!stat(d, &s))
  printf("'%s' is %sa directory.\n", d, (s.st_mode & S_IFDIR)  : "" ? "not ");
  // (s.st_mode & S_IFDIR) can be replaced with S_ISDIR(s.st_mode)
else
  perror("stat()");

Why use Ruby's attr_accessor, attr_reader and attr_writer?

Not all attributes of an object are meant to be directly set from outside the class. Having writers for all your instance variables is generally a sign of weak encapsulation and a warning that you're introducing too much coupling between your classes.

As a practical example: I wrote a design program where you put items inside containers. The item had attr_reader :container, but it didn't make sense to offer a writer, since the only time the item's container should change is when it's placed in a new one, which also requires positioning information.

Convert Decimal to Varchar

Hope this will help you

Cast(columnName as Numeric(10,2)) 
        or

Cast(@s as decimal(10,2))

I am not getting why you want to cast to varchar?.If you cast to varchar again convert back to decimail for two decimal points

Setting width to wrap_content for TextView through code

I am posting android Java base multi line edittext.

EditText editText = findViewById(R.id.editText);/* edittext access */

ViewGroup.LayoutParams params  =  editText.getLayoutParams(); 
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
editText.setLayoutParams(params); /* Gives as much height for multi line*/

editText.setSingleLine(false); /* Makes it Multi line */

Copy all the lines to clipboard

I tried a few of the commands that people have mentioned above. None worked. Then I got hold of the simplest of them all.

Step 1: vi <filename>
Step 2: Right click on the title bar of the Putty window
Step 3: Select "Clear scrollback" (to avoid copying the rest of your SSH session)
Step 4: Right click again and select "Copy all to clipboard".

RegEx to extract all matches from string using RegExp.exec

Use this...

var all_matches = your_string.match(re);
console.log(all_matches)

It will return an array of all matches...That would work just fine.... But remember it won't take groups in account..It will just return the full matches...

Disabling Chrome cache for website development

There is a chrome extension available in the chrome web store named Clear Cache.

I use it every day and its a very useful tool I think. You can use it as a reload button and can clear the cache and if you like also cookies, locale storage, form data etc. Also you can define on which domain this happens. So can clear all this shit with only the reload button which you anyway have to press - on your chosen domains.

Very very nice!

You also can define a Keyboard Shortcut for this in the options!

Also another way is to start your chrome window in incognito-mode. Here the cache also should be completely disabled.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

JS map return object

map rockets and add 10 to its launches:

_x000D_
_x000D_
var rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
rockets.map((itm) => {_x000D_
    itm.launches += 10_x000D_
    return itm_x000D_
})_x000D_
console.log(rockets)
_x000D_
_x000D_
_x000D_

If you don't want to modify rockets you can do:

var plusTen = []
rockets.forEach((itm) => {
    plusTen.push({'country': itm.country, 'launches': itm.launches + 10})
})

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

How to run ~/.bash_profile in mac terminal

No need to start, it would automatically executed while you startup your mac terminal / bash. Whenever you do a change, you may need to restart the terminal.

~ is the default path for .bash_profile

Recyclerview inside ScrollView not scrolling smoothly

XML code:

<android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clipToPadding="false" />

        </android.support.v4.widget.NestedScrollView>

in java code :

  recycleView = (RecyclerView) findViewById(R.id.recycleView);
     recycleView.setNestedScrollingEnabled(false);

Angular 4 setting selected option in Dropdown

Lets see an example with Select control
binded to: $scope.cboPais,
source: $scope.geoPaises

HTML

<select 
  ng-model="cboPais"  
  ng-options="item.strPais for item in geoPaises"
  ></select>

JavaScript

$http.get(strUrl2).success(function (response) {
  if (response.length > 0) {
    $scope.geoPaises = response; //Data source
    nIndex = indexOfUnsortedArray(response, 'iPais', default_values.iPais); //array index of default value, using a custom function to search
    if (nIndex >= 0) {
      $scope.cboPais = response[nIndex]; //if index of array was found
    } else {
      $scope.cboPais = response[0]; //select the first element of array
    }
    $scope.geo_getDepartamentos();
  }
}

How to make html table vertically scrollable

Here's my solution (in Spring with Thymeleaf and jQuery):

html:

<!DOCTYPE html>
<html
    xmlns:th="http://www.thymeleaf.org"
    xmlns:tiles="http://www.thymeleaf.org">
    <body>
        <div id="objects" th:fragment="ObjectList">
            <br/>
            <div id='cap'>
                <span>Objects</span>
            </div>
            <div id="hdr">
                <div>
                    <div class="Cell">Name</div>
                        <div class="Cell">Type</div>
                </div>
            </div>
            <div id="bdy">
                <div th:each="object : ${objectlist}">
                        <div class="Cell" th:text="${object.name}">name</div>
                        <div class="Cell" th:text="${object.type}">type</div>
                </div>
            </div>
        </div>
    </body>
</html> 

css:

@CHARSET "UTF-8";
#cap span {
    display: table-caption;
    border:2px solid;
    font-size: 200%;
    padding: 3px;
}
#hdr {
    display:block;
    padding:0px;
    margin-left:0;
    border:2px solid;
}
#bdy {
    display:block;
    padding:0px;
    margin-left:0;
    border:2px solid;
}
#objects #bdy {
    height:300px;
    overflow-y: auto;
}
#hdr div div{
    margin-left:-3px;
    margin-right:-3px;
    text-align: right;
}
#hdr div:first-child {
    text-align: left;
}
#bdy div div {
    margin-left:-3px;
    margin-right:-3px;
    text-align: right;
}
#bdy div div:first-child {
    text-align: left;
}
.Cell
{
    display: table-cell;
    border: solid;
    border-width: thin;
    padding-left: 5px;
    padding-right: 5px;
}

javascript:

$(document).ready(function(){
    var divs = ['#objects'];
    divs.forEach(function(div)
    {
        if ($(div).length > 0)
        {
            var widths = [];
            var totalWidth = 0;
            $(div+' #hdr div div').each(function() {
                widths.push($(this).width())
            });
            $(div+' #bdy div div').each(function() {
                var col = $(this).index();
                if ( $(this).width() > widths[col] )
                {
                    widths[col] = $(this).width();
                }
            });
            $(div+' #hdr div div').each(function() {
                var newWidth = widths[$(this).index()]+5;
                $(this).css("width", newWidth);
                totalWidth += $(this).outerWidth();
            });
            $(div+' #bdy div div').each(function() {
                $(this).css("width", widths[$(this).index()]+5);
            });
            $(div+' #hdr').css("width", totalWidth);
            $(div+' #bdy').css("width", totalWidth+($(div+' #bdy').css('overflow-y')=='auto'?15:0));
        }
    })
});

How can I know if a branch has been already merged into master?

Here are my techniques when I need to figure out if a branch has been merged, even if it may have been rebased to be up to date with our main branch, which is a common scenario for feature branches.

Neither of these approaches are fool proof, but I've found them useful many times.

1 Show log for all branches

Using a visual tool like gitk or TortoiseGit, or simply git log with --all, go through the history to see all the merges to the main branch. You should be able to spot if this particular feature branch has been merged or not.

2 Always remove remote branch when merging in a feature branch

If you have a good habit of always removing both the local and the remote branch when you merge in a feature branch, then you can simply update and prune remotes on your other computer and the feature branches will disappear.

To help remember doing this, I'm already using git flow extensions (AVH edition) to create and merge my feature branches locally, so I added the following git flow hook to ask me if I also want to auto-remove the remote branch.

Example create/finish feature branch

554 Andreas:MyRepo(develop)$ git flow start tmp
Switched to a new branch 'feature/tmp'

Summary of actions:
- A new branch 'feature/tmp' was created, based on 'develop'
- You are now on branch 'feature/tmp'

Now, start committing on your feature. When done, use:

     git flow feature finish tmp

555 Andreas:MyRepo(feature/tmp)$ git flow finish
Switched to branch 'develop'
Your branch is up-to-date with 'if/develop'.
Already up-to-date.

[post-flow-feature-finish] Delete remote branch? (Y/n)
Deleting remote branch: origin/feature/tmp.

Deleted branch feature/tmp (was 02a3356).

Summary of actions:
- The feature branch 'feature/tmp' was merged into 'develop'
- Feature branch 'feature/tmp' has been locally deleted
- You are now on branch 'develop'

556 Andreas:ScDesktop (develop)$

.git/hooks/post-flow-feature-finish

NAME=$1
ORIGIN=$2
BRANCH=$3

# Delete remote branch
# Allows us to read user input below, assigns stdin to keyboard
exec < /dev/tty

while true; do
  read -p "[post-flow-feature-finish] Delete remote branch? (Y/n) " yn
  if [ "$yn" = "" ]; then
    yn='Y'    
  fi
  case $yn in
      [Yy] ) 
        echo -e "\e[31mDeleting remote branch: $2/$3.\e[0m" || exit "$?"
        git push $2 :$3; 
        break;;
      [Nn] ) 
        echo -e "\e[32mKeeping remote branch.\e[0m" || exit "$?"
        break;;
      * ) echo "Please answer y or n for yes or no.";;
  esac
done

# Stop reading user input (close STDIN)
exec <&-
exit 0

3 Search by commit message

If you do not always remove the remote branch, you can still search for similar commits to determine if the branch has been merged or not. The pitfall here is if the remote branch has been rebased to the unrecognizable, such as squashing commits or changing commit messages.

  • Fetch and prune all remotes
  • Find message of last commit on feature branch
  • See if a commit with same message can be found on master branch

Example commands on master branch:

gru                   
gls origin/feature/foo
glf "my message"

In my bash .profile config

alias gru='git remote update -p'
alias glf=findCommitByMessage

findCommitByMessage() {
    git log -i --grep="$1"
}

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

You can change the owner of your database file and it's folder to django:

chown django:django /home/django/mysite
chown django:django /home/django/mysite/my_db.sqlite3

This work for DigitalOcean's 1-Click Django Droplet

Difference between "process.stdout.write" and "console.log" in node.js?

Another important difference in this context would with process.stdout.clearLine() and process.stdout.cursorTo(0).

This would be useful if you want to show percentage of download or processing in the only one line. If you use clearLine(), cursorTo() with console.log() it doesn't work because it also append \n to the text. Just try out this example:

var waitInterval = 500;
var totalTime = 5000;
var currentInterval = 0;

function showPercentage(percentage){
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
    console.log(`Processing ${percentage}%...` ); //replace this line with process.stdout.write(`Processing ${percentage}%...`);
}

var interval = setInterval(function(){
 currentInterval += waitInterval;
 showPercentage((currentInterval/totalTime) * 100);
}, waitInterval);

setTimeout(function(){
 clearInterval(interval); 
}, totalTime);

What does from __future__ import absolute_import actually do?

The changelog is sloppily worded. from __future__ import absolute_import does not care about whether something is part of the standard library, and import string will not always give you the standard-library module with absolute imports on.

from __future__ import absolute_import means that if you import string, Python will always look for a top-level string module, rather than current_package.string. However, it does not affect the logic Python uses to decide what file is the string module. When you do

python pkg/script.py

pkg/script.py doesn't look like part of a package to Python. Following the normal procedures, the pkg directory is added to the path, and all .py files in the pkg directory look like top-level modules. import string finds pkg/string.py not because it's doing a relative import, but because pkg/string.py appears to be the top-level module string. The fact that this isn't the standard-library string module doesn't come up.

To run the file as part of the pkg package, you could do

python -m pkg.script

In this case, the pkg directory will not be added to the path. However, the current directory will be added to the path.

You can also add some boilerplate to pkg/script.py to make Python treat it as part of the pkg package even when run as a file:

if __name__ == '__main__' and __package__ is None:
    __package__ = 'pkg'

However, this won't affect sys.path. You'll need some additional handling to remove the pkg directory from the path, and if pkg's parent directory isn't on the path, you'll need to stick that on the path too.

How to sum up an array of integers in C#

Yes there is. With .NET 3.5:

int sum = arr.Sum();
Console.WriteLine(sum);

If you're not using .NET 3.5 you could do this:

int sum = 0;
Array.ForEach(arr, delegate(int i) { sum += i; });
Console.WriteLine(sum);

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

XML Serialize generic list of serializable objects

See Introducing XML Serialization:

Items That Can Be Serialized

The following items can be serialized using the XmlSerializer class:

  • Public read/write properties and fields of public classes
  • Classes that implement ICollection or IEnumerable
  • XmlElement objects
  • XmlNode objects
  • DataSet objects

In particular, ISerializable or the [Serializable] attribute does not matter.


Now that you've told us what your problem is ("it doesn't work" is not a problem statement), you can get answers to your actual problem, instead of guesses.

When you serialize a collection of a type, but will actually be serializing a collection of instances of derived types, you need to let the serializer know which types you will actually be serializing. This is also true for collections of object.

You need to use the XmlSerializer(Type,Type[]) constructor to give the list of possible types.

Java - Getting Data from MySQL database

This should work, I think...

ResultSet results = st.executeQuery(sql);

if(results.next()) { //there is a row
 int id = results.getInt(1); //ID if its 1st column
 String str1 = results.getString(2);
 ...
}

Get only specific attributes with from Laravel Collection

This avoid to load unised attributes, directly from db:

DB::table('roles')->pluck('title', 'name');

References: https://laravel.com/docs/5.8/queries#retrieving-results (search for pluck)

Maybe next you can apply toArray() if you need such format

Pointers in C: when to use the ampersand and the asterisk?

Put simply

  • & means the address-of, you will see that in placeholders for functions to modify the parameter variable as in C, parameter variables are passed by value, using the ampersand means to pass by reference.
  • * means the dereference of a pointer variable, meaning to get the value of that pointer variable.
int foo(int *x){
   *x++;
}

int main(int argc, char **argv){
   int y = 5;
   foo(&y);  // Now y is incremented and in scope here
   printf("value of y = %d\n", y); // output is 6
   /* ... */
}

The above example illustrates how to call a function foo by using pass-by-reference, compare with this

int foo(int x){
   x++;
}

int main(int argc, char **argv){
   int y = 5;
   foo(y);  // Now y is still 5
   printf("value of y = %d\n", y); // output is 5
   /* ... */
}

Here's an illustration of using a dereference

int main(int argc, char **argv){
   int y = 5;
   int *p = NULL;
   p = &y;
   printf("value of *p = %d\n", *p); // output is 5
}

The above illustrates how we got the address-of y and assigned it to the pointer variable p. Then we dereference p by attaching the * to the front of it to obtain the value of p, i.e. *p.

How to concatenate two strings in SQL Server 2005

Try this:

DECLARE @COMBINED_STRINGS AS VARCHAR(50); -- Allocate just enough length for the two strings.

SET @COMBINED_STRINGS = 'rupesh''s' + 'malviya';
SELECT @COMBINED_STRINGS; -- Print your combined strings.

Or you can put your strings into variables. Such that:

DECLARE @COMBINED_STRINGS AS VARCHAR(50),
        @STRING1 AS VARCHAR(20),
        @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;

SELECT @COMBINED_STRINGS; 

Output:

rupesh'smalviya

Just add a space in your string as a separator.

The 'json' native gem requires installed build tools

1) Download Ruby 1.9.3

2) cmd check command: ruby -v 'return result ruby 1.9.3 then success full install ruby

3) Download DevKit file from http://rubyinstaller.org/downloads (DevKit-tdm-32-4.5.2-20110712-1620-sfx.exe)

4) Extract DevKit to path C:\Ruby193\DevKit

5) cd C:\Ruby193\DevKit

6) ruby dk.rb init

7) ruby dk.rb review

8) ruby dk.rb install

9) cmd : gem install rails -v3.1.1 'few time installing full process'

10) cmd : rails -v 'return result rails 3.1.1 then its success fully install'

enjoy Ruby on Rails...

How to create a list of objects?

You can create a list of objects in one line using a list comprehension.

class MyClass(object): pass

objs = [MyClass() for i in range(10)]

print(objs)

How to encrypt/decrypt data in php?

     function my_simple_crypt( $string, $action = 'e' ) {
        // you may change these values to your own
        $secret_key = 'my_simple_secret_key';
        $secret_iv = 'my_simple_secret_iv';

        $output = false;
        $encrypt_method = "AES-256-CBC";
        $key = hash( 'sha256', $secret_key );
        $iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );

        if( $action == 'e' ) {
            $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
        }
        else if( $action == 'd' ){
            $output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
        }

        return $output;
    }

SVN "Already Locked Error"

I had the same problem. This problem is easily solved if you issue the Cleanup command from AnkhSVN.

Truncate with condition

As a response to your question: "i want to reset all the data and keep last 30 days inside the table."

you can create an event. Check https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html

For example:

CREATE EVENT DeleteExpiredLog
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM log WHERE date < DATE_SUB(NOW(), INTERVAL 30 DAY);

Will run a daily cleanup in your table, keeping the last 30 days data available

Loop through the rows of a particular DataTable

For Each row As DataRow In dtDataTable.Rows
    strDetail = row.Item("Detail")
Next row

There's also a shorthand:

For Each row As DataRow In dtDataTable.Rows
    strDetail = row("Detail")
Next row

Note that Microsoft's style guidelines for .Net now specifically recommend against using hungarian type prefixes for variables. Instead of "strDetail", for example, you should just use "Detail".

All possible array initialization syntaxes

Enumerable.Repeat(String.Empty, count).ToArray()

Will create array of empty strings repeated 'count' times. In case you want to initialize array with same yet special default element value. Careful with reference types, all elements will refer same object.

How to loop through a checkboxlist and to find what's checked and not checked?

This will give a list of selected

List<ListItem> items =  checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).ToList();

This will give a list of the selected boxes' values (change Value for Text if that is wanted):

var values =  checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).Select(n => n.Value ).ToList()

Using unset vs. setting a variable to empty

As has been said, using unset is different with arrays as well

$ foo=(4 5 6)

$ foo[2]=

$ echo ${#foo[*]}
3

$ unset foo[2]

$ echo ${#foo[*]}
2

Check if Internet Connection Exists with jQuery?

i have a solution who work here to check if internet connection exist :

$.ajax({
    url: "http://www.google.com",
    context: document.body,
    error: function(jqXHR, exception) {
        alert('Offline')
    },
    success: function() {
        alert('Online')
    }
})

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

The .Trim() function will do all the work for you!

I was trying the code above, but after the "trim" function, and I noticed it's all "clean" even before it reaches the replace code!

String input:       "This is an example string.\r\n\r\n"
Trim method result: "This is an example string."

Source: http://www.dotnetperls.com/trim

What is more efficient? Using pow to square or just multiply it with itself?

I have been busy with a similar problem, and I'm quite puzzled by the results. I was calculating x?³/² for Newtonian gravitation in an n-bodies situation (acceleration undergone from another body of mass M situated at a distance vector d) : a = M G d*(d²)?³/² (where d² is the dot (scalar) product of d by itself) , and I thought calculating M*G*pow(d2, -1.5) would be simpler than M*G/d2/sqrt(d2)

The trick is that it is true for small systems, but as systems grow in size, M*G/d2/sqrt(d2) becomes more efficient and I don't understand why the size of the system impacts this result, because repeating the operation on different data does not. It is as if there were possible optimizations as the system grow, but which are not possible with pow

enter image description here

How to simulate target="_blank" in JavaScript

You can extract the href from the a tag:

window.open(document.getElementById('redirect').href);

Checking if a character is a special character in Java

What I would do:

char c;
int cint;
for(int n = 0; n < str.length(); n ++;)
{
    c = str.charAt(n);
    cint = (int)c;
    if(cint <48 || (cint > 57 && cint < 65) || (cint > 90 && cint < 97) || cint > 122)
    {
        specialCharacterCount++
    }
}

That is a simple way to do things, without having to import any special classes. Stick it in a method, or put it straight into the main code.

ASCII chart: http://www.gophoto.it/view.php?i=http://i.msdn.microsoft.com/dynimg/IC102418.gif#.UHsqxFEmG08

Iterating through a golang map

You could just write it out in multiline like this,

$ cat dict.go
package main

import "fmt"

func main() {
        items := map[string]interface{}{
                "foo": map[string]int{
                        "strength": 10,
                        "age": 2000,
                },
                "bar": map[string]int{
                        "strength": 20,
                        "age": 1000,
                },
        }
        for key, value := range items {
                fmt.Println("[", key, "] has items:")
                for k,v := range value.(map[string]int) {
                        fmt.Println("\t-->", k, ":", v)
                }

        }
}

And the output:

$ go run dict.go
[ foo ] has items:
        --> strength : 10
        --> age : 2000
[ bar ] has items:
        --> strength : 20
        --> age : 1000

alert a variable value

var input_val=document.getElementById('my_variable');for (i=0; i<input_val.length; i++) {
xx = input_val[i];``
if (xx.name == "ans") {   
    new = xx.value;
    alert(new);    }}

python ignore certificate validation urllib2

In the meantime urllib2 seems to verify server certificates by default. The warning, that was shown in the past disappeared for 2.7.9 and I currently ran into this problem in a test environment with a self signed certificate (and Python 2.7.9).

My evil workaround (don't do this in production!):

import urllib2
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

urllib2.urlopen("https://your-test-server.local", context=ctx)

According to docs calling SSLContext constructor directly should work, too. I haven't tried that.

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

What is the printf format specifier for bool?

In the tradition of itoa():

#define btoa(x) ((x)?"true":"false")

bool x = true;
printf("%s\n", btoa(x));

How to insert a string which contains an "&"

The correct syntax is

set def off;
insert into tablename values( 'J&J');

How to generate the whole database script in MySQL Workbench?

there is data export option in MySQL workbech

enter image description here

LinkButton Send Value to Code Behind OnClick

Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.

<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere" 
          style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>

<asp:Label id="Label1" runat="server"/>

Then it will be available when in your handler:

protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}

More info on MSDN

Clear android application user data

If you want to do manually then You also can clear your user data by clicking “Clear Data” button in Settings–>Applications–>Manage Aplications–> YOUR APPLICATION

or Is there any other way to do that?

Then Download code here

enter image description here

Simplest way to do grouped barplot

with ggplot2:

library(ggplot2)
Animals <- read.table(
  header=TRUE, text='Category        Reason Species
1   Decline       Genuine      24
2  Improved       Genuine      16
3  Improved Misclassified      85
4   Decline Misclassified      41
5   Decline     Taxonomic       2
6  Improved     Taxonomic       7
7   Decline       Unclear      41
8  Improved       Unclear     117')

ggplot(Animals, aes(factor(Reason), Species, fill = Category)) + 
  geom_bar(stat="identity", position = "dodge") + 
  scale_fill_brewer(palette = "Set1")

Bar Chart

Simple way to sort strings in the (case sensitive) alphabetical order

I recently answered a similar question here. Applying the same approach to your problem would yield following solution:

list.sort(
  p2Ord(stringOrd, stringOrd).comap(new F<String, P2<String, String>>() {
    public P2<String, String> f(String s) {
      return p(s.toLowerCase(), s);
    }
  })
);

How to go to a URL using jQuery?

window.location is just what you need. Other thing you can do is to create anchor element and simulate click on it

$("<a href='your url'></a>").click(); 

Property 'json' does not exist on type 'Object'

For future visitors: In the new HttpClient (Angular 4.3+), the response object is JSON by default, so you don't need to do response.json().data anymore. Just use response directly.

Example (modified from the official documentation):

import { HttpClient } from '@angular/common/http';

@Component(...)
export class YourComponent implements OnInit {

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('https://api.github.com/users')
        .subscribe(response => console.log(response));
  }
}

Don't forget to import it and include the module under imports in your project's app.module.ts:

...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module after BrowserModule.
    HttpClientModule,
    ...
  ],
  ...

How to enable mod_rewrite for Apache 2.2

There's obviously more than one way to do it, but I would suggest using the more standard:

ErrorDocument 404 /index.php?page=404

'this' is undefined in JavaScript class methods

I just wanted to point out that sometimes this error happens because a function has been used as a high order function (passed as an argument) and then the scope of this got lost. In such cases, I would recommend passing such function bound to this. E.g.

this.myFunction.bind(this);

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

How to start a background process in Python?

You probably want to start investigating the os module for forking different threads (by opening an interactive session and issuing help(os)). The relevant functions are fork and any of the exec ones. To give you an idea on how to start, put something like this in a function that performs the fork (the function needs to take a list or tuple 'args' as an argument that contains the program's name and its parameters; you may also want to define stdin, out and err for the new thread):

try:
    pid = os.fork()
except OSError, e:
    ## some debug output
    sys.exit(1)
if pid == 0:
    ## eventually use os.putenv(..) to set environment variables
    ## os.execv strips of args[0] for the arguments
    os.execv(args[0], args)

Setting up enviromental variables in Windows 10 to use java and javac

if you have any version problems (javac -version=15.0.1, java -version=1.8.0)
windows search : edit environment variables for your account
then delete these in your windows Environment variable: system variable: Path
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
C:\Program Files\Common Files\Oracle\Java\javapath

then if you're using java 15
environment variable: system variable : Path
add path C:\Program Files\Java\jdk-15.0.1\bin
is enough

if you're using java 8

  • create JAVA_HOME
  • environment variable: system variable : JAVA_HOME
    JAVA_HOME = C:\Program Files\Java\jdk1.8.0_271
  • environment variable: system variable : Path
    add path = %JAVA_HOME%\bin
  • Download file through an ajax call php

    @joe : Many thanks, this was a good heads up!

    I had a slightly harder problem: 1. sending an AJAX request with POST data, for the server to produce a ZIP file 2. getting a response back 3. download the ZIP file

    So that's how I did it (using JQuery to handle the AJAX request):

    1. Initial post request:

      var parameters = {
           pid     : "mypid",
         "files[]": ["file1.jpg","file2.jpg","file3.jpg"]
      }

      var options = { url: "request/url",//replace with your request url type: "POST",//replace with your request type data: parameters,//see above context: document.body,//replace with your contex success: function(data){ if (data) { if (data.path) { //Create an hidden iframe, with the 'src' attribute set to the created ZIP file. var dlif = $('<iframe/>',{'src':data.path}).hide(); //Append the iFrame to the context this.append(dlif); } else if (data.error) { alert(data.error); } else { alert('Something went wrong'); } } } }; $.ajax(options);

    The "request/url" handles the zip creation (off topic, so I wont post the full code) and returns the following JSON object. Something like:

     //Code to create the zip file
     //......
     //Id of the file
     $zipid = "myzipfile.zip"
     //Download Link - it can be prettier
     $dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
     //JSON response to be handled on the client side
     $result = '{"success":1,"path":"'.$dlink.'","error":null}';
     header('Content-type: application/json;');
     echo $result;
    

    The "request/download" can perform some security checks, if needed, and generate the file transfer:

    $fn = $_GET['file'];
    if ($fn) {
      //Perform security checks
      //.....check user session/role/whatever
      $result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
      if (file_exists($result)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header('Content-Disposition: attachment; filename='.basename($result));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($result));
        ob_clean();
        flush();
        readfile($result);
        @unlink($result);
      }
    
    }
    

    What is the simplest way to swap each pair of adjoining chars in a string with Python?

    One of the easiest way to swap first two characters from a String is

    inputString = '2134'
    
    extractChar = inputString[0:2]
    swapExtractedChar = extractChar[::-1]          """Reverse the order of string"""
    swapFirstTwoChar = swapExtractedChar + inputString[2:]
     
    # swapFirstTwoChar = inputString[0:2][::-1] + inputString[2:]     """For one line code"""
    
    print(swapFirstTwoChar)
    

    How to make a <div> always full screen?

    What I found the best elegant way is like the following, the most trick here is make the div's position: fixed.

    _x000D_
    _x000D_
    .mask {_x000D_
        background-color: rgba(0, 0, 0, 0.5);_x000D_
        position: fixed;_x000D_
        top: 0;_x000D_
        left: 0;_x000D_
        right: 0;_x000D_
        bottom: 0;_x000D_
        margin: 0;_x000D_
        box-sizing: border-box;_x000D_
        width: 100%;_x000D_
        height: 100%;_x000D_
        object-fit: contain;_x000D_
    }
    _x000D_
    <html>_x000D_
      <head>_x000D_
      <title>Test</title>_x000D_
      </head>_x000D_
      <body>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <h1>Whatever it takes</h1>_x000D_
        <div class="mask"></div>_x000D_
        </body>_x000D_
      </html>
    _x000D_
    _x000D_
    _x000D_

    The mask demo

    What is the most efficient way to create HTML elements using jQuery?

    I think you're using the best method, though you could optimize it to:

     $("<div/>");
    

    C# delete a folder and all files and folders within that folder

    Try this.

    namespace EraseJunkFiles
    {
        class Program
        {
            static void Main(string[] args)
            {
                DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\");
                foreach (DirectoryInfo dir in yourRootDir.GetDirectories())
                        DeleteDirectory(dir.FullName, true);
            }
            public static void DeleteDirectory(string directoryName, bool checkDirectiryExist)
            {
                if (Directory.Exists(directoryName))
                    Directory.Delete(directoryName, true);
                else if (checkDirectiryExist)
                    throw new SystemException("Directory you want to delete is not exist");
            }
        }
    }
    

    Makefile, header dependencies

    Most answers are surprisingly complicated or erroneous. However simple and robust examples have been posted elsewhere [codereview]. Admittedly the options provided by the gnu preprocessor are a bit confusing. However, the removal of all directories from the build target with -MM is documented and not a bug [gpp]:

    By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as ‘.c’, and appends the platform's usual object suffix.

    The (somewhat newer) -MMD option is probably what you want. For completeness an example of a makefile that supports multiple src dirs and build dirs with some comments. For a simple version without build dirs see [codereview].

    CXX = clang++
    CXX_FLAGS = -Wfatal-errors -Wall -Wextra -Wpedantic -Wconversion -Wshadow
    
    # Final binary
    BIN = mybin
    # Put all auto generated stuff to this build dir.
    BUILD_DIR = ./build
    
    # List of all .cpp source files.
    CPP = main.cpp $(wildcard dir1/*.cpp) $(wildcard dir2/*.cpp)
    
    # All .o files go to build dir.
    OBJ = $(CPP:%.cpp=$(BUILD_DIR)/%.o)
    # Gcc/Clang will create these .d files containing dependencies.
    DEP = $(OBJ:%.o=%.d)
    
    # Default target named after the binary.
    $(BIN) : $(BUILD_DIR)/$(BIN)
    
    # Actual target of the binary - depends on all .o files.
    $(BUILD_DIR)/$(BIN) : $(OBJ)
        # Create build directories - same structure as sources.
        mkdir -p $(@D)
        # Just link all the object files.
        $(CXX) $(CXX_FLAGS) $^ -o $@
    
    # Include all .d files
    -include $(DEP)
    
    # Build target for every single object file.
    # The potential dependency on header files is covered
    # by calling `-include $(DEP)`.
    $(BUILD_DIR)/%.o : %.cpp
        mkdir -p $(@D)
        # The -MMD flags additionaly creates a .d file with
        # the same name as the .o file.
        $(CXX) $(CXX_FLAGS) -MMD -c $< -o $@
    
    .PHONY : clean
    clean :
        # This should remove all generated files.
        -rm $(BUILD_DIR)/$(BIN) $(OBJ) $(DEP)
    

    This method works because if there are multiple dependency lines for a single target, the dependencies are simply joined, e.g.:

    a.o: a.h
    a.o: a.c
        ./cmd
    

    is equivalent to:

    a.o: a.c a.h
        ./cmd
    

    as mentioned at: Makefile multiple dependency lines for a single target?

    SSL "Peer Not Authenticated" error with HttpClient 4.1

    keytool -import -v -alias cacerts -keystore cacerts.jks -storepass changeit -file C:\cacerts.cer
    

    MySQL select 10 random rows from 600K rows fast

    From book :

    Choose a Random Row Using an Offset

    Still another technique that avoids problems found in the preceding alternatives is to count the rows in the data set and return a random number between 0 and the count. Then use this number as an offset when querying the data set

    $rand = "SELECT ROUND(RAND() * (SELECT COUNT(*) FROM Bugs))";
    $offset = $pdo->query($rand)->fetch(PDO::FETCH_ASSOC);
    $sql = "SELECT * FROM Bugs LIMIT 1 OFFSET :offset";
    $stmt = $pdo->prepare($sql);
    $stmt->execute( $offset );
    $rand_bug = $stmt->fetch();
    

    Use this solution when you can’t assume contiguous key values and you need to make sure each row has an even chance of being selected.

    how to return index of a sorted list?

    How about

    l1 = [2,3,1,4,5]
    l2 = [l1.index(x) for x in sorted(l1)]
    

    Rename Pandas DataFrame Index

    For newer pandas versions

    df.index = df.index.rename('new name')
    

    or

    df.index.rename('new name', inplace=True)
    

    The latter is required if a data frame should retain all its properties.

    How to make a deep copy of Java ArrayList

    Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

    for(Person p : oldList) {
        newList.add(p.clone());
    }
    

    Assuming clone is correctly overriden inPerson.

    Call a React component method from outside

    class AppProvider extends Component {
      constructor() {
        super();
    
        window.alertMessage = this.alertMessage.bind(this);
      }
    
      alertMessage() {
        console.log('Hello World');
     }
    }
    

    You can call this method from the window by using window.alertMessage().

    Drawing an image from a data URL to a canvas

    in javascript , using jquery for canvas id selection :

     var Canvas2 = $("#canvas2")[0];
            var Context2 = Canvas2.getContext("2d");
            var image = new Image();
            image.src = "images/eye.jpg";
            Context2.drawImage(image, 0, 0);
    

    html5:

    <canvas id="canvas2"></canvas>
    

    How to return XML in ASP.NET?

    I've found the proper way to return XML to a client in ASP.NET. I think if I point out the wrong ways, it will make the right way more understandable.

    Incorrect:

    Response.Write(doc.ToString());
    

    Incorrect:

    Response.Write(doc.InnerXml);
    

    Incorrect:

    Response.ContentType = "text/xml";
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    doc.Save(Response.OutputStream);
    

    Correct:

    Response.ContentType = "text/xml"; //Must be 'text/xml'
    Response.ContentEncoding = System.Text.Encoding.UTF8; //We'd like UTF-8
    doc.Save(Response.Output); //Save to the text-writer
          //using the encoding of the text-writer
          //(which comes from response.contentEncoding)
    

    Use a TextWriter

    Do not use Response.OutputStream

    Do use Response.Output

    Both are streams, but Output is a TextWriter. When an XmlDocument saves itself to a TextWriter, it will use the encoding specified by that TextWriter. The XmlDocument will automatically change the xml declaration node to match the encoding used by the TextWriter. e.g. in this case the XML declaration node:

    <?xml version="1.0" encoding="ISO-8859-1"?>
    

    would become

    <?xml version="1.0" encoding="UTF-8"?>
    

    This is because the TextWriter has been set to UTF-8. (More on this in a moment). As the TextWriter is fed character data, it will encode it with the byte sequences appropriate for its set encoding.

    Incorrect:

    doc.Save(Response.OutputStream);
    

    In this example the document is incorrectly saved to the OutputStream, which performs no encoding change, and may not match the response's content-encoding or the XML declaration node's specified encoding.

    Correct

    doc.Save(Response.Output);
    

    The XML document is correctly saved to a TextWriter object, ensuring the encoding is properly handled.


    Set Encoding

    The encoding given to the client in the header:

    Response.ContentEncoding = ...
    

    must match the XML document's encoding:

    <?xml version="1.0" encoding="..."?>
    

    must match the actual encoding present in the byte sequences sent to the client. To make all three of these things agree, set the single line:

    Response.ContentEncoding = System.Text.Encoding.UTF8;
    

    When the encoding is set on the Response object, it sets the same encoding on the TextWriter. The encoding set of the TextWriter causes the XmlDocument to change the xml declaration:

    <?xml version="1.0" encoding="UTF-8"?>
    

    when the document is Saved:

    doc.Save(someTextWriter);
    

    Save to the response Output

    You do not want to save the document to a binary stream, or write a string:

    Incorrect:

    doc.Save(Response.OutputStream);
    

    Here the XML is incorrectly saved to a binary stream. The final byte encoding sequence won't match the XML declaration, or the web-server response's content-encoding.

    Incorrect:

    Response.Write(doc.ToString());
    Response.Write(doc.InnerXml);
    

    Here the XML is incorrectly converted to a string, which does not have an encoding. The XML declaration node is not updated to reflect the encoding of the response, and the response is not properly encoded to match the response's encoding. Also, storing the XML in an intermediate string wastes memory.

    You don't want to save the XML to a string, or stuff the XML into a string and response.Write a string, because that:

    - doesn't follow the encoding specified
    - doesn't set the XML declaration node to match
    - wastes memory
    

    Do use doc.Save(Response.Output);

    Do not use doc.Save(Response.OutputStream);

    Do not use Response.Write(doc.ToString());

    Do not use 'Response.Write(doc.InnerXml);`


    Set the content-type

    The Response's ContentType must be set to "text/xml". If not, the client will not know you are sending it XML.

    Final Answer

    Response.Clear(); //Optional: if we've sent anything before
    Response.ContentType = "text/xml"; //Must be 'text/xml'
    Response.ContentEncoding = System.Text.Encoding.UTF8; //We'd like UTF-8
    doc.Save(Response.Output); //Save to the text-writer
        //using the encoding of the text-writer
        //(which comes from response.contentEncoding)
    Response.End(); //Optional: will end processing
    

    Complete Example

    Rob Kennedy had the good point that I failed to include the start-to-finish example.

    GetPatronInformation.ashx:

    <%@ WebHandler Language="C#" Class="Handler" %>
    
    using System;
    using System.Web;
    using System.Xml;
    using System.IO;
    using System.Data.Common;
    
    //Why a "Handler" and not a full ASP.NET form?
    //Because many people online critisized my original solution
    //that involved the aspx (and cutting out all the HTML in the front file),
    //noting the overhead of a full viewstate build-up/tear-down and processing,
    //when it's not a web-form at all. (It's a pure processing.)
    
    public class Handler : IHttpHandler
    {
       public void ProcessRequest(HttpContext context)
       {
          //GetXmlToShow will look for parameters from the context
          XmlDocument doc = GetXmlToShow(context);
    
          //Don't forget to set a valid xml type.
          //If you leave the default "text/html", the browser will refuse to display it correctly
          context.Response.ContentType = "text/xml";
    
          //We'd like UTF-8.
          context.Response.ContentEncoding = System.Text.Encoding.UTF8;
          //context.Response.ContentEncoding = System.Text.Encoding.UnicodeEncoding; //But no reason you couldn't use UTF-16:
          //context.Response.ContentEncoding = System.Text.Encoding.UTF32; //Or UTF-32
          //context.Response.ContentEncoding = new System.Text.Encoding(500); //Or EBCDIC (500 is the code page for IBM EBCDIC International)
          //context.Response.ContentEncoding = System.Text.Encoding.ASCII; //Or ASCII
          //context.Response.ContentEncoding = new System.Text.Encoding(28591); //Or ISO8859-1
          //context.Response.ContentEncoding = new System.Text.Encoding(1252); //Or Windows-1252 (a version of ISO8859-1, but with 18 useful characters where they were empty spaces)
    
          //Tell the client don't cache it (it's too volatile)
          //Commenting out NoCache allows the browser to cache the results (so they can view the XML source)
          //But leaves the possiblity that the browser might not request a fresh copy
          //context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    
          //And now we tell the browser that it expires immediately, and the cached copy you have should be refreshed
          context.Response.Expires = -1;
    
          context.Response.Cache.SetAllowResponseInBrowserHistory(true); //"works around an Internet&nbsp;Explorer bug"
    
          doc.Save(context.Response.Output); //doc saves itself to the textwriter, using the encoding of the text-writer (which comes from response.contentEncoding)
    
          #region Notes
          /*
           * 1. Use Response.Output, and NOT Response.OutputStream.
           *  Both are streams, but Output is a TextWriter.
           *  When an XmlDocument saves itself to a TextWriter, it will use the encoding
           *  specified by the TextWriter. The XmlDocument will automatically change any
           *  XML declaration node, i.e.:
           *     <?xml version="1.0" encoding="ISO-8859-1"?>
           *  to match the encoding used by the Response.Output's encoding setting
           * 2. The Response.Output TextWriter's encoding settings comes from the
           *  Response.ContentEncoding value.
           * 3. Use doc.Save, not Response.Write(doc.ToString()) or Response.Write(doc.InnerXml)
           * 3. You DON'T want to save the XML to a string, or stuff the XML into a string
           *  and response.Write that, because that
           *   - doesn't follow the encoding specified
           *   - wastes memory
           *
           * To sum up: by Saving to a TextWriter: the XML Declaration node, the XML contents,
           * and the HTML Response content-encoding will all match.
           */
          #endregion Notes
       }
    
       private XmlDocument GetXmlToShow(HttpContext context)
       {
          //Use context.Request to get the account number they want to return
          //GET /GetPatronInformation.ashx?accountNumber=619
    
          //Or since this is sample code, pull XML out of your rear:
          XmlDocument doc = new XmlDocument();
          doc.LoadXml("<Patron><Name>Rob Kennedy</Name></Patron>");
    
          return doc;
       }
    
       public bool IsReusable { get { return false; } }
    }
    

    How to add an extra language input to Android?

    Sliding the space bar only works if you gave more then one input language selected.

    In that case the space bar will also indicate the selected language and show arrows to indicate Sliding will change selection.

    This is easy fast and changes the dictionary at the same time.

    First response seems the mist accurate.

    Regards

    Java: Unresolved compilation problem

    I got this error multiple times and struggled to work out. Finally, I removed the run configuration and re-added the default entries. It worked beautifully.

    Use PPK file in Mac Terminal to connect to remote connection over SSH

    Convert PPK to OpenSSh

    OS X: Install Homebrew, then run

    brew install putty

    Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search

    To generate the private key:

    cd ~

    puttygen id_dsa.ppk -O private-openssh -o id_dsa

    and to generate the public key:

    puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub

    Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:

    mkdir -p ~/.ssh
    mv -i ~/id_dsa* ~/.ssh
    chmod 600 ~/.ssh/id_dsa
    chmod 666 ~/.ssh/id_dsa.pub
    

    connect with ssh server

    ssh -i ~/.ssh/id_dsa username@servername
    

    Port Forwarding to connect mysql remote server

    ssh -i ~/.ssh/id_dsa -L 9001:127.0.0.1:3306 username@serverName
    

    How to create a zip archive of a directory in Python?

    This function will recursively zip up a directory tree, compressing the files, and recording the correct relative filenames in the archive. The archive entries are the same as those generated by zip -r output.zip source_dir.

    import os
    import zipfile
    def make_zipfile(output_filename, source_dir):
        relroot = os.path.abspath(os.path.join(source_dir, os.pardir))
        with zipfile.ZipFile(output_filename, "w", zipfile.ZIP_DEFLATED) as zip:
            for root, dirs, files in os.walk(source_dir):
                # add directory (needed for empty dirs)
                zip.write(root, os.path.relpath(root, relroot))
                for file in files:
                    filename = os.path.join(root, file)
                    if os.path.isfile(filename): # regular files only
                        arcname = os.path.join(os.path.relpath(root, relroot), file)
                        zip.write(filename, arcname)
    

    Copy file from source directory to binary directory using CMake

    If you want to put the content of example into install folder after build:

    code/
      src/
      example/
      CMakeLists.txt
    

    try add the following to your CMakeLists.txt:

    install(DIRECTORY example/ DESTINATION example)
    

    Using @property versus getters and setters

    [TL;DR? You can skip to the end for a code example.]

    I actually prefer to use a different idiom, which is a little involved for using as a one off, but is nice if you have a more complex use case.

    A bit of background first.

    Properties are useful in that they allow us to handle both setting and getting values in a programmatic way but still allow attributes to be accessed as attributes. We can turn 'gets' into 'computations' (essentially) and we can turn 'sets' into 'events'. So let's say we have the following class, which I've coded with Java-like getters and setters.

    class Example(object):
        def __init__(self, x=None, y=None):
            self.x = x
            self.y = y
    
        def getX(self):
            return self.x or self.defaultX()
    
        def getY(self):
            return self.y or self.defaultY()
    
        def setX(self, x):
            self.x = x
    
        def setY(self, y):
            self.y = y
    
        def defaultX(self):
            return someDefaultComputationForX()
    
        def defaultY(self):
            return someDefaultComputationForY()
    

    You may be wondering why I didn't call defaultX and defaultY in the object's __init__ method. The reason is that for our case I want to assume that the someDefaultComputation methods return values that vary over time, say a timestamp, and whenever x (or y) is not set (where, for the purpose of this example, "not set" means "set to None") I want the value of x's (or y's) default computation.

    So this is lame for a number of reasons describe above. I'll rewrite it using properties:

    class Example(object):
        def __init__(self, x=None, y=None):
            self._x = x
            self._y = y
    
        @property
        def x(self):
            return self.x or self.defaultX()
    
        @x.setter
        def x(self, value):
            self._x = value
    
        @property
        def y(self):
            return self.y or self.defaultY()
    
        @y.setter
        def y(self, value):
            self._y = value
    
        # default{XY} as before.
    

    What have we gained? We've gained the ability to refer to these attributes as attributes even though, behind the scenes, we end up running methods.

    Of course the real power of properties is that we generally want these methods to do something in addition to just getting and setting values (otherwise there is no point in using properties). I did this in my getter example. We are basically running a function body to pick up a default whenever the value isn't set. This is a very common pattern.

    But what are we losing, and what can't we do?

    The main annoyance, in my view, is that if you define a getter (as we do here) you also have to define a setter.[1] That's extra noise that clutters the code.

    Another annoyance is that we still have to initialize the x and y values in __init__. (Well, of course we could add them using setattr() but that is more extra code.)

    Third, unlike in the Java-like example, getters cannot accept other parameters. Now I can hear you saying already, well, if it's taking parameters it's not a getter! In an official sense, that is true. But in a practical sense there is no reason we shouldn't be able to parameterize an named attribute -- like x -- and set its value for some specific parameters.

    It'd be nice if we could do something like:

    e.x[a,b,c] = 10
    e.x[d,e,f] = 20
    

    for example. The closest we can get is to override the assignment to imply some special semantics:

    e.x = [a,b,c,10]
    e.x = [d,e,f,30]
    

    and of course ensure that our setter knows how to extract the first three values as a key to a dictionary and set its value to a number or something.

    But even if we did that we still couldn't support it with properties because there is no way to get the value because we can't pass parameters at all to the getter. So we've had to return everything, introducing an asymmetry.

    The Java-style getter/setter does let us handle this, but we're back to needing getter/setters.

    In my mind what we really want is something that capture the following requirements:

    • Users define just one method for a given attribute and can indicate there whether the attribute is read-only or read-write. Properties fail this test if the attribute writable.

    • There is no need for the user to define an extra variable underlying the function, so we don't need the __init__ or setattr in the code. The variable just exists by the fact we've created this new-style attribute.

    • Any default code for the attribute executes in the method body itself.

    • We can set the attribute as an attribute and reference it as an attribute.

    • We can parameterize the attribute.

    In terms of code, we want a way to write:

    def x(self, *args):
        return defaultX()
    

    and be able to then do:

    print e.x     -> The default at time T0
    e.x = 1
    print e.x     -> 1
    e.x = None
    print e.x     -> The default at time T1
    

    and so forth.

    We also want a way to do this for the special case of a parameterizable attribute, but still allow the default assign case to work. You'll see how I tackled this below.

    Now to the point (yay! the point!). The solution I came up for for this is as follows.

    We create a new object to replace the notion of a property. The object is intended to store the value of a variable set to it, but also maintains a handle on code that knows how to calculate a default. Its job is to store the set value or to run the method if that value is not set.

    Let's call it an UberProperty.

    class UberProperty(object):
    
        def __init__(self, method):
            self.method = method
            self.value = None
            self.isSet = False
    
        def setValue(self, value):
            self.value = value
            self.isSet = True
    
        def clearValue(self):
            self.value = None
            self.isSet = False
    

    I assume method here is a class method, value is the value of the UberProperty, and I have added isSet because None may be a real value and this allows us a clean way to declare there really is "no value". Another way is a sentinel of some sort.

    This basically gives us an object that can do what we want, but how do we actually put it on our class? Well, properties use decorators; why can't we? Let's see how it might look (from here on I'm going to stick to using just a single 'attribute', x).

    class Example(object):
    
        @uberProperty
        def x(self):
            return defaultX()
    

    This doesn't actually work yet, of course. We have to implement uberProperty and make sure it handles both gets and sets.

    Let's start with gets.

    My first attempt was to simply create a new UberProperty object and return it:

    def uberProperty(f):
        return UberProperty(f)
    

    I quickly discovered, of course, that this doens't work: Python never binds the callable to the object and I need the object in order to call the function. Even creating the decorator in the class doesn't work, as although now we have the class, we still don't have an object to work with.

    So we're going to need to be able to do more here. We do know that a method need only be represented the one time, so let's go ahead and keep our decorator, but modify UberProperty to only store the method reference:

    class UberProperty(object):
    
        def __init__(self, method):
            self.method = method
    

    It is also not callable, so at the moment nothing is working.

    How do we complete the picture? Well, what do we end up with when we create the example class using our new decorator:

    class Example(object):
    
        @uberProperty
        def x(self):
            return defaultX()
    
    print Example.x     <__main__.UberProperty object at 0x10e1fb8d0>
    print Example().x   <__main__.UberProperty object at 0x10e1fb8d0>
    

    in both cases we get back the UberProperty which of course is not a callable, so this isn't of much use.

    What we need is some way to dynamically bind the UberProperty instance created by the decorator after the class has been created to an object of the class before that object has been returned to that user for use. Um, yeah, that's an __init__ call, dude.

    Let's write up what we want our find result to be first. We're binding an UberProperty to an instance, so an obvious thing to return would be a BoundUberProperty. This is where we'll actually maintain state for the x attribute.

    class BoundUberProperty(object):
        def __init__(self, obj, uberProperty):
            self.obj = obj
            self.uberProperty = uberProperty
            self.isSet = False
    
        def setValue(self, value):
            self.value = value
            self.isSet = True
    
        def getValue(self):
            return self.value if self.isSet else self.uberProperty.method(self.obj)
    
        def clearValue(self):
            del self.value
            self.isSet = False
    

    Now we the representation; how do get these on to an object? There are a few approaches, but the easiest one to explain just uses the __init__ method to do that mapping. By the time __init__ is called our decorators have run, so just need to look through the object's __dict__ and update any attributes where the value of the attribute is of type UberProperty.

    Now, uber-properties are cool and we'll probably want to use them a lot, so it makes sense to just create a base class that does this for all subclasses. I think you know what the base class is going to be called.

    class UberObject(object):
        def __init__(self):
            for k in dir(self):
                v = getattr(self, k)
                if isinstance(v, UberProperty):
                    v = BoundUberProperty(self, v)
                    setattr(self, k, v)
    

    We add this, change our example to inherit from UberObject, and ...

    e = Example()
    print e.x               -> <__main__.BoundUberProperty object at 0x104604c90>
    

    After modifying x to be:

    @uberProperty
    def x(self):
        return *datetime.datetime.now()*
    

    We can run a simple test:

    print e.x.getValue()
    print e.x.getValue()
    e.x.setValue(datetime.date(2013, 5, 31))
    print e.x.getValue()
    e.x.clearValue()
    print e.x.getValue()
    

    And we get the output we wanted:

    2013-05-31 00:05:13.985813
    2013-05-31 00:05:13.986290
    2013-05-31
    2013-05-31 00:05:13.986310
    

    (Gee, I'm working late.)

    Note that I have used getValue, setValue, and clearValue here. This is because I haven't yet linked in the means to have these automatically returned.

    But I think this is a good place to stop for now, because I'm getting tired. You can also see that the core functionality we wanted is in place; the rest is window dressing. Important usability window dressing, but that can wait until I have a change to update the post.

    I'll finish up the example in the next posting by addressing these things:

    • We need to make sure UberObject's __init__ is always called by subclasses.

      • So we either force it be called somewhere or we prevent it from being implemented.
      • We'll see how to do this with a metaclass.
    • We need to make sure we handle the common case where someone 'aliases' a function to something else, such as:

        class Example(object):
            @uberProperty
            def x(self):
                ...
      
            y = x
      
    • We need e.x to return e.x.getValue() by default.

      • What we'll actually see is this is one area where the model fails.
      • It turns out we'll always need to use a function call to get the value.
      • But we can make it look like a regular function call and avoid having to use e.x.getValue(). (Doing this one is obvious, if you haven't already fixed it out.)
    • We need to support setting e.x directly, as in e.x = <newvalue>. We can do this in the parent class too, but we'll need to update our __init__ code to handle it.

    • Finally, we'll add parameterized attributes. It should be pretty obvious how we'll do this, too.

    Here's the code as it exists up to now:

    import datetime
    
    class UberObject(object):
        def uberSetter(self, value):
            print 'setting'
    
        def uberGetter(self):
            return self
    
        def __init__(self):
            for k in dir(self):
                v = getattr(self, k)
                if isinstance(v, UberProperty):
                    v = BoundUberProperty(self, v)
                    setattr(self, k, v)
    
    
    class UberProperty(object):
        def __init__(self, method):
            self.method = method
    
    class BoundUberProperty(object):
        def __init__(self, obj, uberProperty):
            self.obj = obj
            self.uberProperty = uberProperty
            self.isSet = False
    
        def setValue(self, value):
            self.value = value
            self.isSet = True
    
        def getValue(self):
            return self.value if self.isSet else self.uberProperty.method(self.obj)
    
        def clearValue(self):
            del self.value
            self.isSet = False
    
        def uberProperty(f):
            return UberProperty(f)
    
    class Example(UberObject):
    
        @uberProperty
        def x(self):
            return datetime.datetime.now()
    

    [1] I may be behind on whether this is still the case.

    Django MEDIA_URL and MEDIA_ROOT

    Following the steps mentioned above for =>3.0 for Debug mode

    urlpatterns = [
    ...
    ]
    + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    And also the part that caught me out, the above static URL only worked in my main project urls.py file. I was first attempting to add to my app, and wondering why I couldn't see the images.

    Lastly make sure you set the following:

    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    MEDIA_URL = '/media/'
    

    What are the complexity guarantees of the standard containers?

    I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

    Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

    Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

    Read file line by line in PowerShell

    Get-Content has bad performance; it tries to read the file into memory all at once.

    C# (.NET) file reader reads each line one by one

    Best Performace

    foreach($line in [System.IO.File]::ReadLines("C:\path\to\file.txt"))
    {
           $line
    }
    

    Or slightly less performant

    [System.IO.File]::ReadLines("C:\path\to\file.txt") | ForEach-Object {
           $_
    }
    

    The foreach statement will likely be slightly faster than ForEach-Object (see comments below for more information).

    vue.js 'document.getElementById' shorthand

    You can use the directive v-el to save an element and then use it later.

    https://vuejs.org/api/#vm-els

    <div v-el:my-div></div>
    <!-- this.$els.myDiv --->
    

    Edit: This is deprecated in Vue 2, see ??? answer

    Git log to get commits only for a specific branch

    In my situation, we are using Git Flow and GitHub. All you need to do this is: Compare your feature branch with your develop branch on GitHub.

    It will show the commits only made to your feature branch.

    For example:

    https://github.com/your_repo/compare/develop...feature_branch_name

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

    The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

    Eg: - print ("hello",end=" +") will print hello +

    How do I call a dynamically-named method in Javascript?

    Here is a working and simple solution for checking existence of a function and triaging that function dynamically by another function;

    Trigger function

    function runDynmicFunction(functionname){ 
    
        if (typeof window[functionname] == "function"  ) { //check availability
    
            window[functionname]("this is from the function it "); //run function and pass a parameter to it
        }
    }
    

    and you can now generate the function dynamically maybe using php like this

    function runThis_func(my_Parameter){
    
        alert(my_Parameter +" triggerd");
    }
    

    now you can call the function using dynamically generated event

    <?php
    
    $name_frm_somware ="runThis_func";
    
    echo "<input type='button' value='Button' onclick='runDynmicFunction(\"".$name_frm_somware."\");'>";
    
    ?>
    

    the exact HTML code you need is

    <input type="button" value="Button" onclick="runDynmicFunction('runThis_func');">
    

    xxxxxx.exe is not a valid Win32 application

    I got this problem while launching a VS2013 32-bit console application in powershell, launching it in cmd did not issue this problem.

    Auto detect mobile browser (via user-agent?)

    Yes user-agent is used to detect mobile browsers. There are lots of free scripts available to check this. Here is one such php code which will help you redirect mobile users to different website.

    How to Load an Assembly to AppDomain with all references recursively?

    You need to invoke CreateInstanceAndUnwrap before your proxy object will execute in the foreign application domain.

     class Program
    {
        static void Main(string[] args)
        {
            AppDomainSetup domaininfo = new AppDomainSetup();
            domaininfo.ApplicationBase = System.Environment.CurrentDirectory;
            Evidence adevidence = AppDomain.CurrentDomain.Evidence;
            AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo);
    
            Type type = typeof(Proxy);
            var value = (Proxy)domain.CreateInstanceAndUnwrap(
                type.Assembly.FullName,
                type.FullName);
    
            var assembly = value.GetAssembly(args[0]);
            // AppDomain.Unload(domain);
        }
    }
    
    public class Proxy : MarshalByRefObject
    {
        public Assembly GetAssembly(string assemblyPath)
        {
            try
            {
                return Assembly.LoadFile(assemblyPath);
            }
            catch (Exception)
            {
                return null;
                // throw new InvalidOperationException(ex);
            }
        }
    }
    

    Also, note that if you use LoadFrom you'll likely get a FileNotFound exception because the Assembly resolver will attempt to find the assembly you're loading in the GAC or the current application's bin folder. Use LoadFile to load an arbitrary assembly file instead--but note that if you do this you'll need to load any dependencies yourself.

    sqldeveloper error message: Network adapter could not establish the connection error

    In the connection properties window I changed my selection from "SID" to "Service Name", and copied my SID into the Service Name field. No idea why this change happened or why it worked, but it got me back on Oracle.

    Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

    in laragon delete all internal data files from "C:\laragon\data\mysql" and restart it, that worked for me

    How do I test for an empty JavaScript object?

    This is my preferred solution:

    var obj = {};
    return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty
    

    How to move a file?

    Based on the answer described here, using subprocess is another option.

    Something like this:

    subprocess.call("mv %s %s" % (source_files, destination_folder), shell=True)
    

    I am curious to know the pro's and con's of this method compared to shutil. Since in my case I am already using subprocess for other reasons and it seems to work I am inclined to stick with it.

    Is it system dependent maybe?

    Weird behavior of the != XPath operator

    The problem is that the 'and' is being treated as an 'or'.

    No, the problem is that you are using the XPath != operator and you aren't aware of its "weird" semantics.

    Solution:

    Just replace the any x != y expressions with a not(x = y) expression.

    In your specific case:

    Replace:

    <xsl:when test="$AccountNumber != '12345' and $Balance != '0'">
    

    with:

    <xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')">
    

    Explanation:

    By definition whenever one of the operands of the != operator is a nodeset, then the result of evaluating this operator is true if there is a node in the node-set, whose value isn't equal to the other operand.

    So:

     $someNodeSet != $someValue
    

    generally doesn't produce the same result as:

     not($someNodeSet = $someValue)
    

    The latter (by definition) is true exactly when there isn't a node in $someNodeSet whose string value is equal to $someValue.

    Lesson to learn:

    Never use the != operator, unless you are absolutely sure you know what you are doing.

    A generic error occurred in GDI+, JPEG Image to MemoryStream

    If you are getting that error , then I can say that your application doesn't have a write permission on some directory.

    For example, if you are trying to save the Image from the memory stream to the file system , you may get that error.

    Please if you are using XP, make sure to add write permission for the aspnet account on that folder.

    If you are using windows server (2003,2008) or Vista, make sure that add write permission for the Network service account.

    Hope it help some one.

    Response::json() - Laravel 5.1

    use the helper function in laravel 5.1 instead:

    return response()->json(['name' => 'Abigail', 'state' => 'CA']);
    

    This will create an instance of \Illuminate\Routing\ResponseFactory. See the phpDocs for possible parameters below:

    /**
    * Return a new JSON response from the application.
    *
    * @param string|array $data
    * @param int $status
    * @param array $headers
    * @param int $options
    * @return \Symfony\Component\HttpFoundation\Response 
    * @static 
    */
    public static function json($data = array(), $status = 200, $headers = array(), $options = 0){
    
        return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
    }
    

    Oracle SQL - select within a select (on the same table!)

    This is precisely the sort of scenario where analytics come to the rescue.

    Given this test data:

    SQL> select * from employment_history
      2  order by Gc_Staff_Number
      3             , start_date
      4  /
    
    GC_STAFF_NUMBER START_DAT END_DATE  C
    --------------- --------- --------- -
               1111 16-OCT-09           Y
               2222 08-MAR-08 26-MAY-09 N
               2222 12-DEC-09           Y
               3333 18-MAR-07 08-MAR-08 N
               3333 01-JUL-09 21-MAR-09 N
               3333 30-JUL-10           Y
    
    6 rows selected.
    
    SQL> 
    

    An inline view with an analytic LAG() function provides the right answer:

    SQL> select Gc_Staff_Number
      2             , start_date
      3             , prev_end_date
      4  from   (
      5      select Gc_Staff_Number
      6             , start_date
      7             , lag (end_date) over (partition by Gc_Staff_Number
      8                                    order by start_date )
      9                  as prev_end_date
     10             , current_flag
     11      from employment_history
     12  )
     13  where current_flag = 'Y'
     14  /
    
    GC_STAFF_NUMBER START_DAT PREV_END_
    --------------- --------- ---------
               1111 16-OCT-09
               2222 12-DEC-09 26-MAY-09
               3333 30-JUL-10 21-MAR-09
    
    SQL>
    

    The inline view is crucial to getting the right result. Otherwise the filter on CURRENT_FLAG removes the previous rows.

    Preloading CSS Images

    If the page elements and their background images are already in the DOM (i.e. you are not creating/changing them dynamically), then their background images will already be loaded. At that point, you may want to look at compression methods :)

    Run a PHP file in a cron job using CPanel

    I used this command to activate cron job for this.

    /usr/bin/php -q /home/username/public_html/yourfilename.php
    

    on godaddy server, and its working fine.

    How do I update Anaconda?

    To update your installed version to the latest version, say 2019.07, run:

    conda install anaconda=2019.07
    

    In most cases, this method can meet your needs and avoid dependency problems.

    Android: Tabs at the BOTTOM

    Yes, see: link, but he used xml layouts, not activities to create new tab, so put his xml code (set paddingTop for FrameLayout - 0px) and then write the code:

    public class SomeActivity extends ActivityGroup {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
    
        TabHost tab_host = (TabHost) findViewById(R.id.edit_item_tab_host); 
    
        tab_host.setup(this.getLocalActivityManager());
    
        TabSpec ts1 = tab_host.newTabSpec("TAB_DATE"); 
        ts1.setIndicator("tab1"); 
        ts1.setContent(new Intent(this, Registration.class)); 
        tab_host.addTab(ts1); 
    
        TabSpec ts2 = tab_host.newTabSpec("TAB_GEO"); 
        ts2.setIndicator("tab2"); 
        ts2.setContent(new Intent(this, Login.class)); 
        tab_host.addTab(ts2); 
    
        TabSpec ts3 = tab_host.newTabSpec("TAB_TEXT"); 
        ts3.setIndicator("tab3"); 
        ts3.setContent(new Intent(this, Registration.class)); 
        tab_host.addTab(ts3); 
    
        tab_host.setCurrentTab(0);      
    
    
    }
    

    }

    cast class into another class or convert class to another

    Use JSON serialization and deserialization:

    using Newtonsoft.Json;
    
    Class1 obj1 = new Class1();
    Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));
    

    Or:

    public class Class1
    {
        public static explicit operator Class2(Class1 obj)
        {
            return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
        }
    }
    

    Which then allows you to do something like

    Class1 obj1 = new Class1();
    Class2 obj2 = (Class2)obj1;
    

    How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

    To fix this problem, you have to install OpenSSL development package, which is available in standard repositories of all modern Linux distributions.

    To install OpenSSL development package on Debian, Ubuntu or their derivatives:

    $ sudo apt-get install libssl-dev
    

    To install OpenSSL development package on Fedora, CentOS or RHEL:

    $ sudo yum install openssl-devel 
    

    Edit : As @isapir has pointed out, for Fedora version>=22 use the DNF package manager :

    dnf install openssl-devel
    

    How can I scroll a div to be visible in ReactJS?

    I assume that you have some sort of List component and some sort of Item component. The way I did it in one project was to let the item know if it was active or not; the item would ask the list to scroll it into view if necessary. Consider the following pseudocode:

    class List extends React.Component {
      render() {
        return <div>{this.props.items.map(this.renderItem)}</div>;
      }
    
      renderItem(item) {
        return <Item key={item.id} item={item}
                     active={item.id === this.props.activeId}
                     scrollIntoView={this.scrollElementIntoViewIfNeeded} />
      }
    
      scrollElementIntoViewIfNeeded(domNode) {
        var containerDomNode = React.findDOMNode(this);
        // Determine if `domNode` fully fits inside `containerDomNode`.
        // If not, set the container's scrollTop appropriately.
      }
    }
    
    class Item extends React.Component {
      render() {
        return <div>something...</div>;
      }
    
      componentDidMount() {
        this.ensureVisible();
      }
    
      componentDidUpdate() {
        this.ensureVisible();
      }
    
      ensureVisible() {
        if (this.props.active) {
          this.props.scrollIntoView(React.findDOMNode(this));
        }
      }
    }
    

    A better solution is probably to make the list responsible for scrolling the item into view (without the item being aware that it's even in a list). To do so, you could add a ref attribute to a certain item and find it with that:

    class List extends React.Component {
      render() {
        return <div>{this.props.items.map(this.renderItem)}</div>;
      }
    
      renderItem(item) {
        var active = item.id === this.props.activeId;
        var props = {
          key: item.id,
          item: item,
          active: active
        };
        if (active) {
          props.ref = "activeItem";
        }
        return <Item {...props} />
      }
    
      componentDidUpdate(prevProps) {
        // only scroll into view if the active item changed last render
        if (this.props.activeId !== prevProps.activeId) {
          this.ensureActiveItemVisible();
        }
      }
    
      ensureActiveItemVisible() {
        var itemComponent = this.refs.activeItem;
        if (itemComponent) {
          var domNode = React.findDOMNode(itemComponent);
          this.scrollElementIntoViewIfNeeded(domNode);
        }
      }
    
      scrollElementIntoViewIfNeeded(domNode) {
        var containerDomNode = React.findDOMNode(this);
        // Determine if `domNode` fully fits inside `containerDomNode`.
        // If not, set the container's scrollTop appropriately.
      }
    }
    

    If you don't want to do the math to determine if the item is visible inside the list node, you could use the DOM method scrollIntoView() or the Webkit-specific scrollIntoViewIfNeeded, which has a polyfill available so you can use it in non-Webkit browsers.

    How to add a TextView to LinearLayout in Android

    LinearLayout.LayoutParams layoutParams ;
    layoutParams= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    

    How to create a hex dump of file containing only the hex characters without spaces in bash?

    xxd -p file
    

    Or if you want it all on a single line:

    xxd -p file | tr -d '\n'
    

    Gson: Directly convert String to JsonObject (no POJO)

    use JsonParser; for example:

    JsonParser parser = new JsonParser();
    JsonObject o = parser.parse("{\"a\": \"A\"}").getAsJsonObject();