Programs & Examples On #Bytearrayoutputstream

A mechanism for writing byte data to a stream

Create a file from a ByteArrayOutputStream

You can use a FileOutputStream for this.

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(new File("myFile")); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Put data in your baos

    baos.writeTo(fos);
} catch(IOException ioe) {
    // Handle exception here
    ioe.printStackTrace();
} finally {
    fos.close();
}

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

How to create a database from shell command?

cat filename.sql | mysql -u username -p # type mysql password when asked for it

Where filename.sql holds all the sql to create your database. Or...

echo "create database `database-name`" | mysql -u username -p

If you really only want to create a database.

Javascript parse float is ignoring the decimals after my comma

It is better to use this syntax to replace all the commas in a case of a million 1,234,567

var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, ""); 
var number = parseFloat(string);
console.log(number)

The g means to remove all commas.

Check the Jsfiddle demo here.

Figuring out whether a number is a Double in Java

Reflection is slower, but works for a situation when you want to know whether that is of type Dog or a Cat and not an instance of Animal. So you'd do something like:

if(null != items.elementAt(1) && items.elementAt(1).getClass().toString().equals("Cat"))
{
//do whatever with cat.. not any other instance of animal.. eg. hideClaws();
}

Not saying the answer above does not work, except the null checking part is necessary.

Another way to answer that is use generics and you are guaranteed to have Double as any element of items.

List<Double> items = new ArrayList<Double>();

Python ValueError: too many values to unpack

for k, m in self.materials.items():

example:

miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
for k, v in miles_dict.items():
    print("%s: %s" % (k, v))

onCreateOptionsMenu inside Fragments

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_add_customer, container, false);
        setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_sample, menu);
    super.onCreateOptionsMenu(menu,inflater);
}

Unit Testing: DateTime.Now

These are all good answers, this is what I did on a different project:

Usage:

Get Today's REAL date Time

var today = SystemTime.Now().Date;

Instead of using DateTime.Now, you need to use SystemTime.Now()... It's not hard change but this solution might not be ideal for all projects.

Time Traveling (Lets go 5 years in the future)

SystemTime.SetDateTime(today.AddYears(5));

Get Our Fake "today" (will be 5 years from 'today')

var fakeToday = SystemTime.Now().Date;

Reset the date

SystemTime.ResetDateTime();

/// <summary>
/// Used for getting DateTime.Now(), time is changeable for unit testing
/// </summary>
public static class SystemTime
{
    /// <summary> Normally this is a pass-through to DateTime.Now, but it can be overridden with SetDateTime( .. ) for testing or debugging.
    /// </summary>
    public static Func<DateTime> Now = () => DateTime.Now;

    /// <summary> Set time to return when SystemTime.Now() is called.
    /// </summary>
    public static void SetDateTime(DateTime dateTimeNow)
    {
        Now = () =>  dateTimeNow;
    }

    /// <summary> Resets SystemTime.Now() to return DateTime.Now.
    /// </summary>
    public static void ResetDateTime()
    {
        Now = () => DateTime.Now;
    }
}

How to increase font size in NeatBeans IDE?

Go to Tools|options|keymap. Search for 'zoom in text' and set your preferred key. I've set alt+plus and alt+minus.

Clearing content of text file using php

file_put_contents("filelist.txt", "");

You can redirect by using the header() function to modify the Location header.

Center a popup window on screen?

My recommendation is to use top location 33% or 25% from remaining space,
and not 50% as other examples posted here,
mainly because of the window header,
which look better and more comfort to the user,

complete code:

    <script language="javascript" type="text/javascript">
        function OpenPopupCenter(pageURL, title, w, h) {
            var left = (screen.width - w) / 2;
            var top = (screen.height - h) / 4;  // for 25% - devide by 4  |  for 33% - devide by 3
            var targetWin = window.open(pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
        } 
    </script>
</head>
<body>
    <button onclick="OpenPopupCenter('http://www.google.com', 'TEST!?', 800, 600);">click on me</button>
</body>
</html>



check out this line:
var top = (screen.height - h) / 4; // for 25% - devide by 4 | for 33% - devide by 3

Installing mcrypt extension for PHP on OSX Mountain Lion

Why You're Getting This Error

PHP complains if one of the files like mcrypt.so is included using the syntax extension="mcrypt.so" but the file is not in the extension_dir path ( use <?php phpinfo(); ?> or php -i to check that).

It will also tell you which php.ini config file is being loaded so you will know where the settings are coming from. Most likely it will be something like /usr/local/etc/php/5.4/php.ini if you are using the homebrew version.

Take note of the part under it that says something like "Scan this dir for additional .ini files" because what that means is it gives you a place to put your own file, like tweaks.ini that is loaded after the main configuration file so that you can make changes and keep up with them easily. Also remember that all the files in this directory get loaded in alphabetical order, so if you have one called adjustments.ini that contains mcrypt directives, and there is a mcrypt.ini, most likely your settings will be overridden.

One alternative to specifying extension="mcrypt.so" is to specify the full path to the mcrypt.so file. The other option is to edit the extension_dir setting.

What worked for me

On Mavericks I didn't have to do either. I did a fresh install of homebrew and then added the josegonzalez tap using:

brew tap josegonzalez/homebrew-php

(My other laptop was running Mountain Lion and was also using homebrew in this setup.)

After you've tapped that awesome repo you can install php and mcrypt using something like:

brew install php54 php54-mcrypt

What if this doesn't work (and why should I use homebrew anyway?)

I would highly advise trying this route before downloading and building it from source. It's not hard to build from source - but I don't want to have to maintain that. It's one of the reasons to use homebrew in the first place - it's a package manager (with a HUGE community).

There is a lot of development on the homebrew project and - if you have problems I'd suggest checking out their issues page

So yes you can build it from source and that might seem like a good option right now if you just want mcrypt to work but you may hate yourself for doing this later...

If you don't want to be using php54 there is also the php53 branch. They have some instructions at the repo about how to use both of them / switch between them.

If you're new to homebrew you should know that you check out what else is available using brew search php54, which gives something like:

php54                php54-lzf          php54-snappy        
php54-amqp           php54-mailparse    php54-solr          
php54-apc            php54-mcrypt       php54-ssh2          
php54-apcu           php54-memcache     php54-stats         
php54-boxwood        php54-memcached    php54-svm           
php54-chdb           php54-midgard2     php54-tidy          
php54-couchbase      php54-mongo        php54-timezonedb    
php54-dbase          php54-msgpack      php54-tokyotyrant   
php54-ev             php54-mysqlnd_ms   php54-twig          
php54-gearman        php54-oauth        php54-uploadprogress
php54-geoip          php54-opcache      php54-uuid          
php54-gmagick        php54-parsekit     php54-varnish       
php54-graphdat       php54-pcntl        php54-wbxml         
php54-http           php54-pdflib       php54-xcache        
php54-igbinary       php54-phalcon      php54-xdebug        
php54-imagick        php54-proctitle    php54-xhgui         
php54-inclued        php54-pspell       php54-xhp           
php54-intl           php54-pthreads     php54-xhprof        
php54-ioncubeloader  php54-raphf        php54-xmldiff       
php54-jsmin          php54-redis        php54-yac           
php54-judy           php54-riak         php54-yaf           
php54-leveldb        php54-runkit       php54-yaml          
php54-libevent       php54-scrypt       php54-yaz           
php54-libvirt

TLDR

  • You should use homebrew to install mcrypt if at all possible
  • If you're getting errors it's probably because your configuration file(s) are messed up. Check the extension_dir path and figure out where the mcrypt.so file is and see if there is a discrepancy (or specify the full path)

how to sort order of LEFT JOIN in SQL query?

This will get you the most expensive car for the user:

SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName

However, this statement makes me think that you want all of the cars prices sorted, descending:

So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?

So you could try this:

SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC

Git: Recover deleted (remote) branch

  1. find out commit id

    git reflog

  2. recover local branch you deleted by mistake

    git branch need-recover-branch-name commitId

  3. push need-recover-branch-name again if you deleted remote branch too before

    git push origin need-recover-branch-name

How to fix "The ConnectionString property has not been initialized"

The connection string is not in AppSettings.

What you're looking for is in:

System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

To produce the same results:

MessageDigest sha1 = MessageDigest.getInstance("SHA1", BOUNCY_CASTLE_PROVIDER);
byte[] digest = sha1.digest(content);
DERObjectIdentifier sha1oid_ = new DERObjectIdentifier("1.3.14.3.2.26");

AlgorithmIdentifier sha1aid_ = new AlgorithmIdentifier(sha1oid_, null);
DigestInfo di = new DigestInfo(sha1aid_, digest);

byte[] plainSig = di.getDEREncoded();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", BOUNCY_CASTLE_PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] signature = cipher.doFinal(plainSig);

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

I think you can use CHECK constraint - it is exactly what it was invented for.

ALTER TABLE someTable 
ADD CONSTRAINT someField_check CHECK (ISNUMERIC(someField) = 1) ;

My previous answer (also right by may be a bit overkill):

I think the right way is to use INSTEAD OF trigger to prevent the wrong data from being inserted (rather than deleting it post-factum)

How to communicate between iframe and the parent site?

It must be here, because accepted answer from 2012

In 2018 and modern browsers you can send a custom event from iframe to parent window.

iframe:

var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)

parent:

window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
  console.log(e.detail) // outputs: {foo: 'bar'}
}

PS: Of course, you can send events in opposite direction same way.

document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)

How to check whether a file is empty or not?

if you want to check csv file is empty or not .......try this

with open('file.csv','a',newline='') as f:
        csv_writer=DictWriter(f,fieldnames=['user_name','user_age','user_email','user_gender','user_type','user_check'])
        if os.stat('file.csv').st_size > 0:
            pass
        else:
            csv_writer.writeheader()

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

Confirm Password with jQuery Validate

Remove the required: true rule.

Demo: Fiddle

jQuery('.validatedForm').validate({
            rules : {
                password : {
                    minlength : 5
                },
                password_confirm : {
                    minlength : 5,
                    equalTo : "#password"
                }
            }

How to pass a null variable to a SQL Stored Procedure from C#.net code

SqlParameters[1] = new SqlParameter("Date1", SqlDbType.SqlDateTime);
SqlParameters[1].Value = DBNull.Value;
SqlParameters[1].Direction = ParameterDirection.Input;

...then copy for the second.

SQL Server Escape an Underscore

This worked for me, just use the escape '%\_%'

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

Importing csv file into R - numeric values read as characters

I had a similar problem. Based on Joshua's premise that excel was the problem I looked at it and found that the numbers were formatted with commas between every third digit. Reformatting without commas fixed the problem.

Include php files when they are in different folders

You can get to the root from within each site using $_SERVER['DOCUMENT_ROOT']. For testing ONLY you can echo out the path to make sure it's working, if you do it the right way. You NEVER want to show the local server paths for things like includes and requires.

Site 1

echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/';

Includes under site one would be at:

echo $_SERVER['DOCUMENT_ROOT'].'/includes/'; // should be '/main_web_folder/includes/';

Site 2

echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/blog/';

The actual code to access includes from site1 inside of site2 you would say:

include($_SERVER['DOCUMENT_ROOT'].'/../includes/file_from_site_1.php');

It will only use the relative path of the file executing the query if you try to access it by excluding the document root and the root slash:

 //(not as fool-proof or non-platform specific)
 include('../includes/file_from_site_1.php');

Included paths have no place in code on the front end (live) of the site anywhere, and should be secured and used in production environments only.

Additionally for URLs on the site itself you can make them relative to the domain. Browsers will automatically fill in the rest because they know which page they are looking at. So instead of:

<a href='http://www.__domain__name__here__.com/contact/'>Contact</a>

You should use:

<a href='/contact/'>Contact</a>

For good SEO you'll want to make sure that the URLs for the blog do not exist in the other domain, otherwise it may be marked as a duplicate site. With that being said you might also want to add a line to your robots.txt file for ONLY site1:

User-agent: *
Disallow: /blog/

Other possibilities:

Look up your IP address and include this snippet of code:

function is_dev(){
  //use the external IP from Google.
  //If you're hosting locally it's 127.0.01 unless you've changed it.
  $ip_address='xxx.xxx.xxx.xxx';

  if ($_SERVER['REMOTE_ADDR']==$ip_address){
     return true;
  } else {
     return false;
  } 
}

if(is_dev()){
    echo $_SERVER['DOCUMENT_ROOT'];       
}

Remember if your ISP changes your IP, as in you have a DCHP Dynamic IP, you'll need to change the IP in that file to see the results. I would put that file in an include, then require it on pages for debugging.

If you're okay with modern methods like using the browser console log you could do this instead and view it in the browser's debugging interface:

if(is_dev()){
    echo "<script>".PHP_EOL;
    echo "console.log('".$_SERVER['DOCUMENT_ROOT']."');".PHP_EOL;
    echo "</script>".PHP_EOL;       
}

Get most recent row for given ID

I had a similar problem. I needed to get the last version of page content translation, in other words - to get that specific record which has highest number in version column. So I select all records ordered by version and then take the first row from result (by using LIMIT clause).

SELECT *
FROM `page_contents_translations`
ORDER BY version DESC
LIMIT 1

Comparing strings in Java

ou can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).

Use it so:

You can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).

Use it so:

  String a="myWord";
  if(a.compareTo(another_string) <0){
    //a is strictly < to another_string
  }
  else if (a.compareTo(another_string) == 0){
    //a equals to another_string
  }
else{
  // a is strictly > than another_string
}    

How to fill color in a cell in VBA?

  1. Select all cells by left-top corner
  2. Choose [Home] >> [Conditional Formatting] >> [New Rule]
  3. Choose [Format only cells that contain]
  4. In [Format only cells with:], choose "Errors"
  5. Choose proper formats in [Format..] button

Pythonically add header to a csv file

The DictWriter() class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer() and pass in a simple row for the header:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerow(["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

The alternative would be to generate dictionaries when copying across your data:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

What is the use of ByteBuffer in Java?

In Android you can create shared buffer between C++ and Java (with directAlloc method) and manipulate it in both sides.

Changing variable names with Python for loops

Use a list.

groups = [0]*3
for i in xrange(3):
    groups[i] = self.getGroup(selected, header + i)

or more "Pythonically":

groups = [self.getGroup(selected, header + i) for i in xrange(3)]

For what it's worth, you could try to create variables the "wrong" way, i.e. by modifying the dictionary which holds their values:

l = locals()
for i in xrange(3):
    l['group' + str(i)] = self.getGroup(selected, header + i)

but that's really bad form, and possibly not even guaranteed to work.

Laravel Eloquent ORM Transactions

If you want to avoid closures, and happy to use facades, the following keeps things nice and clean:

try {
    \DB::beginTransaction();

    $user = \Auth::user();
    $user->fill($request->all());
    $user->push();

    \DB::commit();

} catch (Throwable $e) {
    \DB::rollback();
}

If any statements fail, commit will never hit, and the transaction won't process.

Ignore files that have already been committed to a Git repository

I have found a weird problem with .gitignore. Everything was in place and seemed correct. The only reason why my .gitignore was "ignored" was, that the line-ending was in Mac-Format (\r). So after saving the file with the correct line-ending (in vi using :set ff=unix) everything worked like a charm!

How to pass a variable from Activity to Fragment, and pass it back?

Sending data from Activity to a Fragment

Activity:

Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();

Fragment:

Reading the value in fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    String myValue = this.getArguments().getString("message");
    ...
    ...
    ...
}

But if you want to send values from Fragment to Activity, read the answer of jpardogo, you must need interfaces, more info: Communicating with other Fragments

libpng warning: iCCP: known incorrect sRGB profile

some background info on this:

Some changes in libpng version 1.6+ cause it to issue a warning or even not work correctly with the original HP/MS sRGB profile, leading to the following stderr: libpng warning: iCCP: known incorrect sRGB profile The old profile uses a D50 whitepoint, where D65 is standard. This profile is not uncommon, being used by Adobe Photoshop, although it was not embedded into images by default.

(source: https://wiki.archlinux.org/index.php/Libpng_errors)

Error detection in some chunks has improved; in particular the iCCP chunk reader now does pretty complete validation of the basic format. Some bad profiles that were previously accepted are now rejected, in particular the very old broken Microsoft/HP sRGB profile. The PNG spec requirement that only grayscale profiles may appear in images with color type 0 or 4 and that even if the image only contains gray pixels, only RGB profiles may appear in images with color type 2, 3, or 6, is now enforced. The sRGB chunk is allowed to appear in images with any color type.

(source: https://forum.qt.io/topic/58638/solved-libpng-warning-iccp-known-incorrect-srgb-profile-drive-me-nuts/16)

Run / Open VSCode from Mac Terminal

Sometimes, just adding the shell command doesn't work. We need to check whether visual studio code is available in "Applications" folder or not. That was the case for me.

The moment you download VS code, it stays in "Downloads" folder and terminal doesn't pick up from there. So, I manually moved my VS code to "Applications" folder to access from Terminal.

Step 1: Download VS code, which will give a zipped folder.

Step 2: Run it, which will give a exe kinda file in downloads folder.

Step 3: Move it to "Applications" folder manually.

Step 4: Open VS code, "Command+Shift+P" and run the shell command.

Step 5: Restart the terminal.

Step 6: Typing "Code ." on terminal should work now.

How to get records randomly from the oracle database?

SELECT *
FROM   (
    SELECT *
    FROM   table
    ORDER BY DBMS_RANDOM.RANDOM)
WHERE  rownum < 21;

How do I return multiple values from a function in C?

One approach is to use macros. Place this in a header file multitype.h

#include <stdlib.h>

/* ============================= HELPER MACROS ============================= */

/* __typeof__(V) abbreviation */

#define TOF(V) __typeof__(V)

/* Expand variables list to list of typeof and variable names */

#define TO3(_0,_1,_2,_3) TOF(_0) v0; TOF(_1) v1; TOF(_2) v2; TOF(_3) v3;
#define TO2(_0,_1,_2)    TOF(_0) v0; TOF(_1) v1; TOF(_2) v2;
#define TO1(_0,_1)       TOF(_0) v0; TOF(_1) v1;
#define TO0(_0)          TOF(_0) v0;

#define TO_(_0,_1,_2,_3,TO_MACRO,...) TO_MACRO

#define TO(...) TO_(__VA_ARGS__,TO3,TO2,TO1,TO0)(__VA_ARGS__)

/* Assign to multitype */

#define MTA3(_0,_1,_2,_3) _0 = mtr.v0; _1 = mtr.v1; _2 = mtr.v2; _3 = mtr.v3;
#define MTA2(_0,_1,_2)    _0 = mtr.v0; _1 = mtr.v1; _2 = mtr.v2;
#define MTA1(_0,_1)       _0 = mtr.v0; _1 = mtr.v1;
#define MTA0(_0)          _0 = mtr.v0;

#define MTA_(_0,_1,_2,_3,MTA_MACRO,...) MTA_MACRO

#define MTA(...) MTA_(__VA_ARGS__,MTA3,MTA2,MTA1,MTA0)(__VA_ARGS__)

/* Return multitype if multiple arguments, return normally if only one */

#define MTR1(...) {                                                           \
    typedef struct mtr_s {                                                    \
      TO(__VA_ARGS__)                                                         \
    } mtr_t;                                                                  \
    mtr_t *mtr = malloc(sizeof(mtr_t));                                       \
    *mtr = (mtr_t){__VA_ARGS__};                                              \
    return mtr;                                                               \
  }

#define MTR0(_0) return(_0)

#define MTR_(_0,_1,_2,_3,MTR_MACRO,...) MTR_MACRO

/* ============================== API MACROS =============================== */

/* Declare return type before function */

typedef void* multitype;

#define multitype(...) multitype

/* Assign return values to variables */

#define let(...)                                                              \
  for(int mti = 0; !mti;)                                                     \
    for(multitype mt; mti < 2; mti++)                                         \
      if(mti) {                                                               \
        typedef struct mtr_s {                                                \
          TO(__VA_ARGS__)                                                     \
        } mtr_t;                                                              \
        mtr_t mtr = *(mtr_t*)mt;                                              \
        MTA(__VA_ARGS__)                                                      \
        free(mt);                                                             \
      } else                                                                  \
        mt

/* Return */

#define RETURN(...) MTR_(__VA_ARGS__,MTR1,MTR1,MTR1,MTR0)(__VA_ARGS__)

This makes it possible to return up to four variables from a function and assign them to up to four variables. As an example, you can use them like this:

multitype (int,float,double) fun() {
    int a = 55;
    float b = 3.9;
    double c = 24.15;

    RETURN (a,b,c);
}

int main(int argc, char *argv[]) {
    int x;
    float y;
    double z;

    let (x,y,z) = fun();

    printf("(%d, %f, %g\n)", x, y, z);

    return 0;
}

This is what it prints:

(55, 3.9, 24.15)

The solution may not be as portable because it requires C99 or later for variadic macros and for-statement variable declarations. But I think it was interesting enough to post here. Another issue is that the compiler will not warn you if you assign them the wrong values, so you have to be careful.

Additional examples, and a stack-based version of the code using unions, are available at my github repository.

how to make label visible/invisible?

You should be able to get it to hide/show by setting:

.style.display = 'none';
.style.display = 'inline';

Declare a Range relative to the Active Cell with VBA

Like this:

Dim rng as Range
Set rng = ActiveCell.Resize(numRows, numCols)

then read the contents of that range to an array:

Dim arr As Variant
arr = rng.Value
'arr is now a two-dimensional array of size (numRows, numCols)

or, select the range (I don't think that's what you really want, but you ask for this in the question).

rng.Select

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

The normal usage of static is to access the function directly with out any object creation. Same as in java main we could not create any object for that class to invoke the main method. It will execute automatically. If we want to execute manually we can call by using main() inside the class and ClassName.main from outside the class.

How to add an element to the beginning of an OrderedDict?

This is now possible with move_to_end(key, last=True)

>>> d = OrderedDict.fromkeys('abcde')
>>> d.move_to_end('b')
>>> ''.join(d.keys())
'acdeb'
>>> d.move_to_end('b', last=False)
>>> ''.join(d.keys())
'bacde'

https://docs.python.org/3/library/collections.html#collections.OrderedDict.move_to_end

How to launch Windows Scheduler by command-line?

This launches the Scheduled Tasks MMC Control Panel:

%SystemRoot%\system32\taskschd.msc /s

Older versions of windows had a splash screen for the MMC control panel and the /s switch would supress it. It's not needed but doesn't hurt either.

Programmatically close aspx page from code behind

If you using RadAjaxManager then here is the code which helps:

RadAjaxManager1.ResponseScripts.Add("window.opener.location.href = '../CaseManagement/LCCase.aspx?" + caseId + "'; 
window.close();");

How to write a CSS hack for IE 11?

In the light of the evolving thread, I have updated the below:

IE 11 (and above..)

_:-ms-fullscreen, :root .foo { property:value; }

IE 10 and above

_:-ms-lang(x), .foo { property:value; }

or

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .foo{property:value;}
}

IE 10 only

_:-ms-lang(x), .foo { property:value\9; }

IE 9 and above

@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
  //.foo CSS
  .foo{property:value;}
}

IE 9 and 10

@media screen and (min-width:0\0) {
    .foo /* backslash-9 removes.foo & old Safari 4 */
}

IE 9 only

@media screen and (min-width:0\0) and (min-resolution: .001dpcm) { 
 //.foo CSS
 .foo{property:value;}
}

IE 8,9 and 10

@media screen\0 {
    .foo {property:value;}
}

IE 8 Standards Mode Only

.foo { property /*\**/: value\9 }

IE 8

html>/**/body .foo {property:value;}

or

@media \0screen {
    .foo {property:value;}
}

IE 7

*+html .foo {property:value;}

or

*:first-child+html .foo {property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .foo {property:value;}
}

IE 6 and 7

@media screen\9 {
    .foo {property:value;}
}

or

.foo { *property:value;}

or

.foo { #property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .foo {property:value;}
}

IE 6

* html .foo {property:value;}

or

.foo { _property:value;}

Javascript alternatives

Modernizr

Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element

User agent selection

Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Adds (e.g) the below to html element:

data-useragent='Mozilla/5.0 (compatible; M.foo 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Allowing very targetted CSS selectors, e.g.:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Footnote

If possible, identify and fix any issue(s) without hacks. Support progressive enhancement and graceful degradation. However, this is an 'ideal world' scenario not always obtainable, as such- the above should help provide some good options.


Attribution / Essential Reading

Partly JSON unmarshal into a map in Go

Further to Stephen Weinberg's answer, I have since implemented a handy tool called iojson, which helps to populate data to an existing object easily as well as encoding the existing object to a JSON string. A iojson middleware is also provided to work with other middlewares. More examples can be found at https://github.com/junhsieh/iojson

Example:

func main() {
    jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}`

    car := NewCar()

    i := iojson.NewIOJSON()

    if err := i.Decode(strings.NewReader(jsonStr)); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    }

    // populating data to a live car object.
    if v, err := i.GetObjFromArr(0, car); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    } else {
        fmt.Printf("car (original): %s\n", car.GetName())
        fmt.Printf("car (returned): %s\n", v.(*Car).GetName())

        for k, item := range car.ItemArr {
            fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName())
        }

        for k, item := range v.(*Car).ItemArr {
            fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName())
        }
    }
}

Sample output:

car (original): My luxury car
car (returned): My luxury car
ItemArr[0] of car (original): Bag
ItemArr[1] of car (original): Pen
ItemArr[0] of car (returned): Bag
ItemArr[1] of car (returned): Pen

Linux command-line call not returning what it should from os.system?

What gets returned is the return value of executing this command. What you see in while executing it directly is the output of the command in stdout. That 0 is returned means, there was no error in execution.

Use popen etc for capturing the output .

Some thing along this line:

import subprocess as sub
p = sub.Popen(['your command', 'arg1', 'arg2', ...],stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
print output

or

import os
p = os.popen('command',"r")
while 1:
    line = p.readline()
    if not line: break
    print line

ON SO : Popen and python

How can I change the color of AlertDialog title and the color of the line under it

check this is useful for you...

public void setCustomTitle (View customTitleView)

you get detail from following link.

http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setCustomTitle%28android.view.View%29

CustomDialog.java

Dialog alert = new Dialog(this);
    alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
    alert.setContentView(R.layout.title);
    TextView msg = (TextView)alert.findViewById(R.id.textView1);
    msg.setText("Hello Friends.\nIP address : 111.111.1.111");
    alert.show();

title.xml

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

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Set IP address"
    android:textColor="#ff0000"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<ImageView 
    android:layout_width="fill_parent"
    android:layout_height="2dp"
    android:layout_marginTop="5dp"
    android:background="#00ff00"
    />
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#775500"
    android:textAppearance="?android:attr/textAppearanceLarge" />

enter image description here

Reset/remove CSS styles for element only

For those of you trying to figure out how to actually remove the styling from the element only, without removing the css from the files, this solution works with jquery:

$('.selector').removeAttr('style');

How do I use disk caching in Picasso?

I use this code and worked, maybe useful for you:

public static void makeImageRequest(final View parentView,final int id, final String imageUrl) {

    final int defaultImageResId = R.mipmap.user;
    final ImageView imageView = (ImageView) parentView.findViewById(id);
    Picasso.with(context)
            .load(imageUrl)
            .networkPolicy(NetworkPolicy.OFFLINE)
            .into(imageView, new Callback() {
                @Override
                public void onSuccess() {
                Log.v("Picasso","fetch image success in first time.");
                }

                @Override
                public void onError() {
                    //Try again online if cache failed
                    Log.v("Picasso","Could not fetch image in first time...");
                    Picasso.with(context).load(imageUrl).networkPolicy(NetworkPolicy.NO_CACHE)
                            .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).error(defaultImageResId)
                            .into(imageView, new Callback() {

                                @Override
                                public void onSuccess() {
                                    Log.v("Picasso","fetch image success in try again.");
                                }

                                @Override
                                public void onError() {
                                  Log.v("Picasso","Could not fetch image again...");
                                }

                            });
                }
            });

}

Fixing Sublime Text 2 line endings?

The comment states

// Determines what character(s) are used to terminate each line in new files.
// Valid values are 'system' (whatever the OS uses), 'windows' (CRLF) and
// 'unix' (LF only).

You are setting

"default_line_ending": "LF",

You should set

"default_line_ending": "unix",

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

String "true" and "false" to boolean

In Rails 5 you can use ActiveRecord::Type::Boolean.new.cast(value) to cast it to a boolean.

PHP convert XML to JSON

Try to use this

$xml = ... // Xml file data

// first approach
$Json = json_encode(simplexml_load_string($xml));

---------------- OR -----------------------

// second approach
$Json = json_encode(simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA));

echo $Json;

Or

You can use this library : https://github.com/rentpost/xml2array

VBScript -- Using error handling

VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.

On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0

The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

If you are using Laravel 5.x, and the error is from trying to modify the attributes of a column, it is possible the error comes from a missing pre-requisite.

Try this:

 composer require doctrine/dbal

Then try running your migrations.

From here: https://laravel.com/docs/master/migrations#modifying-columns

Proper way to make HTML nested list?

If you validate , option 1 comes up as an error in html 5, so option 2 is correct.

How to query as GROUP BY in django?

Django does not support free group by queries. I learned it in the very bad way. ORM is not designed to support stuff like what you want to do, without using custom SQL. You are limited to:

  • RAW sql (i.e. MyModel.objects.raw())
  • cr.execute sentences (and a hand-made parsing of the result).
  • .annotate() (the group by sentences are performed in the child model for .annotate(), in examples like aggregating lines_count=Count('lines'))).

Over a queryset qs you can call qs.query.group_by = ['field1', 'field2', ...] but it is risky if you don't know what query are you editing and have no guarantee that it will work and not break internals of the QuerySet object. Besides, it is an internal (undocumented) API you should not access directly without risking the code not being anymore compatible with future Django versions.

Adding git branch on the Bash command prompt

I have tried a small script in python that goes in a bin folder.... 'gitprompt' file

#!/usr/bin/env python
import subprocess, os
s = os.path.join(os.getcwd(), '.git')
def cut(cmd):
    ret=''
    half=0
    record = False
    for c in cmd:
        if c == "\n":
            if not (record):
                pass
            else:
                break
        if (record) and c!="\n":
            ret = ret + c
        if c=='*':
            half=0.5
        if c==' ':
            if half == 0.5:
                half = 1
        if half == 1:
            record = True
    return ret
if (os.path.isdir(s)):
    out = subprocess.check_output("git branch",shell=True)
    print cut(out)
else:
    print "-"

Make it executable and stuff

Then adjust the bash prompt accordingly like :

\u:\w--[$(gitprompt)] \$ 

How to shift a column in Pandas DataFrame

I suppose imports

import pandas as pd
import numpy as np

First append new row with NaN, NaN,... at the end of DataFrame (df).

s1 = df.iloc[0]    # copy 1st row to a new Series s1
s1[:] = np.NaN     # set all values to NaN
df2 = df.append(s1, ignore_index=True)  # add s1 to the end of df

It will create new DF df2. Maybe there is more elegant way but this works.

Now you can shift it:

df2.x2 = df2.x2.shift(1)  # shift what you want

Get to UIViewController from UIView?

I stumbled upon a situation where I have a small component I want to reuse, and added some code in a reusable view itself(it's really not much more than a button that opens a PopoverController).

While this works fine in the iPad (the UIPopoverController presents itself, therefor needs no reference to a UIViewController), getting the same code to work means suddenly referencing your presentViewController from your UIViewController. Kinda inconsistent right?

Like mentioned before, it's not the best approach to have logic in your UIView. But it felt really useless to wrap the few lines of code needed in a separate controller.

Either way, here's a swift solution, which adds a new property to any UIView:

extension UIView {

    var viewController: UIViewController? {

        var responder: UIResponder? = self

        while responder != nil {

            if let responder = responder as? UIViewController {
                return responder
            }
            responder = responder?.nextResponder()
        }
        return nil
    }
}

Converting JSON data to Java object

HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
    String key = (String) itr.next();
    keyArrayList.put(key, yourJson.get(key).toString());
}

Is it possible to decrypt SHA1

SHA1 is a one way hash. So you can not really revert it.

That's why applications use it to store the hash of the password and not the password itself.

Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.

Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.

Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.

In his blog he shows a table that tells us the probability of collisions for a given input set.

Hash Collision Probabilities Table

As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.

A simple java program will show us what his table shows:

public class Main {

    public static void main(String[] args) {
        char[] inputValue = new char[10];

        Map<Integer, String> hashValues = new HashMap<Integer, String>();

        int collisionCount = 0;

        for (int i = 0; i < 77163; i++) {
            String asString = nextValue(inputValue);
            int hashCode = asString.hashCode();
            String collisionString = hashValues.put(hashCode, asString);
            if (collisionString != null) {
                collisionCount++;
                System.out.println("Collision: " + asString + " <-> " + collisionString);
            }
        }

        System.out.println("Collision count: " + collisionCount);
    }

    private static String nextValue(char[] inputValue) {
        nextValue(inputValue, 0);

        int endIndex = 0;
        for (int i = 0; i < inputValue.length; i++) {
            if (inputValue[i] == 0) {
                endIndex = i;
                break;
            }
        }

        return new String(inputValue, 0, endIndex);
    }

    private static void nextValue(char[] inputValue, int index) {
        boolean increaseNextIndex = inputValue[index] == 'z';

        if (inputValue[index] == 0 || increaseNextIndex) {
            inputValue[index] = 'A';
        } else {
            inputValue[index] += 1;
        }

        if (increaseNextIndex) {
            nextValue(inputValue, index + 1);
        }

    }

}

My output end with:

Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135

It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A and z.

Let's take the last reported collision and check

System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());

My output is

86390
86390

Conclusion:

If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.

And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.

Including external jar-files in a new jar-file build with Ant

This is a classpath issue when running an executable jar as follows:

java -jar myfile.jar

One way to fix the problem is to set the classpath on the java command line as follows, adding the missing log4j jar:

java -cp myfile.jar:log4j.jar:otherjar.jar com.abc.xyz.MyMainClass

Of course the best solution is to add the classpath into the jar manifest so that the we can use the "-jar" java option:

<jar jarfile="myfile.jar">
    ..
    ..
    <manifest>
       <attribute name="Main-Class" value="com.abc.xyz.MyMainClass"/>
       <attribute name="Class-Path" value="log4j.jar otherjar.jar"/>
    </manifest>
</jar>

The following answer demonstrates how you can use the manifestclasspath to automate the seeting of the classpath manifest entry

Cannot find Main Class in File Compiled With Ant

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

It didn't work for me after Enable Incremental Linking -> "No (/INCREMENTAL:NO)", but it works for me after I deleted the rc file.

How to check whether an array is empty using PHP?

if you are to check the array content you may use:

$arr = array();

if(!empty($arr)){
  echo "not empty";
}
else 
{
  echo "empty";
}

see here: http://codepad.org/EORE4k7v

How do I print a datetime in the local timezone?

Think your should look around: datetime.astimezone()

http://docs.python.org/library/datetime.html#datetime.datetime.astimezone

Also see pytz module - it's quite easy to use -- as example:

eastern = timezone('US/Eastern')

http://pytz.sourceforge.net/

Example:

from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal

utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00

Getting the length of two-dimensional array

Expansion for multi-dimension array total length,

Generally for your case, since the shape of the 2D array is "squared".

int length = nir.length * nir[0].length;

However, for 2D array, each row may not have the exact same number of elements. Therefore we need to traverse through each row, add number of elements up.

int length = 0;
for ( int lvl = 0; lvl < _levels.length; lvl++ )
{
    length += _levels[ lvl ].length;
}

If N-D array, which means we need N-1 for loop to get each row's size.

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

I'll try to explain it visually:

_x000D_
_x000D_
/**_x000D_
 * explaining margins_x000D_
 */_x000D_
_x000D_
body {_x000D_
  padding: 3em 15%_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  width: 50%;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  position: relative;_x000D_
  background: lemonchiffon;_x000D_
}_x000D_
_x000D_
.parent:before,_x000D_
.parent:after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
}_x000D_
_x000D_
.parent:before {_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 50%;_x000D_
  border-left: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.parent:after {_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 50%;_x000D_
  border-top: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background: rgba(200, 198, 133, .5);_x000D_
}_x000D_
_x000D_
ul {_x000D_
  padding: 5% 20px;_x000D_
}_x000D_
_x000D_
.set1 .child {_x000D_
  margin: 0;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.set2 .child {_x000D_
  margin-left: 75px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.set3 .child {_x000D_
  margin-left: -75px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
_x000D_
/* position absolute */_x000D_
_x000D_
.set4 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
.set5 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-left: 75px;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
.set6 .child {_x000D_
  top: 50%; /* level from which margin-top starts _x000D_
 - downwards, in the case of a positive margin_x000D_
 - upwards, in the case of a negative margin _x000D_
 */_x000D_
  left: 50%; /* level from which margin-left starts _x000D_
 - towards right, in the case of a positive margin_x000D_
 - towards left, in the case of a negative margin _x000D_
 */_x000D_
  margin: -75px;_x000D_
  position: absolute;_x000D_
}
_x000D_
<!-- content to be placed inside <body>…</body> -->_x000D_
<h2><code>position: relative;</code></h2>_x000D_
<h3>Set 1</h3>_x000D_
<div class="parent set 1">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set1 .child {_x000D_
  margin: 0;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 2</h3>_x000D_
<div class="parent set2">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set2 .child {_x000D_
  margin-left: 75px;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 3</h3>_x000D_
<div class="parent set3">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set3 .child {_x000D_
  margin-left: -75px;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h2><code>position: absolute;</code></h2>_x000D_
_x000D_
<h3>Set 4</h3>_x000D_
<div class="parent set4">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set4 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 5</h3>_x000D_
<div class="parent set5">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set5 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-left: 75px;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 6</h3>_x000D_
<div class="parent set6">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set6 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: -75px;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to find out line-endings in a text file?

You can use the file utility to give you an indication of the type of line endings.

Unix:

$ file testfile1.txt
testfile.txt: ASCII text

"DOS":

$ file testfile2.txt
testfile2.txt: ASCII text, with CRLF line terminators

To convert from "DOS" to Unix:

$ dos2unix testfile2.txt

To convert from Unix to "DOS":

$ unix2dos testfile1.txt

Converting an already converted file has no effect so it's safe to run blindly (i.e. without testing the format first) although the usual disclaimers apply, as always.

How to detect if user select cancel InputBox VBA Excel

If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...

EDIT to properly differentiate between empty string and cancel, according to this answer.

Your example

Private Sub test()
    Dim result As String
    result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
    If StrPtr(result) = 0 Then
        MsgBox ("User canceled!")
    ElseIf result = vbNullString Then
        MsgBox ("User didn't enter anything!")
    Else
        MsgBox ("User entered " & result)
    End If
End Sub

Would tell the user they canceled when they delete the default string, or they click cancel.

See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

Does Hive have a String split function?

There does exist a split function based on regular expressions. It's not listed in the tutorial, but it is listed on the language manual on the wiki:

split(string str, string pat)
   Split str around pat (pat is a regular expression) 

In your case, the delimiter "|" has a special meaning as a regular expression, so it should be referred to as "\\|".

Calculate distance between two points in google maps V3

OFFLINE SOLUTION - Haversine Algorithm

In Javascript

var _eQuatorialEarthRadius = 6378.1370;
var _d2r = (Math.PI / 180.0);

function HaversineInM(lat1, long1, lat2, long2)
{
    return (1000.0 * HaversineInKM(lat1, long1, lat2, long2));
}

function HaversineInKM(lat1, long1, lat2, long2)
{
    var dlong = (long2 - long1) * _d2r;
    var dlat = (lat2 - lat1) * _d2r;
    var a = Math.pow(Math.sin(dlat / 2.0), 2.0) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r) * Math.pow(Math.sin(dlong / 2.0), 2.0);
    var c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
    var d = _eQuatorialEarthRadius * c;

    return d;
}

var meLat = -33.922982;
var meLong = 151.083853;


var result1 = HaversineInKM(meLat, meLong, -32.236457779983745, 148.69094705162837);
var result2 = HaversineInKM(meLat, meLong, -33.609020205923713, 150.77061469270831);

C#

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");

        var meLat = -33.922982;
        double meLong = 151.083853;


        var result1 = HaversineInM(meLat, meLong, -32.236457779983745, 148.69094705162837);
        var result2 = HaversineInM(meLat, meLong, -33.609020205923713, 150.77061469270831);

        Console.WriteLine(result1);
        Console.WriteLine(result2);
    }

    static double _eQuatorialEarthRadius = 6378.1370D;
    static double _d2r = (Math.PI / 180D);

    private static int HaversineInM(double lat1, double long1, double lat2, double long2)
    {
        return (int)(1000D * HaversineInKM(lat1, long1, lat2, long2));
    }

    private static  double HaversineInKM(double lat1, double long1, double lat2, double long2)
    {
        double dlong = (long2 - long1) * _d2r;
        double dlat = (lat2 - lat1) * _d2r;
        double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
        double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
        double d = _eQuatorialEarthRadius * c;

        return d;
    }
}

Reference: https://en.wikipedia.org/wiki/Great-circle_distance

Trigger change() event when setting <select>'s value with val() function

I separate it, and then use an identity comparison to dictate what is does next.

$("#selectField").change(function(){
  if(this.value === 'textValue1'){ $(".contentClass1").fadeIn(); }
  if(this.value === 'textValue2'){ $(".contentclass2").fadeIn(); }
});

Calling a class method raises a TypeError in Python

To minimally modify your example, you could amend the code to:

class myclass(object):
        def __init__(self): # this method creates the class object.
                pass

        def average(self,a,b,c): #get the average of three numbers
                result=a+b+c
                result=result/3
                return result


mystuff=myclass()  # by default the __init__ method is then called.      
print mystuff.average(a,b,c)

Or to expand it more fully, allowing you to add other methods.

class myclass(object):
        def __init__(self,a,b,c):
                self.a=a
                self.b=b
                self.c=c
        def average(self): #get the average of three numbers
                result=self.a+self.b+self.c
                result=result/3
                return result

a=9
b=18
c=27
mystuff=myclass(a, b, c)        
print mystuff.average()

TypeScript: casting HTMLElement

You always can hack type system using:

var script = (<HTMLScriptElement[]><any>document.getElementsByName(id))[0];

Change application's starting activity

 <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

HTML Input Type Date, Open Calendar by default

This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.

<input type="date" data-date-inline-picker="true" />

Here is a small demo

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

Make a drawable file, striking_text.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="line">
            <stroke android:width="1dp" android:color="@android:color/holo_red_dark" />
        </shape>
    </item>
</selector>

layout xml

 <TextView
            ....
            ....
            android:background="@drawable/striking_text"
            android:foreground="@drawable/striking_text"
            android:text="69$"
           />

If your min SDK below API level 23 just use the background or just put the background and foreground in the Textview then the android studio will show an error that says create a layout file for API >23 after that remove the android:foreground="@drawable/stricking_text" from the main layout

Output look like this: enter image description here

JPA entity without id

See the Java Persistence book: Identity and Sequencing

The relevant part for your question is the No Primary Key section:

Sometimes your object or table has no primary key. The best solution in this case is normally to add a generated id to the object and table. If you do not have this option, sometimes there is a column or set of columns in the table that make up a unique value. You can use this unique set of columns as your id in JPA. The JPA Id does not always have to match the database table primary key constraint, nor is a primary key or a unique constraint required.

If your table truly has no unique columns, then use all of the columns as the id. Typically when this occurs the data is read-only, so even if the table allows duplicate rows with the same values, the objects will be the same anyway, so it does not matter that JPA thinks they are the same object. The issue with allowing updates and deletes is that there is no way to uniquely identify the object's row, so all of the matching rows will be updated or deleted.

If your object does not have an id, but its' table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.

Proper way to set response status and JSON content in a REST API made with nodejs and express

A list of HTTP Status Codes

The good-practice regarding status response is to, predictably, send the proper HTTP status code depending on the error (4xx for client errors, 5xx for server errors), regarding the actual JSON response there's no "bible" but a good idea could be to send (again) the status and data as 2 different properties of the root object in a successful response (this way you are giving the client the chance to capture the status from the HTTP headers and the payload itself) and a 3rd property explaining the error in a human-understandable way in the case of an error.

Stripe's API behaves similarly in the real world.

i.e.

OK

200, {status: 200, data: [...]}

Error

400, {status: 400, data: null, message: "You must send foo and bar to baz..."}

WPF Binding StringFormat Short Date String

Try this:

<TextBlock Text="{Binding PropertyPath, StringFormat=d}" />

which is culture sensitive and requires .NET 3.5 SP1 or above.

NOTE: This is case sensitive. "d" is the short date format specifier while "D" is the long date format specifier.

There's a full list of string format on the MSDN page on Standard Date and Time Format Strings and a fuller explanation of all the options on this MSDN blog post

However, there is one gotcha with this - it always outputs the date in US format unless you set the culture to the correct value yourself.

If you do not set this property, the binding engine uses the Language property of the binding target object. In XAML this defaults to "en-US" or inherits the value from the root element (or any element) of the page, if one has been explicitly set.

Source

One way to do this is in the code behind (assuming you've set the culture of the thread to the correct value):

this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);

The other way is to set the converter culture in the binding:

<TextBlock Text="{Binding PropertyPath, StringFormat=d, ConverterCulture=en-GB}" />

Though this doesn't allow you to localise the output.

What are the most useful Intellij IDEA keyboard shortcuts?

These are some of my most used keyboard short cuts

Syntax aware selection in the editor selects a word at the caret and then selects expanding areas of the source code. For example, it may select a method name, then the expression that calls this method, then the whole statement, then the containing block, etc.: Ctrl+W

Basic Code Completion, to complete methods, keywords etc.: Ctrl+Space

Go to Declaration. Use this to navigate to the declaration of a class, method or variable used somewhere in the code: Ctrl+B

Introduce Variable Refactoring, to create a variable from an expression. This expression may even be incomplete or contain errors. Since version 8, IDEA intelligently selects a likely expression when no text is selected: Ctrl+Alt+V

Go to Class, to quickly open any class in the editor: Ctrl+N

To open any file, not just classes: Ctrl+Shift+N

Comment/Uncomment current line or selection: Ctrl+/ and Ctrl+Shift+/

Quick JavaDoc Popup to show the JavaDoc of the method or class at the text cursor: Ctrl+Q (Ctrl+J on Mac OS X)

Smart Type Completion to complete an expression with a method call or variable with a type suitable in the current Context: Ctrl+Shift+Space

Rename refactoring to rename any identifier. Can look in comments, text files and across different languages too: Shift+F6

Select in Popup to quickly select the currently edited element (class, file, method or field) in any view (Project View, Structure View or other): Alt+F1

Highlight Usages in File. Position the text cursor on any identifier without selecting any text and it will show all places in the file where that variable, method etc. is used. Use it on a throws, try or catch keyword to show all places where the exception is thrown. Use it on the implements keyword to highlight the methods of the implemented interface: Ctrl+Shift+F7

EC2 instance types's exact network performance?

FWIW CloudFront supports streaming as well. Might be better than plain streaming from instances.

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

Simple awk-based function will do the job:

shuffle() { 
    awk 'BEGIN{srand();} {printf "%06d %s\n", rand()*1000000, $0;}' | sort -n | cut -c8-
}

usage:

any_command | shuffle

This should work on almost any UNIX. Tested on Linux, Solaris and HP-UX.

Update:

Note, that leading zeros (%06d) and rand() multiplication makes it to work properly also on systems where sort does not understand numbers. It can be sorted via lexicographical order (a.k.a. normal string compare).

Excel - Sum column if condition is met by checking other column in same table

SUMIF didn't worked for me, had to use SUMIFS.

=SUMIFS(TableAmount,TableMonth,"January")

TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.

Hope this can help someone!

How to compile multiple java source files in command line

Here is another example, for compiling a java file in a nested directory.

I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.

Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'

% mkdir -p temp/classes
% curl --get \
    http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
        --output commons-collections-3.2.2.jar

% javac -g -classpath commons-collections-3.2.2.jar \
     -sourcepath src/main/java -d temp/classes \
      src/main/java/org/gradle/Person.java 

% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
   0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
  69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class

Segmentation fault on large array sizes

You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.

If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

int* array = new int[1000000];

But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to 1000000 elements.

How do I list all tables in a schema in Oracle SQL?

You can query USER_TABLES

select TABLE_NAME from user_tables

Is this very likely to create a memory leak in Tomcat?

The key "Transactional Resources" looks like you are talking to the database without a proper transaction. Make sure transaction management is configured properly and no invocation path to the DAO exists that doesn't run under a @Transactional annotation. This can easily happen when you configured transaction management on the Controller level but are invoking DAOs in a timer or are using @PostConstruct annotations. I wrote it up here http://georgovassilis.blogspot.nl/2014/01/tomcat-spring-and-memory-leaks-when.html

Edit: It looks like this is (also?) a bug with spring-data-jpa which has been fixed with v1.4.3. I looked it up in the spring-data-jpa sources of LockModeRepositoryPostProcessor which sets the "Transactional Resources" key. In 1.4.3 it also clears the key again.

Maven2: Best practice for Enterprise Project (EAR file)

I've been searching high and low for an end-to-end example of a complete maven-based ear-packaged application and finally stumbled upon this. The instructions say to select option 2 when running through the CLI but for your purposes, use option 1.

What is the difference between public, protected, package-private and private in Java?

The official tutorial may be of some use to you.


Class Package Subclass
(same pkg)
Subclass
(diff pkg)
World
public + + + + +
protected + + + +
no modifier + + +
private +

+ : accessible
blank : not accessible

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

How does internationalization work in JavaScript?

Mozilla recently released the awesome L20n or localization 2.0. In their own words L20n is

an open source, localization-specific scripting language used to process gender, plurals, conjugations, and most of the other quirky elements of natural language.

Their js implementation is on the github L20n repository.

Import multiple csv files into pandas and concatenate into one DataFrame

import pandas as pd
import glob

path = r'C:\DRO\DCL_rawdata_files' # use your path
file_path_list = glob.glob(path + "/*.csv")

file_iter = iter(file_path_list)

list_df_csv = []
list_df_csv.append(pd.read_csv(next(file_iter)))

for file in file_iter:
    lsit_df_csv.append(pd.read_csv(file, header=0))
df = pd.concat(lsit_df_csv, ignore_index=True)

Why is this jQuery click function not working?

Try adding $(document).ready(function(){ to the beginning of your script, and then });. Also, does the div have the id in it properly, i.e., as an id, not a class, etc.?

JavaScript blob filename without link

I just wanted to expand on the accepted answer with support for Internet Explorer (most modern versions, anyways), and to tidy up the code using jQuery:

$(document).ready(function() {
    saveFile("Example.txt", "data:attachment/text", "Hello, world.");
});

function saveFile (name, type, data) {
    if (data !== null && navigator.msSaveBlob)
        return navigator.msSaveBlob(new Blob([data], { type: type }), name);
    var a = $("<a style='display: none;'/>");
    var url = window.URL.createObjectURL(new Blob([data], {type: type}));
    a.attr("href", url);
    a.attr("download", name);
    $("body").append(a);
    a[0].click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

Here is an example Fiddle. Godspeed.

Android: Test Push Notification online (Google Cloud Messaging)

Found a very easy way to do this.

Open http://phpfiddle.org/

Paste following php script in box. In php script set API_ACCESS_KEY, set device ids separated by coma.

Press F9 or click Run.

Have fun ;)

<?php


// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );


$registrationIds = array("YOUR DEVICE IDS WILL GO HERE" );

// prep the bundle
$msg = array
(
    'message'       => 'here is a message. message',
    'title'         => 'This is a title. title',
    'subtitle'      => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'              => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;
?>

For FCM, google url would be: https://fcm.googleapis.com/fcm/send

For FCM v1 google url would be: https://fcm.googleapis.com/v1/projects/YOUR_GOOGLE_CONSOLE_PROJECT_ID/messages:send

Note: While creating API Access Key on google developer console, you have to use 0.0.0.0/0 as ip address. (For testing purpose).

In case of receiving invalid Registration response from GCM server, please cross check the validity of your device token. You may check the validity of your device token using following url:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=YOUR_DEVICE_TOKEN

Some response codes:

Following is the description of some response codes you may receive from server.

{ "message_id": "XXXX" } - success
{ "message_id": "XXXX", "registration_id": "XXXX" } - success, device registration id has been changed mainly due to app re-install
{ "error": "Unavailable" } - Server not available, resend the message
{ "error": "InvalidRegistration" } - Invalid device registration Id 
{ "error": "NotRegistered"} - Application was uninstalled from the device

Fade In Fade Out Android Animation in Java

Another alternative:

No need to define 2 animation for fadeIn and fadeOut. fadeOut is reverse of fadeIn.

So you can do this with Animation.REVERSE like this:

AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
view.findViewById(R.id.imageview_logo).startAnimation(alphaAnimation);

then onAnimationEnd:

alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
    @Override
        public void onAnimationStart(Animation animation) {
            //TODO: Run when animation start
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            //TODO: Run when animation end
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            //TODO: Run when animation repeat
        }
    });

HTTPS connection Python

Assuming SSL support is enabled for the socket module.

connection1 = httplib.HTTPSConnection('www.somesecuresite.com')

Calendar Recurring/Repeating Events - Best Storage Method

While the currently accepted answer was a huge help to me, I wanted to share some useful modifications that simplify the queries and also increase performance.


"Simple" Repeat Events

To handle events which recur at regular intervals, such as:

Repeat every other day 

or

Repeat every week on Tuesday 

You should create two tables, one called events like this:

ID    NAME
1     Sample Event
2     Another Event

And a table called events_meta like this:

ID    event_id      repeat_start       repeat_interval
1     1             1369008000         604800            -- Repeats every Monday after May 20th 2013
1     1             1369008000         604800            -- Also repeats every Friday after May 20th 2013

With repeat_start being a unix timestamp date with no time (1369008000 corresponds to May 20th 2013) , and repeat_interval an amount in seconds between intervals (604800 is 7 days).

By looping over each day in the calendar you can get repeat events using this simple query:

SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE  (( 1299736800 - repeat_start) % repeat_interval = 0 )

Just substitute in the unix-timestamp (1299736800) for each date in your calendar.

Note the use of the modulo (% sign). This symbol is like regular division, but returns the ''remainder'' instead of the quotient, and as such is 0 whenever the current date is an exact multiple of the repeat_interval from the repeat_start.

Performance Comparison

This is significantly faster than the previously suggested "meta_keys"-based answer, which was as follows:

SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
RIGHT JOIN `events_meta` EM2 ON EM2.`meta_key` = CONCAT( 'repeat_interval_', EM1.`id` )
WHERE EM1.meta_key = 'repeat_start'
    AND (
        ( CASE ( 1299132000 - EM1.`meta_value` )
            WHEN 0
              THEN 1
            ELSE ( 1299132000 - EM1.`meta_value` )
          END
        ) / EM2.`meta_value`
    ) = 1

If you run EXPLAIN this query, you'll note that it required the use of a join buffer:

+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref              | rows | Extra                          |
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
|  1 | SIMPLE      | EM1   | ALL    | NULL          | NULL    | NULL    | NULL             |    2 | Using where                    |
|  1 | SIMPLE      | EV    | eq_ref | PRIMARY       | PRIMARY | 4       | bcs.EM1.event_id |    1 |                                |
|  1 | SIMPLE      | EM2   | ALL    | NULL          | NULL    | NULL    | NULL             |    2 | Using where; Using join buffer |
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+

The solution with 1 join above requires no such buffer.


"Complex" Patterns

You can add support for more complex types to support these types of repeat rules:

Event A repeats every month on the 3rd of the month starting on March 3, 2011

or

Event A repeats second Friday of the month starting on March 11, 2011

Your events table can look exactly the same:

ID    NAME
1     Sample Event
2     Another Event

Then to add support for these complex rules add columns to events_meta like so:

ID    event_id      repeat_start       repeat_interval    repeat_year    repeat_month    repeat_day    repeat_week    repeat_weekday
1     1             1369008000         604800             NULL           NULL            NULL          NULL           NULL             -- Repeats every Monday after May 20, 2013
1     1             1368144000         604800             NULL           NULL            NULL          NULL           NULL             -- Repeats every Friday after May 10, 2013
2     2             1369008000         NULL               2013           *               *             2              5                -- Repeats on Friday of the 2nd week in every month    

Note that you simply need to either specify a repeat_interval or a set of repeat_year, repeat_month, repeat_day, repeat_week, and repeat_weekday data.

This makes selection of both types simultaneously very simple. Just loop through each day and fill in the correct values, (1370563200 for June 7th 2013, and then the year, month, day, week number and weekday as follows):

SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE  (( 1370563200 - repeat_start) % repeat_interval = 0 )
  OR ( 
    (repeat_year = 2013 OR repeat_year = '*' )
    AND
    (repeat_month = 6 OR repeat_month = '*' )
    AND
    (repeat_day = 7 OR repeat_day = '*' )
    AND
    (repeat_week = 2 OR repeat_week = '*' )
    AND
    (repeat_weekday = 5 OR repeat_weekday = '*' )
    AND repeat_start <= 1370563200
  )

This returns all events that repeat on the Friday of the 2nd week, as well as any events that repeat every Friday, so it returns both event ID 1 and 2:

ID    NAME
1     Sample Event
2     Another Event

*Sidenote in the above SQL I used PHP Date's default weekday indexes, so "5" for Friday


Hope this helps others as much as the original answer helped me!

How to get a MemoryStream from a Stream in .NET?

Use this:

var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);

This will convert Stream to MemoryStream.

C# using streams

Streams are good for dealing with large amounts of data. When it's impractical to load all the data into memory at the same time, you can open it as a stream and work with small chunks of it.

I can't understand why this JAXB IllegalAnnotationException is thrown

This is happening be cause you have 2 classes with same name. For, example, I have 2 SOAP web-services named settings and settings2 both have the same class GetEmployee and this is ambiguous proving the error.

What is the iBeacon Bluetooth Profile

It’s very simple, it just advertises a string which contains a few characters conforming to Apple’s iBeacon standard. you can refer the Link http://glimwormbeacons.com/learn/what-makes-an-ibeacon-an-ibeacon/

In vb.net, how to get the column names from a datatable

You can loop through the columns collection of the datatable.

VB

Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
    Console.WriteLine(column.ColumnName)
Next

C#

DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}

Hope this helps!

Closure in Java 7

Here is Neal Gafter's blog one of the pioneers introducing closures in Java. His post on closures from January 28, 2007 is named A Definition of Closures On his blog there is lots of information to get you started as well as videos. An here is an excellent Google talk - Advanced Topics In Programming Languages - Closures For Java with Neal Gafter, as well.

.attr("disabled", "disabled") issue

Try

$(bla).click(function(){        
  if (something) {
     console.log("A:"+$target.prev("input")) // gives out the right object
     $target.toggleClass("open").prev("input").attr("disabled", "disabled");
  }else{
     console.log("A:"+$target.prev("input")) // any thing from there for a single click?
     $target.toggleClass("open").prev("input").removeAttr("disabled"); //this works
  }
});

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

How can I make all images of different height and width the same via CSS?

Set height and width parameters in CSS file

_x000D_
_x000D_
.ImageStyle{_x000D_
_x000D_
    max-height: 17vw;_x000D_
    min-height: 17vw;_x000D_
    max-width:17vw;_x000D_
    min-width: 17vw;_x000D_
    _x000D_
}
_x000D_
_x000D_
_x000D_

Apache and Node.js on the Same Server

You can use a different approach such as writing a reverse proxy server with nodejs to proxy both apache and all other nodejs apps.

First you need to make apache run on a different port other than port 80. ex: port 8080

Then you can write a reverse proxy script with nodejs as:

var proxy = require('redbird')({port: 80, xfwd: false);

proxy.register("mydomain.me/blog", "http://mydomain.me:8080/blog");
proxy.register("mydomain.me", "http://mydomain.me:3000");

Following article describes the whole process of making this.

RUN APACHE WITH NODE JS REVERSE PROXY – USING REDBIRD

Vue.js img src concatenate variable and text

In another case I'm able to use template literal ES6 with backticks, so for yours could be set as:

<img v-bind:src="`${imgPreUrl()}img/logo.png`">

How to create a Jar file in Netbeans

Please do right click on the project and go to properties. Then go to Build and Packaging. You can see the JAR file location that is produced by defualt setting of netbean in the dist directory.

how to use python2.7 pip instead of default pip

There should be a binary called "pip2.7" installed at some location included within your $PATH variable.

You can find that out by typing

which pip2.7

This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py

Now, you should be all set, and

which pip2.7

should return the correct output.

Get String in YYYYMMDD format from JS date object?

Local time:

var date = new Date();
date = date.toJSON().slice(0, 10);

UTC time:

var date = new Date().toISOString();
date = date.substring(0, 10);

date will print 2020-06-15 today as i write this.

toISOString() method returns the date with the ISO standard which is YYYY-MM-DDTHH:mm:ss.sssZ

The code takes the first 10 characters that we need for a YYYY-MM-DD format.

If you want format without '-' use:

var date = new Date();
date = date.toJSON().slice(0, 10).split`-`.join``;

In .join`` you can add space, dots or whatever you'd like.

Set value of textbox using JQuery

Make sure you have the right selector, and then wait until the page is ready and that the element exists until you run the function.

$(function(){
    $('#searchBar').val('hi')
});

As Derek points out, the ID is wrong as well.

Change to $('#main_search')

Conversion failed when converting the nvarchar value ... to data type int

You are trying to concatenate a string and an integer.
You need to cast @ID as a string.
try:

SET @sql=@sql+' AND Emp_Id_Pk=' + CAST(@ID AS NVARCHAR(10))

Entity Framework : How do you refresh the model when the db changes?

Here:

  1. Delete the Tables from the EDMX designer
  2. Rebuild Project/SLN (this will clear the model class)
  3. Update Model from Database(readd all the tables you want)
  4. Rebuild project/SLN (this will recreate your model class including the new columns)

How do I delete all messages from a single queue using the CLI?

RabbitMQ implements the Advanced Message Queuing Protocol (AMQP) so you can use generic tools for stuff like this.

On Debian/Ubuntu or similar system, do:

sudo apt-get install amqp-tools
amqp-delete-queue -q celery  # where celery is the name of the queue to delete

Detect if an element is visible with jQuery

You're looking for:

.is(':visible')

Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code
}

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.


Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {
    $('#testElement').fadeToggle('fast');
}

How to get number of entries in a Lua table?

There's one way, but it might be disappointing: use an additional variable (or one of the table's field) for storing the count, and increase it every time you make an insertion.

count = 0
tbl = {}

tbl["test"] = 47
count = count + 1

tbl[1] = 48
count = count + 1

print(count)   -- prints "2"

There's no other way, the # operator will only work on array-like tables with consecutive keys.

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

Android activity life cycle - what are all these methods for?

I like this question and the answers to it, but so far there isn't coverage of less frequently used callbacks like onPostCreate() or onPostResume(). Steve Pomeroy has attempted a diagram including these and how they relate to Android's Fragment life cycle, at https://github.com/xxv/android-lifecycle. I revised Steve's large diagram to include only the Activity portion and formatted it for letter size one-page printout. I've posted it as a text PDF at https://github.com/code-read/android-lifecycle/blob/master/AndroidActivityLifecycle1.pdf and below is its image:

Android Activity Lifecycle

Is there a concise way to iterate over a stream with indices in Java 8?

If you are trying to get an index based on a predicate, try this:

If you only care about the first index:

OptionalInt index = IntStream.range(0, list.size())
    .filter(i -> list.get(i) == 3)
    .findFirst();

Or if you want to find multiple indexes:

IntStream.range(0, list.size())
   .filter(i -> list.get(i) == 3)
   .collect(Collectors.toList());

Add .orElse(-1); in case you want to return a value if it doesn't find it.

Python datetime to string without microsecond component

As of Python 3.6+, the best way of doing this is by the new timespec argument for isoformat.

isoformat(timespec='seconds', sep=' ')

Usage:

>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'

How to iterate over the files of a certain directory, in Java?

Here is an example that lists all the files on my desktop. you should change the path variable to your path.

Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.

public static void main(String[] args) {
    File path = new File("c:/documents and settings/Zachary/desktop");

    File [] files = path.listFiles();
    for (int i = 0; i < files.length; i++){
        if (files[i].isFile()){ //this line weeds out other directories/folders
            System.out.println(files[i]);
        }
    }
}

What are database normal forms and can you give examples?

Here's a quick, admittedly butchered response, but in a sentence:

1NF : Your table is organized as an unordered set of data, and there are no repeating columns.

2NF: You don't repeat data in one column of your table because of another column.

3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.

For more detail, see wikipedia...

Convert wchar_t to char

Technically, 'char' could have the same range as either 'signed char' or 'unsigned char'. For the unsigned characters, your range is correct; theoretically, for signed characters, your condition is wrong. In practice, very few compilers will object - and the result will be the same.

Nitpick: the last && in the assert is a syntax error.

Whether the assertion is appropriate depends on whether you can afford to crash when the code gets to the customer, and what you could or should do if the assertion condition is violated but the assertion is not compiled into the code. For debug work, it seems fine, but you might want an active test after it for run-time checking too.

How do malloc() and free() work?

It's hard to say because the actual behaviour is different between different compilers/runtimes. Even debug/release builds have different behaviour. Debug builds of VS2005 will insert markers between allocations to detect memory corruption, so instead of a crash, it will assert in free().

How do I get class name in PHP?

Since PHP 5.5 you can use class name resolution via ClassName::class.

See new features of PHP5.5.

<?php

namespace Name\Space;

class ClassName {}

echo ClassName::class;

?>

If you want to use this feature in your class method use static::class:

<?php

namespace Name\Space;

class ClassName {
   /**
    * @return string
    */
   public function getNameOfClass()
   {
      return static::class;
   }
}

$obj = new ClassName();
echo $obj->getNameOfClass();

?>

For older versions of PHP, you can use get_class().

Unable to specify the compiler with CMake

Never try to set the compiler in the CMakeLists.txt file.

See the CMake FAQ about how to use a different compiler:

https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

(Note that you are attempting method #3 and the FAQ says "(avoid)"...)

We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.

The best method is to set the environment variables CC and CXX before calling CMake for the very first time in a build tree.

After CMake detects what compilers to use, it saves them in the CMakeCache.txt file so that it can still generate proper build systems even if those variables disappear from the environment...

If you ever need to change compilers, you need to start with a fresh build tree.

Kill all processes for a given user

The following kills all the processes created by this user:

kill  -9  -1

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

How do I redirect in expressjs while passing some context?

use app.set & app.get

Setting data

router.get(
  "/facebook/callback",
  passport.authenticate("facebook"),
  (req, res) => {
    req.app.set('user', res.req.user)
    return res.redirect("/sign");
  }
);

Getting data

router.get("/sign", (req, res) => {
  console.log('sign', req.app.get('user'))
});

Switch statement: must default be the last case?

It's valid and very useful in some cases.

Consider the following code:

switch(poll(fds, 1, 1000000)){
   default:
    // here goes the normal case : some events occured
   break;
   case 0:
    // here goes the timeout case
   break;
   case -1:
     // some error occurred, you have to check errno
}

The point is that the above code is more readable and efficient than cascaded if. You could put default at the end, but it is pointless as it will focus your attention on error cases instead of normal cases (which here is the default case).

Actually, it's not such a good example, in poll you know how many events may occur at most. My real point is that there are cases with a defined set of input values where there are 'exceptions' and normal cases. If it's better to put exceptions or normal cases at front is a matter of choice.

In software field I think of another very usual case: recursions with some terminal values. If you can express it using a switch, default will be the usual value that contains recursive call and distinguished elements (individual cases) the terminal values. There is usually no need to focus on terminal values.

Another reason is that the order of the cases may change the compiled code behavior, and that matters for performances. Most compilers will generate compiled assembly code in the same order as the code appears in the switch. That makes the first case very different from the others: all cases except the first one will involve a jump and that will empty processor pipelines. You may understand it like branch predictor defaulting to running the first appearing case in the switch. If a case if much more common that the others then you have very good reasons to put it as the first case.

Reading comments it's the specific reason why the original poster asked that question after reading Intel compiler Branch Loop reorganisation about code optimisation.

Then it will become some arbitration between code readability and code performance. Probably better to put a comment to explain to future reader why a case appears first.

Displaying splash screen for longer than default seconds

In swift 4.0
For Delay of 1 second after default launch time...

RunLoop.current.run(until: Date(timeIntervalSinceNow : 1.0))

Min / Max Validator in Angular 2 Final

In my template driven form (Angular 6) I have the following workaround:

 <div class='col-sm-2 form-group'>
            <label for='amount'>Amount</label>
            <input type='number' 
                   id='amount' 
                   name='amount' 
                   required 
                   [ngModel] = 1
                   [pattern] = "'^[1-9][0-9]*$'"
                   class='form-control' 
                   #amountInput='ngModel'/>
            <span class='text-danger' *ngIf="amountInput.touched && amountInput.invalid">
              <p *ngIf="amountInput.errors?.required">This field is <b>required</b>!</p>
              <p *ngIf="amountInput.errors?.pattern">This minimum amount is <b>1</b>!</p>
            </span>
        </div>

Alot of the above examples make use of directives and custom classes which do scale better in more complex forms, but if your looking for a simple numeric min, utilize pattern as a directive and impose a regex restriction on positive numbers only.

Windows 7: unable to register DLL - Error Code:0X80004005

Open the start menu and type cmd into the search box Hold Ctrl + Shift and press Enter

This runs the Command Prompt in Administrator mode.

Now type regsvr32 MyComobject.dll

Different color for each bar in a bar chart; ChartJS

Solution: call the update method to set new values ??:

var barChartData = {
    labels: ["January", "February", "March"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.5)", 
            strokeColor: "rgba(220,220,220,0.8)", 
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [20, 59, 80]
        }
    ]
};

window.onload = function(){
    var ctx = document.getElementById("mycanvas").getContext("2d");
    window.myObjBar = new Chart(ctx).Bar(barChartData, {
          responsive : true
    });

    //nuevos colores
    myObjBar.datasets[0].bars[0].fillColor = "green"; //bar 1
    myObjBar.datasets[0].bars[1].fillColor = "orange"; //bar 2
    myObjBar.datasets[0].bars[2].fillColor = "red"; //bar 3
    myObjBar.update();
}

How to connect to Oracle 11g database remotely

You will need to run the lsnrctl utility on server A to start the listener. You would then connect from computer B using the following syntax:

sqlplus username/password@hostA:1521 /XE

The port information is optional if the default of 1521 is used.

Listener configuration documentation here. Remote connection documentation here.

Ubuntu: Using curl to download an image

For ones who got permission denied for saving operation, here is the command that worked for me:

$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png --output py.png

file_get_contents behind a proxy?

Depending on how the proxy login works stream_context_set_default might help you.

$context  = stream_context_set_default(
  array(
    'http'=>array(
      'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass')
    )
  )
);
$result = file_get_contents('http://..../...');

You can't specify target table for update in FROM clause

In Mysql, you can not update one table by subquery the same table.

You can separate the query in two parts, or do

 UPDATE TABLE_A AS A
 INNER JOIN TABLE_A AS B ON A.field1 = B.field1
 SET field2 = ? 

Java's L number (long) specification

It seems like these would be good to have because (I assume) if you could specify the number you're typing in is a short then java wouldn't have to cast it

Since the parsing of literals happens at compile time, this is absolutely irrelevant in regard to performance. The only reason having short and byte suffixes would be nice is that it lead to more compact code.

In Python, how do I loop through the dictionary and change the value if it equals something?

Comprehensions are usually faster, and this has the advantage of not editing mydict during the iteration:

mydict = dict((k, v if v else '') for k, v in mydict.items())

How to check Network port access and display useful message?

I improved Salselvaprabu's answer in several ways:

  1. It is now a function - you can put in your powershell profile and use anytime you need
  2. It can accept host as hostname or as ip address
  3. No more exceptions if host or port unavaible - just text

Call it like this:

Test-Port example.com 999
Test-Port 192.168.0.1 80

function Test-Port($hostname, $port)
{
    # This works no matter in which form we get $host - hostname or ip address
    try {
        $ip = [System.Net.Dns]::GetHostAddresses($hostname) | 
            select-object IPAddressToString -expandproperty  IPAddressToString
        if($ip.GetType().Name -eq "Object[]")
        {
            #If we have several ip's for that address, let's take first one
            $ip = $ip[0]
        }
    } catch {
        Write-Host "Possibly $hostname is wrong hostname or IP"
        return
    }
    $t = New-Object Net.Sockets.TcpClient
    # We use Try\Catch to remove exception info from console if we can't connect
    try
    {
        $t.Connect($ip,$port)
    } catch {}

    if($t.Connected)
    {
        $t.Close()
        $msg = "Port $port is operational"
    }
    else
    {
        $msg = "Port $port on $ip is closed, "
        $msg += "You may need to contact your IT team to open it. "                                 
    }
    Write-Host $msg
}

Excel: How to check if a cell is empty with VBA?

You could use IsEmpty() function like this:

...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...

you could also use following:

If ActiveCell.Value = vbNullString Then ...

Bootstrap datepicker hide after selection

Haven't seen this mentioned, but this is what fixed it for me:

switchOnClick: true

Doing HTTP requests FROM Laravel to an external API

Definitively, for any PHP project, you may want to use GuzzleHTTP for sending requests. Guzzle has very nice documentation you can check here. I just want to say that, you probably want to centralize the usage of the Client class of Guzzle in any component of your Laravel project (for example a trait) instead of being creating Client instances on several controllers and components of Laravel (as many articles and replies suggest).

I created a trait you can try to use, which allows you to send requests from any component of your Laravel project, just using it and calling to makeRequest.

namespace App\Traits;
use GuzzleHttp\Client;
trait ConsumesExternalServices
{
    /**
     * Send a request to any service
     * @return string
     */
    public function makeRequest($method, $requestUrl, $queryParams = [], $formParams = [], $headers = [], $hasFile = false)
    {
        $client = new Client([
            'base_uri' => $this->baseUri,
        ]);

        $bodyType = 'form_params';

        if ($hasFile) {
            $bodyType = 'multipart';
            $multipart = [];

            foreach ($formParams as $name => $contents) {
                $multipart[] = [
                    'name' => $name,
                    'contents' => $contents
                ];
            }
        }

        $response = $client->request($method, $requestUrl, [
            'query' => $queryParams,
            $bodyType => $hasFile ? $multipart : $formParams,
            'headers' => $headers,
        ]);

        $response = $response->getBody()->getContents();

        return $response;
    }
}

Notice this trait can even handle files sending.

If you want more details about this trait and some other stuff to integrate this trait to Laravel, check this article. Additionally, if interested in this topic or need major assistance, you can take my course which guides you in the whole process.

I hope it helps all of you.

Best wishes :)

How to test REST API using Chrome's extension "Advanced Rest Client"

With latest ARC for GET request with authentication need to add a raw header named Authorization:authtoken.

Please find the screen shot Get request with authentication and query params

To add Query param click on drop down arrow on left side of URL box.

Are string.Equals() and == operator really same?

There are plenty of descriptive answers here so I'm not going to repeat what has already been said. What I would like to add is the following code demonstrating all the permutations I can think of. The code is quite long due to the number of combinations. Feel free to drop it into MSTest and see the output for yourself (the output is included at the bottom).

This evidence supports Jon Skeet's answer.

Code:

[TestMethod]
public void StringEqualsMethodVsOperator()
{
    string s1 = new StringBuilder("string").ToString();
    string s2 = new StringBuilder("string").ToString();

    Debug.WriteLine("string a = \"string\";");
    Debug.WriteLine("string b = \"string\";");

    TryAllStringComparisons(s1, s2);

    s1 = null;
    s2 = null;

    Debug.WriteLine(string.Join(string.Empty, Enumerable.Repeat("-", 20)));
    Debug.WriteLine(string.Empty);
    Debug.WriteLine("string a = null;");
    Debug.WriteLine("string b = null;");

    TryAllStringComparisons(s1, s2);
}
private void TryAllStringComparisons(string s1, string s2)
{
    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- string.Equals --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => string.Equals(a, b), s1, s2);
    Try((a, b) => string.Equals((object)a, b), s1, s2);
    Try((a, b) => string.Equals(a, (object)b), s1, s2);
    Try((a, b) => string.Equals((object)a, (object)b), s1, s2);

    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- object.Equals --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => object.Equals(a, b), s1, s2);
    Try((a, b) => object.Equals((object)a, b), s1, s2);
    Try((a, b) => object.Equals(a, (object)b), s1, s2);
    Try((a, b) => object.Equals((object)a, (object)b), s1, s2);

    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- a.Equals(b) --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => a.Equals(b), s1, s2);
    Try((a, b) => a.Equals((object)b), s1, s2);
    Try((a, b) => ((object)a).Equals(b), s1, s2);
    Try((a, b) => ((object)a).Equals((object)b), s1, s2);

    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- a == b --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => a == b, s1, s2);
#pragma warning disable 252
    Try((a, b) => (object)a == b, s1, s2);
#pragma warning restore 252
#pragma warning disable 253
    Try((a, b) => a == (object)b, s1, s2);
#pragma warning restore 253
    Try((a, b) => (object)a == (object)b, s1, s2);
}
public void Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, T1 in1, T2 in2)
{
    T3 out1;

    Try(tryFunc, e => { }, in1, in2, out out1);
}
public bool Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, Action<Exception> catchFunc, T1 in1, T2 in2, out T3 out1)
{
    bool success = true;
    out1 = default(T3);

    try
    {
        out1 = tryFunc.Compile()(in1, in2);
        Debug.WriteLine("{0}: {1}", tryFunc.Body.ToString(), out1);
    }
    catch (Exception ex)
    {
        Debug.WriteLine("{0}: {1} - {2}", tryFunc.Body.ToString(), ex.GetType().ToString(), ex.Message);
        success = false;
        catchFunc(ex);
    }

    return success;
}

Output:

string a = "string";
string b = "string";

-- string.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- object.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- a.Equals(b) --

a.Equals(b): True
a.Equals(Convert(b)): True
Convert(a).Equals(b): True
Convert(a).Equals(Convert(b)): True

-- a == b --

(a == b): True
(Convert(a) == b): False
(a == Convert(b)): False
(Convert(a) == Convert(b)): False
--------------------

string a = null;
string b = null;

-- string.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- object.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- a.Equals(b) --

a.Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
a.Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.

-- a == b --

(a == b): True
(Convert(a) == b): True
(a == Convert(b)): True
(Convert(a) == Convert(b)): True

How do I check if a given string is a legal/valid file name under Windows?

I use this to get rid of invalid characters in filenames without throwing exceptions:

private static readonly Regex InvalidFileRegex = new Regex(
    string.Format("[{0}]", Regex.Escape(@"<>:""/\|?*")));

public static string SanitizeFileName(string fileName)
{
    return InvalidFileRegex.Replace(fileName, string.Empty);
}

MySQL Multiple Where Clause

select unique red24.image_id from 
( 
    select image_id from `list` where style_id = 24 and style_value = 'red' 
) red24
inner join 
( 
    select image_id from `list` where style_id = 25 and style_value = 'big' 
) big25
on red24.image_id = big25.image_id
inner join 
( 
    select image_id from `list` where style_id = 27 and style_value = 'round' 
) round27
on red24.image_id = round27.image_id

When should I really use noexcept?

  1. There are many examples of functions that I know will never throw, but for which the compiler cannot determine so on its own. Should I append noexcept to the function declaration in all such cases?

noexcept is tricky, as it is part of the functions interface. Especially, if you are writing a library, your client code can depend on the noexcept property. It can be difficult to change it later, as you might break existing code. That might be less of a concern when you are implementing code that is only used by your application.

If you have a function that cannot throw, ask yourself whether it will like stay noexcept or would that restrict future implementations? For example, you might want to introduce error checking of illegal arguments by throwing exceptions (e.g., for unit tests), or you might depend on other library code that could change its exception specification. In that case, it is safer to be conservative and omit noexcept.

On the other hand, if you are confident that the function should never throw and it is correct that it is part of the specification, you should declare it noexcept. However, keep in mind that the compiler will not be able to detect violations of noexcept if your implementation changes.

  1. For which situations should I be more careful about the use of noexcept, and for which situations can I get away with the implied noexcept(false)?

There are four classes of functions that should you should concentrate on because they will likely have the biggest impact:

  1. move operations (move assignment operator and move constructors)
  2. swap operations
  3. memory deallocators (operator delete, operator delete[])
  4. destructors (though these are implicitly noexcept(true) unless you make them noexcept(false))

These functions should generally be noexcept, and it is most likely that library implementations can make use of the noexcept property. For example, std::vector can use non-throwing move operations without sacrificing strong exception guarantees. Otherwise, it will have to fall back to copying elements (as it did in C++98).

This kind of optimization is on the algorithmic level and does not rely on compiler optimizations. It can have a significant impact, especially if the elements are expensive to copy.

  1. When can I realistically expect to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.

The advantage of noexcept against no exception specification or throw() is that the standard allows the compilers more freedom when it comes to stack unwinding. Even in the throw() case, the compiler has to completely unwind the stack (and it has to do it in the exact reverse order of the object constructions).

In the noexcept case, on the other hand, it is not required to do that. There is no requirement that the stack has to be unwound (but the compiler is still allowed to do it). That freedom allows further code optimization as it lowers the overhead of always being able to unwind the stack.

The related question about noexcept, stack unwinding and performance goes into more details about the overhead when stack unwinding is required.

I also recommend Scott Meyers book "Effective Modern C++", "Item 14: Declare functions noexcept if they won't emit exceptions" for further reading.

In Node.js, how do I "include" functions from my other files?

Another method when using node.js and express.js framework

var f1 = function(){
   console.log("f1");
}
var f2 = function(){
   console.log("f2");
}

module.exports = {
   f1 : f1,
   f2 : f2
}

store this in a js file named s and in the folder statics

Now to use the function

var s = require('../statics/s');
s.f1();
s.f2();

How do I "select Android SDK" in Android Studio?

The comment from @Nisarg helped: "set latest version in Compile Sdk Version"

I changed from API 8 to API 23 and the error message disappeared.

Open source face recognition for Android

Here are some links that I found on face recognition libraries.

Image Identification links:

powershell mouse move does not prevent idle mode

I had a similar situation where a download needed to stay active overnight and required a key press that refreshed my connection. I also found that the mouse move does not work. However, using notepad and a send key function appears to have done the trick. I send a space instead of a "." because if there is a [yes/no] popup, it will automatically click the default response using the spacebar. Here is the code used.

param($minutes = 120)

$myShell = New-Object -com "Wscript.Shell"

for ($i = 0; $i -lt $minutes; $i++) {
  Start-Sleep -Seconds 30
  $myShell.sendkeys(" ")
}

This function will work for the designated 120 minutes (2 Hours), but can be modified for the timing desired by increasing or decreasing the seconds of the input, or increasing or decreasing the assigned value of the minutes parameter.

Just run the script in powershell ISE, or powershell, and open notepad. A space will be input at the specified interval for the desired length of time ($minutes).

Good Luck!

PHP fwrite new line

fwrite($handle, "<br>"."\r\n");

Add this under

$password = $_POST['password'].PHP_EOL;

this. .

Loading DLLs at runtime in C#

Activator.CreateInstance() returns an object, which doesn't have an Output method.

It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.

Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?

If you absolutely want to load the assembly via Assembly.Load, you will have to go via reflection to call any members on c

Something like type.GetMethod("Output").Invoke(c, null); should do it.

how to read a long multiline string line by line in python

This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines() is the way to go. I will leave this answer nevertheless as reference.

Old (incorrect) answer:

s =  \
"""line1
line2
line3
"""

lines = s.split('\n')
print(lines)
for line in lines:
    print(line)

How do I filter an array with TypeScript in Angular 2?

To filter an array irrespective of the property type (i.e. for all property types), we can create a custom filter pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: "filter" })
export class ManualFilterPipe implements PipeTransform {
  transform(itemList: any, searchKeyword: string) {
    if (!itemList)
      return [];
    if (!searchKeyword)
      return itemList;
    let filteredList = [];
    if (itemList.length > 0) {
      searchKeyword = searchKeyword.toLowerCase();
      itemList.forEach(item => {
        //Object.values(item) => gives the list of all the property values of the 'item' object
        let propValueList = Object.values(item);
        for(let i=0;i<propValueList.length;i++)
        {
          if (propValueList[i]) {
            if (propValueList[i].toString().toLowerCase().indexOf(searchKeyword) > -1)
            {
              filteredList.push(item);
              break;
            }
          }
        }
      });
    }
    return filteredList;
  }
}

//Usage

//<tr *ngFor="let company of companyList | filter: searchKeyword"></tr>

Don't forget to import the pipe in the app module

We might need to customize the logic to filer with dates.

Virtualenv Command Not Found

this works in ubuntu 18 and above (not tested in previous versions):

sudo apt install python3-virtualenv

How do you check if a string is not equal to an object or other string value in java?

Change your code to:

System.out.println("AM or PM?"); 
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

...

if(Hours == 13){
    if (TimeOfDayStringQ.equals("AM")) {
        TimeOfDayStringQ = "PM"; // <--
    } else {
        TimeOfDayStringQ = "AM"; // <--
    }
            Hours = 1;
    }
 }

SQL query to find third highest salary in company

I found a very good explanation in

http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/

This query should give nth highest salary

SELECT *
FROM Employee Emp1
WHERE (N-1) = (
    SELECT COUNT(DISTINCT(Emp2.Salary))
    FROM Employee Emp2
    WHERE Emp2.Salary > Emp1.Salary)

How to validate array in Laravel?

Asterisk symbol (*) is used to check values in the array, not the array itself.

$validator = Validator::make($request->all(), [
    "names"    => "required|array|min:3",
    "names.*"  => "required|string|distinct|min:3",
]);

In the example above:

  • "names" must be an array with at least 3 elements,
  • values in the "names" array must be distinct (unique) strings, at least 3 characters long.

EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:

$data = $request->validate([
    "name"    => "required|array|min:3",
    "name.*"  => "required|string|distinct|min:3",
]);

Database, Table and Column Naming Conventions?

I work in a database support team with three DBAs and our considered options are:

  1. Any naming standard is better than no standard.
  2. There is no "one true" standard, we all have our preferences
  3. If there is standard already in place, use it. Don't create another standard or muddy the existing standards.

We use singular names for tables. Tables tend to be prefixed with the name of the system (or its acronym). This is useful if the system complex as you can change the prefix to group the tables together logically (ie. reg_customer, reg_booking and regadmin_limits).

For fields we'd expect field names to be include the prefix/acryonm of the table (i.e. cust_address1) and we also prefer the use of a standard set of suffixes ( _id for the PK, _cd for "code", _nm for "name", _nb for "number", _dt for "Date").

The name of the Foriegn key field should be the same as the Primary key field.

i.e.

SELECT cust_nm, cust_add1, booking_dt
FROM reg_customer
INNER JOIN reg_booking
ON reg_customer.cust_id = reg_booking.cust_id

When developing a new project, I'd recommend you write out all the preferred entity names, prefixes and acronyms and give this document to your developers. Then, when they decide to create a new table, they can refer to the document rather than "guess" what the table and fields should be called.

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

In my case I was using Jade and I was using HTTP repository URL. Changing the Url to HTTPS worked for me.

Is it possible to reference one CSS rule within another?

I had this problem yesterday. @Quentin's answer is ok:

No, you cannot reference one rule-set from another.

but I made a javascript function to simulate inheritance in css (like .Net):

_x000D_
_x000D_
    var inherit_array;_x000D_
    var inherit;_x000D_
    inherit_array = [];_x000D_
    Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {_x000D_
        Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {_x000D_
            if (cssRule_i.style != null) {_x000D_
                inherit = cssRule_i.style.getPropertyValue("--inherits").trim();_x000D_
            } else {_x000D_
                inherit = "";_x000D_
            }_x000D_
            if (inherit != "") {_x000D_
                inherit_array.push({ selector: cssRule_i.selectorText, inherit: inherit });_x000D_
            }_x000D_
        });_x000D_
    });_x000D_
    Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {_x000D_
        Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {_x000D_
            if (cssRule_i.selectorText != null) {_x000D_
                inherit_array.forEach(function (inherit_i, index) {_x000D_
                    if (cssRule_i.selectorText.split(", ").includesMember(inherit_i.inherit.split(", ")) == true) {_x000D_
                        cssRule_i.selectorText = cssRule_i.selectorText + ", " + inherit_i.selector;_x000D_
                    }_x000D_
                });_x000D_
            }_x000D_
        });_x000D_
    });
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
Array.prototype.includesMember = function (arr2) {_x000D_
    var arr1;_x000D_
    var includes;_x000D_
    arr1 = this;_x000D_
    includes = false;_x000D_
    arr1.forEach(function (arr1_i, index) {_x000D_
        if (arr2.includes(arr1_i) == true) {_x000D_
            includes = true;_x000D_
        }_x000D_
    });_x000D_
    return includes;_x000D_
}
_x000D_
_x000D_
_x000D_

and equivalent css:

_x000D_
_x000D_
.test {_x000D_
    background-color: yellow;_x000D_
}_x000D_
_x000D_
.productBox, .imageBox {_x000D_
    --inherits: .test;_x000D_
    display: inline-block;_x000D_
}
_x000D_
_x000D_
_x000D_

and equivalent HTML :

_x000D_
_x000D_
<div class="imageBox"></div>
_x000D_
_x000D_
_x000D_

I tested it and worked for me, even if rules are in different css files.

Update: I found a bug in hierarchichal inheritance in this solution, and am solving the bug very soon .

MySQL check if a table exists without throwing an exception

Zend framework

public function verifyTablesExists($tablesName)
    {
        $db = $this->getDefaultAdapter();
        $config_db = $db->getConfig();

        $sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}'  AND table_name = '{$tablesName}'";

        $result = $db->fetchRow($sql);
        return $result;

    }

Python Git Module experiences?

PTBNL's Answer is quite perfect for me. I make a little more for Windows user.

import time
import subprocess
def gitAdd(fileName, repoDir):
    cmd = 'git add ' + fileName
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    print out,error
    pipe.wait()
    return 

def gitCommit(commitMessage, repoDir):
    cmd = 'git commit -am "%s"'%commitMessage
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    print out,error
    pipe.wait()
    return 
def gitPush(repoDir):
    cmd = 'git push '
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    pipe.wait()
    return 

temp=time.localtime(time.time())
uploaddate= str(temp[0])+'_'+str(temp[1])+'_'+str(temp[2])+'_'+str(temp[3])+'_'+str(temp[4])

repoDir='d:\\c_Billy\\vfat\\Programming\\Projector\\billyccm' # your git repository , windows your need to use double backslash for right directory.
gitAdd('.',repoDir )
gitCommit(uploaddate, repoDir)
gitPush(repoDir)

Best way to define private methods for a class in Objective-C

You could use blocks?

@implementation MyClass

id (^createTheObject)() = ^(){ return [[NSObject alloc] init];};

NSInteger (^addEm)(NSInteger, NSInteger) =
^(NSInteger a, NSInteger b)
{
    return a + b;
};

//public methods, etc.

- (NSObject) thePublicOne
{
    return createTheObject();
}

@end

I'm aware this is an old question, but it's one of the first I found when I was looking for an answer to this very question. I haven't seen this solution discussed anywhere else, so let me know if there's something foolish about doing this.

How can I change the width and height of slides on Slick Carousel?

Basically you need to edit the JS and add (in this case, inside $('#featured-articles').slick({ ), this:

variableWidth: true,

This will allow you to edit the width in your CSS where you can, generically use:

.slick-slide {
    width: 100%;
}

or in this case:

.featured {
    width: 100%;
}

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

Post multipart request with Android SDK

For posterity, I didn't see okhttp mentioned. Related post.

Basically you build up the body using a MultipartBody.Builder, and then post this in a request.

Example in kotlin:

    val body = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file", 
                file.getName(),
                RequestBody.create(MediaType.parse("image/png"), file)
            )
            .addFormDataPart("timestamp", Date().time.toString())
            .build()

    val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

    httpClient.newCall(request).enqueue(object : okhttp3.Callback {
        override fun onFailure(call: Call?, e: IOException?) {
            ...
        }

        override fun onResponse(call: Call?, response: Response?) {
            ...
        }
    })

Best way to compare dates in Android

Update: The Joda-Time library is now in maintenance-mode, and recommends migrating to the java.time framework that succeeds it. See the Answer by Ole V.V..


Joda-Time

The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.

LocalDate

If you want date-only without time-of-day, then use the LocalDate class.

Time Zone

Getting the current date depends on the time zone. A new date rolls over in Paris before Montréal. Specify the desired time zone rather than depend on the JVM's default.

Example in Joda-Time 2.3.

DateTimeFormat formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( "1/1/1990" );
boolean outdated = LocalDate.now( DateTimeZone.UTC ).isAfter( localDate );

How to retrieve a module's path?

Command Line Utility

You can tweak it to a command line utility,

python-which <package name>

enter image description here


Create /usr/local/bin/python-which

#!/usr/bin/env python

import importlib
import os
import sys

args = sys.argv[1:]
if len(args) > 0:
    module = importlib.import_module(args[0])
    print os.path.dirname(module.__file__)

Make it executable

sudo chmod +x /usr/local/bin/python-which

socket.error:[errno 99] cannot assign requested address and namespace in python

when you bind localhost or 127.0.0.1, it means you can only connect to your service from local.

you cannot bind 10.0.0.1 because it not belong to you, you can only bind ip owned by your computer

you can bind 0.0.0.0 because it means all ip on your computer, so any ip can connect to your service if they can connect to any of your ip

How to increment variable under DOS?

Directly from the command line:

 for /L %n in (1,1,100) do @echo %n

Using a batch file:

 @echo off
 for /L %%n in (1,1,100) do echo %%n

Displays:

 1
 2
 3
 ...
 100

Using Predicate in Swift

In swift 2.2

func filterContentForSearchText(searchText: String, scope: String) {
    var resultPredicate = NSPredicate(format: "name contains[c]         %@", searchText)
    searchResults = (recipes as NSArray).filteredArrayUsingPredicate(resultPredicate)
}

In swift 3.0

func filterContent(forSearchText searchText: String, scope: String) {
        var resultPredicate = NSPredicate(format: "name contains[c]         %@", searchText)
        searchResults = recipes.filtered(using: resultPredicate)
    }

Java how to sort a Linked List?

You can do it by Java 8 lambda expression :

LinkedList<String> list=new LinkedList<String>();
list.add("bgh");
list.add("asd");
list.add("new");
//lambda expression
list.sort((a,b)->a.compareTo(b));

MySQL query to select events between start/end date

If you would like to use INTERSECT option, the SQL is as follows

(SELECT id FROM events WHERE start BETWEEN '2013-06-13' AND '2013-07-22') 
INTERSECT
(SELECT id FROM events WHERE end BETWEEN '2013-06-13' AND '2013-07-22') 

How to dynamically update labels captions in VBA form?

Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

How to store arbitrary data for some HTML tags

In html, we can store custom attributes with the prefix 'data-' before the attribute name like

<p data-animal='dog'>This animal is a dog.</p>. Check documentation

We can use this property to dynamically set and get attributes using jQuery like: If we have a p tag like

<p id='animal'>This animal is a dog.</p>

Then to create an attribute called 'breed' for the above tag, we can write:

$('#animal').attr('data-breed', 'pug');

To retrieve the data anytime, we can write:

var breedtype = $('#animal').data('breed');

How to scan multiple paths using the @ComponentScan annotation?

You use ComponentScan to scan multiple packages using

@ComponentScan({"com.my.package.first","com.my.package.second"})

git revert back to certain commit

You can revert all your files under your working directory and index by typing following this command

git reset --hard <SHAsum of your commit>

You can also type

git reset --hard HEAD #your current head point

or

git reset --hard HEAD^ #your previous head point

Hope it helps

Changing directory in Google colab (breaking out of the python interpreter)

If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate

.

!ls    # to find the directory you're in ,
%cd ./samplefolder  #if you wanna go into a folder (say samplefolder)

or if you wanna go out of the current folder

%cd ../      

and then navigate to the required folder/file accordingly

Drop default constraint on a column in TSQL

I would like to refer a previous question, Because I have faced same problem and solved by this solution. First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from 
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where 
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.

How to grant remote access to MySQL for a whole subnet?

Motivated by @Malvineaus answer I tried it myself and noticed that it didn't work for me.

You can specify subnet masks with '192.168.1.%' or '192.168.1.0/255.255.255.0' but the subnet must always be on complete octets. see https://mariadb.com/kb/en/create-user/#host-name-component. As result the functionality between one way of specification and the other is the same.

For example '192.168.1.0/255.255.255.128' will not work as it is not on a complete octet boundary.

How to use timeit module

You would create two functions and then run something similar to this. Notice, you want to choose the same number of execution/run to compare apple to apple.
This was tested under Python 3.7.

enter image description here Here is the code for ease of copying it

!/usr/local/bin/python3
import timeit

def fibonacci(n):
    """
    Returns the n-th Fibonacci number.
    """
    if(n == 0):
        result = 0
    elif(n == 1):
        result = 1
    else:
        result = fibonacci(n-1) + fibonacci(n-2)
    return result

if __name__ == '__main__':
    import timeit
    t1 = timeit.Timer("fibonacci(13)", "from __main__ import fibonacci")
    print("fibonacci ran:",t1.timeit(number=1000), "milliseconds")

python request with authentication (access_token)

I had the same problem when trying to use a token with Github.

The only syntax that has worked for me with Python 3 is:

import requests

myToken = '<token>'
myUrl = '<website>'
head = {'Authorization': 'token {}'.format(myToken)}
response = requests.get(myUrl, headers=head)

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

Use data type 'MultilineText':

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

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

How to draw lines in Java

To give you some idea:

public void paint(Graphics g) {
   drawCoordinates(g);
}

private void drawCoordinates(Graphics g) {

  // get width & height here (w,h)

  // define grid width (dh, dv)

  for (int x = 0; i < w; i += dh) {
    g.drawLine(x, 0, x, h);
  }
  for (int y = 0; j < h; j += dv) {
      g.drawLine(0, y, w, y);
  }
}

Checkbox angular material checked by default

You need to make sure the checked property to be true inside the component.ts

export class CheckboxComponent implements OnInit {
 checked = true;
}

How to call a method in another class of the same package?

From the Notes of Fred Swartz (fredosaurus) :

There are two types of methods.

  • Instance methods are associated with an object and use the instance variables of that object. This is the default.

  • Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined Math class.

Qualifying a static call

From outside the defining class, an instance method is called by prefixing it with an object, which is then passed as an implicit parameter to the instance method, eg, inputTF.setText("");

A static method is called by prefixing it with a class name, eg, Math.max(i,j);. Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.

Example

Here is a typical static method:

class MyUtils {
    . . .
    //================================================= mean
    public static double mean(int[] p) {
        int sum = 0;  // sum of all the elements
        for (int i=0; i<p.length; i++) {
            sum += p[i];
        }
        return ((double)sum) / p.length;
    }//endmethod mean
    . . .
}

The only data this method uses or changes is from parameters (or local variables of course).

Why declare a method static

The above mean() method would work just as well if it wasn't declared static, as long as it was called from within the same class. If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly) with an object. Even when used within the class, there are good reasons to define a method as static when it could be.

  • Documentation. Anyone seeing that a method is static will know how to call it (see below). Similarly, any programmer looking at the code will know that a static method can't interact with instance variables, which makes reading and debugging easier.
  • Efficiency. A compiler will usually produce slightly more efficient code because no implicit object parameter has to be passed to the method.

Calling static methods

There are two cases.

Called from within the same class

Just write the static method name. Eg:

// Called from inside the MyUtils class
double avgAtt = mean(attendance);

Called from outside the class

If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. Eg:

// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance); 

If an object is specified before it, the object value will be ignored and the the class of the object will be used.

Accessing static variables

Altho a static method can't access instance variables, it can access static variables. A common use of static variables is to define "constants". Examples from the Java library are Math.PI or Color.RED. They are qualified with the class name, so you know they are static. Any method, static or not, can access static variables. Instance variables can be accessed only by instance methods.

Alternate Call

What's a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case.

Convert Text to Uppercase while typing in Text box

set your CssClass property in textbox1 to "cupper", then in page content create new css class :

<style type="text/css">.cupper {text-transform:uppercase;}</style>

Then, enjoy it ...

How to fill Matrix with zeros in OpenCV?

I presume you are talking about filling zeros of some existing mat? How about this? :)

mat *= 0;

Android Fragment onAttach() deprecated

Currently from the onAttach Fragment code, it is not clear if the Context is the current activity: Source Code

public void onAttach(Context context) {
    mCalled = true;
    final Activity hostActivity = mHost == null ? null : mHost.getActivity();
    if (hostActivity != null) {
        mCalled = false;
        onAttach(hostActivity);
    }
}

If you will take a look at getActivity you will see the same call

/**
 * Return the Activity this fragment is currently associated with.
 */
final public Activity getActivity() {
    return mHost == null ? null : mHost.getActivity();
}

So If you want to be sure that you are getting the Activity then use getActivity() (in onAttach in your Fragment) but don't forget to check for null because if mHost is null your activity will be null

C# Set collection?

If you're using .NET 3.5, you can use HashSet<T>. It's true that .NET doesn't cater for sets as well as Java does though.

The Wintellect PowerCollections may help too.