Programs & Examples On #Amazon sns

Amazon Simple Notification Service (Amazon SNS) is a web service that makes it easy to set up, operate, and send notifications from the cloud. It provides developers with a highly scalable, flexible, and cost-effective capability to publish messages from an application and immediately deliver them to subscribers or other applications. It is designed to make web-scale computing easier for developers.

What is the difference between Amazon SNS and Amazon SQS?

SNS is a distributed publish-subscribe system. Messages are pushed to subscribers as and when they are sent by publishers to SNS.

SQS is distributed queuing system. Messages are not pushed to receivers. Receivers have to poll or pull messages from SQS. Messages can't be received by multiple receivers at the same time. Any one receiver can receive a message, process and delete it. Other receivers do not receive the same message later. Polling inherently introduces some latency in message delivery in SQS unlike SNS where messages are immediately pushed to subscribers. SNS supports several end points such as email, SMS, HTTP end point and SQS. If you want unknown number and type of subscribers to receive messages, you need SNS.

You don't have to couple SNS and SQS always. You can have SNS send messages to email, SMS or HTTP end point apart from SQS. There are advantages to coupling SNS with SQS. You may not want an external service to make connections to your hosts (a firewall may block all incoming connections to your host from outside).

Your end point may just die because of heavy volume of messages. Email and SMS maybe not your choice of processing messages quickly. By coupling SNS with SQS, you can receive messages at your pace. It allows clients to be offline, tolerant to network and host failures. You also achieve guaranteed delivery. If you configure SNS to send messages to an HTTP end point or email or SMS, several failures to send message may result in messages being dropped.

SQS is mainly used to decouple applications or integrate applications. Messages can be stored in SQS for a short duration of time (maximum 14 days). SNS distributes several copies of messages to several subscribers. For example, let’s say you want to replicate data generated by an application to several storage systems. You could use SNS and send this data to multiple subscribers, each replicating the messages it receives to different storage systems (S3, hard disk on your host, database, etc.).

How to replace captured groups only?

Now that Javascript has lookbehind (as of ES2018), on newer environments, you can avoid groups entirely in situations like these. Rather, lookbehind for what comes before the group you were capturing, and lookahead for what comes after, and replace with just !NEW_ID!:

_x000D_
_x000D_
const str = 'name="some_text_0_some_text"';
console.log(
  str.replace(/(?<=name="\w+)\d+(?=\w+")/, '!NEW_ID!')
);
_x000D_
_x000D_
_x000D_

With this method, the full match is only the part that needs to be replaced.

  • (?<=name="\w+) - Lookbehind for name=", followed by word characters (luckily, lookbehinds do not have to be fixed width in Javascript!)
  • \d+ - Match one or more digits - the only part of the pattern not in a lookaround, the only part of the string that will be in the resulting match
  • (?=\w+") - Lookahead for word characters followed by " `

Keep in mind that lookbehind is pretty new. It works in modern versions of V8 (including Chrome, Opera, and Node), but not in most other environments, at least not yet. So while you can reliably use lookbehind in Node and in your own browser (if it runs on a modern version of V8), it's not yet sufficiently supported by random clients (like on a public website).

CSS strikethrough different color from text?

Here is a sample jQuery implementation – thanks to gojomo's answer and utype's suggestion (+1 for both)

$(function(){
  //===================================================================
  // Special price strike-out text
  // Usage:
  //   Normally:    <span class='price'>$59</span>
  //   On special:  <span class='price' special='$29'>$59</span>
  //===================================================================
  $(".price[special]").each(function() {
    var originalPrice = $(this).text();
    $(this).html('<strike><span>' + originalPrice +'</span></strike> ' + $(this).attr('special'))
           .removeAttr('special')
           .addClass('special');
  });
});

The CSS for that could be

.price strike, .price.special { color: Red; }
.price strike span { color: Black; }

Check whether an input string contains a number in javascript

You can also try lodash:

const isNumeric = number => 
  _.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))

How do you do dynamic / dependent drop downs in Google Sheets?

Here you have another solution based on the one provided by @tarheel

function onEdit() {
    var sheetWithNestedSelectsName = "Sitemap";
    var columnWithNestedSelectsRoot = 1;
    var sheetWithOptionPossibleValuesSuffix = "TabSections";

    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var activeSheet = SpreadsheetApp.getActiveSheet();

    // If we're not in the sheet with nested selects, exit!
    if ( activeSheet.getName() != sheetWithNestedSelectsName ) {
        return;
    }

    var activeCell = SpreadsheetApp.getActiveRange();

    // If we're not in the root column or a content row, exit!
    if ( activeCell.getColumn() != columnWithNestedSelectsRoot || activeCell.getRow() < 2 ) {
        return;
    }

    var sheetWithActiveOptionPossibleValues = activeSpreadsheet.getSheetByName( activeCell.getValue() + sheetWithOptionPossibleValuesSuffix );

    // Get all possible values
    var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues.getSheetValues( 1, 1, -1, 1 );

    var possibleValuesValidation = SpreadsheetApp.newDataValidation();
    possibleValuesValidation.setAllowInvalid( false );
    possibleValuesValidation.requireValueInList( activeOptionPossibleValues, true );

    activeSheet.getRange( activeCell.getRow(), activeCell.getColumn() + 1 ).setDataValidation( possibleValuesValidation.build() );
}

It has some benefits over the other approach:

  • You don't need to edit the script every time you add a "root option". You only have to create a new sheet with the nested options of this root option.
  • I've refactored the script providing more semantic names for the variables and so on. Furthermore, I've extracted some parameters to variables in order to make it easier to adapt to your specific case. You only have to set the first 3 values.
  • There's no limit of nested option values (I've used the getSheetValues method with the -1 value).

So, how to use it:

  1. Create the sheet where you'll have the nested selectors
  2. Go to the "Tools" > "Script Editor…" and select the "Blank project" option
  3. Paste the code attached to this answer
  4. Modify the first 3 variables of the script setting up your values and save it
  5. Create one sheet within this same document for each possible value of the "root selector". They must be named as the value + the specified suffix.

Enjoy!

Drawing a dot on HTML5 canvas

This should do the job

//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");

//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

Can attributes be added dynamically in C#?

You can't. One workaround might be to generate a derived class at runtime and adding the attribute, although this is probably bit of an overkill.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

Display date in dd/mm/yyyy format in vb.net

if you want to display date along with time when you export to Excel then you can use this

xlWorkSheet.Cells(nRow, 3).NumberFormat = "dd/mm/yy h:mm AM/PM"

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Make sure you are sending the proper parameters too. This happened to me after switching to UI-Router.

To fix it, I changed $routeParams to use $stateParams in my controller. The main issue was that $stateParams was no longer sending a proper parameter to the resource.

Objective-C and Swift URL encoding

int strLength = 0;
NSString *urlStr = @"http://www";
NSLog(@" urlStr : %@", urlStr );
NSMutableString *mutableUrlStr = [urlStr mutableCopy];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@":" withString:@"%3A" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );

Convert integers to strings to create output filenames at run time

I've tried @Alejandro and @user2361779 already but it gives me an unsatisfied result such as file 1.txt or file1 .txt instead of file1.txt. However i find the better solution:

...
integer :: i
character(len=5) :: char_i     ! use your maximum expected len
character(len=32) :: filename

write(char_i, '(I5)') i        ! convert integer to char
write(filename, '("path/to/file/", A, ".dat")') trim(adjustl(char_i))
...

Explanation:

e.g. set i = 10 and write(char_i, '(I5)') i

char_i                gives  "   10" ! this is original value of char_i

adjustl(char_i)       gives  "10   " ! adjust char_i to the left

trim(adjustl(char_i)) gives  "10"    ! adjust char_i to the left then remove blank space on the right

I think this is a simplest solution that give you a dynamical length filename without any legacy blank spaces from integer to string conversion process.

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

Option 1:

You can set CMake variables at command line like this:

cmake -D CMAKE_C_COMPILER="/path/to/your/c/compiler/executable" -D CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable" /path/to/directory/containing/CMakeLists.txt

See this to learn how to create a CMake cache entry.


Option 2:

In your shell script build_ios.sh you can set environment variables CC and CXX to point to your C and C++ compiler executable respectively, example:

export CC=/path/to/your/c/compiler/executable
export CXX=/path/to/your/cpp/compiler/executable
cmake /path/to/directory/containing/CMakeLists.txt

Option 3:

Edit the CMakeLists.txt file of "Assimp": Add these lines at the top (must be added before you use project() or enable_language() command)

set(CMAKE_C_COMPILER "/path/to/your/c/compiler/executable")
set(CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable")

See this to learn how to use set command in CMake. Also this is a useful resource for understanding use of some of the common CMake variables.


Here is the relevant entry from the official FAQ: https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

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

  • Build solution will perform an incremental build: if it doesn't think it needs to rebuild a project, it won't. It may also use partially-built bits of the project if they haven't changed (I don't know how far it takes this)
  • Rebuild solution will clean and then build the solution from scratch, ignoring anything it's done before. The difference between this and "Clean, followed by Build" is that Rebuild will clean-then-build each project, one at a time, rather than cleaning all and then building all.
  • Clean solution will remove the build artifacts from the previous build. If there are any other files in the build target directories (bin and obj) they may not be removed, but actual build artifacts are. I've seen behaviour for this vary - sometimes deleting fairly thoroughly and sometimes not - but I'll give VS the benefit of the doubt for the moment :)

(The links are to the devenv.exe command line switches, but they do the same as the menu items.)

How to get a tab character?

Posting another alternative to be more complete. When I tried the "pre" based answers, they added extra vertical line breaks as well.

Each tab can be converted to a sequence non-breaking spaces which require no wrapping.

"&nbsp;&nbsp;&nbsp;&nbsp;" 

This is not recommended for repeated/extensive use within a page. A div margin/padding approach would appear much cleaner.

JSON parsing using Gson for Java

Simplest thing usually is to create matching Object hierarchy, like so:

public class Wrapper {
   public Data data;
}
static class Data {
   public Translation[] translations;
}
static class Translation {
   public String translatedText;
}

and then bind using GSON, traverse object hierarchy via fields. Adding getters and setters is pointless for basic data containers.

So something like:

Wrapper value = GSON.fromJSON(jsonString, Wrapper.class);
String text = value.data.translations[0].translatedText;

How can I convert a string with dot and comma into a float in Python

If you have a comma as decimals separator and the dot as thousands separator, you can do:

s = s.replace('.','').replace(',','.')
number = float(s)

Hope it will help

How to check if a particular service is running on Ubuntu

Dirty way to find running services. (sometime it is not accurate because some custom script doesn't have |status| option)

[root@server ~]# for qw in `ls /etc/init.d/*`; do  $qw status | grep -i running; done
auditd (pid  1089) is running...
crond (pid  1296) is running...
fail2ban-server (pid  1309) is running...
httpd (pid  7895) is running...
messagebus (pid  1145) is running...
mysqld (pid  1994) is running...
master (pid  1272) is running...
radiusd (pid  1712) is running...
redis-server (pid  1133) is running...
rsyslogd (pid  1109) is running...
openssh-daemon (pid  7040) is running...

Java Minimum and Maximum values in Array

getMaxValue(array);
// get smallest number
getMinValue(array);

You are calling the methods but not using the returned values.

System.out.println(getMaxValue(array));
System.out.println(getMinValue(array)); 

Difference between string and char[] types in C++

Strings have helper functions and manage char arrays automatically. You can concatenate strings, for a char array you would need to copy it to a new array, strings can change their length at runtime. A char array is harder to manage than a string and certain functions may only accept a string as input, requiring you to convert the array to a string. It's better to use strings, they were made so that you don't have to use arrays. If arrays were objectively better we wouldn't have strings.

How can I style a PHP echo text?

You can style it by the following way:

echo "<p style='color:red;'>" . $ip['cityName'] . "</p>";
echo "<p style='color:red;'>" . $ip['countryName'] . "</p>";

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

You can skip the var declaration and the stringify. Otherwise, that will work just fine.

$.ajax({
    url: '/home/check',
    type: 'POST',
    data: {
        Address1: "423 Judy Road",
        Address2: "1001",
        City: "New York",
        State: "NY",
        ZipCode: "10301",
        Country: "USA"
    },
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert(data.success);
    },
    error: function () {
        alert("error");
    }
});

Delete many rows from a table using id in Mysql

The best way is to use IN statement :

DELETE from tablename WHERE id IN (1,2,3,...,254);

You can also use BETWEEN if you have consecutive IDs :

DELETE from tablename WHERE id BETWEEN 1 AND 254;

You can of course limit for some IDs using other WHERE clause :

DELETE from tablename WHERE id BETWEEN 1 AND 254 AND id<>10;

jQuery Validation using the class instead of the name value

Here's my solution (requires no jQuery... just JavaScript):

function argsToArray(args) {
  var r = []; for (var i = 0; i < args.length; i++)
    r.push(args[i]);
  return r;
}
function bind() {
  var initArgs = argsToArray(arguments);
  var fx =        initArgs.shift();
  var tObj =      initArgs.shift();
  var args =      initArgs;
  return function() {
    return fx.apply(tObj, args.concat(argsToArray(arguments)));
  };
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
  checkbox.addEventListener('change', bind(function(checkbox, salutation) {
    var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
    if (numChecked >= 4)
      checkbox.checked = false;
  }, null, checkbox, salutation), false);
});

Put this in a script block at the end of <body> and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).

Here, I'll even give you a test page (paste it into a file and try it):

<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
    function argsToArray(args) {
      var r = []; for (var i = 0; i < args.length; i++)
        r.push(args[i]);
      return r;
    }
    function bind() {
      var initArgs = argsToArray(arguments);
      var fx =        initArgs.shift();
      var tObj =      initArgs.shift();
      var args =      initArgs;
      return function() {
        return fx.apply(tObj, args.concat(argsToArray(arguments)));
      };
    }
    var salutation = argsToArray(document.getElementsByClassName('salutation'));
    salutation.forEach(function(checkbox) {
      checkbox.addEventListener('change', bind(function(checkbox, salutation) {
        var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
        if (numChecked >= 3)
          checkbox.checked = false;
      }, null, checkbox, salutation), false);
    });
</script></body></html>

python convert list to dictionary

I'd go for recursions:

l = ['a', 'b', 'c', 'd', 'e', ' ']
d = dict([(k, v) for k,v in zip (l[::2], l[1::2])])

How to get data from database in javascript based on the value passed to the function

'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'

For example, if val is "10" then this will end up building the string:

"SELECT * FROM Employ where number = 10;"

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

dataframe['column'].squeeze() should solve this. It basically changes the dataframe column to a list.

Converting dictionary to JSON

Defining r as a dictionary should do the trick:

>>> r: dict = {'is_claimed': 'True', 'rating': 3.5}
>>> print(r['rating'])
3.5
>>> type(r)
<class 'dict'>

Get the correct week number of a given date

In PowerShell 7.x.y: You will need both of the following codelines, if you have the need for the matching WeekYear.

[System.Globalization.ISOWeek]::GetWeekOfYear((get-date))
[System.Globalization.ISOWeek]::GetYear((get-date))

Creating a SOAP call using PHP with an XML body

There are a couple of ways to solve this. The least hackiest and almost what you want:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
    )
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);

This gets you the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
    <SOAP-ENV:Body>
        <ns1:Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </ns1:Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo> tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT, to the options array like this:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
        'style' => SOAP_DOCUMENT,
    )
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);

This results in the following request XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.

How to put a new line into a wpf TextBlock control?

You have to ensure that the textblock has this option enabled:

AcceptsReturn="True"

MySQL Sum() multiple columns

SELECT student, (SUM(mark1)+SUM(mark2)+SUM(mark3)....+SUM(markn)) AS Total
 FROM your_table
 GROUP BY student

The thread has exited with code 0 (0x0) with no unhandled exception

This is just debugging message. You can switch that off by right clicking into the output window and uncheck Thread Exit Messages.

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

In addition to program out from your application, the Output window can display the information about:

  • Modules the debugger has loaded or unloaded.

  • Exceptions that are thrown.

  • Processes that exit.

  • Threads that exit.

How do I remove version tracking from a project cloned from git?

In addition to the steps below, you may want to also remove the .gitignore file.

  • Consider removing the .gitignore file if you want to remove any trace of Git in your project.

  • ** Consider leaving the .gitignore file if you would ever want reincorporate Git into the project.

Some frameworks may automatically produce the .gitignore file so you may want to leave it.


Linux, Mac, or Unix based operating systems

Open a terminal and navigate to the directory of your project, i.e. - cd path_to_your_project.

Run this command:

rm -rf .git*

This will remove the Git tracking and metadata from your project. If you want to keep the metadata (such as .gitignore and .gitkeep), you can delete only the tracking by running rm -rf .git.


Windows

Using the command prompt

The rmdir or rd command will not delete/remove any hidden files or folders within the directory you specify, so you should use the del command to be sure that all files are removed from the .git folder.

  1. Open the command prompt

    1. Either click Start then Run or hit the Windows key key and r at the same time.

    2. Type cmd and hit enter

  2. Navigate to the project directory, i.e. - cd path_to_your_project

  1. Run these commands

    1. del /F /S /Q /A .git

    2. rmdir .git

The first command removes all files and folder within the .git folder. The second removes the .git folder itself.

No command prompt

  1. Open the file explorer and navigate to your project

  2. Show hidden files and folders - refer to this article for a visual guide

    1. In the view menu on the toolbar, select Options

    2. In the Advanced Settings section, find Hidden files and Folders under the Files and Folders list and select Show hidden files and folders

  3. Close the options menu and you should see all hidden folders and files including the .git folder.

    Delete the .git folder Delete the .gitignore file ** (see note at the top of this answer)

How to do this in Laravel, subquery where in

You can use variable by using keyword "use ($category_id)"

$category_id = array('223','15');
Products::whereIn('id', function($query) use ($category_id){
   $query->select('paper_type_id')
     ->from(with(new ProductCategory)->getTable())
     ->whereIn('category_id', $category_id )
     ->where('active', 1);
})->get();

MySQL's now() +1 day

INSERT INTO `table` ( `data` , `date` ) VALUES('".$data."',NOW()+INTERVAL 1 DAY);

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

How to coerce a list object to type 'double'

If you want to convert all elements of a to a single numeric vector and length(a) is greater than 1 (OK, even if it is of length 1), you could unlist the object first and then convert.

as.numeric(unlist(a))
# [1]  10  38  66 101 129 185 283 374

Bear in mind that there aren't any quality controls here. Also, X$Days a mighty odd name.

How to vertically align <li> elements in <ul>?

I had the same problem. Try this.

<nav>
    <ul>
        <li><a href="#">AnaSayfa</a></li>
        <li><a href="#">Hakkimizda</a></li>
        <li><a href="#">Iletisim</a></li>
    </ul>
</nav>
@charset "utf-8";

nav {
    background-color: #9900CC;
    height: 80px;
    width: 400px;
}

ul {
    list-style: none;
    float: right;
    margin: 0;
}

li {
    float: left;
    width: 100px;
    line-height: 80px;
    vertical-align: middle;
    text-align: center;
    margin: 0;
}

nav li a {
    width: 100px;
    text-decoration: none;
    color: #FFFFFF;
}

Spring Boot - Cannot determine embedded database driver class for database type NONE

if you do not have any database in your application simply disable the auto-config of datasource by adding below annotation.

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

force browsers to get latest js and css files in asp.net application

Based on the above answer I've written a small extension class to work with CSS and JS files:

public static class TimestampedContentExtensions
{
    public static string VersionedContent(this UrlHelper helper, string contentPath)
    {
        var context = helper.RequestContext.HttpContext;

        if (context.Cache[contentPath] == null)
        {
            var physicalPath = context.Server.MapPath(contentPath);
            var version = @"v=" + new FileInfo(physicalPath).LastWriteTime.ToString(@"yyyyMMddHHmmss");

            var translatedContentPath = helper.Content(contentPath);

            var versionedContentPath =
                contentPath.Contains(@"?")
                    ? translatedContentPath + @"&" + version
                    : translatedContentPath + @"?" + version;

            context.Cache.Add(physicalPath, version, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero,
                CacheItemPriority.Normal, null);

            context.Cache[contentPath] = versionedContentPath;
            return versionedContentPath;
        }
        else
        {
            return context.Cache[contentPath] as string;
        }
    }
}

Instead of writing something like:

<link href="@Url.Content(@"~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content(@"~/Scripts/bootstrap.min.js")"></script>

You can now write:

<link href="@Url.VersionedContent(@"~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />
<script src="@Url.VersionedContent(@"~/Scripts/bootstrap.min.js")"></script>

I.e. simply replace Url.Content with Url.VersionedContent.

Generated URLs look something like:

<link href="/Content/bootstrap.min.css?v=20151104105858" rel="stylesheet" type="text/css" />
<script src="/Scripts/bootstrap.min.js?v=20151029213517"></script>

If you use the extension class you might want to add error handling in case the MapPath call doesn't work, since contentPath isn't a physical file.

How do I run a single test using Jest?

There is now a nice Jest plugin for this called jest-watch-typeahead it makes this process much simpler.

Can I serve multiple clients using just Flask app.run() as standalone?

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

Possible to make labels appear when hovering over a point in matplotlib?

showing object information in matplotlib statusbar

enter image description here

Features

  • no extra libraries needed
  • clean plot
  • no overlap of labels and artists
  • supports multi artist labeling
  • can handle artists from different plotting calls (like scatter, plot, add_patch)
  • code in library style

Code

### imports
import matplotlib as mpl
import matplotlib.pylab as plt
import numpy as np


# https://stackoverflow.com/a/47166787/7128154
# https://matplotlib.org/3.3.3/api/collections_api.html#matplotlib.collections.PathCollection
# https://matplotlib.org/3.3.3/api/path_api.html#matplotlib.path.Path
# https://stackoverflow.com/questions/15876011/add-information-to-matplotlib-navigation-toolbar-status-bar
# https://stackoverflow.com/questions/36730261/matplotlib-path-contains-point
# https://stackoverflow.com/a/36335048/7128154
class StatusbarHoverManager:
    """
    Manage hover information for mpl.axes.Axes object based on appearing
    artists.

    Attributes
    ----------
    ax : mpl.axes.Axes
        subplot to show status information
    artists : list of mpl.artist.Artist
        elements on the subplot, which react to mouse over
    labels : list (list of strings) or strings
        each element on the top level corresponds to an artist.
        if the artist has items
        (i.e. second return value of contains() has key 'ind'),
        the element has to be of type list.
        otherwise the element if of type string
    cid : to reconnect motion_notify_event
    """
    def __init__(self, ax):
        assert isinstance(ax, mpl.axes.Axes)


        def hover(event):
            if event.inaxes != ax:
                return
            info = 'x={:.2f}, y={:.2f}'.format(event.xdata, event.ydata)
            ax.format_coord = lambda x, y: info
        cid = ax.figure.canvas.mpl_connect("motion_notify_event", hover)

        self.ax = ax
        self.cid = cid
        self.artists = []
        self.labels = []

    def add_artist_labels(self, artist, label):
        if isinstance(artist, list):
            assert len(artist) == 1
            artist = artist[0]

        self.artists += [artist]
        self.labels += [label]

        def hover(event):
            if event.inaxes != self.ax:
                return
            info = 'x={:.2f}, y={:.2f}'.format(event.xdata, event.ydata)
            for aa, artist in enumerate(self.artists):
                cont, dct = artist.contains(event)
                if not cont:
                    continue
                inds = dct.get('ind')
                if inds is not None:  # artist contains items
                    for ii in inds:
                        lbl = self.labels[aa][ii]
                        info += ';   artist [{:d}, {:d}]: {:}'.format(
                            aa, ii, lbl)
                else:
                    lbl = self.labels[aa]
                    info += ';   artist [{:d}]: {:}'.format(aa, lbl)
            self.ax.format_coord = lambda x, y: info

        self.ax.figure.canvas.mpl_disconnect(self.cid)
        self.cid = self.ax.figure.canvas.mpl_connect(
            "motion_notify_event", hover)



def demo_StatusbarHoverManager():
    fig, ax = plt.subplots()
    shm = StatusbarHoverManager(ax)

    poly = mpl.patches.Polygon(
        [[0,0], [3, 5], [5, 4], [6,1]], closed=True, color='green', zorder=0)
    artist = ax.add_patch(poly)
    shm.add_artist_labels(artist, 'polygon')

    artist = ax.scatter([2.5, 1, 2, 3], [6, 1, 1, 7], c='blue', s=10**2)
    lbls = ['point ' + str(ii) for ii in range(4)]
    shm.add_artist_labels(artist, lbls)

    artist = ax.plot(
        [0, 0, 1, 5, 3], [0, 1, 1, 0, 2], marker='o', color='red')
    lbls = ['segment ' + str(ii) for ii in range(5)]
    shm.add_artist_labels(artist, lbls)

    plt.show()


# --- main
if __name__== "__main__":
    demo_StatusbarHoverManager()

How to recursively delete an entire directory with PowerShell 2.0?

When deleting files recursively using a simple Remove-Item "folder" -Recurse I sometimes see an intermittent error : [folder] cannot be removed because it is not empty.

This answer attempts to prevent that error by individually deleting the files.

function Get-Tree($Path,$Include='*') { 
    @(Get-Item $Path -Include $Include -Force) + 
        (Get-ChildItem $Path -Recurse -Include $Include -Force) | 
        sort pspath -Descending -unique
} 

function Remove-Tree($Path,$Include='*') { 
    Get-Tree $Path $Include | Remove-Item -force -recurse
} 

Remove-Tree some_dir

An important detail is the sorting of all the items with pspath -Descending so that the leaves are deleted before the roots. The sorting is done on the pspath parameter since that has more chance of working for providers other than the file system. The -Include parameter is just a convenience if you want to filter the items to delete.

It's split into two functions since I find it useful to see what I'm about to delete by running

Get-Tree some_dir | select fullname

Not an enclosing class error Android Studio

It should be

Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);

You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.

not an enclosing class error is thrown because of your usage of this keyword. this is a reference to the current object — the object whose method or constructor is being called. With this you can only refer to any member of the current object from within an instance method or a constructor.

Katra_home.this is invalid construct

The requested resource does not support HTTP method 'GET'

In my case, the route signature was different from the method parameter. I had id, but I was accepting documentId as parameter, that caused the problem.

[Route("Documents/{id}")]   <--- caused the webapi error
[Route("Documents/{documentId}")] <-- solved
public Document Get(string documentId)
{
  ..
}

Mercurial stuck "waiting for lock"

If it only happens on mapped drives it might be bug https://bitbucket.org/tortoisehg/thg/issue/889/cant-commit-file-over-network-share. Using UNC path instead of drive letter seems to sidestep the issue.

Need to get current timestamp in Java

Joda-Time

Here is the same kind of code but using the third-party library Joda-Time 2.3.

In real life, I would specify a time zone, as relying on default zone is usually a bad practice. But omitted here for simplicity of example.

org.joda.time.DateTime now = new DateTime();
org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy h:mm:ss a" );
String nowAsString = formatter.print( now );

System.out.println( "nowAsString: " + nowAsString );

When run…

nowAsString: 11/28/2013 11:28:15 PM

Spring JUnit: How to Mock autowired component in autowired component

I created blog post on the topic. It contains also link to Github repository with working example.

The trick is using test configuration, where you override original spring bean with fake one. You can use @Primary and @Profile annotations for this trick.

Is it possible to make desktop GUI application in .NET Core?

It will be available using .NET 6: https://devblogs.microsoft.com/dotnet/announcing-net-6-preview-1/

But you can already create WinForms applications using netcore 3.1 and net 5 (at least in Visual Studio 2019 16.8.4+).

Create winforms app sample

UI Constructor available

How to generate components in a specific folder with Angular CLI?

To open a terminal in VS code just type CTRL + ~ which will open the terminal. Here are the steps:

  1. Check for the particular component where you need to generate the new component.

  2. Redirect the path to the particular folder/component where you need to generate another component

FOR EXAMPLE: cd src/app/particularComponent

In the place of particularComponent, type the component name in which you need to generate the new component.

  1. Once you are in the component where you need to generate the new component, just type this command: ng g c NewComponentName

(Change the name NewComponentName to your required component name.)

How to keep indent for second line in ordered lists via CSS?

CSS provides only two values for its "list-style-position" - inside and outside. With "inside" second lines are flush with the list points not with the superior line:

In ordered lists, without intervention, if you give "list-style-position" the value "inside", the second line of a long list item will have no indent, but will go back to the left edge of the list (i.e. it will left-align with the number of the item). This is peculiar to ordered lists and doesn't happen in unordered lists.

If you instead give "list-style-position" the value "outside", the second line will have the same indent as the first line.

I had a list with a border and had this problem. With "list-style-position" set to "inside", my list didn't look like I wanted it to. But with "list-style-position" set to "outside", the numbers of the list items fell outside the box.

I solved this by simply setting a wider left margin for the whole list, which pushed the whole list toward the right, back into the position it was in before.

CSS:

ol.classname {margin:0;padding:0;}

ol.classname li {margin:0.5em 0 0 0;padding-left:0;list-style-position:outside;}

HTML:

<ol class="classname" style="margin:0 0 0 1.5em;">

How does database indexing work?

Just a quick suggestion.. As indexing costs you additional writes and storage space, so if your application requires more insert/update operation, you might want to use tables without indexes, but if it requires more data retrieval operations, you should go for indexed table.

How can I show a combobox in Android?

In android it is called a Spinner you can take a look at the tutorial here.

Hello, Spinner

And this is a very vague question, you should try to be more descriptive of your problem.

How to display HTML tags as plain text

You can use htmlentities when echoing to the browser, this will show the tag rather than have html interpret it.

See here http://uk3.php.net/manual/en/function.htmlentities.php

Example:

 echo htmlentities("<strong>Look just like this line - so then know how to type it</strong>"); 

Output:

<strong>Look just like this line - so then know how to type it</strong>

Why is &#65279; appearing in my HTML?

Try:

<?php 
// Tell me the root folder path.
// You can also try this one
// $HOME = $_SERVER["DOCUMENT_ROOT"];
// Or this
// dirname(__FILE__)
$HOME = dirname(__FILE__);

// Is this a Windows host ? If it is, change this line to $WIN = 1;
$WIN = 0;

// That's all I need
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>UTF8 BOM FINDER and REMOVER</title>
<style>
body { font-size: 10px; font-family: Arial, Helvetica, sans-serif; background: #FFF; color: #000; }
.FOUND { color: #F30; font-size: 14px; font-weight: bold; }
</style>
</head>
<body>
<?php
$BOMBED = array();
RecursiveFolder($HOME);
echo '<h2>These files had UTF8 BOM, but i cleaned them:</h2><p class="FOUND">';
foreach ($BOMBED as $utf) { echo $utf ."<br />\n"; }
echo '</p>';

// Recursive finder
function RecursiveFolder($sHOME) {
  global $BOMBED, $WIN;

  $win32 = ($WIN == 1) ? "\\" : "/";

  $folder = dir($sHOME);

  $foundfolders = array();
  while ($file = $folder->read()) {
    if($file != "." and $file != "..") {
      if(filetype($sHOME . $win32 . $file) == "dir"){
        $foundfolders[count($foundfolders)] = $sHOME . $win32 . $file;
      } else {
        $content = file_get_contents($sHOME . $win32 . $file);
        $BOM = SearchBOM($content);
        if ($BOM) {
          $BOMBED[count($BOMBED)] = $sHOME . $win32 . $file;

          // Remove first three chars from the file
          $content = substr($content,3);
          // Write to file 
          file_put_contents($sHOME . $win32 . $file, $content);
        }
      }
    }
  }
  $folder->close();

  if(count($foundfolders) > 0) {
    foreach ($foundfolders as $folder) {
      RecursiveFolder($folder, $win32);
    }
  }
}

// Searching for BOM in files
function SearchBOM($string) { 
    if(substr($string,0,3) == pack("CCC",0xef,0xbb,0xbf)) return true;
    return false; 
}
?>
</body>
</html>

copy this code to php file upload to root and run it.

for more about this: http://forum.virtuemart.net/index.php?topic=98700.0

Responsive width Facebook Page Plugin

Hi everybody!

My version with a live demonstration(native JavaScript):

1). Javascript code in a separate file (the best solution):

Codepen

_x000D_
_x000D_
/* Vanilla JS */_x000D_
function setupFBframe(frame) {_x000D_
  var container = frame.parentNode;_x000D_
_x000D_
  var containerWidth = container.offsetWidth;_x000D_
  var containerHeight = container.offsetHeight;_x000D_
_x000D_
  var src =_x000D_
    "https://www.facebook.com/plugins/page.php" +_x000D_
    "?href=https%3A%2F%2Fwww.facebook.com%2Ffacebook" +_x000D_
    "&tabs=timeline" +_x000D_
    "&width=" +_x000D_
    containerWidth +_x000D_
    "&height=" +_x000D_
    containerHeight +_x000D_
    "&small_header=false" +_x000D_
    "&adapt_container_width=false" +_x000D_
    "&hide_cover=true" +_x000D_
    "&hide_cta=true" +_x000D_
    "&show_facepile=true" +_x000D_
    "&appId";_x000D_
_x000D_
  frame.width = containerWidth;_x000D_
  frame.height = containerHeight;_x000D_
  frame.src = src;_x000D_
}_x000D_
_x000D_
/* begin Document Ready                                _x000D_
############################################ */_x000D_
_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  var facebookIframe = document.querySelector('#facebook_iframe');_x000D_
  setupFBframe(facebookIframe);_x000D_
 _x000D_
  /* begin Window Resize                                _x000D_
  ############################################ */_x000D_
  _x000D_
  // Why resizeThrottler? See more : https://developer.mozilla.org/ru/docs/Web/Events/resize_x000D_
  (function() {_x000D_
    window.addEventListener("resize", resizeThrottler, false);_x000D_
_x000D_
    var resizeTimeout;_x000D_
_x000D_
    function resizeThrottler() {_x000D_
      if (!resizeTimeout) {_x000D_
        resizeTimeout = setTimeout(function() {_x000D_
          resizeTimeout = null;_x000D_
          actualResizeHandler();_x000D_
        }, 66);_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function actualResizeHandler() {_x000D_
      document.querySelector('#facebook_iframe').removeAttribute('src');_x000D_
      setupFBframe(facebookIframe);_x000D_
    }_x000D_
  })();_x000D_
  /* end Window Resize_x000D_
  ############################################ */_x000D_
});_x000D_
/* end Document Ready                                _x000D_
############################################ */
_x000D_
@import url('https://fonts.googleapis.com/css?family=Indie+Flower');_x000D_
body {_x000D_
  font-family: 'Indie Flower', cursive;_x000D_
}_x000D_
.container {_x000D_
  max-width: 1170px;_x000D_
  width: 100%;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
}_x000D_
.content {_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.left_sidebar {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 30%;_x000D_
  max-width: 300px;_x000D_
}_x000D_
_x000D_
.main_content {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 70%;_x000D_
  background-color: #DDEFF7;_x000D_
}_x000D_
/* ------- begin Widget Facebook -------------- */_x000D_
.widget--facebook--container {_x000D_
  padding: 10px;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.widget-facebook {_x000D_
  height: 500px;_x000D_
}_x000D_
_x000D_
.widget-facebook .facebook_iframe {_x000D_
  border: none;_x000D_
}_x000D_
_x000D_
/* ---------- end Widget Facebook---------------- */_x000D_
_x000D_
/* ----------------- no need -------------------- */_x000D_
.block {_x000D_
  color: #fff;_x000D_
  height: 300px;_x000D_
  background-color: #00A7F7;_x000D_
  border: 1px solid #005dff;_x000D_
}_x000D_
_x000D_
.block h3 {_x000D_
  line-height: 300px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<!-- Min. responsive 180px -->_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    <div class="left_sidebar">_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
      <!-- begin Widget Facebook_x000D_
    ========================================= -->_x000D_
      <aside class="widget--facebook--container">_x000D_
        <div class="widget-facebook">_x000D_
          <iframe id="facebook_iframe" class="facebook_iframe"></iframe>_x000D_
        </div>_x000D_
      </aside>_x000D_
      <!-- end Widget Facebook_x000D_
      ========================================= -->_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
    </div>_x000D_
    <div class="main_content">_x000D_
      <h1>Responsive width Facebook Page Plugin</h1>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

2). Javascript code is written in HTML:

Codepen

_x000D_
_x000D_
@import url('https://fonts.googleapis.com/css?family=Indie+Flower');_x000D_
body {_x000D_
  font-family: 'Indie Flower', cursive;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  max-width: 1170px;_x000D_
  width: 100%;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.left_sidebar {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 30%;_x000D_
  max-width: 300px;_x000D_
}_x000D_
_x000D_
.main_content {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 70%;_x000D_
  background-color: #DDEFF7;_x000D_
}_x000D_
_x000D_
_x000D_
/* ------- begin Widget Facebook -------------- */_x000D_
_x000D_
.widget--facebook--container {_x000D_
  padding: 10px;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.widget-facebook {_x000D_
  height: 500px;_x000D_
}_x000D_
_x000D_
.widget-facebook .facebook_iframe {_x000D_
  border: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* ---------- end Widget Facebook---------------- */_x000D_
_x000D_
_x000D_
/* ----------------- no need -------------------- */_x000D_
_x000D_
.block {_x000D_
  color: #fff;_x000D_
  height: 300px;_x000D_
  background-color: #00A7F7;_x000D_
  border: 1px solid #005dff;_x000D_
}_x000D_
_x000D_
.block h3 {_x000D_
  line-height: 300px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<!-- Vanilla JS -->_x000D_
<!-- Min. responsive 180px -->_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    <div class="left_sidebar">_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
      <!-- begin Widget Facebook_x000D_
      ========================================= -->_x000D_
      <aside class="widget--facebook--container">_x000D_
        <div class="widget-facebook">_x000D_
          <script>_x000D_
            function setupFBframe(frame) {_x000D_
              if (frame.src) return; // already set up_x000D_
_x000D_
              var container = frame.parentNode;_x000D_
              console.log(frame.parentNode);_x000D_
_x000D_
              var containerWidth = container.offsetWidth;_x000D_
              var containerHeight = container.offsetHeight;_x000D_
_x000D_
              var src =_x000D_
                "https://www.facebook.com/plugins/page.php" +_x000D_
                "?href=https%3A%2F%2Fwww.facebook.com%2Ffacebook" +_x000D_
                "&tabs=timeline" +_x000D_
                "&width=" +_x000D_
                containerWidth +_x000D_
                "&height=" +_x000D_
                containerHeight +_x000D_
                "&small_header=false" +_x000D_
                "&adapt_container_width=false" +_x000D_
                "&hide_cover=true" +_x000D_
                "&hide_cta=true" +_x000D_
                "&show_facepile=true" +_x000D_
                "&appId";_x000D_
_x000D_
              frame.width = containerWidth;_x000D_
              frame.height = containerHeight;_x000D_
              frame.src = src;_x000D_
            }_x000D_
_x000D_
            var facebookIframe;_x000D_
_x000D_
            /* begin Window Resize                                _x000D_
            ############################################ */_x000D_
_x000D_
            // Why resizeThrottler? See more : https://developer.mozilla.org/ru/docs/Web/Events/resize_x000D_
            (function() {_x000D_
              window.addEventListener("resize", resizeThrottler, false);_x000D_
_x000D_
              var resizeTimeout;_x000D_
_x000D_
              function resizeThrottler() {_x000D_
                if (!resizeTimeout) {_x000D_
                  resizeTimeout = setTimeout(function() {_x000D_
                    resizeTimeout = null;_x000D_
                    actualResizeHandler();_x000D_
                  }, 66);_x000D_
                }_x000D_
              }_x000D_
_x000D_
              function actualResizeHandler() {_x000D_
                document.querySelector('#facebook_iframe').removeAttribute('src');_x000D_
                setupFBframe(facebookIframe);_x000D_
              }_x000D_
            })();_x000D_
            /* end Window Resize_x000D_
            ############################################ */_x000D_
          </script>_x000D_
          <iframe id="facebook_iframe" class="facebook_iframe" onload="facebookIframe = this; setupFBframe(facebookIframe)"></iframe>_x000D_
        </div>_x000D_
      </aside>_x000D_
      <!-- end Widget Facebook_x000D_
      ========================================= -->_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
    </div>_x000D_
    <div class="main_content">_x000D_
      <h1>Responsive width Facebook Page Plugin</h1>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Thanks storsoc!

All the best to you all and have a nice day!

using BETWEEN in WHERE condition

I think we can write like this : $this->db->where('accommodation >=', minvalue); $this->db->where('accommodation <=', maxvalue);

//without dollar($) sign It's work for me :)

Row count with PDO

fetchColumn()

used if want to get count of record [effisien]

$sql   = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
$res   = $conn->query($sql);
$count = $res->fetchColumn(); // ex = 2

query()

used if want to retrieve data and count of record [options]

$sql = "SELECT * FROM fruit WHERE calories > 100";
$res = $conn->query($sql);

if ( $res->rowCount() > 0) {

    foreach ( $res as $row ) {
        print "Name: {$row['NAME']} <br />";
    }

}
else {
    print "No rows matched the query.";
}

PDOStatement::rowCount

How to delete and update a record in Hive

Once you have installed and configured Hive , create simple table :

hive>create table testTable(id int,name string)row format delimited fields terminated by ',';

Then, try to insert few rowsin test table.

hive>insert into table testTable values (1,'row1'),(2,'row2');

Now try to delete records , you just inserted in table.

hive>delete from testTable where id = 1;

Error! FAILED: SemanticException [Error 10294]: Attempt to do update or delete using transaction manager that does not support these operations.

By default transactions are configured to be off. It is been said that update is not supported with the delete operation used in the conversion manager. To support update/delete , you must change following configuration.

cd  $HIVE_HOME
vi conf/hive-site.xml

Add below properties to file

<property>
  <name>hive.support.concurrency</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.enforce.bucketing</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.exec.dynamic.partition.mode</name>
  <value>nonstrict</value>
 </property>
 <property>
  <name>hive.txn.manager</name>
  <value>org.apache.hadoop.hive.ql.lockmgr.DbTxnManager</value>
 </property>
 <property>
  <name>hive.compactor.initiator.on</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.compactor.worker.threads</name>
  <value>2</value>
 </property>

Restart the service and then try delete command again :

Error!

FAILED: LockException [Error 10280]: Error communicating with the metastore.

There is problem with metastore. In order to use insert/update/delete operation, You need to change following configuration in conf/hive-site.xml as feature is currently in development.

<property>
  <name>hive.in.test</name>
  <value>true</value>
 </property>

Restart the service and then delete command again :

hive>delete from testTable where id = 1;

Error!

FAILED: SemanticException [Error 10297]: Attempt to do update or delete on table default.testTable that does not use an AcidOutputFormat or is not bucketed.

Only ORC file format is supported in this first release. The feature has been built such that transactions can be used by any storage format that can determine how updates or deletes apply to base records (basically, that has an explicit or implicit row id), but so far the integration work has only been done for ORC.

Tables must be bucketed to make use of these features. Tables in the same system not using transactions and ACID do not need to be bucketed.

See below built table example with ORCFileformat, bucket enabled and ('transactional'='true').

hive>create table testTableNew(id int ,name string ) clustered by (id) into 2 buckets stored as orc TBLPROPERTIES('transactional'='true');

Insert :

hive>insert into table testTableNew values (1,'row1'),(2,'row2'),(3,'row3');

Update :

hive>update testTableNew set name = 'updateRow2' where id = 2;

Delete :

hive>delete from testTableNew where id = 1;

Test :

hive>select * from testTableNew ;

Python check if list items are integers?

The usual way to check whether something can be converted to an int is to try it and see, following the EAFP principle:

try:
    int_value = int(string_value)
except ValueError:
    # it wasn't an int, do something appropriate
else:
    # it was an int, do something appropriate

So, in your case:

for item in mylist:
    try:
        int_value = int(item)
    except ValueError:
        pass
    else:
        mynewlist.append(item) # or append(int_value) if you want numbers

In most cases, a loop around some trivial code that ends with mynewlist.append(item) can be turned into a list comprehension, generator expression, or call to map or filter. But here, you can't, because there's no way to put a try/except into an expression.

But if you wrap it up in a function, you can:

def raises(func, *args, **kw):
    try:
        func(*args, **kw)
    except:
        return True
    else:
        return False

mynewlist = [item for item in mylist if not raises(int, item)]

… or, if you prefer:

mynewlist = filter(partial(raises, int), item)

It's cleaner to use it this way:

def raises(exception_types, func, *args, **kw):
    try:
        func(*args, **kw)
    except exception_types:
        return True
    else:
        return False

This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True, but if any unexpected exceptions are raised, they'll propagate out. So:

mynewlist = [item for item in mylist if not raises(ValueError, int, item)]

… will do what you want, but:

mynewlist = [item for item in mylist if not raises(ValueError, item, int)]

… will raise a TypeError, as it should.

Using Spring 3 autowire in a standalone Java application

Spring works in standalone application. You are using the wrong way to create a spring bean. The correct way to do it like this:

@Component
public class Main {

    public static void main(String[] args) {
        ApplicationContext context = 
            new ClassPathXmlApplicationContext("META-INF/config.xml");

        Main p = context.getBean(Main.class);
        p.start(args);
    }

    @Autowired
    private MyBean myBean;
    private void start(String[] args) {
        System.out.println("my beans method: " + myBean.getStr());
    }
}

@Service 
public class MyBean {
    public String getStr() {
        return "string";
    }
}

In the first case (the one in the question), you are creating the object by yourself, rather than getting it from the Spring context. So Spring does not get a chance to Autowire the dependencies (which causes the NullPointerException).

In the second case (the one in this answer), you get the bean from the Spring context and hence it is Spring managed and Spring takes care of autowiring.

Showing all errors and warnings

Set these on php.ini:

;display_startup_errors = On
display_startup_errors=off
display_errors =on
html_errors= on

From your PHP page, use a suitable filter for error reporting.

error_reporting(E_ALL);

Filers can be made according to requirements.

E_ALL
E_ALL | E_STRICT

Upload failed You need to use a different version code for your APK because you already have one with version code 2

Sometimes the PlayStore encounters a bug when you upload an APK during a Release creation, and you are stuck because you cannot upload the same APK again, for the current draft release. You get the error "Upload failed..."

The solution is to go to the Artifact library menu, under Release management and to delete the draft artifact. Once this is done, you will be able to upload the APK again, and to finish your release.

Hope it will help others...

Ben

How do I get the width and height of a HTML5 canvas?

The answers mentioning canvas.width return the internal dimensions of the canvas, i.e. those specified when creating the element:

<canvas width="500" height="200">

If you size the canvas with CSS, its DOM dimensions are accessible via .scrollWidth and .scrollHeight:

_x000D_
_x000D_
var canvasElem = document.querySelector('canvas');_x000D_
document.querySelector('#dom-dims').innerHTML = 'Canvas DOM element width x height: ' +_x000D_
      canvasElem.scrollWidth +_x000D_
      ' x ' +_x000D_
      canvasElem.scrollHeight_x000D_
_x000D_
var canvasContext = canvasElem.getContext('2d');_x000D_
document.querySelector('#internal-dims').innerHTML = 'Canvas internal width x height: ' +_x000D_
      canvasContext.canvas.width +_x000D_
      ' x ' +_x000D_
      canvasContext.canvas.height;_x000D_
_x000D_
canvasContext.fillStyle = "#00A";_x000D_
canvasContext.fillText("Distorted", 0, 10);
_x000D_
<p id="dom-dims"></p>_x000D_
<p id="internal-dims"></p>_x000D_
<canvas style="width: 100%; height: 123px; border: 1px dashed black">
_x000D_
_x000D_
_x000D_

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>

Java system properties and environment variables

How to apply two CSS classes to a single element

As others have pointed out, you simply delimit them with a space.

However, knowing how the selectors work is also useful.

Consider this piece of HTML...

<div class="a"></div>
<div class="b"></div>
<div class="a b"></div>

Using .a { ... } as a selector will select the first and third. However, if you want to select one which has both a and b, you can use the selector .a.b { ... }. Note that this won't work in IE6, it will simply select .b (the last one).

Converting map to struct

I adapt dave's answer, and add a recursive feature. I'm still working on a more user friendly version. For example, a number string in the map should be able to be converted to int in the struct.

package main

import (
    "fmt"
    "reflect"
)

func SetField(obj interface{}, name string, value interface{}) error {

    structValue := reflect.ValueOf(obj).Elem()
    fieldVal := structValue.FieldByName(name)

    if !fieldVal.IsValid() {
        return fmt.Errorf("No such field: %s in obj", name)
    }

    if !fieldVal.CanSet() {
        return fmt.Errorf("Cannot set %s field value", name)
    }

    val := reflect.ValueOf(value)

    if fieldVal.Type() != val.Type() {

        if m,ok := value.(map[string]interface{}); ok {

            // if field value is struct
            if fieldVal.Kind() == reflect.Struct {
                return FillStruct(m, fieldVal.Addr().Interface())
            }

            // if field value is a pointer to struct
            if fieldVal.Kind()==reflect.Ptr && fieldVal.Type().Elem().Kind() == reflect.Struct {
                if fieldVal.IsNil() {
                    fieldVal.Set(reflect.New(fieldVal.Type().Elem()))
                }
                // fmt.Printf("recursive: %v %v\n", m,fieldVal.Interface())
                return FillStruct(m, fieldVal.Interface())
            }

        }

        return fmt.Errorf("Provided value type didn't match obj field type")
    }

    fieldVal.Set(val)
    return nil

}

func FillStruct(m map[string]interface{}, s interface{}) error {
    for k, v := range m {
        err := SetField(s, k, v)
        if err != nil {
            return err
        }
    }
    return nil
}

type OtherStruct struct {
    Name string
    Age  int64
}


type MyStruct struct {
    Name string
    Age  int64
    OtherStruct *OtherStruct
}



func main() {
    myData := make(map[string]interface{})
    myData["Name"]        = "Tony"
    myData["Age"]         = int64(23)
    OtherStruct := make(map[string]interface{})
    myData["OtherStruct"] = OtherStruct
    OtherStruct["Name"]   = "roxma"
    OtherStruct["Age"]    = int64(23)

    result := &MyStruct{}
    err := FillStruct(myData,result)
    fmt.Println(err)
    fmt.Printf("%v %v\n",result,result.OtherStruct)
}

change html text from link with jquery

You have to use the jquery's text() function. What it does is:

Get the combined text contents of all matched elements.

The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents. Cannot be used on input elements. For input field text use the val attribute.

For example:

Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the bold is gone).

var str = $("p:first").text();
$("p:last").html(str);

Test Paragraph.

Test Paragraph.

With your markup you have to do:

$('a#a_tbnotesverbergen').text('new text');

and it will result in

<a id="a_tbnotesverbergen" href="#nothing">new text</a>

How to change Visual Studio 2012,2013 or 2015 License Key?

For those of you using Visual Studio 2017 Professional, the registry key is:

HKCR\Licenses\5C505A59-E312-4B89-9508-E162F8150517

I also recommend you first export the registry key, before you delete it, so you'll have a backup if you accidentally delete the wrong key.

How to update a record using sequelize for node?

I have used sequelize.js, node.js and transaction in below code and added proper error handling if it doesn't find data it will throw error that no data found with that id

editLocale: async (req, res) => {

    sequelize.sequelize.transaction(async (t1) => {

        if (!req.body.id) {
            logger.warn(error.MANDATORY_FIELDS);
            return res.status(500).send(error.MANDATORY_FIELDS);
        }

        let id = req.body.id;

        let checkLocale= await sequelize.Locale.findOne({
            where: {
                id : req.body.id
            }
        });

        checkLocale = checkLocale.get();
        if (checkLocale ) {
            let Locale= await sequelize.Locale.update(req.body, {
                where: {
                    id: id
                }
            });

            let result = error.OK;
            result.data = Locale;

            logger.info(result);
            return res.status(200).send(result);
        }
        else {
            logger.warn(error.DATA_NOT_FOUND);
            return res.status(404).send(error.DATA_NOT_FOUND);
        }
    }).catch(function (err) {
        logger.error(err);
        return res.status(500).send(error.SERVER_ERROR);
    });
},

Scrolling a flexbox with overflowing content

The following CSS changes in bold (plus a bunch of content in the columns to test scrolling) will work. See the result in this Pen.

.content { flex: 1; display: flex; height: 1px; }

.column { padding: 20px; border-right: 1px solid #999; overflow: auto; }

The trick seems to be that a scrollable panel needs to have a height literally set somewhere (in this case, via its parent), not just determined by flexbox. So even height: 1px works. The flex-grow:1 will still size the panel to fit properly.

Convert bytes to int?

Lists of bytes are subscriptable (at least in Python 3.6). This way you can retrieve the decimal value of each byte individually.

>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist)       # b'@x04\x1a\xa3\xff'

>>> for b in bytelist:
...    print(b)                     # 64  4  26  163  255

>>> [b for b in bytelist]           # [64, 4, 26, 163, 255]

>>> bytelist[2]                     # 26 

How to set delay in android?

I think the easiest and most stable and the most useful way as of 2020 is using delay function of Coroutines instead of Runnable. Coroutines is a good concept to handle asynchronous jobs and its delay component will be this answer's focus.

WARNING: Coroutines need Kotlin language and I didn't convert the codes to Kotlin but I think everybody can understand the main concept..

Just add the Coroutines on your build.gradle:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'

Add a job to your class (activity, fragment or something) which you will use coroutines in it:

private var job: Job = Job()
override val coroutineContext: CoroutineContext
    get() = Dispatchers.Main + job

And you can use Coroutines anywhere on the class by using launch{ } body. So you can write your code like this:

public void onClick(View v) {

    launch {

        switch(v.getId()) {
            case R . id . rollDice :
            Random ranNum = new Random();
            int number = ranNum . nextInt (6) + 1;
            diceNum.setText("" + number);
            sum = sum + number;
            for (i= 0;i < 8;i++){
                for (j= 0;j < 8;j++){
                    int value =(Integer) buttons [i][j].getTag();
                    if (value == sum) {
                        inew = i;
                        jnew = j;

                        buttons[inew][jnew].setBackgroundColor(Color.BLACK);
                        delay(2000)
                        buttons[inew][jnew].setBackgroundColor(Color.WHITE);
                        break;
                    }
                }
        }
            break;

        }
    }
}

It's All...

Dont't forget that launch{} function is asynchronous and the for loop will not wait for delay function to finish if you write like this:

launch{
    buttons[inew][jnew].setBackgroundColor(Color.BLACK);
    delay(2000)
    buttons[inew][jnew].setBackgroundColor(Color.WHITE);
}

So, launch{ } should cover the for loop if you want all the for loop to wait for delay.

Another benefit of launch{ } is that you are making the for loop asynchronous, which means it is not gonna block the main UI thread of the application on heavy processes.

Javascript Regular Expression Remove Spaces

str.replace(/\s/g,'')

Works for me.

jQuery.trim has the following hack for IE, although I'm not sure what versions it affects:

// Check if a string has a non-whitespace character in it
rnotwhite = /\S/

// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
    trimLeft = /^[\s\xA0]+/;
    trimRight = /[\s\xA0]+$/;
}

Postgres DB Size Command

You can get the names of all the databases that you can connect to from the "pg_datbase" system table. Just apply the function to the names, as below.

select t1.datname AS db_name,  
       pg_size_pretty(pg_database_size(t1.datname)) as db_size
from pg_database t1
order by pg_database_size(t1.datname) desc;

If you intend the output to be consumed by a machine instead of a human, you can cut the pg_size_pretty() function.

Regex number between 1 and 100

Regular Expression for 0 to 100 with the decimal point.

^100(\.[0]{1,2})?|([0-9]|[1-9][0-9])(\.[0-9]{1,2})?$

Understanding lambda in python and using it to pass multiple arguments

Why do you need to state both x and y before the :?

Because it's a function definition and it needs to know what parameters the function accepts, and in what order. It can't just look at the expression and use the variables names in that, because some of those names you might want to use existing local or global variable values for, and even if it did that, it wouldn't know what order it should expect to get them.

Your error message means that Tk is calling your lambda with one argument, while your lambda is written to accept no arguments. If you don't need the argument, just accept one and don't use it. (Demosthenex has the code, I would have posted it but was beaten to it.)

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

You can disable the constraints on the dataset. It will allow you to identify bad data and help resolve the issue.

e.g.

dataset.TableA.Clear();
dataset.EnforceConstraints = false;
dataAdapter1.daTableA.Fill(dataset, TableA");

The fill method might be slightly different for you.

Header and footer in CodeIgniter

I had this problem where I want a controller to end with a message such as 'Thanks for that form' and generic 'not found etc'. I do this under views->message->message_v.php

<?php
    $title = "Message";
    $this->load->view('templates/message_header', array("title" => $title));
?>
<h1>Message</h1>
<?php echo $msg_text; ?>
<h2>Thanks</h2>
<?php $this->load->view('templates/message_footer'); ?>

which allows me to change message rendering site wide in that single file for any thing that calls

$this->load->view("message/message_v", $data);

Convert Python program to C/C++ code?

I know this is an older thread but I wanted to give what I think to be helpful information.

I personally use PyPy which is really easy to install using pip. I interchangeably use Python/PyPy interpreter, you don't need to change your code at all and I've found it to be roughly 40x faster than the standard python interpreter (Either Python 2x or 3x). I use pyCharm Community Edition to manage my code and I love it.

I like writing code in python as I think it lets you focus more on the task than the language, which is a huge plus for me. And if you need it to be even faster, you can always compile to a binary for Windows, Linux, or Mac (not straight forward but possible with other tools). From my experience, I get about 3.5x speedup over PyPy when compiling, meaning 140x faster than python. PyPy is available for Python 3x and 2x code and again if you use an IDE like PyCharm you can interchange between say PyPy, Cython, and Python very easily (takes a little of initial learning and setup though).

Some people may argue with me on this one, but I find PyPy to be faster than Cython. But they're both great choices though.

Edit: I'd like to make another quick note about compiling: when you compile, the resulting binary is much bigger than your python script as it builds all dependencies into it, etc. But then you get a few distinct benefits: speed!, now the app will work on any machine (depending on which OS you compiled for, if not all. lol) without Python or libraries, it also obfuscates your code and is technically 'production' ready (to a degree). Some compilers also generate C code, which I haven't really looked at or seen if it's useful or just gibberish. Good luck.

Hope that helps.

Integer.toString(int i) vs String.valueOf(int i)

The implementation of String.valueOf() that you see is the simplest way to meet the contract specified in the API: "The representation is exactly the one returned by the Integer.toString() method of one argument."

Using quotation marks inside quotation marks

You need to escape it. (Using Python 3 print function):

>>> print("The boy said \"Hello!\" to the girl")
The boy said "Hello!" to the girl
>>> print('Her name\'s Jenny.')
Her name's Jenny.

See the python page for string literals.

static linking only some libraries

From the manpage of ld (this does not work with gcc), referring to the --static option:

You may use this option multiple times on the command line: it affects library searching for -l options which follow it.

One solution is to put your dynamic dependencies before the --static option on the command line.

Another possibility is to not use --static, but instead provide the full filename/path of the static object file (i.e. not using -l option) for statically linking in of a specific library. Example:

# echo "int main() {}" > test.cpp
# c++ test.cpp /usr/lib/libX11.a
# ldd a.out
linux-vdso.so.1 =>  (0x00007fff385cc000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f9a5b233000)
libm.so.6 => /lib/libm.so.6 (0x00007f9a5afb0000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f9a5ad99000)
libc.so.6 => /lib/libc.so.6 (0x00007f9a5aa46000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9a5b53f000)

As you can see in the example, libX11 is not in the list of dynamically-linked libraries, as it was linked statically.

Beware: An .so file is always linked dynamically, even when specified with a full filename/path.

How to validate phone number using PHP?

Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.

php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.

An example

$phone = '000-0000-0000';

if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
  // $phone is valid
}

Using margin / padding to space <span> from the rest of the <p>

Use div instead of span, or add display: block; to your css style for the span tag.

Error: Configuration with name 'default' not found in Android Studio

I also faced the same problem and the problem was that the libraries were missing in some of the following files.

settings.gradle, app/build.gradle, package.json, MainApplication.java

Suppose the library is react-native-vector-icons then it should be mentioned in following files;

In app/build.gradle file under dependencies section add:

compile project(':react-native-vector-icons')

In settings.gradle file under android folder, add the following:

include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')

In MainApplication.java, add the following:

Import the dependency: import com.oblador.vectoricons.VectorIconsPackage;

and then add: new VectorIconsPackage() in getPackages() method.

JSON and escaping characters

This is not a bug in either implementation. There is no requirement to escape U+00B0. To quote the RFC:

2.5. Strings

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

Any character may be escaped.

Escaping everything inflates the size of the data (all code points can be represented in four or fewer bytes in all Unicode transformation formats; whereas encoding them all makes them six or twelve bytes).

It is more likely that you have a text transcoding bug somewhere in your code and escaping everything in the ASCII subset masks the problem. It is a requirement of the JSON spec that all data use a Unicode encoding.

Run a command shell in jenkins

Error shows that script does not exists

The file does not exists. check your full path

C:\Windows\TEMP\hudson6299483223982766034.sh
The system cannot find the file specified

Moreover, to launch .sh scripts into windows, you need to have CYGWIN installed and well configured into your path

Confirm that script exists.

Into jenkins script, do the following to confirm that you do have the file

cd C:\Windows\TEMP\
ls -rtl
sh -xe hudson6299483223982766034.sh

A method to reverse effect of java String.split()?

For Android: in android.text.TextUtils there are methods:

public static String join (CharSequence delimiter, Iterable tokens)
public static String join (CharSequence delimiter, Object[] tokens)

Returns a string containing the tokens joined by delimiters.

tokens -- an array objects to be joined. Strings will be formed from the objects by calling object.toString().

Simple way to measure cell execution time in ipython notebook

you may also want to look in to python's profiling magic command %prunwhich gives something like -

def sum_of_lists(N):
    total = 0
    for i in range(5):
        L = [j ^ (j >> i) for j in range(N)]
        total += sum(L)
    return total

then

%prun sum_of_lists(1000000)

will return

14 function calls in 0.714 seconds  

Ordered by: internal time      

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    5    0.599    0.120    0.599    0.120 <ipython-input-19>:4(<listcomp>)
    5    0.064    0.013    0.064    0.013 {built-in method sum}
    1    0.036    0.036    0.699    0.699 <ipython-input-19>:1(sum_of_lists)
    1    0.014    0.014    0.714    0.714 <string>:1(<module>)
    1    0.000    0.000    0.714    0.714 {built-in method exec}

I find it useful when working with large chunks of code.

AWS S3: how do I see how much disk space is using

I use Cloud Turtle to get the size of individual buckets. If the bucket size exceeds >100 Gb, then it would take some time to display the size. Cloud turtle is freeware.

How to delete node from XML file using C#

You can use Linq to XML to do this:

XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
        let attr = node.Attribute("name")
        where attr != null && attr.Value == "File1"
        select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");

How to check if element has any children in Javascript?

Try the childElementCount property:

if ( element.childElementCount !== 0 ){
      alert('i have children');
} else {
      alert('no kids here');
}

javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

This should work

 BitmapFactory.Options options = new BitmapFactory.Options();
 options.inSampleSize = 8;

 mBitmapSampled = BitmapFactory.decodeFile(mCurrentPhotoPath,options);

Get input type="file" value when it has multiple files selected

You use input.files property. It's a collection of File objects and each file has a name property:

onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

How to process SIGTERM signal gracefully?

Found easiest way for me. Here an example with fork for clarity that this way is useful for flow control.

import signal
import time
import sys
import os

def handle_exit(sig, frame):
    raise(SystemExit)

def main():
    time.sleep(120)

signal.signal(signal.SIGTERM, handle_exit)

p = os.fork()
if p == 0:
    main()
    os._exit()

try:
    os.waitpid(p, 0)
except (KeyboardInterrupt, SystemExit):
    print('exit handled')
    os.kill(p, 15)
    os.waitpid(p, 0)

How to get info on sent PHP curl request

If you set CURLINFO_HEADER_OUT to true, outgoing headers are available in the array returned by curl_getinfo(), under request_header key:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

curl_exec($ch);

$info = curl_getinfo($ch);
print_r($info['request_header']);

This will print:

GET /bar HTTP/1.1
Authorization: Basic c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk
Host: foo.com
Accept: */*

Note the auth details are base64-encoded:

echo base64_decode('c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk');
// prints: someusername:secretpassword

Also note that username and password need to be percent-encoded to escape any URL reserved characters (/, ?, &, : and so on) they might contain:

curl_setopt($ch, CURLOPT_USERPWD, urlencode($username).':'.urlencode($password));

shell-script headers (#!/bin/sh vs #!/bin/csh)

This is known as a Shebang:

http://en.wikipedia.org/wiki/Shebang_(Unix)

#!interpreter [optional-arg]

A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).

When a shell executes the script it will use the specified interpreter.

Example:

#!/bin/bash
# file: foo.sh
echo 1

$ chmod u+x foo.sh
$ ./foo.sh
  1

How to change FontSize By JavaScript?

<span id="span">HOI</span>
<script>
   var span = document.getElementById("span");
   console.log(span);

   span.style.fontSize = "25px";
   span.innerHTML = "String";
</script>

You have two errors in your code:

  1. document.getElementById - This retrieves the element with an Id that is "span", you did not specify an id on the span-element.

  2. Capitals in Javascript - Also you forgot the capital of Size.

Disable single warning error

Example:

#pragma warning(suppress:0000)  // (suppress one error in the next line)

This pragma is valid for C++ starting with Visual Studio 2005.
https://msdn.microsoft.com/en-us/library/2c8f766e(v=vs.80).aspx

The pragma is NOT valid for C# through Visual Studio 2005 through Visual Studio 2015.
Error: "Expected disable or restore".
(I guess they never got around to implementing suppress ...)
https://msdn.microsoft.com/en-us/library/441722ys(v=vs.140).aspx

C# needs a different format. It would look like this (but not work):

#pragma warning suppress 0642  // (suppress one error in the next line)

Instead of suppress, you have to disable and enable:

if (condition)
#pragma warning disable 0642
    ;  // Empty statement HERE provokes Warning: "Possible mistaken empty statement" (CS0642)
#pragma warning restore 0642
else

That is SO ugly, I think it is smarter to just re-style it:

if (condition)
{
    // Do nothing (because blah blah blah).
}
else

Matlab: Running an m-file from command-line

Since none of the answers has information about feeding input argument, it is important to add it here. After some research, I found this link

Feeding the arguments is very similar to how we run a Matlab function.

matlab -r 'try myfunction(argument1,argument2); catch; end; quit'

If you are somehow getting an argument from bash/terminal, you simply need to insert that into the bash command as:

matlab -r 'try myfunction($MY_BASH_ARG,argument2); catch; end; quit'

(This is after a couple of trial and error)

Linq to Sql: Multiple left outer joins

I think you should be able to follow the method used in this post. It looks really ugly, but I would think you could do it twice and get the result you want.

I wonder if this is actually a case where you'd be better off using DataContext.ExecuteCommand(...) instead of converting to linq.

MongoError: connect ECONNREFUSED 127.0.0.1:27017

Please ensure that your mongo DB is set Automatic and running at Control Panel/Administrative Tools/Services like below. That way you wont have to start mongod.exe manually each time.

enter image description here

Converting Columns into rows with their respective data in sql server

i solved the query this way

SELECT
    ca.ID, ca.[Name]
FROM [Emp2]
CROSS APPLY (
      Values
         ('ID' , cast(ID as varchar)),
         ('[Name]' , Name)

  ) as CA (ID, Name)

output look like

  ID     Name
------ --------------------------------------------------
ID     1
[Name] Joy
ID     2
[Name] jean
ID     4
[Name] paul

how to generate a unique token which expires after 24 hours?

you need to store the token while creating for 1st registration. When you retrieve data from login table you need to differentiate entered date with current date if it is more than 1 day (24 hours) you need to display message like your token is expired.

To generate key refer here

Get JSF managed bean by name in any Servlet related class

You can get the managed bean by passing the name:

public static Object getBean(String beanName){
    Object bean = null;
    FacesContext fc = FacesContext.getCurrentInstance();
    if(fc!=null){
         ELContext elContext = fc.getELContext();
         bean = elContext.getELResolver().getValue(elContext, null, beanName);
    }

    return bean;
}

How to set seekbar min and max value

You can set max value for your seekbar by using this code:

    sb1.setMax(100);

This will set the max value for your seekbar.

But you cannot set the minimum value but yes you can do some arithmetic to adjust value. Use arithmetic to adjust your application-required value.

For example, suppose you have data values from -50 to 100 you want to display on the SeekBar. Set the SeekBar's maximum to be 150 (100-(-50)), then subtract 50 from the raw value to get the number you should use when setting the bar position.

You can get more info via this link.

How to find foreign key dependencies in SQL Server?

This query will return details about foreign keys in a table, it supports multiple column keys.

    SELECT *
    FROM
    (
    SELECT 
    T1.constraint_name ConstraintName,
    T2.COLUMN_NAME ColumnName,
    T3.TABLE_NAME RefTableName, 
    T3.COLUMN_NAME RefColumnName,
    T1.MATCH_OPTION MatchOption, 
    T1.UPDATE_RULE UpdateRule, 
    T1.DELETE_RULE DeleteRule
    FROM 
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS T1
    INNER JOIN
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE T2 
    ON T1.CONSTRAINT_NAME = T2.CONSTRAINT_NAME
    INNER JOIN
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE T3 
    ON T1.UNIQUE_CONSTRAINT_NAME = T3.CONSTRAINT_NAME 
    AND T2.ORDINAL_POSITION = T3.ORDINAL_POSITION) A
    WHERE A.ConstraintName = 'table_name'

How can I see an the output of my C programs using Dev-C++?

Add a line getchar(); or system("pause"); before your return 0; in main function. It will work for you.

python: create list of tuples from lists

Use the builtin function zip():

In Python 3:

z = list(zip(x,y))

In Python 2:

z = zip(x,y)

How can I create an error 404 in PHP?

try this once.

$wp_query->set_404();
status_header(404);
get_template_part('404'); 

Comparing the contents of two files in Sublime Text

UPDATE OCTOBER 2017 I never knew this feature existed in Sublime Text, but the interface appears to have changed slightly from the previous answer - at least on OS X. Here are the detailed steps I followed:

  1. In the Menu Bar click File -> Open...
  2. Navigate to the FOLDER that contains the files to be compared and with the FOLDER selected, click the Open button, this makes the FOLDERS sidebar appear
  3. In the FOLDERS sidebar, click on the first file to be compared
  4. Hold the Ctrl on Windows or ? on OS X, and click the second file
  5. With both files selected, right click on one and select Diff Files...

This opens a new tab showing the comparison. The first file in red, the second in green.

Using GregorianCalendar with SimpleDateFormat

Why such complications?

public static GregorianCalendar convertFromDMY(String dd_mm_yy) throws ParseException 
{
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = fmt.parse(dd_mm_yy);
    GregorianCalendar cal = GregorianCalendar.getInstance();
    cal.setTime(date);
    return cal;
}

Is <div style="width: ;height: ;background: "> CSS?

Yes, it is called Inline CSS, Here you styling the div using some height, width, and background.

Here the example:

<div style="width:50px;height:50px;background color:red">

You can achieve same using Internal or External CSS

2.Internal CSS:

  <head>
    <style>
    div {
    height:50px;
    width:50px;
    background-color:red;
    foreground-color:white;
    }
    </style>
  </head>
  <body>
    <div></div>
  </body>

3.External CSS:

<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div></div>
</body>

style.css /external css file/

 div {
        height:50px;
        width:50px;
        background-color:red;
    }

remove empty lines from text file with PowerShell

You can use -match instead -eq if you also want to exclude files that only contain whitespace characters:

@(gc c:\FileWithEmptyLines.txt) -match '\S'  | out-file c:\FileWithNoEmptyLines

jQuery UI dialog box not positioned center screen

For me jquery.dimensions.js was the Culprit

How can I clear the Scanner buffer in Java?

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

Change color and appearance of drop down arrow

Not easily done I am afraid. The problem is Css cannot replace the arrow in a select as this is rendered by the browser. But you can build a new control from div and input elements and Javascript to perform the same function as the select.

Try looking at some of the autocomplete plugins for Jquery for example.

Otherwise there is some info on the select element here:

http://www.devarticles.com/c/a/Web-Style-Sheets/Taming-the-Select/

Shared-memory objects in multiprocessing

If you use an operating system that uses copy-on-write fork() semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).

The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy or array), place that in shared memory, wrap it with multiprocessing.Array, and pass that to your functions. This answer shows how to do that.

If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).

The Manager approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.

There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.

How can I format decimal property to currency?

Try this;

  string.Format(new CultureInfo("en-SG", false), "{0:c0}", 123423.083234);

It will convert 123423.083234 to $1,23,423 format.

How to select data of a table from another database in SQL Server?

I've used this before to setup a query against another server and db via linked server:

EXEC sp_addlinkedserver @server='PWA_ProjectServer', @srvproduct='',
@provider='SQLOLEDB', @datasrc='SERVERNAME\PWA_ProjectServer'

per the comment above:

select * from [server].[database].[schema].[table]

e.g.

select top 6 * from [PWA_ProjectServer].[PWA_ProjectServer_Reporting].[dbo].[MSP_AdminStatus]

How to check if the URL contains a given string?

Suppose you have this script

<div>
  <p id="response"><p>
  <script>
    var query = document.location.href.substring(document.location.href.indexOf("?") + 1);
    var text_input = query.split("&")[0].split("=")[1];
    document.getElementById('response').innerHTML=text_input;
  </script> </div>

And the url form is www.localhost.com/web_form_response.html?text_input=stack&over=flow

The text written to <p id="response"> will be stack

Hive cast string to date dd-MM-yyyy

Let's say you have a column 'birth_day' in your table which is in string format, you should use the following query to filter using birth_day

date_Format(birth_day, 'yyyy-MM-dd')

You can use it in a query in the following way

select * from yourtable
where 
date_Format(birth_day, 'yyyy-MM-dd') = '2019-04-16';

How to check if an integer is within a range of numbers in PHP?

Here is my little contribution:

function inRange($number) {
  $ranges = [0, 13, 17, 24, 34, 44, 54, 65, 200];
  $n = count($ranges);

  while($n--){
    if( $number > $ranges[$n] )
      return $ranges[$n]+1 .'-'. $ranges[$n + 1];
  }

How can I use a C++ library from node.js?

There is a fresh answer to that question now. SWIG, as of version 3.0 seems to provide javascript interface generators for Node.js, Webkit and v8.

I've been using SWIG extensively for Java and Python for a while, and once you understand how SWIG works, there is almost no effort(compared to ffi or the equivalent in the target language) needed for interfacing C++ code to the languages that SWIG supports.

As a small example, say you have a library with the header myclass.h:

#include<iostream>

class MyClass {
        int myNumber;
public:
        MyClass(int number): myNumber(number){}
        void sayHello() {
                std::cout << "Hello, my number is:" 
                << myNumber <<std::endl;
        }
};

In order to use this class in node, you simply write the following SWIG interface file (mylib.i):

%module "mylib"
%{
#include "myclass.h"
%}
%include "myclass.h"

Create the binding file binding.gyp:

{
  "targets": [
    {
      "target_name": "mylib",
      "sources": [ "mylib_wrap.cxx" ]
    }
  ]
}

Run the following commands:

swig -c++ -javascript -node mylib.i
node-gyp build

Now, running node from the same folder, you can do:

> var mylib = require("./build/Release/mylib")
> var c = new mylib.MyClass(5)
> c.sayHello()
Hello, my number is:5

Even though we needed to write 2 interface files for such a small example, note how we didn't have to mention the MyClass constructor nor the sayHello method anywhere, SWIG discovers these things, and automatically generates natural interfaces.

Adding Counter in shell script

Here's how you might implement a counter:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       exit 0
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter: $counter times reached; Exiting loop!"
       exit 1
  else
       counter=$((counter+1))
       echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Some Explanations:

  • counter=$((counter+1)) - this is how you can increment a counter. The $ for counter is optional inside the double parentheses in this case.
  • elif [[ "$counter" -gt 20 ]]; then - this checks whether $counter is not greater than 20. If so, it outputs the appropriate message and breaks out of your while loop.

How to compare strings in sql ignoring case?

SELECT STRCMP("string1", "string2");

this returns 0 if the strings are equal.

  • If string1 = string2, this function returns 0 (ignoring the case)
  • If string1 < string2, this function returns -1
  • If string1 > string2, this function returns 1

https://www.w3schools.com/sql/func_mysql_strcmp.asp

How can I zoom an HTML element in Firefox and Opera?

For me this works well with IE10, Chrome, Firefox and Safari:

   #MyDiv>*
   {
        zoom: 50%;
        -moz-transform: scale(0.5);
        -webkit-transform: scale(1.0);
   }

This zooms all content in to 50%.

How do I pass a unique_ptr argument to a constructor or a function?

Yes you have to if you take the unique_ptr by value in the constructor. Explicity is a nice thing. Since unique_ptr is uncopyable (private copy ctor), what you wrote should give you a compiler error.

Call to undefined method mysqli_stmt::get_result

Your system is missing the mysqlnd driver!

If you are able to install new packages on your (Debian/Ubuntu-based) server, install the driver:

sudo apt-get install php5-mysqlnd

and then restart your web server:

sudo /etc/init.d/apache2 restart

Converting string to Date and DateTime

Use strtotime() on your first date then date('Y-m-d') to convert it back:

$time = strtotime('10/16/2003');

$newformat = date('Y-m-d',$time);

echo $newformat;
// 2003-10-16

Make note that there is a difference between using forward slash / and hyphen - in the strtotime() function. To quote from php.net:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

Stopping a windows service when the stop option is grayed out

You could do it in one line (useful for ci-environments):

taskkill /fi "Services eq SERVICE_NAME" /F

Filter -> Services -> ServiceName equals SERVICE_NAMES -> Force

Source: https://technet.microsoft.com/en-us/library/bb491009.aspx

Java switch statement: Constant expression required, but it IS constant

Sometimes the switch variable can also make that error for example:

switch(view.getTag()) {//which is an Object type

   case 0://will give compiler error that says Constant expression required

   //...
}

To solve you should cast the variable to int(in this case). So:

switch((int)view.getTag()) {//will be int

   case 0: //No Error

   //...
}

Check if a variable is between two numbers with Java

You can use this simply:

I'm using this function to check if the input int number is between 20 and 30

    static boolean isValidInput(int input) {
    return (input >= 20 && input <= 30);
}

Composer - the requested PHP extension mbstring is missing from your system

sudo apt-get install php-mbstring

# if your are using php 7.1
sudo apt-get install php7.1-mbstring

# if your are using php 7.2
sudo apt-get install php7.2-mbstring

Div with horizontal scrolling only

For horizontal scroll, keep these two properties in mind:

overflow-x:scroll;
white-space: nowrap;

See working link : click me

HTML

<p>overflow:scroll</p>
<div class="scroll">You can use the overflow property when you want to have better   control of the layout. The default value is visible.You can use the overflow property when you want     to have better control of the layout. The default value is visible.</div>

CSS

div.scroll
{
background-color:#00FFFF;
height:40px;
overflow-x:scroll;
white-space: nowrap;
}

How to set a DateTime variable in SQL Server 2008?

2011-01-15 = 2011-16 = 1995. This is then being implicitly converted from an integer to a date, giving you the 1995th day, starting from 1st Jan 1900.

You need to use SET @test = '2011-02-15'

Windows ignores JAVA_HOME: how to set JDK as default?

Windows doesn't ignore anything. This is an issue with your setup; Windows just uses what you provide. It has no special knowledge of JAVA_HOME.

CLASSPATH has nothing to do with Windows, either. To Windows it's only an environmental variable that gets expanded to a folder location.

Check your %PATH% environmental variable. It's what's making Windows find one before the other. The path (as the post you linked to said) should point to %JAVA_HOME%\bin;<remainder of path>. Again, the post you linked to gave you a way to set this using a batch file.

(For others who might not know this: The easiest way to inspect the %PATH% is to open a command prompt and type echo %PATH%. You can also get there by right-clicking on Computer in the right pane of the Start Menu and choosing Properties, then Advanced System Settings, and the tne Environmental Variables button.)

How to insert logo with the title of a HTML page?

Are you referring to the favicon?

Upload a 16x16px ico to your site, and link it in your head section.

<link rel="shortcut icon" href="/favicon.ico" />

There are a multitude of sites that help you convert images into .ico format too. This is just the first one I saw on Google. http://www.favicon.cc/

Meaning of delta or epsilon argument of assertEquals for double values

Note that if you're not doing math, there's nothing wrong with asserting exact floating point values. For instance:

public interface Foo {
    double getDefaultValue();
}

public class FooImpl implements Foo {
    public double getDefaultValue() { return Double.MIN_VALUE; }
}

In this case, you want to make sure it's really MIN_VALUE, not zero or -MIN_VALUE or MIN_NORMAL or some other very small value. You can say

double defaultValue = new FooImpl().getDefaultValue();
assertEquals(Double.MIN_VALUE, defaultValue);

but this will get you a deprecation warning. To avoid that, you can call assertEquals(Object, Object) instead:

// really you just need one cast because of autoboxing, but let's be clear
assertEquals((Object)Double.MIN_VALUE, (Object)defaultValue);

And, if you really want to look clever:

assertEquals(
    Double.doubleToLongBits(Double.MIN_VALUE), 
    Double.doubleToLongBits(defaultValue)
);

Or you can just use Hamcrest fluent-style assertions:

// equivalent to assertEquals((Object)Double.MIN_VALUE, (Object)defaultValue);
assertThat(defaultValue, is(Double.MIN_VALUE));

If the value you're checking does come from doing some math, though, use the epsilon.

Loading basic HTML in Node.js

I think this would be a better option as it shows the URL running the server:

var http = require('http'),
    fs = require('fs');

const hostname = '<your_machine_IP>';
const port = 3000;

const html=fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    }
        http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(port, hostname, () => {
            console.log(`Server running at http://${hostname}:${port}/`);
        })
}); 

How can I stream webcam video with C#?

I've used VideoCapX for our project. It will stream out as MMS/ASF stream which can be open by media player. You can then embed media player into your webpage.

If you won't need much control, or if you want to try out VideoCapX without writing a code, try U-Broadcast, they use VideoCapX behind the scene.

Average of multiple columns

Select Req_ID, sum(R1+R2+R3+R4+R5)/5 as Average
from Request
Group by Req_ID;

How can I count the number of elements of a given value in a matrix?

this would be perfect cause we are doing operation on matrix, and the answer should be a single number

sum(sum(matrix==value))

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

A cron job for rails: best practices?

you can use resque and resque-schedular gem for creating cron, this is very easy to do.

https://github.com/resque/resque

https://github.com/resque/resque-scheduler

How to convert string representation of list to a list?

The json module is a better solution whenever there is a stringified list of dictionaries. The json.loads(your_data) function can be used to convert it to a list.

>>> import json
>>> x = '[ "A","B","C" , " D"]'
>>> json.loads(x)
['A', 'B', 'C', ' D']

Similarly

>>> x = '[ "A","B","C" , {"D":"E"}]'
>>> json.loads(x)
['A', 'B', 'C', {'D': 'E'}]

Using Tkinter in python to edit the title bar

Example of python GUI


Here is an example:

from tkinter import *;
screen = Tk();
screen.geometry("370x420"); //size of screen

Change the name of window

  screen.title('Title Name')

Run it:

screen.mainloop();

anaconda/conda - install a specific package version

To install a specific package:

conda install <pkg>=<version>

eg:

conda install matplotlib=1.4.3

How update the _id of one MongoDB Document?

You cannot update it. You'll have to save the document using a new _id, and then remove the old document.

// store the document in a variable
doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})

// set a new _id on the document
doc._id = ObjectId("4c8a331bda76c559ef000004")

// insert the document, using the new _id
db.clients.insert(doc)

// remove the document with the old _id
db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})

What exactly is Python's file.flush() doing?

It flushes the internal buffer, which is supposed to cause the OS to write out the buffer to the file.[1] Python uses the OS's default buffering unless you configure it do otherwise.

But sometimes the OS still chooses not to cooperate. Especially with wonderful things like write-delays in Windows/NTFS. Basically the internal buffer is flushed, but the OS buffer is still holding on to it. So you have to tell the OS to write it to disk with os.fsync() in those cases.

[1] http://docs.python.org/library/stdtypes.html

How to set String's font size, style in Java using the Font class?

Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29

JComponent has a setFont() method. You will control the font there, not on the String.

Such as

JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

MongoDB vs Firebase

I will answer this question in terms of AngularFire, Firebase's library for Angular.

  1. Tl;dr: superpowers. :-)

  2. AngularFire's three-way data binding. Angular binds the view and the $scope, i.e., what your users do in the view automagically updates in the local variables, and when your JavaScript updates a local variable the view automagically updates. With Firebase the cloud database also updates automagically. You don't need to write $http.get or $http.put requests, the data just updates.

  3. Five-way data binding, and seven-way, nine-way, etc. I made a tic-tac-toe game using AngularFire. Two players can play together, with the two views updating the two $scopes and the cloud database. You could make a game with three or more players, all sharing one Firebase database.

  4. AngularFire's OAuth2 library makes authorization easy with Facebook, GitHub, Google, Twitter, tokens, and passwords.

  5. Double security. You can set up your Angular routes to require authorization, and set up rules in Firebase about who can read and write data.

  6. There's no back end. You don't need to make a server with Node and Express. Running your own server can be a lot of work, require knowing about security, require that someone do something if the server goes down, etc.

  7. Fast. If your server is in San Francisco and the client is in San Jose, fine. But for a client in Bangalore connecting to your server will be slower. Firebase is deployed around the world for fast connections everywhere.

Entry point for Java applications: main(), init(), or run()?

Java has a special static method:

public static void main(String[] args) { ... }

which is executed in a class when the class is started with a java command line:

$ java Class

would execute said method in the class "Class" if it existed.

public void run() { ... }

is required by the Runnable interface, or inherited from the Thread class when creating new threads.

How to change the link color in a specific class for a div CSS

It can be something like this:

a.register:link { color:#FFF; text-decoration:none; font-weight:normal; }
a.register:visited { color: #FFF; text-decoration:none; font-weight:normal; }
a.register:hover { color: #FFF; text-decoration:underline; font-weight:normal; }
a.register:active { color: #FFF; text-decoration:none; font-weight:normal; }

ngModel cannot be used to register form controls with a parent formGroup directive

when you write formcontrolname Angular 2 do not accept. You have to write formControlName . it is about uppercase second words.

<input type="number" [(ngModel)]="myObject.name" formcontrolname="nameFormControl"/>

if the error still conitnue try to set form control for all of object(myObject) field.

between start <form> </form> for example: <form [formGroup]="myForm" (ngSubmit)="submitForm(myForm.value)"> set form control for all input field </form>.

Using a batch to copy from network drive to C: or D: drive

Just do the following change

echo off
cls

echo Would you like to do a backup?

pause

copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER

pause

How to verify if $_GET exists?

You are use PHP isset

Example

if (isset($_GET["id"])) {
    echo $_GET["id"];
}

Obtain smallest value from array in Javascript?

Here is a recursive way on how to do it using ternary operators both for the recursion and decision whether you came across a min number or not.

const findMin = (arr, min, i) => arr.length === i ? min :
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)

Code snippet:

_x000D_
_x000D_
const findMin = (arr, min, i) => arr.length === i ? min :_x000D_
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)_x000D_
  _x000D_
const arr = [5, 34, 2, 1, 6, 7, 9, 3];_x000D_
const min = findMin(arr, arr[0], 0)_x000D_
console.log(min);
_x000D_
_x000D_
_x000D_

no debugging symbols found when using gdb

I know this was answered a long time ago, but I've recently spent hours trying to solve a similar problem. The setup is local PC running Debian 8 using Eclipse CDT Neon.2, remote ARM7 board (Olimex) running Debian 7. Tool chain is Linaro 4.9 using gdbserver on the remote board and the Linaro GDB on the local PC. My issue was that the debug session would start and the program would execute, but breakpoints did not work and when manually paused "no source could be found" would result. My compile line options (Linaro gcc) included -ggdb -O0 as many have suggested but still the same problem. Ultimately I tried gdb proper on the remote board and it complained of no symbols. The curious thing was that 'file' reported debug not stripped on the target executable.

I ultimately solved the problem by adding -g to the linker options. I won't claim to fully understand why this helped, but I wanted to pass this on for others just in case it helps. In this case Linux did indeed need -g on the linker options.

How to implement 2D vector array?

I use this piece of code . works fine for me .copy it and run on your computer. you'll understand by yourself .

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector <vector <int> > matrix;
    size_t row=3 , col=3 ;
    for(int i=0,cnt=1 ; i<row ; i++)
    {
        for(int j=0 ; j<col ; j++)
        {
            vector <int> colVector ;
            matrix.push_back(colVector) ;
            matrix.at(i).push_back(cnt++) ;
        }
    }
    matrix.at(1).at(1) = 0;     //matrix.at(columns).at(rows) = intValue 
    //printing all elements
    for(int i=0,cnt=1 ; i<row ; i++)
    {
        for(int j=0 ; j<col ; j++)
        {
            cout<<matrix[i][j] <<" " ;
        }
        cout<<endl ;
    }
}

html vertical align the text inside input type button

Try adding the property line-height: 22px; to the code.

Why does this iterative list-growing code give IndexError: list assignment index out of range?

j.append(l)

Also avoid using lower-case "L's" because it is easy for them to be confused with 1's

AWS S3 CLI - Could not connect to the endpoint URL

Everyone has different defaults, and interestingly it will change after time. As an example, first I was on global, and then after 15 minutes it shows Ohio (which is us-east-2).

The best approach is to check it during your work -- in console of your AWS working area, just set it on the right above side near your name on top bar check your region name and click on the down arrow to see your region.

In AWS CLI type aws configure or aws2 configure, give your access and secret id, then during default region, write your region and press Enter.

You will definitely get access to specific region set and it will work.

How do I change the owner of a SQL Server database?

to change the object owner try the following

EXEC sp_changedbowner 'sa'

that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that

Download a file from NodeJS Server using Express

Use res.download()

It transfers the file at path as an “attachment”. For instance:

var express = require('express');
var router = express.Router();

// ...

router.get('/:id/download', function (req, res, next) {
    var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
    var fileName = "report.pdf"; // The default name the browser will use

    res.download(filePath, fileName);    
});

How to create correct JSONArray in Java using JSONObject

Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject  getPerson(String firstName, String lastName){
   JSONObject person = new JSONObject();
   person .put("firstName", firstName);
   person .put("lastName", lastName);
   return person ;
} 

public JSONObject getJsonResponse(){

    JSONArray employees = new JSONArray();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));

    JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));

    JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
  }

how to add value to combobox item

Instead of adding Reader("Name") you add a new ListItem. ListItem has a Text and a Value property that you can set.

Maven and adding JARs to system scope

Use a repository manager and install this kind of jars into it. That solves your problems at all and for all computers in your network.

SQL alias for SELECT statement

Not sure exactly what you try to denote with that syntax, but in almost all RDBMS-es you can use a subquery in the FROM clause (sometimes called an "inline-view"):

SELECT..
FROM (
     SELECT ...
     FROM ...
     ) my_select
WHERE ...

In advanced "enterprise" RDBMS-es (like oracle, SQL Server, postgresql) you can use common table expressions which allows you to refer to a query by name and reuse it even multiple times:

-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;

(example from http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx)

Remove credentials from Git

Using latest version of git for Windows on Windows 10 Professional and I had a similar issue whereby I have two different GitHub accounts and also a Bitbucket account so things got a bit confusing for VS2017, git extensions and git bash.

I first checked how git was handling my credentials with this command (run git bash with elevated commands or you get errors):

git config --list

I found the entry Credential Manager so I clicked on the START button > typed Credential Manager to and left-clicked on the credential manager yellow safe icon which launched the app. I then clicked on the Windows Credentials tabs and found the entry for my current git account which happened to be Bit-bucket so I deleted this account.

But this didn't do the trick so the next step was to unset the credentials and I did this from the repository directory on my laptop that contains the GitHub project I am trying to push to the remote. I typed the following command:

git config --system --unset credential.helper

Then I did a git push and I was prompted for a GitHub username which I entered (the correct one I needed) and then the associated password and everything got pushed correctly.

I am not sure how much of an issue this is going forward most people probably work off the one repository but I have to work across several and using different providers so may encounter this issue again.

powershell mouse move does not prevent idle mode

<# Stay Awake by Frank Poth 2019-04-16 #>

(Get-Host).UI.RawUI.WindowTitle = "Stay Awake"

[System.Console]::BufferWidth  = [System.Console]::WindowWidth  = 40
[System.Console]::BufferHeight = [System.Console]::WindowHeight = 10

$shell = New-Object -ComObject WScript.Shell

$start_time = Get-Date -UFormat %s <# Get the date in MS #>
$current_time = $start_time
$elapsed_time = 0

Write-Host "I am awake!"

Start-Sleep -Seconds 5

$count = 0

while($true) {

  $shell.sendkeys("{NUMLOCK}{NUMLOCK}") <# Fake some input! #>

  if ($count -eq 8) {

    $count = 0
    Clear-Host

  }

  if ($count -eq 0) {

    $current_time = Get-Date -UFormat %s
    $elapsed_time = $current_time - $start_time

    Write-Host "I've been awake for "([System.Math]::Round(($elapsed_time / 60), 2))" minutes!"

  } else { Write-Host "Must stay awake..." }

  $count ++

  Start-Sleep -Seconds 2.5

}

The part that matters is $shell.sendkeys("{NUMLOCK}{NUMLOCK}") This registers two presses on the numlock key and fools the shell into thinking input was entered. I wrote this today after searching through various scripts that didn't work for me. Hope it helps someone!

What is the standard naming convention for html/css ids and classes?

There isn't one.

I use underscores all the time, due to hyphens messing up the syntax highlighting of my text editor (Gedit), but that's personal preference.

I've seen all these conventions used all over the place. Use the one that you think is best - the one that looks nicest/easiest to read for you, as well as easiest to type because you'll be using it a lot. For example, if you've got your underscore key on the underside of the keyboard (unlikely, but entirely possible), then stick to hyphens. Just go with what is best for yourself. Additionally, all 3 of these conventions are easily readable. If you're working in a team, remember to keep with the team-specified convention (if any).

Update 2012

I've changed how I program over time. I now use camel case (thisIsASelector) instead of hyphens now; I find the latter rather ugly. Use whatever you prefer, which may easily change over time.

Update 2013

It looks like I like to mix things up yearly... After switching to Sublime Text and using Bootstrap for a while, I've gone back to dashes. To me now they look a lot cleaner than un_der_scores or camelCase. My original point still stands though: there isn't a standard.

Update 2015

An interesting corner case with conventions here is Rust. I really like the language, but the compiler will warn you if you define stuff using anything other than underscore_case. You can turn the warning off, but it's interesting the compiler strongly suggests a convention by default. I imagine in larger projects it leads to cleaner code which is no bad thing.

Update 2016 (you asked for it)

I've adopted the BEM standard for my projects going forward. The class names end up being quite verbose, but I think it gives good structure and reusability to the classes and CSS that goes with them. I suppose BEM is actually a standard (so my no becomes a yes perhaps) but it's still up to you what you decide to use in a project. Most importantly: be consistent with what you choose.

Update 2019 (you asked for it)

After writing no CSS for quite a while, I started working at a place that uses OOCSS in one of their products. I personally find it pretty unpleasant to litter classes everywhere, but not having to jump between HTML and CSS all the time feels quite productive.

I'm still settled on BEM, though. It's verbose, but the namespacing makes working with it in React components very natural. It's also great for selecting specific elements when browser testing.

OOCSS and BEM are just some of the CSS standards out there. Pick one that works for you - they're all full of compromises because CSS just isn't that good.

Update 2020

A boring update this year. I'm still using BEM. My position hasn't really changed from the 2019 update for the reasons listed above. Use what works for you that scales with your team size and hides as much or as little of CSS' poor featureset as you like.

MySql server startup error 'The server quit without updating PID file '

In my case, I got this issue on vps, cPanel.

I was try most of the above answers, but not success.

  1. check where your error log. It would be mentioned at the end of error line.

ERROR! The server quit without updating PID file (/var/lib/mysql/111318.vps-11.com.pid).

  1. Open that file (/var/lib/mysql/111318.vps-11.com.err) and chek the bottom for lates lines. In my case, there is

[ERROR] Fatal error: Can't open and lock privilege tables: Table './mysql/db' is marked as crashed and should be repaired

  1. How solve this: Recovering and fixing the table indexes by command:

[~]# myisamchk -r /var/lib/mysql/mysql/db.MYI

https://forums.cpanel.net/threads/mysql-is-not-running.407142/

  1. (Re)Start your mysql

String or binary data would be truncated. The statement has been terminated

When you define varchar etc without a length, the default is 1.

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

So, if you expect 400 bytes in the @trackingItems1 column from stock, use nvarchar(400).

Otherwise, you are trying to fit >1 character into nvarchar(1) = fail

As a comment, this is bad use of table value function too because it is "multi statement". It can be written like this and it will run better

ALTER FUNCTION [dbo].[testing1](@price int)
RETURNS
AS
   SELECT ta.item, ta.warehouse, ta.price 
   FROM   stock ta
   WHERE  ta.price >= @price;

Of course, you could just use a normal SELECT statement..

400 BAD request HTTP error code meaning?

Using 400 status codes for any other purpose than indicating that the request is malformed is just plain wrong.

If the request payload contains a byte-sequence that could not be parsed as application/json (if the server expects that dataformat), the appropriate status code is 415:

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.

If the request payload is syntactically correct but semantically incorrect, the non-standard 422 response code may be used, or the standard 403 status code:

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated.

How do I make a branch point at a specific commit?

You can make master point at 1258f0d0aae this way:

git checkout master
git reset --hard 1258f0d0aae

But you have to be careful about doing this. It may well rewrite the history of that branch. That would create problems if you have published it and other people are working on the branch.

Also, the git reset --hard command will throw away any uncommitted changes (i.e. those just in your working tree or the index).

You can also force an update to a branch with:

git branch -f master 1258f0d0aae

... but git won't let you do that if you're on master at the time.

Android ViewPager with bottom dots

Here is how I did this, somewhat similar to the solutions above. Just make sure you call the loadDots() method after all images are downloaded.

    private int dotsCount;
    private TextView dotsTextView[];

    private void setupAdapter() {
        adapter = new SomeAdapter(getContext(), images);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
    }

    private final ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

        @Override
        public void onPageSelected(int position) {
            for (int i = 0; i < dotsCount; i++)
                dotsTextView[i].setTextColor(Color.GRAY);

            dotsTextView[position].setTextColor(Color.WHITE);
        }

        @Override
        public void onPageScrollStateChanged(int state) {}
    };

    protected void loadDots() {
        dotsCount = adapter.getCount();
        dotsTextView = new TextView[dotsCount];
        for (int i = 0; i < dotsCount; i++) {
            dotsTextView[i] = new TextView(getContext());
            dotsTextView[i].setText(R.string.dot);
            dotsTextView[i].setTextSize(45);
            dotsTextView[i].setTypeface(null, Typeface.BOLD);
            dotsTextView[i].setTextColor(android.graphics.Color.GRAY);
            mDotsLayout.addView(dotsTextView[i]);
        }
        dotsTextView[0].setTextColor(Color.WHITE);
    }

XML

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

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:background="#00000000"/>


    <ImageView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/introImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:id="@+id/image_count"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#00000000"
        android:gravity="center|bottom"
        android:orientation="horizontal"/>
</FrameLayout>

How to $watch multiple variable change in angular

There is many way to watch multiple values :

//angular 1.1.4
$scope.$watchCollection(['foo', 'bar'], function(newValues, oldValues){
    // do what you want here
});

or more recent version

//angular 1.3
$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
  //do what you want here
});

Read official doc for more informations : https://docs.angularjs.org/api/ng/type/$rootScope.Scope

JavaScript for detecting browser language preference

Update of year 2014.

Now there is a way to get Accept-Languages in Firefox and Chrome using navigator.languages (works in Chrome >= 32 and Firefox >= 32)

Also, navigator.language in Firefox these years reflects most preferred language of content, not language of UI. But since this notion is yet to be supported by other browsers, it is not very useful.

So, to get most preferred content language when possible, and use UI language as fallback:

navigator.languages
    ? navigator.languages[0]
    : (navigator.language || navigator.userLanguage)

Convert object array to hash map, indexed by an attribute value of the Object

This is fairly trivial to do with Array.prototype.reduce:

_x000D_
_x000D_
var arr = [_x000D_
    { key: 'foo', val: 'bar' },_x000D_
    { key: 'hello', val: 'world' }_x000D_
];_x000D_
_x000D_
var result = arr.reduce(function(map, obj) {_x000D_
    map[obj.key] = obj.val;_x000D_
    return map;_x000D_
}, {});_x000D_
_x000D_
console.log(result);_x000D_
// { foo:'bar', hello:'world' }
_x000D_
_x000D_
_x000D_

Note: Array.prototype.reduce() is IE9+, so if you need to support older browsers you will need to polyfill it.

How to get current moment in ISO 8601 format with date, hour, and minute?

If you care about performance, I created a library which outperforms standard Java parser and formatter in manipulating with ISO8601-formatted dates. DatetimeProcessor implementations are thread-safe and can be cached in a concurrent map or static fields.

<dependency>
  <groupId>com.axibase</groupId>
  <artifactId>date-processor</artifactId>
  <version>1.0.3</version>
</dependency>
import com.axibase.date.DatetimeProcessor;
import com.axibase.date.PatternResolver;
import org.junit.Before;
import org.junit.Test;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

public class DateFormatTest {
    private Clock clock;

    @Before
    public void prepare() {
        clock = Clock.fixed(Instant.ofEpochMilli(1571285405300L), ZoneId.of("Europe/Berlin"));
    }

    @Test
    public void testIsoMillis(){
        final DatetimeProcessor formatter = PatternResolver.createNewFormatter("iso");
        assertThat(formatter.print(clock.millis(), ZoneOffset.UTC), is("2019-10-17T04:10:05.300Z"));
    }

    @Test
    public void testIsoMillisLocalZone(){
        final DatetimeProcessor formatter = PatternResolver.createNewFormatter("iso");
        assertThat(formatter.print(clock.millis(), clock.getZone()), is("2019-10-17T06:10:05.300+02:00"));
    }

    @Test
    public void testIsoMinutes(){
        final DatetimeProcessor formatter = PatternResolver.createNewFormatter("yyyy-MM-ddTHH:mmXXX");
        assertThat(formatter.print(clock.millis(), ZoneOffset.UTC), is("2019-10-17T04:10Z"));
    }
}

JQuery $.each() JSON array object iteration

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

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

Should print out everything you were trying in your question.

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

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

Difference between ref and out parameters in .NET

out:

In C#, a method can return only one value. If you would like to return more than one value, you can use the out keyword. The out modifier returns as return-by-reference. The simplest answer is that the keyword “out” is used to get the value from the method.

  • You don't need to initialize the value in the calling function.
  • You must assign the value in the called function, otherwise the compiler will report an error.

ref:

In C#, when you pass a value type such as int, float, double etc. as an argument to the method parameter, it is passed by value. Therefore, if you modify the parameter value, it does not affect argument in the method call. But if you mark the parameter with “ref” keyword, it will reflect in the actual variable.

  • You need to initialize the variable before you call the function.
  • It’s not mandatory to assign any value to the ref parameter in the method. If you don’t change the value, what is the need to mark it as “ref”?

Shortcut to exit scale mode in VirtualBox

I was having the similar issue when using VirtualBox on Ubuntu 12.04LTS. Now if anyone is using or has ever used Ubuntu, you might be aware that how things are hard sometimes when using shortcut keys in Ubuntu. For me, when i was trying to revert back the Host key, it was just not happening and the shortcut keys won't just work. I even tried the command line option to revert back the scale mode and it won't work either. Finally i found the following when all the other options fails:

Fix the Scale Mode Issue in Oracle VirtualBox in Ubuntu using the following steps:

  1. Close all virtual machines and VirtualBox windows.
  2. Find your machine config files (i.e. /home/<username>/VirtualBox VMs/ANKSVM) where ANKSVM is your VM Name and edit and change the following in ANKSVM.vbox and ANKSVM.vbox-prev files:

  3. Edit the line: <ExtraDataItem name="GUI/Scale" value="on"/> to <ExtraDataItem name="GUI/Scale" value="off"/>

  4. Restart VirtualBox

You are done.

This works every time specially when all other options fails like how it happened for me.

How should I pass an int into stringWithFormat?

You want to use %d or %i for integers. %@ is used for objects.

It's worth noting, though, that the following code will accomplish the same task and is much clearer.

label.intValue = count;

Is there an eval() function in Java?

Writing your own library is not that hard as u might thing. Here is link for Shunting-yard algorithm with step by step algorithm explenation. Although, you will have to parse the input for tokens first.

There are 2 other questions wich can give you some information too: Turn a String into a Math Expression? What's a good library for parsing mathematical expressions in java?

jQuery select option elements by value

$("#h273yrjdfhgsfyiruwyiywer").children('[value="' + i + '"]').prop("selected", true);