Programs & Examples On #Boost filesystem

The Boost.Filesystem library provides facilities to manipulate files and directories, and the paths that identify them.

Rounding a double to turn it into an int (java)

If you don't like Math.round() you can use this simple approach as well:

int a = (int) (doubleVar + 0.5);

Why am I getting a " Traceback (most recent call last):" error?

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

TypeError: 'int' object is not callable

My code for Python 3 is as follows:

# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error

raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: {M_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: {F_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: {G_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: {inches_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    # Printing error in the line below
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

I hope this helps.

Symfony 2 EntityManager injection in service

Your class's constructor method should be called __construct(), not __constructor():

public function __construct(EntityManager $entityManager)
{
    $this->em = $entityManager;
}

Array to String PHP?

The implode() function returns a string from the elements of an array.

<?php
    $arr = array('Hello','World!','Beautiful','Day!');
    echo implode(" ",$arr);
?>

Output: Hello World! Beautiful Day!

<?php
    $arr = array('Hello','World!','Beautiful','Day!');
    echo implode("|",$arr);
?>

Output: Hello|World!|Beautiful|Day!

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')

...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

Alt + Shift + F10 will show the menu associated with the smart tag.

How to parse/format dates with LocalDateTime? (Java 8)

Parsing a string with date and time into a particular point in time (Java calls it an "Instant") is quite complicated. Java has been tackling this in several iterations. The latest one, java.time and java.time.chrono, covers almost all needs (except Time Dilation :) ).

However, that complexity brings a lot of confusion.

The key to understand date parsing is:

Why does Java have so many ways to parse a date

  1. There are several systems to measure a time. For instance, the historical Japanese calendars were derived from the time ranges of the reign of the respective emperor or dynasty. Then there is e.g. UNIX timestamp. Fortunately, the whole (business) world managed to use the same.
  2. Historically, the systems were being switched from/to, for various reasons. E.g. from Julian calendar to Gregorian calendar in 1582. So 'western' dates before that need to be treated differently.
  3. And of course the change did not happen at once. Because the calendar came from the headquarteds of some religion and other parts of Europe believed in other dieties, for instance Germany did not switch until the year 1700.

...and why is the LocalDateTime, ZonedDateTime et al. so complicated

  1. There are time zones. A time zone is basically a "stripe"*[1] of the Earth's surface whose authorities follow the same rules of when does it have which time offset. This includes summer time rules.
    The time zones change over time for various areas, mostly based on who conquers whom. And one time zone's rules change over time as well.

  2. There are time offsets. That is not the same as time zones, because a time zone may be e.g. "Prague", but that has summer time offset and winter time offset.
    If you get a timestamp with a time zone, the offset may vary, depending on what part of the year it is in. During the leap hour, the timestamp may mean 2 different times, so without additional information, it can't be reliably converted.
    Note: By timestamp I mean "a string that contains a date and/or time, optionally with a time zone and/or time offset."

  3. Several time zones may share the same time offset for certain periods. For instance, GMT/UTC time zone is the same as "London" time zone when the summer time offset is not in effect.

To make it a bit more complicated (but that's not too important for your use case) :

  1. The scientists observe Earth's dynamic, which changes over time; based on that, they add seconds at the end of individual years. (So 2040-12-31 24:00:00 may be a valid date-time.) This needs regular updates of the metadata that systems use to have the date conversions right. E.g. on Linux, you get regular updates to the Java packages including these new data.
  2. The updates do not always keep the previous behavior for both historical and future timestamps. So it may happen that parsing of the two timestamps around some time zone's change comparing them may give different results when running on different versions of the software. That also applies to comparing between the affected time zone and other time zone.

    Should this cause a bug in your software, consider using some timestamp that does not have such complicated rules, like UNIX timestamp.

  3. Because of 7, for the future dates, we can't convert dates exactly with certainty. So, for instance, current parsing of 8524-02-17 12:00:00 may be off a couple of seconds from the future parsing.

JDK's APIs for this evolved with the contemporary needs

  • The early Java releases had just java.util.Date which had a bit naive approach, assuming that there's just the year, month, day, and time. This quickly did not suffice.
  • Also, the needs of the databases were different, so quite early, java.sql.Date was introduced, with it's own limitations.
  • Because neither covered different calendars and time zones well, the Calendar API was introduced.
  • This still did not cover the complexity of the time zones. And yet, the mix of the above APIs was really a pain to work with. So as Java developers started working on global web applications, libraries that targeted most use cases, like JodaTime, got quickly popular. JodaTime was the de-facto standard for about a decade.
  • But the JDK did not integrate with JodaTime, so working with it was a bit cumbersome. So, after a very long discussion on how to approach the matter, JSR-310 was created mainly based on JodaTime.

How to deal with it in Java's java.time

Determine what type to parse a timestamp to

When you are consuming a timestamp string, you need to know what information it contains. This is the crucial point. If you don't get this right, you end up with a cryptic exceptions like "Can't create Instant" or "Zone offset missing" or "unknown zone id" etc.

Does it contain the date and the time?

  1. Does it have a time offset?
    A time offset is the +hh:mm part. Sometimes, +00:00 may be substituted with Z as 'Zulu time', UTC as Universal Time Coordinated, or GMT as Greenwich Mean Time. These also set the time zone.
    For these timestamps, you use OffsetDateTime.

  2. Does it have a time zone?
    For these timestamps, you use ZonedDateTime.
    Zone is specified either by

    • name ("Prague", "Pacific Standard Time", "PST"), or
    • "zone ID" ("America/Los_Angeles", "Europe/London"), represented by java.time.ZoneId.

    The list of time zones is compiled by a "TZ database", backed by ICAAN.

    According to ZoneId's javadoc, The zone id's can also somehow be specified as Z and offset. I'm not sure how this maps to real zones. If the timestamp, which only has a TZ, falls into a leap hour of time offset change, then it is ambiguous, and the interpretation is subject of ResolverStyle, see below.

  3. If it has neither, then the missing context is assumed or neglected. And the consumer has to decide. So it needs to be parsed as LocalDateTime and converted to OffsetDateTime by adding the missing info:

    • You can assume that it is a UTC time. Add the UTC offset of 0 hours.
    • You can assume that it is a time of the place where the conversion is happening. Convert it by adding the system's time zone.
    • You can neglect and just use it as is. That is useful e.g. to compare or substract two times (see Duration), or when you don't know and it doesn't really matter (e.g. local bus schedule).

Partial time information

  • Based on what the timestamp contains, you can take LocalDate, LocalTime, OffsetTime, MonthDay, Year, or YearMonth out of it.

If you have the full information, you can get a java.time.Instant. This is also internally used to convert between OffsetDateTime and ZonedDateTime.

Figure out how to parse it

There is an extensive documentation on DateTimeFormatter which can both parse a timestamp string and format to string.

The pre-created DateTimeFormatters should cover moreless all standard timestamp formats. For instance, ISO_INSTANT can parse 2011-12-03T10:15:30.123457Z.

If you have some special format, then you can create your own DateTimeFormatter (which is also a parser).

private static final DateTimeFormatter TIMESTAMP_PARSER = new DateTimeFormatterBuilder()
   .parseCaseInsensitive()
   .append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SX"))
   .toFormatter();

I recommend to look at the source code of DateTimeFormatter and get inspired on how to build one using DateTimeFormatterBuilder. While you're there, also have a look at ResolverStyle which controls whether the parser is LENIENT, SMART or STRICT for the formats and ambiguous information.

TemporalAccessor

Now, the frequent mistake is to go into the complexity of TemporalAccessor. This comes from how the developers were used to work with SimpleDateFormatter.parse(String). Right, DateTimeFormatter.parse("...") gives you TemporalAccessor.

// No need for this!
TemporalAccessor ta = TIMESTAMP_PARSER.parse("2011-... etc");

But, equiped with the knowledge from the previous section, you can conveniently parse into the type you need:

OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z", TIMESTAMP_PARSER);

You do not actually need to the DateTimeFormatter either. The types you want to parse have the parse(String) methods.

OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z");

Regarding TemporalAccessor, you can use it if you have a vague idea of what information there is in the string, and want to decide at runtime.

I hope I shed some light of understanding onto your soul :)

Note: There's a backport of java.time to Java 6 and 7: ThreeTen-Backport. For Android it has ThreeTenABP.

[1] Not just that they are not stripes, but there also some weird extremes. For instance, some neighboring pacific islands have +14:00 and -11:00 time zones. That means, that while on one island, there is 1st May 3 PM, on another island not so far, it is still 30 April 12 PM (if I counted correctly :) )

What is the fastest way to create a checksum for large files in C#

I did tests with buffer size, running this code

using (var stream = new BufferedStream(File.OpenRead(file), bufferSize))
{
    SHA256Managed sha = new SHA256Managed();
    byte[] checksum = sha.ComputeHash(stream);
    return BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower();
}

And I tested with a file of 29½ GB in size, the results were

  • 10.000: 369,24s
  • 100.000: 362,55s
  • 1.000.000: 361,53s
  • 10.000.000: 434,15s
  • 100.000.000: 435,15s
  • 1.000.000.000: 434,31s
  • And 376,22s when using the original, none buffered code.

I am running an i5 2500K CPU, 12 GB ram and a OCZ Vertex 4 256 GB SSD drive.

So I thought, what about a standard 2TB harddrive. And the results were like this

  • 10.000: 368,52s
  • 100.000: 364,15s
  • 1.000.000: 363,06s
  • 10.000.000: 678,96s
  • 100.000.000: 617,89s
  • 1.000.000.000: 626,86s
  • And for none buffered 368,24

So I would recommend either no buffer or a buffer of max 1 mill.

ImportError: No module named Crypto.Cipher

To date, I'm having same issue when importing from Crypto.Cipher import AES even when I've installed/reinstalled pycrypto a few times. End up it's because pip defaulted to python3.

~ pip --version
pip 18.0 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

installing pycrypto with pip2 should solve this issue.

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

(Basically what @user3464070 already said)

For Mac:

cd ~/Library/Android/sdk
# download latest tools
curl -O https://dl.google.com/android/repository/tools_r25.2.3-macosx.zip
# overwrite existing tools folder without prompting
unzip -o tools_r25.2.3-macosx.zip
# clean up
rm tools_r25.2.3-macosx.zip

How to replace a string in multiple files in linux command line

If you have list of files you can use

replace "old_string" "new_string" -- file_name1 file_name2 file_name3

If you have all files you can use

replace "old_string" "new_string" -- *

If you have list of files with extension, you can use

replace "old_string" "new_string" -- *.extension

Disabling browser print options (headers, footers, margins) from page?

I solved my problem using some css into the web page.

<style media="print">
   @page {
      size: auto;
      margin: 0;
  }
</style>

Disable EditText blinking cursor

You can use either the xml attribute android:cursorVisible="false" or programatically:

  • java: view.setCursorVisible(false)
  • kotlin: view.isCursorVisible = false

How do android screen coordinates work?

This picture will remove everyone's confusion hopefully which is collected from there.

Android screen coordinate

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

A simple work around(it worked for me) is use the IP address instead of localhost. This should be fine for your development tasks.

send bold & italic text on telegram bot with html

So when sending the message to telegram you use:

$token = <Enter Your Token Here>
$url = "https://api.telegram.org/bot".$token;

$chat_id = <The Chat Id Goes Here>;
$test = <Message goes Here>;

//sending Message normally without styling
$response = file_get_content($url."\sendMessage?chat_id=$chat_id&text=$text");

If our message has html tags in it we add "parse_mode" so that our url becomes:

$response = file_get_content($url."\sendMessage?chat_id=$chat_id&text=$text&parse_mode=html")

parse mode can be "HTML" or "markdown"

Passing parameters to addTarget:action:forControlEvents

I was creating several buttons for each phone number in an array so each button needed a different phone number to call. I used the setTag function as I was creating several buttons within a for loop:

for (NSInteger i = 0; i < _phoneNumbers.count; i++) {

    UIButton *phoneButton = [[UIButton alloc] initWithFrame:someFrame];
    [phoneButton setTitle:_phoneNumbers[i] forState:UIControlStateNormal];

    [phoneButton setTag:i];

    [phoneButton addTarget:self
                    action:@selector(call:)
          forControlEvents:UIControlEventTouchUpInside];
}

Then in my call: method I used the same for loop and an if statement to pick the correct phone number:

- (void)call:(UIButton *)sender
{
    for (NSInteger i = 0; i < _phoneNumbers.count; i++) {
        if (sender.tag == i) {
            NSString *callString = [NSString stringWithFormat:@"telprompt://%@", _phoneNumbers[i]];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callString]];
        }
    }
}

How can I commit files with git?

Git uses "the index" to prepare commits. You can add and remove changes from the index before you commit (in your paste you already have deleted ~10 files with git rm). When the index looks like you want it, run git commit.

Usually this will fire up vim. To insert text hit i, <esc> goes back to normal mode, hit ZZ to save and quit (ZQ to quit without saving). voilà, there's your commit

Download file from web in Python 3

You can use wget which is popular downloading shell tool for that. https://pypi.python.org/pypi/wget This will be the simplest method since it does not need to open up the destination file. Here is an example.

import wget
url = 'https://i1.wp.com/python3.codes/wp-content/uploads/2015/06/Python3-powered.png?fit=650%2C350'  
wget.download(url, '/Users/scott/Downloads/cat4.jpg') 

"This project is incompatible with the current version of Visual Studio"

I checked if i could create a new solution and was unable because SSAS,SSIS and SSRS weren't there as options.

I downloaded SSDT from here and installed and it worked...

https://docs.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt?view=sql-server-2017

How to check if a std::string is set or not?

I don't think you can tell with the std::string class. However, if you really need this information, you could always derive a class from std::string and give the derived class the ability to tell if it had been changed since construction (or some other arbitrary time). Or better yet, just write a new class that wraps std::string since deriving from std::string may not be a good idea given the lack of a base class virtual destructor. That's probably more work, but more work tends to be needed for an optimal solution.

Of course, you can always just assume if it contains something other than "" then it has been "set", this won't detect it manually getting set to "" though.

How to fetch data from local JSON file on react native?

Take a look at this Github issue:

https://github.com/facebook/react-native/issues/231

They are trying to require non-JSON files, in particular JSON. There is no method of doing this right now, so you either have to use AsyncStorage as @CocoOS mentioned, or you could write a small native module to do what you need to do.

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

What is the difference between dynamic and static polymorphism in Java?

Consider the code below:

public class X
{
    public void methodA() // Base class method
    {
        System.out.println ("hello, I'm methodA of class X");
    }
}

public class Y extends X
{
    public void methodA() // Derived Class method
    {
        System.out.println ("hello, I'm methodA of class Y");
    }
}
public class Z
{
public static void main (String args []) {

    //this takes input from the user during runtime
    System.out.println("Enter x or y");
    Scanner scanner = new Scanner(System.in);
    String value= scanner.nextLine();

    X obj1 = null;
    if(value.equals("x"))
        obj1 = new X(); // Reference and object X
    else if(value.equals("y"))
        obj2 = new Y(); // X reference but Y object
    else
        System.out.println("Invalid param value");

    obj1.methodA();
}
}

Now, looking at the code you can never tell which implementation of methodA() will be executed, Because it depends on what value the user gives during runtime. So, it is only decided during the runtime as to which method will be called. Hence, Runtime polymorphism.

How to get input text length and validate user in javascript

JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.

var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
    //red
    textBox.style.backgroundColor = "#FF0000";
}
else
{
    //green
    textBox.style.backgroundColor = "#00FF00";
}

Android Facebook integration with invalid key hash

If you are facing this problem then put this key into your developer.facebook.com:

Enter image description here

Then make sure your app is live on developer.facebook.com.

This green circle is indicating the app is live:

Enter image description here

If it is not then follow these two steps for make your app live:

Step 1 Go to your application→settingadd Contact Email and apply Save Changes.

Step 2 Go to the App Review option and make sure this toggle is Yes. I added a screenshot:

Enter image description here

Note: If you want to copy the hashkey, check the BlueServiceQueue in LogCat.

Convert generic List/Enumerable to DataTable?

A small change to Marc's answer to make it work with value types like List<string> to data table:

public static DataTable ListToDataTable<T>(IList<T> data)
{
    DataTable table = new DataTable();

    //special handling for value types and string
    if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
    {

        DataColumn dc = new DataColumn("Value", typeof(T));
        table.Columns.Add(dc);
        foreach (T item in data)
        {
            DataRow dr = table.NewRow();
            dr[0] = item;
            table.Rows.Add(dr);
        }
    }
    else
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        foreach (PropertyDescriptor prop in properties)
        {
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
            {
                try
                {
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                }
                catch (Exception ex)
                {
                    row[prop.Name] = DBNull.Value;
                }
            }
            table.Rows.Add(row);
        }
    }
    return table;
}

Undefined Reference to

Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:

foo.h:

namespace foo {
    void bar();
}

foo.cc:

namespace foo {
    namespace {  // wrong
        void bar() { cout << "hello"; };
    }
}

other.cc file:

#include "foo.h"

void baz() {
    foo::bar();
}

Transactions in .net

It also depends on what you need. For basic SQL transactions you could try doing TSQL transactions by using BEGIN TRANS and COMMIT TRANS in your code. That is the easiest way but it does have complexity and you have to be careful to commit properly (and rollback).

I would use something like

SQLTransaction trans = null;
using(trans = new SqlTransaction)
{
    ...
    Do SQL stuff here passing my trans into my various SQL executers
    ...
    trans.Commit  // May not be quite right
}

Any failure will pop you right out of the using and the transaction will always commit or rollback (depending on what you tell it to do). The biggest problem we faced was making sure it always committed. The using ensures the scope of the transaction is limited.

Angular 1.6.0: "Possibly unhandled rejection" error

I had this same notice appear after making some changes. It turned out to be because I had changed between a single $http request to multiple requests using angularjs $q service.

I hadn't wrapped them in an array. e.g.

$q.all(request1, request2).then(...) 

rather than

$q.all([request1, request2]).then(...)

I hope this might save somebody some time.

How to get current time and date in C++?

In C++ 11 you can use std::chrono::system_clock::now()

Example (copied from en.cppreference.com):

#include <iostream>
#include <chrono>
#include <ctime>    

int main()
{
    auto start = std::chrono::system_clock::now();
    // Some computation here
    auto end = std::chrono::system_clock::now();

    std::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s\n";
}

This should print something like this:

finished computation at Mon Oct  2 00:59:08 2017
elapsed time: 1.88232s

How to retrieve a user environment variable in CMake (Windows)

Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.

If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.

You need to open a new command line prompt after you change the user settings.

The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.

How do you write a migration to rename an ActiveRecord model and its table in Rails?

Here's an example:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

I had to go and rename the model declaration file manually.

Edit:

In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

(You still have to go through and manually rename your files.)

Basic example of using .ajax() with JSONP?

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
  format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
  $.each(data.items, function(i,item){
  $("<img/>").attr("src", item.media.m).appendTo("#images");

 });
});</script>
</body>
</html> 

The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

Running javascript in Selenium using Python

If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):

# 1) Get back to the main body page
driver.switch_to.default_content()

# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js: 
    # 3) Read the jquery from a file
    jquery = jquery_js.read() 
    # 4) Load jquery lib
    driver.execute_script(jquery)
    # 5) Execute your command 
    driver.execute_script('$("#myId").click()')

Convert StreamReader to byte[]

Just throw everything you read into a MemoryStream and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.

var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
    var buffer = new byte[512];
    var bytesRead = default(int);
    while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
        memstream.Write(buffer, 0, bytesRead);
    bytes = memstream.ToArray();
}

Or if you don't want to manage the buffers:

var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
    reader.BaseStream.CopyTo(memstream);
    bytes = memstream.ToArray();
}

Can't use System.Windows.Forms

may be necesssary, unreference system.windows.forms and reference again.

How do I count cells that are between two numbers in Excel?

Example-

For cells containing the values between 21-31, the formula is:

=COUNTIF(M$7:M$83,">21")-COUNTIF(M$7:M$83,">31")

Converting a column within pandas dataframe from int to string

Change data type of DataFrame column:

To int:

df.column_name = df.column_name.astype(np.int64)

To str:

df.column_name = df.column_name.astype(str)

difference between width auto and width 100 percent

Width 100% : It will make content with 100%. margin, border, padding will be added to this width and element will overflow if any of these added.

Width auto : It will fit the element in available space including margin, border and padding. space remaining after adjusting margin + padding + border will be available width/ height.

Width 100% + box-sizing: border box : It will also fits the element in available space including border, padding (margin will make it overflow the container).

Your password does not satisfy the current policy requirements

NOTE: This might not be a secure solution. But if you are working on a test environment, just need a quick fix and doesn't even care about the security settings. This is a quick solution.

The same issue happened to me when I ran "mysql_secure_installation" and modified password security level to 'medium'.

I bypassed the error by running the followings:

mysql -h localhost -u root -p
mysql>uninstall plugin validate_password;

make sure you reinstall the plugin "validate_password" if necessary.

How do you merge two Git repositories?

I wanted to move a small project to a subdirectory of a larger one. Since my small project did not have many commits, I used git format-patch --output-directory /path/to/patch-dir. Then on the larger project, I used git am --directory=dir/in/project /path/to/patch-dir/*.

This feels way less scary and way more cleaner than a filter-branch. Granted, it may not be applicable to all cases.

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

Install sshpass, then launch the command:

sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname

Convert and format a Date in JSP

In JSP, you'd normally like to use JSTL <fmt:formatDate> for this. You can of course also throw in a scriptlet with SimpleDateFormat, but scriptlets are strongly discouraged since 2003.

Assuming that ${bean.date} returns java.util.Date, here's how you can use it:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<fmt:formatDate value="${bean.date}" pattern="yyyy-MM-dd HH:mm:ss" />

If you're actually using a java.util.Calendar, then you can invoke its getTime() method to get a java.util.Date out of it that <fmt:formatDate> accepts:

<fmt:formatDate value="${bean.calendar.time}" pattern="yyyy-MM-dd HH:mm:ss" />

Or, if you're actually holding the date in a java.lang.String (this indicates a serious design mistake in the model; you should really fix your model to store dates as java.util.Date instead of as java.lang.String!), here's how you can convert from one date string format e.g. MM/dd/yyyy to another date string format e.g. yyyy-MM-dd with help of JSTL <fmt:parseDate>.

<fmt:parseDate pattern="MM/dd/yyyy" value="${bean.dateString}" var="parsedDate" />
<fmt:formatDate value="${parsedDate}" pattern="yyyy-MM-dd" />

Does SVG support embedding of bitmap images?

It is also possible to include bitmaps. I think you also can use transformations on that.

Plotting two variables as lines using ggplot2 on the same graph

The general approach is to convert the data to long format (using melt() from package reshape or reshape2) or gather()/pivot_longer() from the tidyr package:

library("reshape2")
library("ggplot2")

test_data_long <- melt(test_data, id="date")  # convert to long format

ggplot(data=test_data_long,
       aes(x=date, y=value, colour=variable)) +
       geom_line()

ggplot2 output

Also see this question on reshaping data from wide to long.

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

In IntelliJ Community Edition 2019.02, Changing the following settings worked for me

  1. Update File->Project structure->Project Settings->Project->Project Language level to Java 11 (update to the java version that you wish to use in your project) using drop down.

  2. Update File->Project structure->Project Settings->Modules->Language level

  3. Update File->Settings->Build,Execution,Deployment -> Compiler -> Java Compiler-> Project ByteCode Version to java 11.

  4. Update Target version for all the entries under File->Settings->Build,Execution,Deployment -> Compiler -> Java Compiler-> Per module Byte Code Version.

How do I read all classes from a Java package in the classpath?

  1. Bill Burke has written a (nice article about class scanning] and then he wrote Scannotation.

  2. Hibernate has this already written:

    • org.hibernate.ejb.packaging.Scanner
    • org.hibernate.ejb.packaging.NativeScanner
  3. CDI might solve this, but don't know - haven't investigated fully yet

.

@Inject Instance< MyClass> x;
...
x.iterator() 

Also for annotations:

abstract class MyAnnotationQualifier
extends AnnotationLiteral<Entity> implements Entity {}

How to write a caption under an image?

<div style="margin: 0 auto; text-align: center; overflow: hidden;">
  <div style="float: left;">
    <a href="http://xyz.com/hello"><img src="hello.png" width="100px" height="100px"></a>
    caption 1
  </div>
 <div style="float: left;">
   <a href="http://xyz.com/hi"><img src="hi.png" width="100px" height="100px"></a>
   caption 2                      
 </div>
</div>

Precision String Format Specifier In Swift

Plenty of good answers above, but sometimes a pattern is more appropriate than the "%.3f" sort of gobbledygook. Here's my take using a NumberFormatter in Swift 3.

extension Double {
  func format(_ pattern: String) -> String {
    let formatter = NumberFormatter()
    formatter.format = pattern
    return formatter.string(from: NSNumber(value: self))!
  }    
}

let n1 = 0.350, n2 = 0.355
print(n1.format("0.00#")) // 0.35
print(n2.format("0.00#")) // 0.355

Here I wanted 2 decimals to be always shown, but the third only if it wasn't zero.

How to sanity check a date in Java

Two comments on the use of SimpleDateFormat.

it should be declared as a static instance if declared as static access should be synchronized as it is not thread safe

IME that is better that instantiating an instance for each parse of a date.

How to get base url in CodeIgniter 2.*

You need to add url helper in config/autoload

$autoload['helper'] = array('form', 'url', 'file', 'html'); <-- Like This

Then you can use base_url or any kind of url.

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

If you've enabled two factor authentication, then you'll need to generate a personal access token and use that instead of your regular password. More info here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/

gcc makefile error: "No rule to make target ..."

In my experience, this error is frequently caused by a spelling error.

I got this error today.

make[1]: *** No rule to make target maintenaceDialog.cpp', needed bymaintenaceDialog.o'. Stop.

In my case the error was simply a spelling error. The word MAINTENANCE was missing it's third N.

Also check the spelling on your filenames.

Socket send and receive byte array

First, do not use DataOutputStream unless it’s really necessary. Second:

Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);

Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.

Purpose of "%matplotlib inline"

Provided you are running IPython, the %matplotlib inline will make your plot outputs appear and be stored within the notebook.

According to documentation

To set this up, before any plotting or import of matplotlib is performed you must execute the %matplotlib magic command. This performs the necessary behind-the-scenes setup for IPython to work correctly hand in hand with matplotlib; it does not, however, actually execute any Python import commands, that is, no names are added to the namespace.

A particularly interesting backend, provided by IPython, is the inline backend. This is available only for the Jupyter Notebook and the Jupyter QtConsole. It can be invoked as follows:

%matplotlib inline

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

Writing List of Strings to Excel CSV File in Python

Very simple to fix, you just need to turn the parameter to writerow into a list.

for item in RESULTS:
     wr.writerow([item,])

How to update and order by using ms sql

You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:

UPDATE  messages 
SET status=10 
WHERE ID in (SELECT TOP (10) Id 
             FROM Table 
             WHERE status=0 
             ORDER BY priority DESC);

Should I set max pool size in database connection string? What happens if I don't?

We can define maximum pool size in following way:

                <pool> 
               <min-pool-size>5</min-pool-size>
                <max-pool-size>200</max-pool-size>
                <prefill>true</prefill>
                <use-strict-min>true</use-strict-min>
                <flush-strategy>IdleConnections</flush-strategy>
                </pool>

this in equals method

this refers to the current instance of the class (object) your equals-method belongs to. When you test this against an object, the testing method (which is equals(Object obj) in your case) will check wether or not the object is equal to the current instance (referred to as this).

An example:

Object obj = this; this.equals(obj); //true   Object obj = this; new Object().equals(obj); //false 

Meaning of "487 Request Terminated"

The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.

15.1.2 UAS Behavior==> BYE Handling in RFC 3261

The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.

How to execute python file in linux

You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.

It should look like that :

#!/usr/bin/env python

or the real path

#!/usr/bin/python

You should also check the file have the right to be execute. chmod +x file.py

As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Force to open "Save As..." popup open at text link click for PDF in HTML

I just used this, but I don't know if it works across all browsers.

It works in Firefox:

<a href="myfile.pdf" download>Click to Download</a>

How do I get the project basepath in CodeIgniter

use base_url()

echo $baseurl=base_url();

if you need to pass url to a function then use site_url()

 echo site_url('controller/function');

if you need the root path then FCPATH..

echo FCPATH;

Change the jquery show()/hide() animation?

Use slidedown():

$("test").slideDown("slow");

"Port 4200 is already in use" when running the ng serve command

The most simple one line command:

 sudo fuser -k 4200/tcp

How to find locked rows in Oracle

Look at the dba_blockers, dba_waiters and dba_locks for locking. The names should be self explanatory.

You could create a job that runs, say, once a minute and logged the values in the dba_blockers and the current active sql_id for that session. (via v$session and v$sqlstats).

You may also want to look in v$sql_monitor. This will be default log all SQL that takes longer than 5 seconds. It is also visible on the "SQL Monitoring" page in Enterprise Manager.

Copy rows from one table to another, ignoring duplicates

Your problem is that you need another where clause in the subquery that identifies what makes a duplicate:

INSERT INTO destTable
SELECT Field1,Field2,Field3,... 
FROM srcTable
WHERE NOT EXISTS(SELECT * 
                 FROM destTable 
                 WHERE (srcTable.Field1=destTable.Field1 and
                       SrcTable.Field2=DestTable.Field2...etc.)
                 )

As noted by another answerer, an outer join is probably a more concise approach. My above example was just an attempt to explain using your current query to be more understandible. Either approach could technically work.

INSERT INTO destTable
SELECT s.field1,s.field2,s.field3,... 
FROM srcTable s 
       LEFT JOIN destTable d ON (d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...)
WHERE d.Key1 IS NULL

Both of the above approaches assume you are woried about inserting rows from source that might already be in destination. If you are instead concerned about the possibility that source has duplicate rows you should try something like.

INSERT INTO destTable
SELECT Distinct field1,field2,field3,... 
FROM srcTable  

One more thing. I'd also suggest listing the specific fields on your insert statement instead of using SELECT *.

C# Inserting Data from a form into an access Database

 private void Add_Click(object sender, EventArgs e) {
 OleDbConnection con = new OleDbConnection(@ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
 OleDbCommand cmd = con.CreateCommand();
 con.Open();
 cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
 cmd.ExecuteNonQuery();
 MessageBox.Show("Record Submitted", "Congrats");
 con.Close();
} 

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

How to enable authentication on MongoDB through Docker?

I have hard time when trying to

  • Create other db than admin
  • Add new users and enable authentication to the db above

So I made 2020 answer here

My directory looks like this

+-- docker-compose.yml
+-- mongo-entrypoint
    +-- entrypoint.js

My docker-compose.yml looks like this

version: '3.4'
services:
  mongo-container:
    # If you need to connect to your db from outside this container 
    network_mode: host
    image: mongo:4.2
    environment:
        - MONGO_INITDB_ROOT_USERNAME=admin
        - MONGO_INITDB_ROOT_PASSWORD=pass
    ports:
      - "27017:27017"
    volumes:
      - "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
    command: mongod

Please change admin and pass with your need.

Inside mongo-entrypoint, I have entrypoint.js file with this content:

var db = connect("mongodb://admin:pass@localhost:27017/admin");

db = db.getSiblingDB('new_db'); // we can not use "use" statement here to switch db

db.createUser(
    {
        user: "user",
        pwd: "pass",
        roles: [ { role: "readWrite", db: "new_db"} ],
        passwordDigestor: "server",
    }
)

Here again you need to change admin:pass to your root mongo credentials in your docker-compose.yml that you stated before. In additional you need to change new_db, user, pass to your new database name and credentials that you need.

Now you can:

docker-compose up -d

And connect to this db from localhost, please note that I already have mongo cli, you can install it or you can exec to the container above to use mongo command:

mongo new_db -u user -p pass

Or you can connect from other computer

mongo host:27017/new_db -u user -p pass

My git repository: https://github.com/sexydevops/docker-compose-mongo

Hope it can help someone, I lost my afternoon for this ;)

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Used to face the same problem. The reason was in incorrect context passing to AlertDialog.Builder(here). use like AlertDialog.Builder(Homeactivity.this)

Open a new tab in the background?

Here is a complete example for navigating valid URL on a new tab with focused.

HTML:

<div class="panel">
  <p>
    Enter Url: 
    <input type="text" id="txturl" name="txturl" size="30" class="weburl" />
    &nbsp;&nbsp;    
    <input type="button" id="btnopen"  value="Open Url in New Tab" onclick="openURL();"/>
  </p>
</div>

CSS:

.panel{
  font-size:14px;
}
.panel input{
  border:1px solid #333;
}

JAVASCRIPT:

function isValidURL(url) {
    var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

    if (RegExp.test(url)) {
        return true;
    } else {
        return false;
    }
}

function openURL() {
    var url = document.getElementById("txturl").value.trim();
    if (isValidURL(url)) {
        var myWindow = window.open(url, '_blank');
        myWindow.focus();
        document.getElementById("txturl").value = '';
    } else {
        alert("Please enter valid URL..!");
        return false;
    }
}

I have also created a bin with the solution on http://codebins.com/codes/home/4ldqpbw

Center Plot title in ggplot2

As stated in the answer by Henrik, titles are left-aligned by default starting with ggplot 2.2.0. Titles can be centered by adding this to the plot:

theme(plot.title = element_text(hjust = 0.5))

However, if you create many plots, it may be tedious to add this line everywhere. One could then also change the default behaviour of ggplot with

theme_update(plot.title = element_text(hjust = 0.5))

Once you have run this line, all plots created afterwards will use the theme setting plot.title = element_text(hjust = 0.5) as their default:

theme_update(plot.title = element_text(hjust = 0.5))
ggplot() + ggtitle("Default is now set to centered")

enter image description here

To get back to the original ggplot2 default settings you can either restart the R session or choose the default theme with

theme_set(theme_gray())

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

Check your AWS S3 Bucket Region and Pass proper Region in Connection Request.

In My Senario I have set 'APSouth1' for Asia Pacific (Mumbai)

using (var client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.APSouth1))
{
    GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest
    {
        BucketName = bucketName,
        Key = keyName,
        Expires = DateTime.Now.AddMinutes(50),
    };
    urlString = client.GetPreSignedURL(request1);
}

if (select count(column) from table) > 0 then

Edit:

The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql

No, just use the value directly:

begin
  if (select count(*) from table) > 0 then
     update table
  end if;
end;

Note there is no need for an "else".

Edited

You can simply do it all within the update statement (ie no if construct):

update table
set ...
where ...
and exists (select 'x' from table where ...)

org.json.simple cannot be resolved

The jar file is missing. You can download the jar file and add it as external libraries in your project . You can download this from

http://www.findjar.com/jar/com/googlecode/json-simple/json-simple/1.1/json-simple-1.1.jar.html

Mapping a JDBC ResultSet to an object

No need of storing resultSet values into String and again setting into POJO class. Instead set at the time you are retrieving.

Or best way switch to ORM tools like hibernate instead of JDBC which maps your POJO object direct to database.

But as of now use this:

List<User> users=new ArrayList<User>();

while(rs.next()) {
   User user = new User();      
   user.setUserId(rs.getString("UserId"));
   user.setFName(rs.getString("FirstName"));
  ...
  ...
  ...


  users.add(user);
} 

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

I solve this trouble with config APACHE ! All methods (in this topic) is incorrect for me... Then I try chanche apache config:

Timeout 3600

Then my script worked!

What is the dual table in Oracle?

From Wikipedia

History

The DUAL table was created by Chuck Weiss of Oracle corporation to provide a table for joining in internal views:

I created the DUAL table as an underlying object in the Oracle Data Dictionary. It was never meant to be seen itself, but instead used inside a view that was expected to be queried. The idea was that you could do a JOIN to the DUAL table and create two rows in the result for every one row in your table. Then, by using GROUP BY, the resulting join could be summarized to show the amount of storage for the DATA extent and for the INDEX extent(s). The name, DUAL, seemed apt for the process of creating a pair of rows from just one. 1

It may not be obvious from the above, but the original DUAL table had two rows in it (hence its name). Nowadays it only has one row.

Optimization

DUAL was originally a table and the database engine would perform disk IO on the table when selecting from DUAL. This disk IO was usually logical IO (not involving physical disk access) as the disk blocks were usually already cached in memory. This resulted in a large amount of logical IO against the DUAL table.

Later versions of the Oracle database have been optimized and the database no longer performs physical or logical IO on the DUAL table even though the DUAL table still actually exists.

Ruby on Rails - Import Data from a CSV file

This can help. It has code examples too:

http://csv-mapper.rubyforge.org/

Or for a rake task for doing the same:

http://erikonrails.snowedin.net/?p=212

How can I query for null values in entity framework?

It appears that Linq2Sql has this "problem" as well. It appears that there is a valid reason for this behavior due to whether ANSI NULLs are ON or OFF but it boggles the mind why a straight "== null" will in fact work as you'd expect.

Is < faster than <=?

TL;DR answer

For most combinations of architecture, compiler and language, < will not be faster than <=.

Full answer

Other answers have concentrated on x86 architecture, and I don't know the ARM architecture (which your example assembler seems to be) well enough to comment specifically on the code generated, but this is an example of a micro-optimisation which is very architecture specific, and is as likely to be an anti-optimisation as it is to be an optimisation.

As such, I would suggest that this sort of micro-optimisation is an example of cargo cult programming rather than best software engineering practice.

Counterexample

There are probably some architectures where this is an optimisation, but I know of at least one architecture where the opposite may be true. The venerable Transputer architecture only had machine code instructions for equal to and greater than or equal to, so all comparisons had to be built from these primitives.

Even then, in almost all cases, the compiler could order the evaluation instructions in such a way that in practice, no comparison had any advantage over any other. Worst case though, it might need to add a reverse instruction (REV) to swap the top two items on the operand stack. This was a single byte instruction which took a single cycle to run, so had the smallest overhead possible.

Summary

Whether or not a micro-optimisation like this is an optimisation or an anti-optimisation depends on the specific architecture you are using, so it is usually a bad idea to get into the habit of using architecture specific micro-optimisations, otherwise you might instinctively use one when it is inappropriate to do so, and it looks like this is exactly what the book you are reading is advocating.

Count how many files in directory PHP

You should have :

<div id="header">
<?php 
    // integer starts at 0 before counting
    $i = 0; 
    $dir = 'uploads/';
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false){
            if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) 
                $i++;
        }
    }
    // prints out how many were in the directory
    echo "There were $i files";
?>
</div>

How do I find which transaction is causing a "Waiting for table metadata lock" state?

SHOW ENGINE INNODB STATUS \G

Look for the Section -

TRANSACTIONS

We can use INFORMATION_SCHEMA Tables.

Useful Queries

To check about all the locks transactions are waiting for:

USE INFORMATION_SCHEMA;
SELECT * FROM INNODB_LOCK_WAITS;

A list of blocking transactions:

SELECT * 
FROM INNODB_LOCKS 
WHERE LOCK_TRX_ID IN (SELECT BLOCKING_TRX_ID FROM INNODB_LOCK_WAITS);

OR

SELECT INNODB_LOCKS.* 
FROM INNODB_LOCKS
JOIN INNODB_LOCK_WAITS
  ON (INNODB_LOCKS.LOCK_TRX_ID = INNODB_LOCK_WAITS.BLOCKING_TRX_ID);

A List of locks on particular table:

SELECT * FROM INNODB_LOCKS 
WHERE LOCK_TABLE = db_name.table_name;

A list of transactions waiting for locks:

SELECT TRX_ID, TRX_REQUESTED_LOCK_ID, TRX_MYSQL_THREAD_ID, TRX_QUERY
FROM INNODB_TRX
WHERE TRX_STATE = 'LOCK WAIT';

Reference - MySQL Troubleshooting: What To Do When Queries Don't Work, Chapter 6 - Page 96.

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

scrollIntoView Scrolls just too far

I solved this problem by using,

element.scrollIntoView({ behavior: 'smooth', block: 'center' });

This makes the element appear in the center after scrolling, so I don't have to calculate yOffset.

Hope it helps...

How to launch another aspx web page upon button click?

This button post to the current page while at the same time opens OtherPage.aspx in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.

<asp:Button ID="myBtn" runat="server" Text="Click me" 
     onclick="myBtn_Click" OnClientClick="window.open('OtherPage.aspx', 'OtherPage');" />

How do I exit from a function?

Use the return keyword.

return; //exit this event

Heatmap in matplotlib with pcolor?

Main issue is that you first need to set the location of your x and y ticks. Also, it helps to use the more object-oriented interface to matplotlib. Namely, interact with the axes object directly.

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data)

# put the major ticks at the middle of each cell, notice "reverse" use of dimension
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)


ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

Hope that helps.

How to stop the task scheduled in java.util.Timer class

You should stop the task that you have scheduled on the timer: Your timer:

Timer t = new Timer();
TimerTask tt = new TimerTask() {
    @Override
    public void run() {
        //do something
    };
}
t.schedule(tt,1000,1000);

In order to stop:

tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread

Notice that just cancelling the timer will not terminate ongoing timertasks.

How to run a function in jquery

function doosomething ()
{
  //Doo something
}


$(function () {


  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

using OR and NOT in solr query

Putting together comments from a couple different answers here, in the Solr docs and on the other SO question, I found that the following syntax produces the correct result for my use case

(my_field=my_value or my_field is null):

(my_field:"my_value" OR (*:* NOT my_field:*))

This works for solr 4.1.0. This is slightly different than the use case in the OP; but, I thought that others would find it useful.

Javascript checkbox onChange

Use an onclick event, because every click on a checkbox actually changes it.

Counting inversions in an array

The number of inversions can be found by analyzing the merge process in merge sort : merge process

When copying a element from the second array to the merge array (the 9 in this exemple), it keeps its place relatively to other elements. When copying a element from the first array to the merge array (the 5 here) it is inverted with all the elements staying in the second array (2 inversions with the 3 and the 4). So a little modification of merge sort can solve the problem in O(n ln n).
For exemple, just uncomment the two # lines in the mergesort python code below to have the count.

def merge(l1,l2):
    l = []
    # global count
    while l1 and l2:
        if l1[-1] <= l2[-1]:
            l.append(l2.pop())
        else:
            l.append(l1.pop())
            # count += len(l2)
    l.reverse()
    return l1 + l2 + l

def sort(l): 
    t = len(l) // 2
    return merge(sort(l[:t]), sort(l[t:])) if t > 0 else l

count=0
print(sort([5,1,2,4,9,3]), count)
# [1, 2, 3, 4, 5, 9] 6

EDIT 1

The same task can be achieved with a stable version of quick sort, known to be slightly faster :

def part(l):
    pivot=l[-1]
    small,big = [],[]
    count = big_count = 0
    for x in l:
        if x <= pivot:
            small.append(x)
            count += big_count
        else:
            big.append(x)
            big_count += 1
    return count,small,big

def quick_count(l):
    if len(l)<2 : return 0
    count,small,big = part(l)
    small.pop()
    return count + quick_count(small) + quick_count(big)

Choosing pivot as the last element, inversions are well counted, and execution time 40% better than merge one above.

EDIT 2

For performance in python, a numpy & numba version :

First the numpy part, which use argsort O (n ln n) :

def count_inversions(a):
    n = a.size
    counts = np.arange(n) & -np.arange(n)  # The BIT
    ags = a.argsort(kind='mergesort')    
    return  BIT(ags,counts,n)

And the numba part for the efficient BIT approach :

@numba.njit
def BIT(ags,counts,n):
    res = 0        
    for x in ags :
        i = x
        while i:
            res += counts[i]
            i -= i & -i
        i = x+1
        while i < n:
            counts[i] -= 1
            i += i & -i
    return  res  

Format an Integer using Java String Format

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"

As StringUtils.leftPad() is faster than String.format()

Spring configure @ResponseBody JSON format

Doesn't answer the question but this is the top google result.

If anybody comes here and wants do do it for Spring 4 (as it happened to me), you can use the annotation

@JsonInclude(Include.NON_NULL)

on the returning class.

How do I set log4j level on the command line?

log4j does not support this directly.

As you do not want a configuration file, you most likely use programmatic configuration. I would suggest that you look into scanning all the system properties, and explicitly program what you want based on this.

java.lang.IllegalArgumentException: No converter found for return value of type

The answer written by @Marc is also valid. But the concrete answer is the Getter method is required. You don't even need a Setter.

Making an API call in Python with an API that requires a bearer token

The token has to be placed in an Authorization header according to the following format:

Authorization: Bearer [Token_Value]

Code below:

import urllib2
import json

def get_auth_token():
    """
    get an auth token
    """
    req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    token_string=json_obj["token"].encode("ascii","ignore")
    return token_string

def get_response_json_object(url, auth_token):
    """
    returns json object with info
    """
    auth_token=get_auth_token()
    req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    return json_obj

Difference between ${} and $() in Bash

  1. $() means: "first evaluate this, and then evaluate the rest of the line".

    Ex :

    echo $(pwd)/myFile.txt
    

    will be interpreted as

    echo /my/path/myFile.txt
    

    On the other hand ${} expands a variable.

    Ex:

    MY_VAR=toto
    echo ${MY_VAR}/myFile.txt
    

    will be interpreted as

    echo toto/myFile.txt
    
  2. Why can't I use it as bash$ while ((i=0;i<10;i++)); do echo $i; done

    I'm afraid the answer is just that the bash syntax for while just isn't the same as the syntax for for.

Relative frequencies / proportions with dplyr

Here is a base R answer using aggregate and ave :

df1 <- with(mtcars, aggregate(list(n = mpg), list(am = am, gear = gear), length))
df1$prop <- with(df1, n/ave(n, am, FUN = sum))
#Also with prop.table
#df1$prop <- with(df1, ave(n, am, FUN = prop.table))
df1

#  am gear  n      prop
#1  0    3 15 0.7894737
#2  0    4  4 0.2105263
#3  1    4  8 0.6153846
#4  1    5  5 0.3846154 

We can also use prop.table but the output displays differently.

prop.table(table(mtcars$am, mtcars$gear), 1)
   
#            3         4         5
#  0 0.7894737 0.2105263 0.0000000
#  1 0.0000000 0.6153846 0.3846154

Powershell: count members of a AD group

Something I'd like to share..

$adinfo.members actually give twice the number of actual members. $adinfo.member (without the "s") returns the correct amount. Even when dumping $adinfo.members & $adinfo.member to screen outputs the lower amount of members.

No idea how to explain this!

Can someone explain mappedBy in JPA and Hibernate?

mappedby="object of entity of same class created in another class”

Note:-Mapped by can be used only in one class because one table must contain foreign key constraint. if mapped by can be applied on both side then it remove foreign key from both table and without foreign key there is no relation b/w two tables.

Note:- it can be use for following annotations:- 1.@OneTone 2.@OneToMany 3.@ManyToMany

Note---It cannot be use for following annotation :- 1.@ManyToOne

In one to one :- Perform at any side of mapping but perform at only one side . It will remove the extra column of foreign key constraint on the table on which class it is applied.

For eg . If we apply mapped by in Employee class on employee object then foreign key from Employee table will be removed.

What are good ways to prevent SQL injection?

My answer is quite easy:

Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.

As a bonus, it's very easy to work with as well.

How to implement authenticated routes in React Router 4?

You're going to want to use the Redirect component. There's a few different approaches to this problem. Here's one I like, have a PrivateRoute component that takes in an authed prop and then renders based on that props.

function PrivateRoute ({component: Component, authed, ...rest}) {
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
  )
}

Now your Routes can look something like this

<Route path='/' exact component={Home} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />

If you're still confused, I wrote this post that may help - Protected routes and authentication with React Router v4

Print PHP Call Stack

To log the trace

$e = new Exception;
error_log(var_export($e->getTraceAsString(), true));

Thanks @Tobiasz

Ajax using https on an http page

Check out the opensource Forge project. It provides a JavaScript TLS implementation, along with some Flash to handle the actual cross-domain requests:

http://github.com/digitalbazaar/forge/blob/master/README

In short, Forge will enable you to make XmlHttpRequests from a web page loaded over http to an https site. You will need to provide a Flash cross-domain policy file via your server to enable the cross-domain requests. Check out the blog posts at the end of the README to get a more in-depth explanation for how it works.

However, I should mention that Forge is better suited for requests between two different https-domains. The reason is that there's a potential MiTM attack. If you load the JavaScript and Flash from a non-secure site it could be compromised. The most secure use is to load it from a secure site and then use it to access other sites (secure or otherwise).

How to declare a global variable in C++

Not sure if this is correct in any sense but this seems to work for me.

someHeader.h
inline int someVar;

I don't have linking/multiple definition issues and it "just works"... ;- )

It's quite handy for "quick" tests... Try to avoid global vars tho, because every says so... ;- )

How do I remove a property from a JavaScript object?

This post is very old and I find it very helpful so I decided to share the unset function I wrote in case someone else see this post and think why it's not so simple as it in PHP unset function.

The reason for writing this new unset function, is to keep the index of all other variables in this hash_map. Look at the following example, and see how the index of "test2" did not change after removing a value from the hash_map.

_x000D_
_x000D_
function unset(unsetKey, unsetArr, resort) {
  var tempArr = unsetArr;
  var unsetArr = {};
  delete tempArr[unsetKey];
  if (resort) {
    j = -1;
  }
  for (i in tempArr) {
    if (typeof(tempArr[i]) !== 'undefined') {
      if (resort) {
        j++;
      } else {
        j = i;
      }
      unsetArr[j] = tempArr[i];
    }
  }
  return unsetArr;
}

var unsetArr = ['test', 'deletedString', 'test2'];

console.log(unset('1', unsetArr, true)); // output Object {0: "test", 1: "test2"}
console.log(unset('1', unsetArr, false)); // output Object {0: "test", 2: "test2"}
_x000D_
_x000D_
_x000D_

Calculate distance between two latitude-longitude points? (Haversine formula)

Here is the SQL Implementation to calculate the distance in km,

SELECT UserId, ( 3959 * acos( cos( radians( your latitude here ) ) * cos( radians(latitude) ) * 
cos( radians(longitude) - radians( your longitude here ) ) + sin( radians( your latitude here ) ) * 
sin( radians(latitude) ) ) ) AS distance FROM user HAVING
distance < 5  ORDER BY distance LIMIT 0 , 5;

For further details in the implementation by programming langugage, you can just go through the php script given here

How do I change the font size of a UILabel in Swift?

Apple keep changing things for no reason: Swift 4+:

myLabel.font = UIFont.systemFont(ofSize: 16)

thanks apple for wasting people time to figure out what "font size" methods they need to use!

"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.

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

Javascript date regex DD/MM/YYYY

Do the following change to the jquery.validationengine-en.js file and update the dd/mm/yyyy inline validation by including leap year:

"date": {
    // Check if date is valid by leap year
    "func": function (field) {
    //var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
    var pattern = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})$/);
    var match = pattern.exec(field.val());
    if (match == null)
    return false;

    //var year = match[1];
    //var month = match[2]*1;
    //var day = match[3]*1;
    var year = match[3];
    var month = match[2]*1;
    var day = match[1]*1;
    var date = new Date(year, month - 1, day); // because months starts from 0.

    return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in DD-MM-YYYY format"

What is console.log?

It will post a log message to the browser's javascript console, e.g. Firebug or Developer Tools (Chrome / Safari) and will show the line and file where it was executed from.

Moreover, when you output a jQuery Object it will include a reference to that element in the DOM, and clicking it will go to that in the Elements/HTML tab.

You can use various methods, but beware that for it to work in Firefox, you must have Firebug open, otherwise the whole page will crash. Whether what you're logging is a variable, array, object or DOM element, it will give you a full breakdown including the prototype for the object as well (always interesting to have a poke around). You can also include as many arguments as you want, and they will be replaced by spaces.

console.log(  myvar, "Logged!");
console.info( myvar, "Logged!");
console.warn( myvar, "Logged!");
console.debug(myvar, "Logged!");
console.error(myvar, "Logged!");

These show up with different logos for each command.

You can also use console.profile(profileName); to start profiling a function, script etc. And then end it with console.profileEnd(profileName); and it will show up in you Profiles tab in Chrome (don't know with FF).

For a complete reference go to http://getfirebug.com/logging and I suggest you read it. (Traces, groups, profiling, object inspection).

Hope this helps!

throwing an exception in objective-c/cocoa

I think to be consistant it's nicer to use @throw with your own class that extends NSException. Then you use the same notations for try catch finally:

@try {
.....
}
@catch{
...
}
@finally{
...
}

Apple explains here how to throw and handle exceptions: Catching Exceptions Throwing Exceptions

Extract time from date String

I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.

Find length of 2D array Python

You can use numpy.shape.

import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])

Result:

>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.shape(x)
(3, 2)

First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.

How to view unallocated free space on a hard disk through terminal

To see in TB:

# parted /dev/sda unit TB print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

To see in GB:

# parted /dev/sda unit GB print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

To see in MB:

# parted /dev/sda unit MB print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

To see in bytes:

# parted /dev/sda unit B print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

To see in %:

# parted /dev/sda unit '%' print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

To see in sectors:

# parted /dev/sda unit s print free | grep 'Free Space' | tail -n1 | awk '{print $3}'

Change /dev/sda to whatever device you are trying to find the information about. If you are using the result in any calculations, make sure to trim the trailing characters.

How to get the name of the current method from code

Does this not work?

System.Reflection.MethodBase.GetCurrentMethod()

Returns a MethodBase object representing the currently executing method.

Namespace: System.Reflection

Assembly: mscorlib (in mscorlib.dll)

http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx

Git list of staged files

You can Try using :- git ls-files -s

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

Internally, Javascript strings are all Unicode (actually UCS-2, a subset of UTF-16).

If you're retrieving the JSON files separately via AJAX, then you only need to make sure that the JSON files are served with the correct Content-Type and charset: Content-Type: application/json; charset="utf-8"). If you do that, jQuery should already have interpreted them properly by the time you access the deserialized objects.

Could you post an example of the code you’re using to retrieve the JSON objects?

MVC4 StyleBundle not resolving images

It is not necessary to specify a transform or have crazy subdirectory paths. After much troubleshooting I isolated it to this "simple" rule (is it a bug?)...

If your bundle path does not start with relative root of the items being included, then the web application root will not be taken into account.

Sounds like more of a bug to me, but anyway that's how you fix it with the current .NET 4.51 version. Perhaps the other answers were necessary on older ASP.NET builds, can't say don't have time to retrospectively test all that.

To clarify, here is an example:

I have these files...

~/Content/Images/Backgrounds/Some_Background_Tile.gif
~/Content/Site.css  - references the background image relatively, i.e. background: url('Images/...')

Then setup the bundle like...

BundleTable.Add(new StyleBundle("~/Bundles/Styles").Include("~/Content/Site.css"));

And render it like...

@Styles.Render("~/Bundles/Styles")

And get the "behaviour" (bug), the CSS files themselves have the application root (e.g. "http://localhost:1234/MySite/Content/Site.css") but the CSS image within all start "/Content/Images/..." or "/Images/..." depending on whether I add the transform or not.

Even tried creating the "Bundles" folder to see if it was to do with the path existing or not, but that didn't change anything. The solution to the problem is really the requirement that the name of the bundle must start with the path root.

Meaning this example is fixed by registering and rendering the bundle path like..

BundleTable.Add(new StyleBundle("~/Content/StylesBundle").Include("~/Content/Site.css"));
...
@Styles.Render("~/Content/StylesBundle")

So of course you could say this is RTFM, but I am quite sure me and others picked-up this "~/Bundles/..." path from the default template or somewhere in documentation at MSDN or ASP.NET web site, or just stumbled upon it because actually it's a quite logical name for a virtual path and makes sense to choose such virtual paths which do not conflict with real directories.

Anyway, that's the way it is. Microsoft see no bug. I don't agree with this, either it should work as expected or some exception should be thrown, or an additional override to adding the bundle path which opts to include the application root or not. I can't imagine why anyone would not want the application root included when there was one (normally unless you installed your web site with a DNS alias/default web site root). So actually that should be the default anyway.

How to auto-generate a C# class file from a JSON string

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

List of ANSI color escape sequences

For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).

Differences between fork and exec

fork() splits the current process into two processes. Or in other words, your nice linear easy to think of program suddenly becomes two separate programs running one piece of code:

 int pid = fork();

 if (pid == 0)
 {
     printf("I'm the child");
 }
 else
 {
     printf("I'm the parent, my child is %i", pid);
     // here we can kill the child, but that's not very parently of us
 }

This can kind of blow your mind. Now you have one piece of code with pretty much identical state being executed by two processes. The child process inherits all the code and memory of the process that just created it, including starting from where the fork() call just left off. The only difference is the fork() return code to tell you if you are the parent or the child. If you are the parent, the return value is the id of the child.

exec is a bit easier to grasp, you just tell exec to execute a process using the target executable and you don't have two processes running the same code or inheriting the same state. Like @Steve Hawkins says, exec can be used after you forkto execute in the current process the target executable.

Remove all items from a FormArray in Angular

To keep the code clean I have created the following extension method for anyone using Angular 7 and below. This can also be used to extend any other functionality of Reactive Forms.

import { FormArray } from '@angular/forms';

declare module '@angular/forms/src/model' {
  interface FormArray {
    clearArray: () => FormArray;
  }
}

FormArray.prototype.clearArray = function () {
  const _self = this as FormArray;
  _self.controls = [];
  _self.setValue([]);
  _self.updateValueAndValidity();
  return _self;
}

Archive the artifacts in Jenkins

An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.

It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.

What is your favorite C programming trick?

I'm fond of using = {0}; to initialize structures without needing to call memset.

struct something X = {0};

This will initialize all of the members of the struct (or array) to zero (but not any padding bytes - use memset if you need to zero those as well).

But you should be aware there are some issues with this for large, dynamically allocated structures.

Nested attributes unpermitted parameters

or you can simply use

def question_params

  params.require(:question).permit(team_ids: [])

end

Correct file permissions for WordPress

Correct permissions for the file is 644 Correct permissions for the folder is 755

To change the permissions , use terminal and following commands.

find foldername -type d -exec chmod 755 {} \;
find foldername -type f -exec chmod 644 {} \;

755 for folders and 644 for files.

Get list of a class' instance methods

TestClass.methods(false) 

to get only methods that belong to that class only.

TestClass.instance_methods(false) would return the methods from your given example (since they are instance methods of TestClass).

NameError: name 'reduce' is not defined in Python

In this case I believe that the following is equivalent:

l = sum([1,2,3,4]) % 2

The only problem with this is that it creates big numbers, but maybe that is better than repeated modulo operations?

How to convert a Django QuerySet to a list

Try this values_list('column_name', flat=True).

answers = Answer.objects.filter(id__in=[answer.id for answer in answer_set.answers.all()]).values_list('column_name', flat=True)

It will return you a list with specified column values

psql: server closed the connection unexepectedly

Solved by setting a password for the user first.

In terminal

sudo -u <username> psql

ALTER USER <username> PASSWORD 'SetPassword';
# ALTER ROLE

\q

In pgAdmin

**Connection**

Host name/address: 127.0.0.1
Port: 5432
Maintenance database: postgres
username: postgres
password: XXXXXX

How to run a javascript function during a mouseover on a div

Using the title attribute:

<div id="sub1 sub2 sub3" title="some text on mouse over">some text</div>

The module was expected to contain an assembly manifest

I found another strange reason and i thought maybe another developer confused as me. I did run install.bat that created to install my service in developer Command Prompt of VS2010 but my service generated in VS2012. it was going to this error and drives me to crazy but i try VS2012 Developer Command Prompt tools and everything gone to be OK. I don't no why but my problem was solved. so you can test it and if anyone know reason of that please share with us. Thanks.

Explaining the 'find -mtime' command

To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.

find . -mtime -1 -ls

Python module for converting PDF to text

Found that solution today. Works great for me. Even rendering PDF pages to PNG images. http://www.swftools.org/gfx_tutorial.html

How to output (to a log) a multi-level array in a format that is human-readable?

I just wonder why nobody uses or recommends the way I prefer to debug an array:

error_log(json_encode($array));

Next to my browser I tail my server log in the console eg.

tail -f /var/log/apache2/error.log

Android - Share on Facebook, Twitter, Mail, ecc

String message = "This is testing."
Intent shareText = new Intent(Intent.ACTION_SEND);
shareText .setType("text/plain");
shareText .putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(shareText , "Title of the dialog the system will open"));

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

How to add to an existing hash in Ruby

x = {:ca => "Canada", :us => "United States"}
x[:de] = "Germany"
p x

Why can't I have abstract static methods in C#?

The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).

Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?

This limitation, which was only due to historical, code legacy reasons, has been lifted in recent versions of MySQL:

Changes in MySQL 5.6.5 (2012-04-10, Milestone 8)

Previously, at most one TIMESTAMP column per table could be automatically initialized or updated to the current date and time. This restriction has been lifted. Any TIMESTAMP column definition can have any combination of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses. In addition, these clauses now can be used with DATETIME column definitions. For more information, see Automatic Initialization and Updating for TIMESTAMP and DATETIME.

http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html

Adding an item to an associative array

I know this is an old question but you can use:

array_push($data, array($category => $question));

This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:

array_push($data,$question);

PostgreSQL Error: Relation already exists

Another reason why you might get errors like "relation already exists" is if the DROP command did not execute correctly.

One reason this can happen is if there are other sessions connected to the database which you need to close first.

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

There could be various reason for getting the SSH error:

sign_and_send_pubkey: signing failed: agent refused operation

Some of them could be related to the issues highlighted by the other answers (see this thread answers), some of them could be hidden and thus would require a closer investigation.

In my case I've got the following error message:

sign_and_send_pubkey: signing failed: agent refused operation

[email protected]: Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

The only way to find the real problem was to invoke the -v verbose option which resulted in printing a lot of debugging info:

debug1: Connecting to website.domain.com [xxx.xxx.xxx.xxx] port 22.
debug1: Connection established.
debug1: identity file /home/user/.ssh/id_rsa.website.domain.com type 0
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_rsa.website.domain.com-cert type -1

Please note that the line saying key_load_public: No such file or directory is referring the next line and not the previous line.

So what SSH really says is that it could not find the public key file named id_rsa.website.domain.com-cert and that seemed to be the problem in my case since my public key file did not contain the -cert suffix.

Long story short: the fix in my case was just to make sure that the public key file was named as expected. I could never suspected that without debugging the connection.

The bottom line is USE THE SSH VERBOSE MODE (-v option) to figure out what is wrong, there could be various reasons, none that could be found on this/another thread.

Check whether there is an Internet connection available on Flutter app

The connectivity plugin states in its docs that it only provides information if there is a network connection, but not if the network is connected to the Internet

Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.

You can use

import 'dart:io';
...
try {
  final result = await InternetAddress.lookup('google.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    print('connected');
  }
} on SocketException catch (_) {
  print('not connected');
}

Revert to a commit by a SHA hash in Git?

If you want to commit on top of the current HEAD with the exact state at a different commit, undoing all the intermediate commits, then you can use reset to create the correct state of the index to make the commit.

# Reset the index and working tree to the desired tree
# Ensure you have no uncommitted changes that you want to keep
git reset --hard 56e05fced

# Move the branch pointer back to the previous HEAD
git reset --soft HEAD@{1}

git commit -m "Revert to 56e05fced"

How to format a JavaScript date

Try this:

_x000D_
_x000D_
function init(){_x000D_
    var d = new Date();_x000D_
    var day = d.getDate();_x000D_
    var x = d.toDateString().substr(4, 3);_x000D_
    var year = d.getFullYear();_x000D_
    document.querySelector("#mydate").innerHTML = day + '-' + x + '-' + year;_x000D_
}_x000D_
window.onload = init;
_x000D_
<div id="mydate"></div>
_x000D_
_x000D_
_x000D_

CSS hover vs. JavaScript mouseover

The CSS one is much more maintainable and readable.

How to get filename without extension from file path in Ruby

If you have access to ENV variables, scan combined with this little regex (which finds the last but one word, a dot, then the last word of the string) will put the file's name into 'filename':

filename = ENV['SCRIPT_NAME'].scan(/\w+\.\w+$/)

Obviously, you can use scan and the regex on any path name that includes the filename, and __FILE__ is the obvious choice:

__FILE__.scan(/\w+\.\w+$/)

How can Print Preview be called from Javascript?

I think the best that's possible in cross-browser JavaScript is window.print(), which (in Firefox 3, for me) brings up the 'print' dialog and not the print preview dialog.

FYI, the print dialog is your computer's Print popup, what you get when you do Ctrl-p. The print preview is Firefox's own Preview window, and it has more options. It's what you get with Firefox Menu > Print...

Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET

I think you are using chrome. The problem is the certificate mismatch or the expiration of the certificate.Check your certificate properly.

Just visit here for more information.

Catch an exception thrown by an async void method

The reason the exception is not caught is because the Foo() method has a void return type and so when await is called, it simply returns. As DoFoo() is not awaiting the completion of Foo, the exception handler cannot be used.

This opens up a simpler solution if you can change the method signatures - alter Foo() so that it returns type Task and then DoFoo() can await Foo(), as in this code:

public async Task Foo() {
    var x = await DoSomethingThatThrows();
}

public async void DoFoo() {
    try {
        await Foo();
    } catch (ProtocolException ex) {
        // This will catch exceptions from DoSomethingThatThrows
    }
}

Custom Date/Time formatting in SQL Server

in MS SQL Server you can do:

SET DATEFORMAT ymd

year, month, day,

Display A Popup Only Once Per User

You can use removeItem() class of localStorage to destroy that key on browser close with:

window.onbeforeunload = function{
    localStorage.removeItem('your key');
};

PHP code to remove everything but numbers

You would need to enclose the pattern in a delimiter - typically a slash (/) is used. Try this:

echo preg_replace("/[^0-9]/","",'604-619-5135');

Android: Force EditText to remove focus?

In the comments you asked if another view can be focused instead of the EditText. Yes it can. Use .requestFocus() method for the view you want to be focused at the beginning (in onCreate() method)

Also focusing other view will cut out some amount of code. (code for hiding the keyboard for example)

How to Specify "Vary: Accept-Encoding" header in .htaccess

To gzip up your font files as well!

add "x-font/otf x-font/ttf x-font/eot"

as in:

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml x-font/otf x-font/ttf x-font/eot

npm install gives error "can't find a package.json file"

You don't say what module you want to install - hence npm looks for a file package.json which describes your dependencies, and obviously this file is missing.

So either you have to explicitly tell npm which module to install, e.g.

npm install express

or

npm install -g express-generator

or you have to add a package.json file and register your modules here. The easiest way to get such a file is to let npm create one by running

npm init

and then add what you need. Please note that this does only work for locally installed modules, not for global ones.

A simple example might look like this:

{
  "name": "myapp",
  "version": "0.0.1",
  "dependencies": {
    "express": "4.0.0"
  }
}

or something like that. For more info on the package.json file see its official documentation and this interactive guide.

How to select ALL children (in any level) from a parent in jQuery?

I think you could do:

$('#google_translate_element').find('*').each(function(){
    $(this).unbind('click');
});

but it would cause a lot of overhead

How to calculate the sentence similarity using word2vec model of gensim with python

Since you're using gensim, you should probably use it's doc2vec implementation. doc2vec is an extension of word2vec to the phrase-, sentence-, and document-level. It's a pretty simple extension, described here

http://cs.stanford.edu/~quocle/paragraph_vector.pdf

Gensim is nice because it's intuitive, fast, and flexible. What's great is that you can grab the pretrained word embeddings from the official word2vec page and the syn0 layer of gensim's Doc2Vec model is exposed so that you can seed the word embeddings with these high quality vectors!

GoogleNews-vectors-negative300.bin.gz (as linked in Google Code)

I think gensim is definitely the easiest (and so far for me, the best) tool for embedding a sentence in a vector space.

There exist other sentence-to-vector techniques than the one proposed in Le & Mikolov's paper above. Socher and Manning from Stanford are certainly two of the most famous researchers working in this area. Their work has been based on the principle of compositionally - semantics of the sentence come from:

1. semantics of the words

2. rules for how these words interact and combine into phrases

They've proposed a few such models (getting increasingly more complex) for how to use compositionality to build sentence-level representations.

2011 - unfolding recursive autoencoder (very comparatively simple. start here if interested)

2012 - matrix-vector neural network

2013 - neural tensor network

2015 - Tree LSTM

his papers are all available at socher.org. Some of these models are available, but I'd still recommend gensim's doc2vec. For one, the 2011 URAE isn't particularly powerful. In addition, it comes pretrained with weights suited for paraphrasing news-y data. The code he provides does not allow you to retrain the network. You also can't swap in different word vectors, so you're stuck with 2011's pre-word2vec embeddings from Turian. These vectors are certainly not on the level of word2vec's or GloVe's.

Haven't worked with the Tree LSTM yet, but it seems very promising!

tl;dr Yeah, use gensim's doc2vec. But other methods do exist!

How to use Global Variables in C#?

There's no such thing as a global variable in C#. Period.

You can have static members if you want:

public static class MyStaticValues
{
   public static bool MyStaticBool {get;set;}
}

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

So, when you are doing some JavaScript things with an <a /> tag and if you put href="#" as well, you can add return false at the end of the event (in case of inline event binding) like:

<a href="#" onclick="myJsFunc(); return false;">Run JavaScript Code</a>

Or you can change the href attribute with JavaScript like:

<a href="javascript://" onclick="myJsFunc();">Run JavaScript Code</a>

or

<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>

But semantically, all the above ways to achieve this are wrong (it works fine though). If any element is not created to navigate the page and that have some JavaScript things associated with it, then it should not be a <a> tag.

You can simply use a <button /> instead to do things or any other element like b, span or whatever fits there as per your need, because you are allowed to add events on all the elements.


So, there is one benefit to use <a href="#">. You get the cursor pointer by default on that element when you do a href="#". For that, I think you can use CSS for this like cursor:pointer; which solves this problem also.

And at the end, if you are binding the event from the JavaScript code itself, there you can do event.preventDefault() to achieve this if you are using <a> tag, but if you are not using a <a> tag for this, there you get an advantage, you don't need to do this.

So, if you see, it's better not to use a tag for this kind of stuff.

UITextView that expands to text using auto layout

Obj C:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic) UITextView *textView;
@end



#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize textView;

- (void)viewDidLoad{
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor grayColor]];
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(30,10,250,20)];
    self.textView.delegate = self;
    [self.view addSubview:self.textView];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

- (void)textViewDidChange:(UITextView *)txtView{
    float height = txtView.contentSize.height;
    [UITextView beginAnimations:nil context:nil];
    [UITextView setAnimationDuration:0.5];

    CGRect frame = txtView.frame;
    frame.size.height = height + 10.0; //Give it some padding
    txtView.frame = frame;
    [UITextView commitAnimations];
}

@end

Error: Cannot access file bin/Debug/... because it is being used by another process

I understand this is an old question. Unfortunately I was facing the same issue with my .net core 2.0 application in visual studio 2017. So, I thought of sharing the solution which worked for me. Before this solution I had tried the below steps.

  1. Restarted visual studio
  2. Closed all the application
  3. Clean my solution and rebuild

None of the above steps didn't fix the issue.

And then I opened my Task Manager and selected dotnet process and then clicked End task button. Later I opened my Visual Studio and everything was working fine.

enter image description here

jQuery ajax request with json response, how to?

You need to call the

$.parseJSON();

For example:

...
success: function(data){
       var json = $.parseJSON(data); // create an object with the key of the array
       alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
    },
    error: function(data){
       var json = $.parseJSON(data);
       alert(json.error);
    } ...

see this in http://api.jquery.com/jQuery.parseJSON/

if you still have the problem of slashes: search for security.magicquotes.disabling.php or: function.stripslashes.php

Note:

This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.

ITSAppUsesNonExemptEncryption export compliance while internal testing?

There are basically 2 things to bear in mind. You are only allowed to set it to NO if you either don't use encryption at all, or you are part of the exempt regulations. This applies to the following kind of applications:

Source: Chamber of Commerce: https://www.bis.doc.gov/index.php/policy-guidance/encryption/encryption-faqs#15

Consumer applications

  • piracy and theft prevention for software or music;
  • music, movies, tunes/music, digital photos – players, recorders and organizers
  • games/gaming – devices, runtime software, HDMI and other component interfaces, development tools
  • LCD TV, Blu-ray / DVD, video on demand (VoD), cinema, digital video recorders (DVRs) / personal video recorders (PVRs) – devices, on-line media guides, commercial content integrity and protection, HDMI and other component interfaces (not videoconferencing);
  • printers, copiers, scanners, digital cameras, Internet cameras – including parts and sub-assemblies
  • household utilities and appliances

Business / systems applications: systems operations, integration and control. Some examples

  • business process automation (BPA) – process planning and scheduling, supply chain management, inventory and delivery

  • transportation – safety and maintenance, systems monitoring and on-board controllers (including aviation, railway, and commercial automotive systems), ‘smart highway’ technologies, public transit operations and fare collection, etc.

  • industrial, manufacturing or mechanical systems - including robotics, plant safety, utilities, factory and other heavy equipment, facilities systems controllers such as fire alarms and HVAC

  • medical / clinical – including diagnostic applications, patient scheduling, and medical data records confidentiality

  • applied geosciences – mining / drilling, atmospheric sampling / weather monitoring, mapping / surveying, dams / hydrology

Research /scientific /analytical. Some examples:

  • business process management (BPM) – business process abstraction and modeling

  • scientific visualization / simulation / co-simulation (excluding such tools for computing, networking, cryptanalysis, etc.)

  • data synthesis tools for social, economic, and political sciences (e.g., economic, population, global climate change, public opinion polling, etc. forecasting and modeling)

Secure intellectual property delivery and installation. Some examples

  • software download auto-installers and updaters

  • license key product protection and similar purchase validation

  • software and hardware design IP protection

  • computer aided design (CAD) software and other drafting tools

Note: These regulations are also true for testing your app using TestFlight

PHP split alternative?

explode is an alternative. However, if you meant to split through a regular expression, the alternative is preg_split instead.

CSS animation delay in repeating

I would rather write a little JavaScript than make the CSS less manageable.

First, only apply the CSS animation on a data attribute change:

.progbar[data-animation="barshine"] {
    animation: barshine 1s linear;
}

Then add javascript to toggle the animation at half the delay amount.

var progbar = document.querySelector('.progbar');
var on = false;

setInterval(function () {
    progbar.setAttribute('data-animation', (on) ? 'barshine' : '');
    on = !on;
}, 3000);

Or if you don't want the animation to run when the tab is hidden:

var progbar = document.querySelector('.progbar');
var on = false;

var update = function () {
    progbar.setAttribute('data-animation', (on) ? 'barshine' : '');
    on = !on;
    setTimer();
};

var setTimer = function () {
    setTimeout(function () {
        requestAnimationFrame(update);
    }, 3000);
};

setTimer();

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 ...

Heap space out of memory

No. The heap is cleared by the garbage collector whenever it feels like it. You can ask it to run (with System.gc()) but it is not guaranteed to run.

First try increasing the memory by setting -Xmx256m

How do I minimize the command prompt from my bat file

One option is to find one of the various utilities that can change the window state of the currently running console window and make a call to it from within the batch script.

You can run it as the first thing in your batch script. Here are two such tools:

min.exe http://www.paulsadowski.com/wsh/cmdprogs.htm

cmdow http://www.commandline.co.uk/cmdow/index.html

JTable won't show column headers

The main difference between this answer and the accepted answer is the use of setViewportView() instead of add().

How to put JTable in JScrollPane using Eclipse IDE:

  1. Create JScrollPane container via Design tab.
  2. Stretch JScrollPane to desired size (applies to Absolute Layout).
  3. Drag and drop JTable component on top of JScrollPane (Viewport area).

In Structure > Components, table should be a child of scrollPane. enter image description here

The generated code would be something like this:

JScrollPane scrollPane = new JScrollPane();
...

JTable table = new JTable();
scrollPane.setViewportView(table);

Delete directory with files in it?

As seen in most voted comment on PHP manual page about rmdir() (see http://php.net/manual/es/function.rmdir.php), glob() function does not return hidden files. scandir() is provided as an alternative that solves that issue.

Algorithm described there (which worked like a charm in my case) is:

<?php 
    function delTree($dir)
    { 
        $files = array_diff(scandir($dir), array('.', '..')); 

        foreach ($files as $file) { 
            (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
        }

        return rmdir($dir); 
    } 
?>

ERROR: Google Maps API error: MissingKeyMapError

The script element that loads the API is missing the required authentication parameter. If you are using the standard Maps JavaScript API, you must use a key parameter with a valid API key. If you are a Premium Plan customer, you must use either a client parameter with your client ID or a key parameter with a valid API key.

See the guide to API keys and client IDs.

Correct way to find max in an Array in Swift

Update: This should probably be the accepted answer since maxElement appeared in Swift.


Use the almighty reduce:

let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, { max($0, $1) })

Similarly:

let numMin = nums.reduce(Int.max, { min($0, $1) })

reduce takes a first value that is the initial value for an internal accumulator variable, then applies the passed function (here, it's anonymous) to the accumulator and each element of the array successively, and stores the new value in the accumulator. The last accumulator value is then returned.

Checking if a key exists in a JS object

var obj = {
    "key1" : "k1",
    "key2" : "k2",
    "key3" : "k3"
};

if ("key1" in obj)
    console.log("has key1 in obj");

=========================================================================

To access a child key of another key

var obj = {
    "key1": "k1",
    "key2": "k2",
    "key3": "k3",
    "key4": {
        "keyF": "kf"
    }
};

if ("keyF" in obj.key4)
    console.log("has keyF in obj");

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

To prevent the flex items from shrinking, set the flex shrink factor to 0:

The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1.

.boxcontainer .box {
  flex-shrink: 0;
}

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
.wrapper {_x000D_
  width: 200px;_x000D_
  background-color: #EEEEEE;_x000D_
  border: 2px solid #DDDDDD;_x000D_
  padding: 1rem;_x000D_
}_x000D_
.boxcontainer {_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  border: 2px solid #BDC3C7;_x000D_
  transition: all 0.4s ease;_x000D_
  display: flex;_x000D_
}_x000D_
.boxcontainer .box {_x000D_
  width: 100%;_x000D_
  padding: 1rem;_x000D_
  flex-shrink: 0;_x000D_
}_x000D_
.boxcontainer .box:first-child {_x000D_
  background-color: #F47983;_x000D_
}_x000D_
.boxcontainer .box:nth-child(2) {_x000D_
  background-color: #FABCC1;_x000D_
}_x000D_
#slidetrigger:checked ~ .wrapper .boxcontainer {_x000D_
  left: -100%;_x000D_
}_x000D_
#overflowtrigger:checked ~ .wrapper {_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<input type="checkbox" id="overflowtrigger" />_x000D_
<label for="overflowtrigger">Hide overflow</label><br />_x000D_
<input type="checkbox" id="slidetrigger" />_x000D_
<label for="slidetrigger">Slide!</label>_x000D_
<div class="wrapper">_x000D_
  <div class="boxcontainer">_x000D_
    <div class="box">_x000D_
      First bunch of content._x000D_
    </div>_x000D_
    <div class="box">_x000D_
      Second load  of content._x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I check if a C++ string is an int?

If you're just checking if word is a number, that's not too hard:

#include <ctype.h>

...

string word;
bool isNumber = true;
for(string::const_iterator k = word.begin(); k != word.end(); ++k)
    isNumber &&= isdigit(*k);

Optimize as desired.

Bootstrap col-md-offset-* not working

Kindly use offset-md-4 instead of col-md-offset-4 in bootstrap 4. It's little changes adopted in bootstrap 4.

For more info

CAST DECIMAL to INT

A more optimized way in for this purpose*:

SELECT columnName DIV 1 AS columnName, moreColumns, etc
FROM myTable
WHERE ...

Using DIV 1 is a huge speed improvement over FLOOR, not to mention string based functions like FORMAT

mysql> SELECT BENCHMARK(10000000,1234567 DIV 7) ;
+-----------------------------------+
| BENCHMARK(10000000,1234567 DIV 7) |
+-----------------------------------+
|                                 0 |
+-----------------------------------+
1 row in set (0.83 sec)

mysql> SELECT BENCHMARK(10000000,1234567 / 7) ;
+---------------------------------+
| BENCHMARK(10000000,1234567 / 7) |
+---------------------------------+
|                               0 |
+---------------------------------+
1 row in set (7.26 sec)

mysql> SELECT BENCHMARK(10000000,FLOOR(1234567 / 7)) ;
+----------------------------------------+
| BENCHMARK(10000000,FLOOR(1234567 / 7)) |
+----------------------------------------+
|                                      0 |
+----------------------------------------+
1 row in set (8.80 sec)

(*) NOTE: As pointed by Grbts, be aware of the behaviour of DIV 1 when used with non unsigned/positive values.

Android: alternate layout xml for landscape mode

By default, the layouts in /res/layout are applied to both portrait and landscape.

If you have for example

/res/layout/main.xml

you can add a new folder /res/layout-land, copy main.xml into it and make the needed adjustments.

orientation

See also http://www.androidpeople.com/android-portrait-amp-landscape-differeent-layouts and http://www.devx.com/wireless/Article/40792/1954 for some more options.

Convert a matrix to a 1 dimensional array

Either read it in with 'scan', or just do as.vector() on the matrix. You might want to transpose the matrix first if you want it by rows or columns.

> m=matrix(1:12,3,4)
> m
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> as.vector(m)
 [1]  1  2  3  4  5  6  7  8  9 10 11 12
> as.vector(t(m))
 [1]  1  4  7 10  2  5  8 11  3  6  9 12

When is a language considered a scripting language?

I always looked at scripting languages as a means to communicate with some sort of application or program. In contrast, a language which is compiled actually creates the program itself.

Now keep in mind that a scripting language usually adds on to or modifies the program that was initially created with a language that was compiled. Thus, it can certainly be part of the larger picture but the initial binaries are first created with a language that is compiled.

So I could create a scripting language which lets users perform various actions or customize my program. My program would interpret the scripted code and in turn call some kind of function. This is just a basic example. It just gives you a way to dynamically call routines within the program.

My program would have to parse the scripted code (you could refer to these as commands) and execute whatever action was intended in real time.

I see this question was already answered several times but I thought I would add my way of looking at things into the mix. Granted, some folks may disagree with this answer but this way of thinking has always helped me.

Cannot find module cv2 when using OpenCV

Try this out:

sudo ldconfig

sudo nano /etc/ld.so.conf.d/opencv.conf

and add this following line in the opencv.conf not in the command window

/usr/local/lib

Then:

sudo ldconfig

sudo nano /etc/bash.bashrc

and add this two lines in the bash.bashrc not in the command window

PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig       
export PKG_CONFIG_PATH

at last reboot your Pi sudo reboot now

and try import cv2

CSS media query to target iPad and iPad only?

<html>
<head>
    <title>orientation and device detection in css3</title>

    <link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:portrait)" href="iphone-portrait.css" />
    <link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:landscape)" href="iphone-landscape.css" />
    <link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait)" href="ipad-portrait.css" />
    <link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape)" href="ipad-landscape.css" />
    <link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 1184px) and (orientation:portrait)" href="htcdesire-portrait.css" />
    <link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 390px) and (orientation:landscape)" href="htcdesire-landscape.css" />
    <link rel="stylesheet" media="all and (min-device-width: 1025px)" href="desktop.css" />

</head>
<body>
    <div id="iphonelandscape">iphone landscape</div>
    <div id="iphoneportrait">iphone portrait</div>
    <div id="ipadlandscape">ipad landscape</div>
    <div id="ipadportrait">ipad portrait</div>
    <div id="htcdesirelandscape">htc desire landscape</div>
    <div id="htcdesireportrait">htc desire portrait</div>
    <div id="desktop">desktop</div>
    <script type="text/javascript">
        function res() { document.write(screen.width + ', ' + screen.height); }
        res();
    </script>
</body>
</html>

Getting list of lists into pandas DataFrame

Call the pd.DataFrame constructor directly:

df = pd.DataFrame(table, columns=headers)
df

   Heading1  Heading2
0         1         2
1         3         4

Converting byte array to String (Java)

You can try this.

String s = new String(bytearray);

Insert using LEFT JOIN and INNER JOIN

You have to be specific about the columns you are selecting. If your user table had four columns id, name, username, opted_in you must select exactly those four columns from the query. The syntax looks like:

INSERT INTO user (id, name, username, opted_in)
  SELECT id, name, username, opted_in 
  FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id

However, there does not appear to be any reason to join against user_permission here, since none of the columns from that table would be inserted into user. In fact, this INSERT seems bound to fail with primary key uniqueness violations.

MySQL does not support inserts into multiple tables at the same time. You either need to perform two INSERT statements in your code, using the last insert id from the first query, or create an AFTER INSERT trigger on the primary table.

INSERT INTO user (name, username, email, opted_in) VALUES ('a','b','c',0);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(), 4)

Or using a trigger:

CREATE TRIGGER creat_perms AFTER INSERT ON `user`
FOR EACH ROW
BEGIN
  INSERT INTO user_permission (user_id, permission_id) VALUES (NEW.id, 4)
END