Programs & Examples On #Scalable

What is correct media query for IPad Pro?

For those who want to target an iPad Pro 11" the device-width is 834px, device-height is 1194px and the device-pixel-ratio is 2. Source: screen.width, screen.height and devicePixelRatio reported by Safari on iOS Simulator.

Exact media query for portrait: (device-height: 1194px) and (device-width: 834px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

I solved this error using the bellow i get it from here

ionic cordova run browser will load those native plugins that support browser platform.

disable viewport zooming iOS 10+ safari?

This is a new feature in iOS 10.

From the iOS 10 beta 1 release notes:

  • To improve accessibility on websites in Safari, users can now pinch-to-zoom even when a website sets user-scalable=no in the viewport.

I expect we're going to see a JS add-on soon to disable this in some way.

This page didn't load Google Maps correctly. See the JavaScript console for technical details

Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.

In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:

Google Maps API error: MissingKeyMapError [SOLVED]

Also, remember to replace YOUR_API_KEY with your actual API key!

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

FontAwesome icons not showing. Why?

Use this link:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/brands.min.css" integrity="sha512-AMDXrE+qaoUHsd0DXQJr5dL4m5xmpkGLxXZQik2TvR2VCVKT/XRPQ4e/LTnwl84mCv+eFm92UG6ErWDtGM/Q5Q==" crossorigin="anonymous" />

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>
      <TileColor>#009900</TileColor>
    </tile>
  </msapplication>
</browserconfig>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...
  </div>
</div>

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

<script>
function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;
}
</script>

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

This meta tag is used by all responsive web pages, that is those that are designed to layout well across device types - phone, tablet, and desktop. The attributes do what they say. However, as MDN's Using the viewport meta tag to control layout on mobile browsers indicates,

On high dpi screens, pages with initial-scale=1 will effectively be zoomed by browsers.

I've found that the following ensures that the page displays with zero zoom by default.

<meta name="viewport" content="width=device-width, initial-scale=0.86, maximum-scale=3.0, minimum-scale=0.86">

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">

see https://docs.angularjs.org/api/ngRoute

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

Add style="width:100%; height:100%;" to the div see what that does

not to the #map_canvas but the main div

example

<body>
    <div style="height:100%; width:100%;">
         <div id="map-canvas"></div>
    </div>
</body> 

There are some other answers on here the explain why this is necessary

Using Address Instead Of Longitude And Latitude With Google Maps API

var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
  zoom: 8,
  center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}

function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == 'OK') {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
    });
  } else {
    alert('Geocode was not successful for the following reason: ' + status);
  }
});
}

<body onload="initialize()">
 <div id="map" style="width: 320px; height: 480px;"></div>
 <div>
   <input id="address" type="textbox" value="Sydney, NSW">
   <input type="button" value="Encode" onclick="codeAddress()">
 </div>
</body>

Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding

Show pop-ups the most elegant way

  • Create a 'popup' directive and apply it to the container of the popup content
  • In the directive, wrap the content in a absolute position div along with the mask div below it.
  • It is OK to move the 2 divs in the DOM tree as needed from within the directive. Any UI code is OK in the directives, including the code to position the popup in center of screen.
  • Create and bind a boolean flag to controller. This flag will control visibility.
  • Create scope variables that bond to OK / Cancel functions etc.

Editing to add a high level example (non functional)

<div id='popup1-content' popup='showPopup1'>
  ....
  ....
</div>


<div id='popup2-content' popup='showPopup2'>
  ....
  ....
</div>



.directive('popup', function() {
  var p = {
      link : function(scope, iElement, iAttrs){
           //code to wrap the div (iElement) with a abs pos div (parentDiv)
          // code to add a mask layer div behind 
          // if the parent is already there, then skip adding it again.
         //use jquery ui to make it dragable etc.
          scope.watch(showPopup, function(newVal, oldVal){
               if(newVal === true){
                   $(parentDiv).show();
                 } 
              else{
                 $(parentDiv).hide();
                }
          });
      }


   }
  return p;
});

@Media min-width & max-width

The correct value for the content attribute should include initial-scale instead:

_x000D_
_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
                                                   ^^^^^^^^^^^^^^^
_x000D_
_x000D_
_x000D_

Google Maps API Multiple Markers with Infowindows

If you also want to bind closing of infowindow to some event, try something like this

google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
    return function() {
        infowindow.setContent(content);
        infowindow.open(map,marker);
        windows.push(infowindow)
        google.maps.event.addListener(map,'click', function(){ 
            infowindow.close();
        }); 
    };
})(marker,content,infowindow)); 

Disable scrolling in all mobile devices

For future generations:

To prevent scrolling but keep the contextmenu, try

document.body.addEventListener('touchmove', function(e){ e.preventDefault(); });

It still prevents way more than some might like, but for most browsers the only default behaviour prevented should be scrolling.

For a more sophisticated solution that allows for scrollable elements within the nonscrollable body and prevents rubberband, have a look at my answer over here:

https://stackoverflow.com/a/20250111/1431156

Google Maps API: open url by clicking on marker

You can add a specific url to each point, e.g.:

var points = [
    ['name1', 59.9362384705039, 30.19232525792222, 12, 'www.google.com'],
    ['name2', 59.941412822085645, 30.263564729357767, 11, 'www.amazon.com'],
    ['name3', 59.939177197629455, 30.273554411974955, 10, 'www.stackoverflow.com']
];

Add the url to the marker values in the for-loop:

var marker = new google.maps.Marker({
    ...
    zIndex: place[3],
    url: place[4]
});

Then you can add just before to the end of your for-loop:

google.maps.event.addListener(marker, 'click', function() {
    window.location.href = this.url;
});

Also see this example.

How to move a marker in Google Maps API

moveBus() is getting called before initialize(). Try putting that line at the end of your initialize() function. Also Lat/Lon 0,0 is off the map (it's coordinates, not pixels), so you can't see it when it moves. Try 54,54. If you want the center of the map to move to the new location, use panTo().

Demo: http://jsfiddle.net/ThinkingStiff/Rsp22/

HTML:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>

CSS:

#map-canvas 
{ 
height: 400px; 
width: 500px;
}

Script:

function initialize() {

    var myLatLng = new google.maps.LatLng( 50, 50 ),
        myOptions = {
            zoom: 4,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            },
        map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
        marker = new google.maps.Marker( {position: myLatLng, map: map} );

    marker.setMap( map );
    moveBus( map, marker );

}

function moveBus( map, marker ) {

    marker.setPosition( new google.maps.LatLng( 0, 0 ) );
    map.panTo( new google.maps.LatLng( 0, 0 ) );

};

initialize();

How do I automatically resize an image for a mobile site?

img
{
    max-width: 100%;
    min-width: 300px;
    height: auto;
}

Best way to store chat messages in a database?

There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.

Actually you can find here in Stack Overflow a link to an example schema for a chat: example

If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages

CSS: 100% font size - 100% of what?

Relative to the default size defined to that font.

If someone opens your page on a web browser, there's a default font and font size it uses.

jquery mobile background image

I think your answer will be background-size:cover.

.ui-page
{
background: #000;
background-image:url(image.gif);
background-size:cover;  
}

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

You should not use the viewport meta tag at all if your design is not responsive. Misusing this tag may lead to broken layouts. You may read this article for documentation about why you should'n use this tag unless you know what you're doing. http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho

"user-scalable=no" also helps to prevent the zoom-in effect on iOS input boxes.

Is there a way to use max-width and height for a background image?

It looks like you're trying to scale the background image? There's a great article in the reference bellow where you can use css3 to achieve this.

And if I miss-read the question then I humbly accept the votes down. (Still good to know though)

Please consider the following code:

#some_div_or_body { 
   background: url(images/bg.jpg) no-repeat center center fixed; 
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
}

This will work on all major browsers, of course it doesn't come easy on IE. There are some workarounds however such as using Microsoft's filters:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";

There are some alternatives that can be used with a little bit peace of mind by using jQuery:

HTML

<img src="images/bg.jpg" id="bg" alt="">

CSS

#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }

jQuery:

 $(window).load(function() {    

var theWindow        = $(window),
    $bg              = $("#bg"),
    aspectRatio      = $bg.width() / $bg.height();

function resizeBg() {

    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
        $bg
            .removeClass()
            .addClass('bgheight');
    } else {
        $bg
            .removeClass()
            .addClass('bgwidth');
    }

}

theWindow.resize(resizeBg).trigger("resize");

});

I hope this helps!

Src: Perfect Full Page Background Image

How do you disable viewport zooming on Mobile Safari?

Try adding the following to your head-tag:

<meta name="viewport" content="width=device-width, initial-scale=1.0, 
minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

additionally

<meta name="HandheldFriendly" content="true">

Finally, either as a style-attribute or in your css file, add the following text for webkit-based Browsers:

html {
    -webkit-text-size-adjust: none
}

Android Webview - Webpage should fit the device screen

These work for me and fit the WebView to screen width:

// get from xml, with all size set "fill_parent"  
webView = (WebView) findViewById(R.id.webview_in_layout);  
// fit the width of screen
webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); 
// remove a weird white line on the right size
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);  

Thanks above advises and White line in eclipse Web view

Can I change the viewport meta tag in mobile safari on the fly?

This has been answered for the most part, but I will expand...

Step 1

My goal was to enable zoom at certain times, and disable it at others.

// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');    
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');

// ...later...

// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');

Step 2

The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...

It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.

// after updating viewport tag, force the page to pick up changes           
document.body.style.opacity = .9999;
setTimeout(function(){
    document.body.style.opacity = 1;
}, 1);

Step 3

My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).

// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;

I hope this helps somebody. I spent several hours banging my mouse before finding a solution.

Disable scrolling in an iPhone web application?

I tried above answers and particularly Gajus's but none works. Finally I found the answer below to solve the problem such that only the main body doesn't scroll but other scrolling sections inside my web app all work fine. Simply set position fixed for your body:

body {

height: 100%;
overflow: hidden;
width: 100%;
position: fixed;
}

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

Maven parent pom vs modules pom

In my opinion, to answer this question, you need to think in terms of project life cycle and version control. In other words, does the parent pom have its own life cycle i.e. can it be released separately of the other modules or not?

If the answer is yes (and this is the case of most projects that have been mentioned in the question or in comments), then the parent pom needs his own module from a VCS and from a Maven point of view and you'll end up with something like this at the VCS level:

root
|-- parent-pom
|   |-- branches
|   |-- tags
|   `-- trunk
|       `-- pom.xml
`-- projectA
    |-- branches
    |-- tags
    `-- trunk
        |-- module1
        |   `-- pom.xml
        |-- moduleN
        |   `-- pom.xml
        `-- pom.xml

This makes the checkout a bit painful and a common way to deal with that is to use svn:externals. For example, add a trunks directory:

root
|-- parent-pom
|   |-- branches
|   |-- tags
|   `-- trunk
|       `-- pom.xml
|-- projectA
|   |-- branches
|   |-- tags
|   `-- trunk
|       |-- module1
|       |   `-- pom.xml
|       |-- moduleN
|       |   `-- pom.xml
|       `-- pom.xml
`-- trunks

With the following externals definition:

parent-pom http://host/svn/parent-pom/trunk
projectA http://host/svn/projectA/trunk

A checkout of trunks would then result in the following local structure (pattern #2):

root/
  parent-pom/
    pom.xml
  projectA/

Optionally, you can even add a pom.xml in the trunks directory:

root
|-- parent-pom
|   |-- branches
|   |-- tags
|   `-- trunk
|       `-- pom.xml
|-- projectA
|   |-- branches
|   |-- tags
|   `-- trunk
|       |-- module1
|       |   `-- pom.xml
|       |-- moduleN
|       |   `-- pom.xml
|       `-- pom.xml
`-- trunks
    `-- pom.xml

This pom.xml is a kind of "fake" pom: it is never released, it doesn't contain a real version since this file is never released, it only contains a list of modules. With this file, a checkout would result in this structure (pattern #3):

root/
  parent-pom/
    pom.xml
  projectA/
  pom.xml

This "hack" allows to launch of a reactor build from the root after a checkout and make things even more handy. Actually, this is how I like to setup maven projects and a VCS repository for large builds: it just works, it scales well, it gives all the flexibility you may need.

If the answer is no (back to the initial question), then I think you can live with pattern #1 (do the simplest thing that could possibly work).

Now, about the bonus questions:

  • Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).

Honestly, I don't know how to not give a general answer here (like "use the level at which you think it makes sense to mutualize things"). And anyway, child poms can always override inherited settings.

  • How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?

The setup I use works well, nothing particular to mention.

Actually, I wonder how the maven-release-plugin deals with pattern #1 (especially with the <parent> section since you can't have SNAPSHOT dependencies at release time). This sounds like a chicken or egg problem but I just can't remember if it works and was too lazy to test it.

How to send a html email with the bash command "sendmail"?

This page should help - http://www.zedwood.com/article/103/bash-send-mail-with-an-attachment

It includes a script to send e-mail with a MIME attachment, ie with a HTML page and images included.

Does Android support near real time push notification?

They have their listeners which has to be used by you by using their library classes in your code. You need not to bother about pushing. You have to send the message to server server will push the message to the device. They use OAuth. Regarding Protocols, there are two methods using CCS and XMPP. CCS just uses XMPP as an authenticated transport layer, so you can use most XMPP libraries to manage the connection. To send notifications to device you can write code in android app to send as well as your server code. the message sending will be done only by your code. Rest will be taken care by Google Server in GCM case. You can check detail at this link

http://developer.android.com/google/gcm/server.html

Also, for security issues

google cloud messaging security https://groups.google.com/forum/#!topic/android-gcm/M-EevBitbhQ

In case your app is not running then also devices can recieve notification because you have to write code for broadcast listeners. In background it will be listening to server and whenever any message packet will be there it will recieve the message as notification. Android has service you need to not to bother about it. You have only to use those resources using the library class that makes your work easier and let them write if your app is not running then also it recieve notification. Obviously, there would be some listener whick make the app to recieve.Check "Recieve the message" section in this link

http://developer.android.com/google/gcm/client.html

It will acccept request from users also. For GCM it will do. Please check "Send a message"

http://developer.android.com/google/gcm/client.html

Sleep Command in T-SQL?

Look at the WAITFOR command.

E.g.

-- wait for 1 minute
WAITFOR DELAY '00:01'

-- wait for 1 second
WAITFOR DELAY '00:00:01'

This command allows you a high degree of precision but is only accurate within 10ms - 16ms on a typical machine as it relies on GetTickCount. So, for example, the call WAITFOR DELAY '00:00:00:001' is likely to result in no wait at all.

How to format font style and color in echo

 echo "<a href='#' style = \"font-color: #ff0000;\"> Movie List for {$key} 2013 </a>";

endsWith in JavaScript

UPDATE (Nov 24th, 2015):

This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:

Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple this.substr(-suffix.length) === suffix approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: jsperf.com/endswith-stackoverflow/14 And faster across the board when the result is false: jsperf.com/endswith-stackoverflow-when-false Of course, with ES6 adding endsWith, the point is moot. :-)


ORIGINAL ANSWER:

I know this is a year old question... but I need this too and I need it to work cross-browser so... combining everyone's answer and comments and simplifying it a bit:

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
  • Doesn't create a substring
  • Uses native indexOf function for fastest results
  • Skip unnecessary comparisons using the second parameter of indexOf to skip ahead
  • Works in Internet Explorer
  • NO Regex complications

Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version:

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

EDIT: As noted by @hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a typeof check like so:

if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

Java 8 stream's .min() and .max(): why does this compile?

Apart from the information given by David M. Lloyd one could add that the mechanism that allows this is called target typing.

The idea is that the type the compiler assigns to a lambda expressions or a method references does not depend only on the expression itself, but also on where it is used.

The target of an expression is the variable to which its result is assigned or the parameter to which its result is passed.

Lambda expressions and method references are assigned a type which matches the type of their target, if such a type can be found.

See the Type Inference section in the Java Tutorial for more information.

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

Submit form without page reloading

It's a must to take help of jquery-ajax in this case. Without ajax, there is currently no solution.

First, call a JavaScript function when the form is submitted. Just set onsubmit="func()". Even if the function is called, the default action of the submission would be performed. If it is performed there would be no way of stoping the page from refreshing or redirecting. So, next task is to prevent the default action. Insert the following line at the start of func().

event.preventDefault()

Now, there will be no redirecting or refreshing. So, you simply make an ajax call from func() and do whatever you want to do when call ends.

Example:

Form:

<form id="form-id" onsubmit="func()">
    <input id="input-id" type="text">
</form>

Javascript:

function func(){
    event.preventDefault();
    var newValue = $('#input-field-id').val();
    $.ajax({
        type: 'POST',
        url: '...',
        data: {...},
        datatype: 'JSON',
        success: function(data){...},
        error: function(){...},
    });
}

Why is 1/1/1970 the "epoch time"?

http://en.wikipedia.org/wiki/Unix_time#History explains a little about the origins of Unix time and the chosen epoch. The definition of unix time and the epoch date went through a couple of changes before stabilizing on what it is now.

But it does not say why exactly 1/1/1970 was chosen in the end.

Notable excerpts from the Wikipedia page:

The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".

Because of [the] limited range, the epoch was redefined more than once, before the rate was changed to 1 Hz and the epoch was set to its present value.

Several later problems, including the complexity of the present definition, result from Unix time having been defined gradually by usage rather than fully defined to start with.

How do I make Git use the editor of my choice for commits?

For Windows users who want to use Kinesics Text Editor

Create a file called 'k.sh', add the following text and place in your home directory (~):

winpty "C:\Program Files (x86)\Kinesics Text Editor\x64\k.exe" $1

At the git prompt type:

git config --global core.editor ~/k.sh

What's the difference between Apache's Mesos and Google's Kubernetes

Kubernetes is an open source project that brings 'Google style' cluster management capabilities to the world of virtual machines, or 'on the metal' scenarios. It works very well with modern operating system environments (like CoreOS or Red Hat Atomic) that offer up lightweight computing 'nodes' that are managed for you. It is written in Golang and is lightweight, modular, portable and extensible. We (the Kubernetes team) are working with a number of different technology companies (including Mesosphere who curate the Mesos open source project) to establish Kubernetes as the standard way to interact with computing clusters. The idea is to reproduce the patterns that we see people needing to build cluster applications based on our experience at Google. Some of these concepts include:

  • pods — a way to group containers together
  • replication controllers — a way to handle the lifecycle of containers
  • labels — a way to find and query containers, and
  • services — a set of containers performing a common function.

So with Kubernetes alone you will have something that is simple, easy to get up-and-running, portable and extensible that adds 'cluster' as a noun to the things that you manage in the lightest weight manner possible. Run an application on a cluster, and stop worrying about an individual machine. In this case, cluster is a flexible resource just like a VM. It is a logical computing unit. Turn it up, use it, resize it, turn it down quickly and easily.

With Mesos, there is a fair amount of overlap in terms of the basic vision, but the products are at quite different points in their lifecycle and have different sweet spots. Mesos is a distributed systems kernel that stitches together a lot of different machines into a logical computer. It was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application run well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps. It is somewhat more heavy weight than the Kubernetes project, but is getting easier and easier to manage thanks to the work of folks like Mesosphere.

Now what gets really interesting is that Mesos is currently being adapted to add a lot of the Kubernetes concepts and to support the Kubernetes API. So it will be a gateway to getting more capabilities for your Kubernetes app (high availability master, more advanced scheduling semantics, ability to scale to a very large number of nodes) if you need them, and is well suited to run production workloads (Kubernetes is still in an alpha state).

When asked, I tend to say:

  1. Kubernetes is a great place to start if you are new to the clustering world; it is the quickest, easiest and lightest way to kick the tires and start experimenting with cluster oriented development. It offers a very high level of portability since it is being supported by a lot of different providers (Microsoft, IBM, Red Hat, CoreOs, MesoSphere, VMWare, etc).

  2. If you have existing workloads (Hadoop, Spark, Kafka, etc), Mesos gives you a framework that let's you interleave those workloads with each other, and mix in a some of the new stuff including Kubernetes apps.

  3. Mesos gives you an escape valve if you need capabilities that are not yet implemented by the community in the Kubernetes framework.

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

For 3-D visualization pythreejs is the best way to go probably in the notebook. It leverages the interactive widget infrastructure of the notebook, so connection between the JS and python is seamless.

A more advanced library is bqplot which is a d3-based interactive viz library for the iPython notebook, but it only does 2D

Can I install the "app store" in an IOS simulator?

You can install other builds but not Appstore build.

From Xcode 8.2,drag and drop the build to simulator for the installation.

https://stackoverflow.com/a/41671233/1522584

PHP - remove <img> tag from string

Sean it works fine i've just used this code

$content = preg_replace("/<img[^>]+\>/i", " ", $content); 
echo $content;

//the result it's only the plain text. It works!!!

Descending order by date filter in AngularJs

In my case, the orderBy is determined by a select box. I prefer Ludwig's response because you can set the sort direction in the select options as such:

        $scope.options = [
            { label: 'Title', value: 'title' },
            { label: 'Newest', value: '-publish_date' },
            { label: 'Featured', value: '-featured' }
        ]; 

markup:

<select ng-model="orderProp" ng-options="opt as opt.label for opt in options"></select>
<ul>
    <li ng-repeat="item in items | orderBy:orderProp.value"></li>
</ul>

File Upload without Form

Step 1: Create HTML Page where to place the HTML Code.

Step 2: In the HTML Code Page Bottom(footer)Create Javascript: and put Jquery Code in Script tag.

Step 3: Create PHP File and php code copy past. after Jquery Code in $.ajax Code url apply which one on your php file name.

JS

//$(document).on("change", "#avatar", function() {   // If you want to upload without a submit button 
$(document).on("click", "#upload", function() {
  var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
  var form_data = new FormData(); // Creating object of FormData class
  form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
  form_data.append("user_id", 123) // Adding extra parameters to form_data
  $.ajax({
    url: "/upload_avatar", // Upload Script
    dataType: 'script',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data, // Setting the data attribute of ajax with file_data
    type: 'post',
    success: function(data) {
      // Do something after Ajax completes 
    }
  });
});

HTML

<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />

Php

print_r($_FILES);
print_r($_POST);

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

It depends on the kind of test double you want to interact with:

  • If you don't use doNothing and you mock an object, the real method is not called
  • If you don't use doNothing and you spy an object, the real method is called

In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.

WAITING at sun.misc.Unsafe.park(Native Method)

I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.

In my case, that just fix my progressive increase of similar blocked threads:

  • I've used ExecutorService::awaitTermination(x, TimeUnit) and ExecutorService::shutdownNow() (if necessary) in my finally clause.
  • For information, I've used the following commands to detect thread count & list locked threads:

    ps -u javaAppuser -L|wc -l

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log

    cat threadPrint*.log |grep "pool-"|wc -l

Difference between CR LF, LF and CR line break types?

CR - ASCII code 13

LF - ASCII code 10.

Theoretically CR returns cursor to the first position (on the left). LF feeds one line moving cursor one line down. This is how in old days you controled printers and text-mode monitors. These characters are usually used to mark end of lines in text files. Different operating systems used different conventions. As you pointed out Windows uses CR/LF combination while pre-OSX Macs use just CR and so on.

How to close jQuery Dialog within the dialog?

Using $(this).dialog('close'); only works inside the click function of a button within the modal. If your button is not within the dialog box, as in this example, specify a selector:

$('#form-dialog').dialog('close');

For more information, see the documentation

Why does a base64 encoded string have an = sign at the end

The equals sign (=) is used as padding in certain forms of base64 encoding. The Wikipedia article on base64 has all the details.

How to move the cursor word by word in the OS X Terminal

Hold down the Option key and click where you'd like the cursor to move

How do I convert dmesg timestamp to custom date format?

With the help of dr answer, I wrote a workaround that makes the conversion to put in your .bashrc. It won't break anything if you don't have any timestamp or already correct timestamps.

dmesg_with_human_timestamps () {
    $(type -P dmesg) "$@" | perl -w -e 'use strict;
        my ($uptime) = do { local @ARGV="/proc/uptime";<>}; ($uptime) = ($uptime =~ /^(\d+)\./);
        foreach my $line (<>) {
            printf( ($line=~/^\[\s*(\d+)\.\d+\](.+)/) ? ( "[%s]%s\n", scalar localtime(time - $uptime + $1), $2 ) : $line )
        }'
}
alias dmesg=dmesg_with_human_timestamps

Also, a good reading on the dmesg timestamp conversion logic & how to enable timestamps when there are none: https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk92677

javascript - pass selected value from popup window to parent window input box

use: opener.document.<id of document>.innerHTML = xmlhttp.responseText;

warning: assignment makes integer from pointer without a cast

The expression *src refers to the first character in the string, not the whole string. To reassign src to point to a different string tgt, use src = tgt;.

align text center with android

You can use the following:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/showdescriptioncontenttitle"
    android:paddingTop="10dp"
    android:paddingBottom="10dp">

 <TextView
        android:id="@+id/textview1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Your text"
        android:typeface="serif" />
</LinearLayout>

The layout needs to be relative for the "center" property to be used.

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Can't import javax.servlet.annotation.WebServlet

If you are using IBM RAD, then ensure the to remove any j2ee.jar in your projects build path -> libraries tab, and then click on "add external jar" and select the j2ee.jar that is shipped with RAD.

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

Run this command -

_x000D_
_x000D_
lsof -wni tcp:3000
_x000D_
_x000D_
_x000D_

then you will get the following table -

_x000D_
_x000D_
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
ruby    2552 shyam   17u  IPv4  44599      0t0  TCP 127.0.0.1:3000 (LISTEN)
ruby    2552 shyam   18u  IPv6  44600      0t0  TCP [::1]:3000 (LISTEN)
_x000D_
_x000D_
_x000D_

Run this command and replace PID from the Above table

_x000D_
_x000D_
kill -9 PID
_x000D_
_x000D_
_x000D_

example:

_x000D_
_x000D_
kill -9 2552
_x000D_
_x000D_
_x000D_

Fatal error: Call to undefined function sqlsrv_connect()

If you are using Microsoft Drivers 3.1, 3.0, and 2.0. Please check your PHP version already install with IIS.

Use this script to check the php version:

<?php echo phpinfo(); ?>

OR

If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.

Then:
If you are using new PHP version (5.6) please download Drivers from here

For PHP version Lower than 5.6 - please download Drivers from here

  • PHP Driver version 3.1 requires PHP 5.4.32, or PHP 5.5.16, or later.
  • PHP Driver version 3.0 requires PHP 5.3.0 or later. If possible, use PHP 5.3.6, or later.
  • PHP Driver version 2.0 driver works with PHP 5.2.4 or later, but not with PHP 5.4. If possible, use PHP 5.2.13, or later.

Then use the PHP Manager to add that downloaded drivers into php config file.You can do it as shown below (browse the files and press OK). Then Restart the IIS Server

enter image description here

If this method not work please change the php version and try to run your php script. enter image description here

Tip:Change the php version to lower and try to understand what happened.then you can download relevant drivers.

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

Extracting Path from OpenFileDialog path/filename

Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

string directoryPath = Path.GetDirectoryName(filePath);

Business logic in MVC

A1: Business Logic goes to Model part in MVC. Role of Model is to contain data and business logic. Controller on the other hand is responsible to receive user input and decide what to do.

A2: A Business Rule is part of Business Logic. They have a has a relationship. Business Logic has Business Rules.

Take a look at Wikipedia entry for MVC. Go to Overview where it mentions the flow of MVC pattern.

Also look at Wikipedia entry for Business Logic. It is mentioned that Business Logic is comprised of Business Rules and Workflow.

Converting a String to Object

A Java String is an Object. (String extends Object.)

So you can get an Object reference via assignment/initialisation:

String a = "abc";
Object b = a;

Not equal string

Try this:

if(myString != "-1")

The opperand is != and not =!

You can also use Equals

if(!myString.Equals("-1"))

Note the ! before myString

What is the difference between range and xrange functions in Python 2.X?

xrange returns an iterator and only keeps one number in memory at a time. range keeps the entire list of numbers in memory.

Error 'tunneling socket' while executing npm install

Removing the proxy settings resolved the issue:

If you are no using any proxy:

npm config rm proxy
npm config rm https-proxy

If you are using Proxy:

npm config set proxy http://proxyhostname:proxyport
npm config set https-proxy https://proxyhostname:proxyport

Hopefully this will solve your problem :)

jQuery select change show/hide div event

Try the below JS

$(function() {
    $('#type').change(function(){
        $('#row_dim').hide(); 
        if ($(this).val() == 'parcel')
        {
             $('#row_dim').show();
        }
    });
});

How to split data into 3 sets (train, validation and test)?

Considering that df id your original dataframe:

1 - First you split data between Train and Test (10%):

my_test_size = 0.10

X_train_, X_test, y_train_, y_test = train_test_split(
    df.index.values,
    df.label.values,
    test_size=my_test_size,
    random_state=42,
    stratify=df.label.values,    
)

2 - Then you split the train set between train and validation (20%):

my_val_size = 0.20

X_train, X_val, y_train, y_val = train_test_split(
    df.loc[X_train_].index.values,
    df.loc[X_train_].label.values,
    test_size=my_val_size,
    random_state=42,
    stratify=df.loc[X_train_].label.values,  
)

3 - Then, you slice the original dataframe according to the indices generated in the steps above:

# data_type is not necessary. 
df['data_type'] = ['not_set']*df.shape[0]
df.loc[X_train, 'data_type'] = 'train'
df.loc[X_val, 'data_type'] = 'val'
df.loc[X_test, 'data_type'] = 'test'

The result is going to be like this:

enter image description here

Note: This soluctions uses the workaround mentioned in the question.

Android studio doesn't list my phone under "Choose Device"

Error handling with PHPMailer

We wrote a wrapper class that captures the buffer and converts the printed output to an exception. this lets us upgrade the phpmailer file without having to remember to comment out the echo statements each time we upgrade.

The wrapper class has methods something along the lines of:

public function AddAddress($email, $name = null) {
    ob_start();
    parent::AddAddress($email, $name);
    $error = ob_get_contents();
    ob_end_clean();
    if( !empty($error) ) {
        throw new Exception($error);
    }
}

How to get certain commit from GitHub project

To just download a commit using the 7-digit SHA1 short form do:

Working Example:

https://github.com/python/cpython/archive/31af650.zip  

Description:

 `https://github.com/username/projectname/archive/commitshakey.zip`

If you have the long hash key 31af650ee25f65794b75d4dfefed6fe4758781c1, just get the first 7 chars 31af650. It's the default for GitHub.

how to enable sqlite3 for php?

For Debian distributions. Nothing worked for until I added the debian main repositories on the apt sources (I don't know how were they removed): sudo vi /etc/apt/sources.list

and added

deb  http://deb.debian.org/debian  stretch main
deb-src  http://deb.debian.org/debian  stretch main

after that sudo apt-get update (you can upgrade too) and finally sudo apt-get install php-sqlite3

Formatting ISODate from Mongodb

MongoDB's ISODate() is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.

You can still use all of the same methods as working with a normal JS Date, such as:

ISODate("2012-07-14T01:00:00+01:00").toLocaleTimeString()

// Note that getHours() and getMinutes() do not include leading 0s for single digit #s
ISODate("2012-07-14T01:00:00+01:00").getHours()
ISODate("2012-07-14T01:00:00+01:00").getMinutes()

How can I convert the "arguments" object to an array in JavaScript?

Here's a clean and concise solution:

_x000D_
_x000D_
function argsToArray() {_x000D_
  return Object.values(arguments);_x000D_
}_x000D_
_x000D_
// example usage_x000D_
console.log(_x000D_
  argsToArray(1, 2, 3, 4, 5)_x000D_
  .map(arg => arg*11)_x000D_
);
_x000D_
_x000D_
_x000D_

Object.values( ) will return the values of an object as an array, and since arguments is an object, it will essentially convert arguments into an array, thus providing you with all of an array's helper functions such as map, forEach, filter, etc.

How do I get the current mouse screen coordinates in WPF?

If you're looking for a 1 liner, this does well.

new Point(Mouse.GetPosition(mWindow).X + mWindow.Left, Mouse.GetPosition(mWindow).Y + mWindow.Top)

The + mWindow.Left and + mWindow.Top makes sure the position is in the right place even when the user drags the window around.

Adding a Time to a DateTime in C#

   DateTime newDateTime = dtReceived.Value.Date.Add(TimeSpan.Parse(dtReceivedTime.Value.ToShortTimeString()));

How to insert a new line in Linux shell script?

The simplest way to insert a new line between echo statements is to insert an echo without arguments, for example:

echo Create the snapshots
echo
echo Snapshot created

That is, echo without any arguments will print a blank line.

Another alternative to use a single echo statement with the -e flag and embedded newline characters \n:

echo -e "Create the snapshots\n\nSnapshot created"

However, this is not portable, as the -e flag doesn't work consistently in all systems. A better way if you really want to do this is using printf:

printf "Create the snapshots\n\nSnapshot created\n"

This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n at the end, as printf doesn't append a newline automatically as echo does.

How to append binary data to a buffer in node.js

insert byte to specific place.

insertToArray(arr,index,item) {
   return Buffer.concat([arr.slice(0,index),Buffer.from(item,"utf-8"),arr.slice(index)]);
}

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

src is the first argument to cv2.cvtColor.

The error you are getting is because it is not the right form. cv2.Umat() is functionally equivalent to np.float32(), so your last line of code should read:

gray = cv2.cvtColor(np.float32(imgUMat), cv2.COLOR_RGB2GRAY)

Primitive type 'short' - casting in Java

In C# and Java, the arithmatic expression on the right hand side of the assignment evaluates to int by default. That's why you need to cast back to a short, because there is no implicit conversion form int to short, for obvious reasons.

How to reference a file for variables using Bash?

in Bash, to source some command's output, instead of a file:

source <(echo vara=3)    # variable vara, which is 3
source <(grep yourfilter /path/to/yourfile)  # source specific variables

reference

Convert String to Double - VB

VB.NET Sample Code

Dim A as String = "5.3"
Dim B as Double

B = CDbl(Val(A)) '// Val do hard work

'// Get output 
MsgBox (B) '// Output is 5,3 Without Val result is 53.0

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

A good way to inspect objects is to use node --inspect option with Chrome DevTools for Node.

node.exe --inspect www.js

Open chrome://inspect/#devices in chrome and click Open dedicated DevTools for Node

Now every logged object is available in inspector like regular JS running in chrome.

enter image description here

There is no need to reopen inspector, it connects to node automatically as soon as node starts or restarts. Both --inspect and Chrome DevTools for Node may not be available in older versions of Node and Chrome.

What is the `data-target` attribute in Bootstrap 3?

data-target is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.

The data-target attribute should contain a CSS selector that points to the HTML Element that will be changed.

Modal Example Code from BS3:

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  [...]
</div>

In this example, the button has data-target="#myModal", if you click on it, <div id="myModal">...</div> will be modified (in this case faded in). This happens because #myModal in CSS selectors points to elements that have an id attribute with the myModal value.

Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

Java generics: multiple generic parameters?

a and b must both be sets of the same type. But nothing prevents you from writing

myfunction(Set<X> a, Set<Y> b)

UICollectionView cell selection and cell reuse

Only @stefanB solution worked for me on iOS 9.3

Here what I have to change for Swift 2

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        //prepare your cell here..

        //Add background view for normal cell
        let backgroundView: UIView = UIView(frame: cell!.bounds)
        backgroundView.backgroundColor = UIColor.lightGrayColor()
        cell!.backgroundView = backgroundView

        //Add background view for selected cell
        let selectedBGView: UIView = UIView(frame: cell!.bounds)
        selectedBGView.backgroundColor = UIColor.redColor()
        cell!.selectedBackgroundView = selectedBGView

        return cell!
 }

 func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
 }

 func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
 }

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

Finding rows that don't contain numeric data in Oracle

From http://www.dba-oracle.com/t_isnumeric.htm

LENGTH(TRIM(TRANSLATE(, ' +-.0123456789', ' '))) is null

If there is anything left in the string after the TRIM it must be non-numeric characters.

Angular - "has no exported member 'Observable'"

The angular-split component is not supported in Angular 6, so to make it compatible with Angular 6 install following dependency in your application

To get this working until it's updated use:

"dependencies": {
"angular-split": "1.0.0-rc.3",
"rxjs": "^6.2.2",
    "rxjs-compat": "^6.2.2",
}

How to get the version of ionic framework?

The method version on ionic object returns the current version in string format.

How we can bold only the name in table td tag not the value

Surround what you want to be bold with:

<span style="font-weight:bold">Your bold text</span>

This would go inside your <td> tag.

Free Rest API to retrieve current datetime as string (timezone irrelevant)

TimezoneDb provides a free API: http://timezonedb.com/api

GenoNames also has a RESTful API available to get the current time for a given location: http://www.geonames.org/export/ws-overview.html.

You can use Greenwich, UK if you'd like GMT.

What is <=> (the 'Spaceship' Operator) in PHP 7?

Its a new operator for combined comparison. Similar to strcmp() or version_compare() in behavior, but it can be used on all generic PHP values with the same semantics as <, <=, ==, >=, >. It returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It uses exactly the same comparison rules as used by our existing comparison operators: <, <=, ==, >= and >.

click here to know more

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

my solution was - just remove '*' character from the expression ^__^

<div ngFor="let talk in talks">

Eloquent ORM laravel 5 Get Array of ids

Just an extra info, if you are using DB:

DB::table('test')->where('id', '>', 0)->pluck('id')->toArray();

And if using Eloquent model:

test::where('id', '>', 0)->lists('id')->toArray();

Android - Dynamically Add Views into View

See the LayoutInflater class.

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);

How to delete a workspace in Eclipse?

Click on the menu Window > Preferences and go to Workspaces like below :

| General
    | Startup and Shutdown
        | Workspaces

Select the workspace to delete and click on the Remove button.

How to append a date in batch files

As has been noted, parsing the date and time is only useful if you know the format being used by the current user (eg. MM/dd/yy or dd-MM-yyyy just to name 2). This could be determined, but by the time you do all the stressing and parsing, you will still end up with some situation where there is an unexpected format used, and more tweaks will be be necessary.

You can also use some external program that will return a date slug in your preferred format, but that has disadvantages of needing to distribute the utility program with your script/batch.

there are also batch tricks using the CMOS clock in a pretty raw way, but that is tooo close to bare wires for most people, and also not always the preferred place to retrieve the date/time.

Below is a solution that avoids the above problems. Yes, it introduces some other issues, but for my purposes I found this to be the easiest, clearest, most portable solution for creating a datestamp in .bat files for modern Windows systems. This is just an example, but I think you will see how to modify for other date and/or time formats, etc.

reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f
reg add "HKCU\Control Panel\International" /v sShortDate /d "yyMMdd" /f
@REM the following may be needed to be sure cache is clear before using the new setting
reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f

How to get the selected item from ListView?

Though I am using kotlin, the following code answered your question. This return selected item:

val item = myListView.adapter.getItem(i).toString()

The following is the whole selecteditem Listener

myListView.setOnItemClickListener(object : OnItemClickListener {
       override fun onItemClick(parent: AdapterView<*>, view: View, i: Int,
                        id: Long) {
           val item = myListView.adapter.getItem(i).toString()

       }
    })

The code returns the item clicked by its index i as shown in the code

How to compile Tensorflow with SSE4.2 and AVX instructions?

I have recently installed it from source and bellow are all the steps needed to install it from source with the mentioned instructions available.

Other answers already describe why those messages are shown. My answer gives a step-by-step on how to isnstall, which may help people struglling on the actual installation as I did.

  1. Install Bazel

Download it from one of their available releases, for example 0.5.2. Extract it, go into the directory and configure it: bash ./compile.sh. Copy the executable to /usr/local/bin: sudo cp ./output/bazel /usr/local/bin

  1. Install Tensorflow

Clone tensorflow: git clone https://github.com/tensorflow/tensorflow.git Go to the cloned directory to configure it: ./configure

It will prompt you with several questions, bellow I have suggested the response to each of the questions, you can, of course, choose your own responses upon as you prefer:

Using python library path: /usr/local/lib/python2.7/dist-packages
Do you wish to build TensorFlow with MKL support? [y/N] y
MKL support will be enabled for TensorFlow
Do you wish to download MKL LIB from the web? [Y/n] Y
Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native]: 
Do you wish to use jemalloc as the malloc implementation? [Y/n] n
jemalloc disabled
Do you wish to build TensorFlow with Google Cloud Platform support? [y/N] N
No Google Cloud Platform support will be enabled for TensorFlow
Do you wish to build TensorFlow with Hadoop File System support? [y/N] N
No Hadoop File System support will be enabled for TensorFlow
Do you wish to build TensorFlow with the XLA just-in-time compiler (experimental)? [y/N] N
No XLA JIT support will be enabled for TensorFlow
Do you wish to build TensorFlow with VERBS support? [y/N] N
No VERBS support will be enabled for TensorFlow
Do you wish to build TensorFlow with OpenCL support? [y/N] N
No OpenCL support will be enabled for TensorFlow
Do you wish to build TensorFlow with CUDA support? [y/N] N
No CUDA support will be enabled for TensorFlow
  1. The pip package. To build it you have to describe which instructions you want (you know, those Tensorflow informed you are missing).

Build pip script: bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mfpmath=both --copt=-msse4.1 --copt=-msse4.2 -k //tensorflow/tools/pip_package:build_pip_package

Build pip package: bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

Install Tensorflow pip package you just built: sudo pip install /tmp/tensorflow_pkg/tensorflow-1.2.1-cp27-cp27mu-linux_x86_64.whl

Now next time you start up Tensorflow it will not complain anymore about missing instructions.

encapsulation vs abstraction real world example

Everything has many properties and behaviours so take whatever object you want TV, Mobile, Car, Human or anything.

Abstraction:

  1. Process of picking the essence of an object you really need
  2. In other words, pick the properties you need from the object Example:
    a. TV - Sound, Visuals, Power Input, Channels Input.
    b. Mobile - Button/Touch screen, power button, volume button, sim port.
    c. Car - Steering, Break, Clutch, Accelerator, Key Hole.
    d. Human - Voice, Body, Eye Sight, Hearing, Emotions.

Encapsulation:

  1. Process of hiding the details of an object you don't need
  2. In other words, hide the properties and operations you don't need from the object but are required for the object to work properly Example:
    a. TV - Internal and connections of Speaker, Display, Power distribution b/w components, Channel mechanism.
    b. Mobile - How the input is parsed and processed, How pressing a button on/off or changes volumes, how sim will connect to service providers.
    c. Car - How turning steering turns the car, How break slow or stops the car, How clutch works, How accelerator increases speed, How key hole switch on/of the car.
    d. Human - How voice is produced, What's inside the body, How eye sight works, How hearing works, How emotions generate and effect us.

ABSTRACT everything you need and ENCAPSULATE everything you don't need ;)

How to use if-else option in JSTL

I got away with simply using two if tags, thought I'd add an answer in case it's of use to anyone else:

<c:if test="${condition}">
  ...
</c:if>
<c:if test="${!condition}">
  ...
</c:if>

whilst technically not an if-else per se, the behaviour is the same and avoids the clunky approach of using the choose tag, so depending on how complex your requirement is this might be preferable.

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

Select Tomcat server in Targeted Runtime

Project->Properties->Targeted Runtimes (Select your Tomcat Server)

Convert list to tuple in Python

I find many answers up to date and properly answered but will add something new to stack of answers.

In python there are infinite ways to do this, here are some instances
Normal way

>>> l= [1,2,"stackoverflow","python"]
>>> l
[1, 2, 'stackoverflow', 'python']
>>> tup = tuple(l)
>>> type(tup)
<type 'tuple'>
>>> tup
(1, 2, 'stackoverflow', 'python')

smart way

>>>tuple(item for item in l)
(1, 2, 'stackoverflow', 'python')

Remember tuple is immutable ,used for storing something valuable. For example password,key or hashes are stored in tuples or dictionaries. If knife is needed why to use sword to cut apples. Use it wisely, it will also make your program efficient.

Changing background color of text box input not working when empty

You could have the CSS first style the textbox, then have js change it:

<input type="text" style="background-color: yellow;" id="subEmail" />

js:

function changeColor() {
  document.getElementById("subEmail").style.backgroundColor = "Insert color here"
}

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

We had the same issue when we had a typo in the mybatis mapping file like

        ....
        #{column1Name,          jdbcType=INTEGER},
        #{column2Name,          jdbcType=VARCHAR},
        #{column3Name,      jdbcTyep=VARCHAR}  -- do you see the typo ?
        .....

So check this kind of typos as well. Unfortunately, it can not understand the typo in compile/build time, it causes an unchecked exception and booms in runtime.

How to manage local vs production settings in Django?

As an alternative to maintain different file if you wiil: If you are using git or any other VCS to push codes from local to server, what you can do is add the settings file to .gitignore.

This will allow you to have different content in both places without any problem. SO on server you can configure an independent version of settings.py and any changes made on the local wont reflect on server and vice versa.

In addition, it will remove the settings.py file from github also, the big fault, which i have seen many newbies doing.

How to print a string at a fixed width?

EDIT 2013-12-11 - This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax.

You can use string formatting like this:

>>> print '%5s' % 'aa'
   aa
>>> print '%5s' % 'aaa'
  aaa
>>> print '%5s' % 'aaaa'
 aaaa
>>> print '%5s' % 'aaaaa'
aaaaa

Basically:

  • the % character informs python it will have to substitute something to a token
  • the s character informs python the token will be a string
  • the 5 (or whatever number you wish) informs python to pad the string with spaces up to 5 characters.

In your specific case a possible implementation could look like:

>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
...     print 'value %3s - num of occurances = %d' % item # %d is the token of integers
... 
value   a - num of occurances = 1
value  ab - num of occurances = 1
value abc - num of occurances = 1

SIDE NOTE: Just wondered if you are aware of the existence of the itertools module. For example you could obtain a list of all your combinations in one line with:

>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

and you could get the number of occurrences by using combinations in conjunction with count().

json_encode sparse PHP array as JSON array, not JSON object

Array in JSON are indexed array only, so the structure you're trying to get is not valid Json/Javascript.

PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.

If you want to get such structure you can do:

$indexedOnly = array();

foreach ($associative as $row) {
    $indexedOnly[] = array_values($row);
}

json_encode($indexedOnly);

Will returns something like:

[
     [0, "name1", "n1"],
     [1, "name2", "n2"],
]

How to capture no file for fs.readFileSync()?

The JavaScript try…catch mechanism cannot be used to intercept errors generated by asynchronous APIs. A common mistake for beginners is to try to use throw inside an error-first callback:

// THIS WILL NOT WORK:
const fs = require('fs');

try {
  fs.readFile('/some/file/that/does-not-exist', (err, data) => {
    // Mistaken assumption: throwing here...
    if (err) {
      throw err;
    }
  });
} catch (err) {
  // This will not catch the throw!
  console.error(err);
}

This will not work because the callback function passed to fs.readFile() is called asynchronously. By the time the callback has been called, the surrounding code, including the try…catch block, will have already exited. Throwing an error inside the callback can crash the Node.js process in most cases. If domains are enabled, or a handler has been registered with process.on('uncaughtException'), such errors can be intercepted.

reference: https://nodejs.org/api/errors.html

Android - styling seek bar

Small correction to the answer by @arnav-rao:

to make sure that the thumb is colored properly, use:

<style name="MySeekBar" parent="Widget.AppCompat.SeekBar">
    <item name="android:progressBackgroundTint">@color/colorBgTint</item>
    <item name="android:progressTint">@color/colorProgressTint</item>
    <item name="android:thumbTint">@color/colorThumbTint</item>
</style>

here android:thumbTint actually colors the "thumb"

Cocoa: What's the difference between the frame and the bounds?

Frame its relative to its SuperView whereas Bounds relative to its NSView.

Example:X=40,Y=60.Also contains 3 Views.This Diagram shows you clear idea.

FRAME

BOUNDS

Remove "whitespace" between div element

Using a <br/> for making a new row it's a bad solution from the start. Make your container #div1 to have a width equal to 3 child-divs. <br/> in my opinion should not be used in other places than paragraphs.

Basic communication between two fragments

I give my activity an interface that all the fragments can then use. If you have have many fragments on the same activity, this saves a lot of code re-writing and is a cleaner solution / more modular than making an individual interface for each fragment with similar functions. I also like how it is modular. The downside, is that some fragments will have access to functions they don't need.

    public class MyActivity extends AppCompatActivity
    implements MyActivityInterface {

        private List<String> mData; 

        @Override
        public List<String> getData(){return mData;}

        @Override
        public void setData(List<String> data){mData = data;}
    }


    public interface MyActivityInterface {

        List<String> getData(); 
        void setData(List<String> data);
    }

    public class MyFragment extends Fragment {

         private MyActivityInterface mActivity; 
         private List<String> activityData; 

         public void onButtonPress(){
              activityData = mActivity.getData()
         }

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            if (context instanceof MyActivityInterface) {
                mActivity = (MyActivityInterface) context;
            } else {
                throw new RuntimeException(context.toString()
                        + " must implement MyActivityInterface");
            }
        }

        @Override
        public void onDetach() {
            super.onDetach();
            mActivity = null;
        }
    } 

Opening database file from within SQLite command-line shell

You can simply specify the database file name in the command line:

bash-3.2 # sqlite3 UserDb.sqlite
SQLite version 3.16.2 2017-01-06 16:32:41
Enter ".help" for usage hints.

sqlite> .databases
main: /db/UserDb.sqlite

sqlite> .tables
accountLevelSettings  genres               syncedThumbs
collectionActivity    recordingFilter      thumbs
contentStatus         syncedContentStatus 

sqlite> select count(*) from genres;
10

Moreover, you can execute your query from the command line:

bash-3.2 # sqlite3 UserDb.sqlite 'select count(*) from genres'
10

You could attach another database file from the SQLite shell:

sqlite> attach database 'RelDb.sqlite' as RelDb;

sqlite> .databases
main: /db/UserDb.sqlite
RelDb: /db/RelDb_1.sqlite

sqlite> .tables
RelDb.collectionRelationship  contentStatus               
RelDb.contentRelationship     genres                      
RelDb.leagueRelationship      recordingFilter             
RelDb.localizedString         syncedContentStatus         
accountLevelSettings          syncedThumbs                
collectionActivity            thumbs                      

The tables from this 2nd database will be accessible via prefix of the database:

sqlite> select count(*) from RelDb.localizedString;
2442

But who knows how to specify multiple database files from the command line to execute the query from the command line?

Creating a list of pairs in java

If you want multiplicities, you can put it in map that maps pair to ammount. This way there will only be one pair of given values, but it can represent multiple occurances.

Then if you have lot of repeatet values and want to perform some operation on all values, you can save lot of computations.

How to grant remote access to MySQL for a whole subnet?

You would just use '%' as your wildcard like this:

GRANT ALL ON *.* to root@'192.168.1.%' IDENTIFIED BY 'your-root-password';

Regular expression for a hexadecimal number?

How about the following?

0[xX][0-9a-fA-F]+

Matches expression starting with a 0, following by either a lower or uppercase x, followed by one or more characters in the ranges 0-9, or a-f, or A-F

Add animated Gif image in Iphone UIImageView

UIImageView* animatedImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
animatedImageView.animationImages = [NSArray arrayWithObjects:    
                               [UIImage imageNamed:@"image1.gif"],
                               [UIImage imageNamed:@"image2.gif"],
                               [UIImage imageNamed:@"image3.gif"],
                               [UIImage imageNamed:@"image4.gif"], nil];
animatedImageView.animationDuration = 1.0f;
animatedImageView.animationRepeatCount = 0;
[animatedImageView startAnimating];
[self.view addSubview: animatedImageView];

You can load more than one gif images.

You can split your gif using the following ImageMagick command:

convert +adjoin loading.gif out%d.gif

How to export collection to CSV in MongoDB?

If you want, you can export all collections to csv without specifying --fields (will export all fields).

From http://drzon.net/export-mongodb-collections-to-csv-without-specifying-fields/ run this bash script

OIFS=$IFS;
IFS=",";

# fill in your details here
dbname=DBNAME
user=USERNAME
pass=PASSWORD
host=HOSTNAME:PORT

# first get all collections in the database
collections=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();db.getCollectionNames();"`;
collections=`mongo $dbname --eval "rs.slaveOk();db.getCollectionNames();"`;
collectionArray=($collections);

# for each collection
for ((i=0; i<${#collectionArray[@]}; ++i));
do
    echo 'exporting collection' ${collectionArray[$i]}
    # get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
    keys=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();var keys = []; for(var key in db.${collectionArray[$i]}.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
    # now use mongoexport with the set of keys to export the collection to csv
    mongoexport --host $host -u $user -p $pass -d $dbname -c ${collectionArray[$i]} --fields "$keys" --csv --out $dbname.${collectionArray[$i]}.csv;
done

IFS=$OIFS;

php check if array contains all array values from another array

Look at array_intersect().

$containsSearch = count(array_intersect($search_this, $all)) == count($search_this);

How to delete large data of table in SQL without log?

@m-ali answer is right but also keep in mind that logs could grow a lot if you don't commit the transaction after each chunk and perform a checkpoint. This is how I would do it and take this article http://sqlperformance.com/2013/03/io-subsystem/chunk-deletes as reference, with performance tests and graphs:

DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;


WHILE (@Deleted_Rows > 0)
  BEGIN

   BEGIN TRANSACTION

   -- Delete some small number of rows at a time
     DELETE TOP (10000)  LargeTable 
     WHERE readTime < dateadd(MONTH,-7,GETDATE())

     SET @Deleted_Rows = @@ROWCOUNT;

   COMMIT TRANSACTION
   CHECKPOINT -- for simple recovery model
END

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

How do you create a temporary table in an Oracle database?

CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';

Any easy way to use icons from resources?

Forms maintain separate resource files (SomeForm.Designer.resx) added via the designer. To use icons embedded in another resource file requires codes. (this.Icone = Project.Resources.SomeIcon;)

Inserting created_at data with Laravel

In my case, I wanted to unit test that users weren't able to verify their email addresses after 1 hour had passed, so I didn't want to do any of the other answers since they would also persist when not unit testing, so I ended up just manually updating the row after insert:

// Create new user
$user = factory(User::class)->create();

// Add an email verification token to the 
// email_verification_tokens table
$token = $user->generateNewEmailVerificationToken();

// Get the time 61 minutes ago
$created_at = (new Carbon())->subMinutes(61);

// Do the update
\DB::update(
    'UPDATE email_verification_tokens SET created_at = ?',
    [$created_at]
);

Note: For anything other than unit testing, I would look at the other answers here.

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

How to read all files in a folder from Java?

Simple example that works with Java 1.7 to recursively list files in directories specified on the command-line:

import java.io.File;

public class List {
    public static void main(String[] args) {
        for (String f : args) {
            listDir(f);
        }
    }

    private static void listDir(String dir) {
        File f = new File(dir);
        File[] list = f.listFiles();

        if (list == null) {
            return;
        }

        for (File entry : list) {
            System.out.println(entry.getName());
            if (entry.isDirectory()) {
                listDir(entry.getAbsolutePath());
            }
        }
    }
}

Submit button not working in Bootstrap form

Your problem is this

<button type="button" value=" Send" class="btn btn-success" type="submit" id="submit" />

You've set the type twice. Your browser is only accepting the first, which is "button".

<button type="submit" value=" Send" class="btn btn-success" id="submit" />

Viewing root access files/folders of android on windows

I was looking long and hard for a solution to this problem and the best I found was a root FTP server on the phone that you connect to on Windows with an FTP client like FileZilla, on the same WiFi network of course.

The root FTP server app I ended up using is FTP Droid. I tried a lot of other FTP apps with bigger download numbers but none of them worked for me for whatever reason. So install this app and set a user with home as / or wherever you want.

Then make note of the phone IP and connect with FileZilla and you should have access to the root of the phone. The biggest benefit I found is I can download entire folders and FTP will just queue it up and take care of it. So I downloaded all of my /data/data/ folder when I was looking for an app and could search on my PC. Very handy.

How to access the elements of a function's return array?

<?php
function demo($val,$val1){
    return $arr=array("value"=>$val,"value1"=>$val1);

}
$arr_rec=demo(25,30);
echo $arr_rec["value"];
echo $arr_rec["value1"];
?>

When to use 'npm start' and when to use 'ng serve'?

From the document

npm-start :

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

which means it will call the start scripts inside the package.json

"scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite --baseDir ./app --port 8001\" ",
"lite": "lite-server",
 ...
}

ng serve:

Provided by angular/angular-cli to start angular2 apps which created by angular-cli. when you install angular-cli, it will create ng.cmd under C:\Users\name\AppData\Roaming\npm (for windows) and execute "%~dp0\node.exe" "%~dp0\node_modules\angular-cli\bin\ng" %*

So using npm start you can make your own execution where is ng serve is only for angular-cli

See Also : What happens when you run ng serve?

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

I face the same problem and changing

 $cfg['Servers'][$i]['host'] = 'localhost';

to

 $cfg['Servers'][$i]['host'] = '127.0.0.1';

Solved this issue.

Java function for arrays like PHP's join()?

To get "str1, str2" from "str1", "str2", "" :

Stream.of("str1", "str2", "").filter(str -> !str.isEmpty()).collect(Collectors.joining(", ")); 

Also you can add extra null-check

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

IMHO, the reason why 2 queries

SELECT * FROM count_test WHERE b = 666 ORDER BY c LIMIT 5;
SELECT count(*) FROM count_test WHERE b = 666;

are faster than using SQL_CALC_FOUND_ROWS

SELECT SQL_CALC_FOUND_ROWS * FROM count_test WHERE b = 555 ORDER BY c LIMIT 5;

has to be seen as a particular case.

It in facts depends on the selectivity of the WHERE clause compared to the selectivity of the implicit one equivalent to the ORDER + LIMIT.

As Arvids told in comment (http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-1174394), the fact that the EXPLAIN use, or not, a temporay table, should be a good base for knowing if SCFR will be faster or not.

But, as I added (http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-8166482), the result really, really depends on the case. For a particular paginator, you could get to the conclusion that “for the 3 first pages, use 2 queries; for the following pages, use a SCFR” !

z-index not working with position absolute

I faced this issue a lot when using position: absolute;, I faced this issue by using position: relative in the child element. don't need to change position: absolute to relative, just need to add in the child element look into the beneath two examples:

_x000D_
_x000D_
let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
_x000D_
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
_x000D_
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>
_x000D_
_x000D_
_x000D_

This's how it can be fixed using position relative:

_x000D_
_x000D_
let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
_x000D_
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
  
  // Just add position relative;
  position: relative;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
_x000D_
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>
_x000D_
_x000D_
_x000D_

Sandbox here

What is the difference between Step Into and Step Over in a debugger

When debugging lines of code, here are the usual scenarios:

  • (Step Into) A method is about to be invoked, and you want to debug into the code of that method, so the next step is to go into that method and continue debugging step-by-step.
  • (Step Over) A method is about to be invoked, but you're not interested in debugging this particular invocation, so you want the debugger to execute that method completely as one entire step.
  • (Step Return) You're done debugging this method step-by-step, and you just want the debugger to run the entire method until it returns as one entire step.
  • (Resume) You want the debugger to resume "normal" execution instead of step-by-step
  • (Line Breakpoint) You don't care how it got there, but if execution reaches a particular line of code, you want the debugger to temporarily pause execution there so you can decide what to do.

Eclipse has other advanced debugging features, but these are the basic fundamentals.

See also

Rules for C++ string literals escape character

With the magic of user-defined literals, we have yet another solution to this. C++14 added a std::string literal operator.

using namespace std::string_literals;
auto const x = "\0" "0"s;

Constructs a string of length 2, with a '\0' character (null) followed by a '0' character (the digit zero). I am not sure if it is more or less clear than the initializer_list<char> constructor approach, but it at least gets rid of the ' and , characters.

Java 8 method references: provide a Supplier capable of supplying a parameterized result

optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));

Printing string variable in Java

You are printing the wrong value. Instead if the string you print the scanners object. Try this

Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);

How to Pass Parameters to Activator.CreateInstance<T>()

Yes.

(T)Activator.CreateInstance(typeof(T), param1, param2);

Jenkins CI: How to trigger builds on SVN commit

I made a tool using Python with some bash to trigger a Jenkins build. Basically you have to collect these two values from post-commit when a commit hits the SVN server:

REPOS="$1"
REV="$2"

Then you use "svnlook dirs-changed $1 -r $2" to get the path which is has just committed. Then from that you can check which repository you want to build. Imagine you have hundred of thousand of projects. You can't check the whole repository, right?

You can check out my script from GitHub.

Center fixed div with dynamic width (CSS)

You can center a fixed or absolute positioned element setting right and left to 0, and then margin-left & margin-right to auto as if you were centering a static positioned element.

#example {
    position: fixed;
    /* center the element */
    right: 0;
    left: 0;
    margin-right: auto;
    margin-left: auto;
    /* give it dimensions */
    min-height: 10em;
    width: 90%;
}

See this example working on this fiddle.

Error: "setFile(null,false) call failed" when using log4j

this error is coming because of appender file location you have provided is not reachable with current user access.

Quick Solution, change the log4j.appender.FILE.File setting to point to file using absolute path which location is reachable to the current user you have logged in, for example /tmp/myapp.log. Now You should not get an error.

Object of class mysqli_result could not be converted to string in

The mysqli_query() method returns an object resource to your $result variable, not a string.

You need to loop it up and then access the records. You just can't directly use it as your $result variable.

while ($row = $result->fetch_assoc()) {
    echo $row['classtype']."<br>";
}

A better way to check if a path exists or not in PowerShell

Another option is to use IO.FileInfo which gives you so much file info it make life easier just using this type:

PS > mkdir C:\Temp
PS > dir C:\Temp\
PS > [IO.FileInfo] $foo = 'C:\Temp\foo.txt'
PS > $foo.Exists
False
PS > New-TemporaryFile | Move-Item -Destination C:\Temp\foo.txt
PS > $foo.Refresh()
PS > $foo.Exists
True
PS > $foo | Select-Object *


Mode              : -a----
VersionInfo       : File:             C:\Temp\foo.txt
                    InternalName:
                    OriginalFilename:
                    FileVersion:
                    FileDescription:
                    Product:
                    ProductVersion:
                    Debug:            False
                    Patched:          False
                    PreRelease:       False
                    PrivateBuild:     False
                    SpecialBuild:     False
                    Language:

BaseName          : foo
Target            : {}
LinkType          :
Length            : 0
DirectoryName     : C:\Temp
Directory         : C:\Temp
IsReadOnly        : False
FullName          : C:\Temp\foo.txt
Extension         : .txt
Name              : foo.txt
Exists            : True
CreationTime      : 2/27/2019 8:57:33 AM
CreationTimeUtc   : 2/27/2019 1:57:33 PM
LastAccessTime    : 2/27/2019 8:57:33 AM
LastAccessTimeUtc : 2/27/2019 1:57:33 PM
LastWriteTime     : 2/27/2019 8:57:33 AM
LastWriteTimeUtc  : 2/27/2019 1:57:33 PM
Attributes        : Archive

More details on my blog.

UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

frame.origin = center - bounds.size / 2

(which is the same as)

center = frame.origin + bounds.size / 2

(and there’s also)

frame.size = bounds.size

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

http://clipboardjs.com does this and quite well. Although your expectation of the copied version being exactly as in the original so you can play and learn with it, may not be realistic.

Adding System.Web.Script reference in class library

The ScriptIgnoreAttribute class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.

You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.

Use Ant for running program with command line arguments

If you do not want to handle separate properties for each possible argument, I suggest you'd use:

<arg line="${args}"/>

You can check if the property is not set using a specific target with an unless attribute and inside do:

<input message="Type the desired command line arguments:" addProperty="args"/>

Putting it all together gives:

<target name="run" depends="compile, input-runargs" description="run the project">
  <!-- You can use exec here, depending on your needs -->
  <java classname="Main">
    <arg line="${args}"/>
  </java>
</target>
<target name="input-runargs" unless="args" description="prompts for command line arguments if necessary">
  <input addProperty="args" message="Type the desired command line arguments:"/>
</target>

You can use it as follows:

ant
ant run
ant run -Dargs='--help'

The first two commands will prompt for the command-line arguments, whereas the latter won't.

How can I add the new "Floating Action Button" between two widgets/layouts

Seems like the cleanest way in this example is to:

  • Use a RelativeLayout
  • Position the 2 adjacent views one below the other
  • Align the FAB to the parent right/end and add a right/end margin
  • Align the FAB to the bottom of the header view and add a negative margin, half the size of the FAB including shadow

Example adapted from shamanland implementation, use whatever FAB you wish. Assume FAB is 64dp high including shadow:

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

    <View
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="120dp"
    />

    <View
        android:id="@+id/body"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/header"
    />

    <fully.qualified.name.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignBottom="@id/header"
        android:layout_marginBottom="-32dp"
        android:layout_marginRight="20dp"
    />

</RelativeLayout>

FAB Layout example

How to parse freeform street/postal address out of text, and into components

I'm late to the party, here is an Excel VBA script I wrote years ago for Australia. It can be easily modified to support other Countries. I've made a GitHub repository of the C# code here. I've hosted it on my site and you can download it here: http://jeremythompson.net/rocks/ParseAddress.xlsm

Strategy

For any country with a PostCode that's numeric or can be matched with a RegEx my strategy works very well:

  1. First we detect the First and Surname which are assumed to be the top line. Its easy to skip the name and start with the address by unticking the checkbox (called 'Name is top row' as shown below).

  2. Next its safe to expect the Address consisting of the Street and Number come before the Suburb and the St, Pde, Ave, Av, Rd, Cres, loop, etc is a separator.

  3. Detecting the Suburb vs the State and even Country can trick the most sophisticated parsers as there can be conflicts. To overcome this I use a PostCode look up based on the fact that after stripping Street and Apartment/Unit numbers as well as the PoBox,Ph,Fax,Mobile etc, only the PostCode number will remain. This is easy to match with a regEx to then look up the suburb(s) and country.

Your National Post Office Service will provide a list of post codes with Suburbs and States free of charge that you can store in an excel sheet, db table, text/json/xml file, etc.

  1. Finally, since some Post Codes have multiple Suburbs we check which suburb appears in the Address.

Example

enter image description here

VBA Code

DISCLAIMER, I know this code is not perfect, or even written well however its very easy to convert to any programming language and run in any type of application.The strategy is the answer depending on your country and rules, take this code as an example:

Option Explicit

Private Const TopRow As Integer = 0

Public Sub ParseAddress()
Dim strArr() As String
Dim sigRow() As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim Stat As String
Dim SpaceInName As Integer
Dim Temp As String
Dim PhExt As String

On Error Resume Next

Temp = ActiveSheet.Range("Address")

'Split info into array
strArr = Split(Temp, vbLf)

'Trim the array
For i = 0 To UBound(strArr)
strArr(i) = VBA.Trim(strArr(i))
Next i

'Remove empty items/rows    
ReDim sigRow(LBound(strArr) To UBound(strArr))
For i = LBound(strArr) To UBound(strArr)
    If Trim(strArr(i)) <> "" Then
        sigRow(j) = strArr(i)
        j = j + 1
    End If
Next i
ReDim Preserve sigRow(LBound(strArr) To j)

'Find the name (MUST BE ON THE FIRST ROW UNLESS CHECKBOX UNTICKED)
i = TopRow
If ActiveSheet.Shapes("chkFirst").ControlFormat.Value = 1 Then

SpaceInName = InStr(1, sigRow(i), " ", vbTextCompare) - 1

If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("FirstName") = VBA.Left(sigRow(i), SpaceInName)
Else
 If MsgBox("First Name: " & VBA.Mid$(sigRow(i), 1, SpaceInName), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("FirstName") = VBA.Left(sigRow(i), SpaceInName)
End If

If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Surname") = VBA.Mid(sigRow(i), SpaceInName + 2)
Else
  If MsgBox("Surame: " & VBA.Mid(sigRow(i), SpaceInName + 2), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Surname") = VBA.Mid(sigRow(i), SpaceInName + 2)
End If
sigRow(i) = ""
End If

'Find the Street by looking for a "St, Pde, Ave, Av, Rd, Cres, loop, etc"
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
    For j = 0 To 8
    If InStr(1, VBA.UCase(sigRow(i)), Street(j), vbTextCompare) > 0 Then

    'Find the position of the street in order to get the suburb
    SpaceInName = InStr(1, VBA.UCase(sigRow(i)), Street(j), vbTextCompare) + Len(Street(j)) - 1

    'If its a po box then add 5 chars
    If VBA.Right(Street(j), 3) = "BOX" Then SpaceInName = SpaceInName + 5

    If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
    ActiveSheet.Range("Street") = VBA.Mid(sigRow(i), 1, SpaceInName)
    Else
      If MsgBox("Street Address: " & VBA.Mid(sigRow(i), 1, SpaceInName), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Street") = VBA.Mid(sigRow(i), 1, SpaceInName)
    End If
    'Trim the Street, Number leaving the Suburb if its exists on the same line
    sigRow(i) = VBA.Mid(sigRow(i), SpaceInName) + 2
    sigRow(i) = Replace(sigRow(i), VBA.Mid(sigRow(i), 1, SpaceInName), "")

    GoTo PastAddress:
    End If
    Next j
End If
Next i
PastAddress:

'Mobile
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
    For j = 0 To 3
    Temp = Mb(j)
        If VBA.Left(VBA.UCase(sigRow(i)), Len(Temp)) = Temp Then
        If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
        ActiveSheet.Range("Mobile") = VBA.Mid(sigRow(i), Len(Temp) + 2)
        Else
          If MsgBox("Mobile: " & VBA.Mid(sigRow(i), Len(Temp) + 2), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Mobile") = VBA.Mid(sigRow(i), Len(Temp) + 2)
        End If
    sigRow(i) = ""
    GoTo PastMobile:
    End If
    Next j
End If
Next i
PastMobile:

'Phone
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
    For j = 0 To 1
    Temp = Ph(j)
        If VBA.Left(VBA.UCase(sigRow(i)), Len(Temp)) = Temp Then

            'TODO: Detect the intl or national extension here.. or if we can from the postcode.
            If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
            ActiveSheet.Range("Phone") = VBA.Mid(sigRow(i), Len(Temp) + 3)
            Else
              If MsgBox("Phone: " & VBA.Mid(sigRow(i), Len(Temp) + 3), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Phone") = VBA.Mid(sigRow(i), Len(Temp) + 3)
            End If

        sigRow(i) = ""
        GoTo PastPhone:
        End If
    Next j
End If
Next i
PastPhone:


'Email
For i = 1 To UBound(sigRow)
    If Len(sigRow(i)) > 0 Then
        'replace with regEx search
        If InStr(1, sigRow(i), "@", vbTextCompare) And InStr(1, VBA.UCase(sigRow(i)), ".CO", vbTextCompare) Then
        Dim email As String
        email = sigRow(i)
        email = Replace(VBA.UCase(email), "EMAIL:", "")
        email = Replace(VBA.UCase(email), "E-MAIL:", "")
        email = Replace(VBA.UCase(email), "E:", "")
        email = Replace(VBA.UCase(Trim(email)), "E ", "")
        email = VBA.LCase(email)

            If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
            ActiveSheet.Range("Email") = email
            Else
              If MsgBox("Email: " & email, vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Email") = email
            End If
        sigRow(i) = ""
        Exit For
        End If
    End If
Next i

'Now the only remaining items will be the postcode, suburb, country
'there shouldn't be any numbers (eg. from PoBox,Ph,Fax,Mobile) except for the Post Code

'Join the string and filter out the Post Code
Temp = Join(sigRow, vbCrLf)
Temp = Trim(Temp)

For i = 1 To Len(Temp)

Dim postCode As String
postCode = VBA.Mid(Temp, i, 4)

'In Australia PostCodes are 4 digits
If VBA.Mid(Temp, i, 1) <> " " And IsNumeric(postCode) Then

    If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
    ActiveSheet.Range("PostCode") = postCode
    Else
      If MsgBox("Post Code: " & postCode, vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("PostCode") = postCode
    End If

    'Lookup the Suburb and State based on the PostCode, the PostCode sheet has the lookup
    Dim mySuburbArray As Range
    Set mySuburbArray = Sheets("PostCodes").Range("A2:B16670")

    Dim suburbs As String
    For j = 1 To mySuburbArray.Columns(1).Cells.Count
    If mySuburbArray.Cells(j, 1) = postCode Then
        'Check if the suburb is listed in the address
        If InStr(1, UCase(Temp), mySuburbArray.Cells(j, 2), vbTextCompare) > 0 Then

        'Set the Suburb and State
        ActiveSheet.Range("Suburb") = mySuburbArray.Cells(j, 2)
        Stat = mySuburbArray.Cells(j, 3)
        ActiveSheet.Range("State") = Stat

        'Knowing the State - for Australia we can get the telephone Ext
        PhExt = PhExtension(VBA.UCase(Stat))
        ActiveSheet.Range("PhExt") = PhExt

        'remove the phone extension from the number
        Dim prePhone As String
        prePhone = ActiveSheet.Range("Phone")
        prePhone = Replace(prePhone, PhExt & " ", "")
        prePhone = Replace(prePhone, "(" & PhExt & ") ", "")
        prePhone = Replace(prePhone, "(" & PhExt & ")", "")
        ActiveSheet.Range("Phone") = prePhone
        Exit For
        End If
    End If
    Next j
Exit For
End If
Next i

End Sub


Private Function PhExtension(ByVal State As String) As String
Select Case State
Case Is = "NSW"
PhExtension = "02"
Case Is = "QLD"
PhExtension = "07"
Case Is = "VIC"
PhExtension = "03"
Case Is = "NT"
PhExtension = "04"
Case Is = "WA"
PhExtension = "05"
Case Is = "SA"
PhExtension = "07"
Case Is = "TAS"
PhExtension = "06"
End Select
End Function

Private Function Ph(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Ph = "PH"
Case Is = 1
Ph = "PHONE"
'Case Is = 2
'Ph = "P"
End Select
End Function

Private Function Mb(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Mb = "MB"
Case Is = 1
Mb = "MOB"
Case Is = 2
Mb = "CELL"
Case Is = 3
Mb = "MOBILE"
'Case Is = 4
'Mb = "M"
End Select
End Function

Private Function Fax(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Fax = "FAX"
Case Is = 1
Fax = "FACSIMILE"
'Case Is = 2
'Fax = "F"
End Select
End Function

Private Function State(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
State = "NSW"
Case Is = 1
State = "QLD"
Case Is = 2
State = "VIC"
Case Is = 3
State = "NT"
Case Is = 4
State = "WA"
Case Is = 5
State = "SA"
Case Is = 6
State = "TAS"
End Select
End Function

Private Function Street(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Street = " ST"
Case Is = 1
Street = " RD"
Case Is = 2
Street = " AVE"
Case Is = 3
Street = " AV"
Case Is = 4
Street = " CRES"
Case Is = 5
Street = " LOOP"
Case Is = 6
Street = "PO BOX"
Case Is = 7
Street = " STREET"
Case Is = 8
Street = " ROAD"
Case Is = 9
Street = " AVENUE"
Case Is = 10
Street = " CRESENT"
Case Is = 11
Street = " PARADE"
Case Is = 12
Street = " PDE"
Case Is = 13
Street = " LANE"
Case Is = 14
Street = " COURT"
Case Is = 15
Street = " BLVD"
Case Is = 16
Street = "P.O. BOX"
Case Is = 17
Street = "P.O BOX"
Case Is = 18
Street = "PO BOX"
Case Is = 19
Street = "POBOX"
End Select
End Function

How to cancel a local git commit

Use below command:

$ git reset HEAD~1

After this you also able to view files what revert back like below response.

Unstaged changes after reset:
M   application/config/config.php
M   application/config/database.php

how can get index & count in vuejs

you can just add 1

<li v-for="(catalog, itemObjKey) in catalogs">this index : {{itemObjKey + 1}}</li>

to get the length of an array/objects

{{ catalogs.length }}

How to make Java work with SQL Server?

I had the same problem with a client of my company, the problem was that the driver sqljdbc4.jar, tries a convertion of character between the database and the driver. Each time that it did a request to the database, now you can imagine 650 connections concurrently, this did my sistem very very slow, for avoid this situation i add at the String of connection the following parameter:

 SendStringParametersAsUnicode=false, then te connection must be something like url="jdbc:sqlserver://IP:PORT;DatabaseName=DBNAME;SendStringParametersAsUnicode=false"

After that, the system is very very fast, as the users are very happy with the change, i hope my input be of same.

ISO C90 forbids mixed declarations and code in C

Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99.

Scala vs. Groovy vs. Clojure

I never had time to play with clojure. But for scala vs groovy, this is words from James Strachan - Groovy creator

"Though my tip though for the long term replacement of javac is Scala. I'm very impressed with it! I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy."

You can read the whole story here

Create a pointer to two-dimensional array

You can always avoid fiddling around with the compiler by declaring the array as linear and doing the (row,col) to array index calculation by yourself.

static uint8_t l_matrix[200];

void test(int row, int col, uint8_t val)

{

   uint8_t* matrix_ptr = l_matrix;
   matrix_ptr [col+y*row] = val; // to assign a value

}

this is what the compiler would have done anyway.

How do I perform a JAVA callback between classes?

Define an interface, and implement it in the class that will receive the callback.

Have attention to the multi-threading in your case.

Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html

interface CallBack {                   //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
    void methodToCallBack();
}

class CallBackImpl implements CallBack {          //class that implements the method to callback defined in the interface
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();       //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
        caller.register(callBack);
    }
} 

In your case, apart from multi-threading you could do like this:

interface ServerInterface {
    void newSeverConnection(Socket socket);
}

public class Server implements ServerInterface {

    public Server(int _address) {
        System.out.println("Starting Server...");
        serverConnectionHandler = new ServerConnections(_address, this);
        workers.execute(serverConnectionHandler);
        System.out.println("Do something else...");
    }

    void newServerConnection(Socket socket) {
        System.out.println("A function of my child class was called.");
    }

}

public class ServerConnections implements Runnable {

    private ServerInterface serverInterface;

    public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
      serverPort = _serverPort;
      serverInterface = _serverInterface;
    }

    @Override
    public void run() {
        System.out.println("Starting Server Thread...");

        if (serverInterface == null) {
            System.out.println("Server Thread error: callback null");
        }

        try {
            mainSocket = new ServerSocket(serverPort);

            while (true) {
                serverInterface.newServerConnection(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Multi-threading

Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.

The observer-pattern

The observer-pattern does nearly this, the major difference is the use of an ArrayList for adding more than one listener. Where this is not needed, you get better performance with one reference.

Why there is no ConcurrentHashSet against ConcurrentHashMap

Set<String> mySet = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());

Laravel 5: Display HTML with Blade

You can use {!! $text !!} for render HTML code in Laravel

{!! $text !!}

If you use

{{ $text }}

It will not render HTML code and print as a string.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

If issue remains even after updating dependency version, then delete everything present under
C:\Users\[your_username]\.m2\repository\com\fasterxml

And, make sure following dependencies are present:

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson.version}</version>
            </dependency>

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>${jackson.version}</version>
            </dependency>

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>${jackson.version}</version>
            </dependency>

Redeploy alternatives to JRebel

Take a look at DCEVM, it's a modification of the HotSpot VM that allows unlimited class redefinitions at runtime. You can add/remove fields and methods and change the super types of a class at runtime.

The binaries available on the original site are limited to Java 6u25 and to early versions of Java 7. The project has been forked on Github and supports recent versions of Java 7 and 8. The maintainer provides binaries for 32/64 bits VMs on Windows/Linux. Starting with Java 11 the project moved to a new GitHub repository and now also provides binaries for OS X.

DCEVM is packaged for Debian and Ubuntu, it's conveniently integrated with OpenJDK and can be invoked with java -dcevm. The name of the package depends on the version of the default JDK:

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

swap may not be the red herring previously suggested. How big is the python process in question just before the ENOMEM?

Under kernel 2.6, /proc/sys/vm/swappiness controls how aggressively the kernel will turn to swap, and overcommit* files how much and how precisely the kernel may apportion memory with a wink and a nod. Like your facebook relationship status, it's complicated.

...but swap is actually available on demand (according to the web host)...

but not according to the output of your free(1) command, which shows no swap space recognized by your server instance. Now, your web host may certainly know much more than I about this topic, but virtual RHEL/CentOS systems I've used have reported swap available to the guest OS.

Adapting Red Hat KB Article 15252:

A Red Hat Enterprise Linux 5 system will run just fine with no swap space at all as long as the sum of anonymous memory and system V shared memory is less than about 3/4 the amount of RAM. .... Systems with 4GB of ram or less [are recommended to have] a minimum of 2GB of swap space.

Compare your /proc/sys/vm settings to a plain CentOS 5.3 installation. Add a swap file. Ratchet down swappiness and see if you live any longer.

What causing this "Invalid length for a Base-64 char array"

I've seen this error caused by the combination of good sized viewstate and over aggressive content-filtering devices/firewalls (especially when dealing with K-12 Educational institutions).

We worked around it by storing Viewstate in SQL Server. Before going that route, I would recommend trying to limit your use of viewstate by not storing anything large in it and turning it off for all controls which do not need it.

References for storing ViewState in SQL Server:
MSDN - Overview of PageStatePersister
ASP Alliance - Simple method to store viewstate in SQL Server
Code Project - ViewState Provider Model

Any reason not to use '+' to concatenate two strings?

I use the following with python 3.8

string4 = f'{string1}{string2}{string3}'

Android: Access child views from a ListView

int position = 0;
listview.setItemChecked(position, true);
View wantedView = adapter.getView(position, null, listview);

#pragma mark in Swift?

Professional programer must be use this tag for good code. It is also good for team work.

// MARK: example Web Service start here
// TODO: example 1
// FIXME: Please change BASE url before live 

It is easy to find method like this

It is easy to find method like this

How to convert array to SimpleXML

function toXML($data, $obj = false, $dom) {
    $is_first_level = false;
    if($obj === false) {
        $dom = new DomDocument('1.0');
        $obj = $dom;
        $is_first_level = true;
    }

    if(is_array($data)) {
        foreach($data as $key => $item) {
            $this->toXML($item, $obj->appendChild($dom->createElement($key)), $dom);
        }
    }else {
        $obj->appendChild($dom->createTextNode($data));
    }

    if($is_first_level) {
        $obj->formatOutput = true;
        return $obj->saveXML();
    }
    return $obj;
}

Space between two rows in a table?

You can fill the <td/> elements with <div/> elements, and apply any margin to those divs that you like. For a visual space between the rows, you can use a repeating background image on the <tr/> element. (This was the solution I just used today, and it appears to work in both IE6 and FireFox 3, though I didn't test it any further.)

Also, if you're averse to modifying your server code to put <div/>s inside the <td/>s, you can use jQuery (or something similar) to dynamically wrap the <td/> contents in a <div/>, enabling you to apply the CSS as desired.

MySQL select where column is not empty

We can use CASE for setting blank value to some char or String. I am using NA as Default string.

SELECT phone,   
CASE WHEN phone2 = '' THEN 'NA' END AS phone2 ELSE ISNULL(phone2,0) 
FROM jewishyellow.users  WHERE phone LIKE '813%'

Get a list of checked checkboxes in a div using jQuery

I needed the count of all checkboxes which are checked. Instead of writing a loop i did this

$(".myCheckBoxClass:checked").length;

Compare it with the total number of checkboxes to see if they are equal. Hope it will help someone

How can I find the number of years between two dates?

import java.util.Calendar;
import java.util.Locale;
import static java.util.Calendar.*;
import java.util.Date;

public static int getDiffYears(Date first, Date last) {
    Calendar a = getCalendar(first);
    Calendar b = getCalendar(last);
    int diff = b.get(YEAR) - a.get(YEAR);
    if (a.get(MONTH) > b.get(MONTH) || 
        (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
        diff--;
    }
    return diff;
}

public static Calendar getCalendar(Date date) {
    Calendar cal = Calendar.getInstance(Locale.US);
    cal.setTime(date);
    return cal;
}

Is it possible to run one logrotate check manually?

Yes: logrotate --force $CONFIG_FILE

Fastest way(s) to move the cursor on a terminal command line?

Use Meta-b / Meta-f to move backward/forward by a word respectively.

In OSX, Meta translates as ESC, which sucks.

But alternatively, you can open terminal preferences -> settings -> profile -> keyboard and check "use option as meta key"

Create list of single item repeated N times

Itertools has a function just for that:

import itertools
it = itertools.repeat(e,n)

Of course itertools gives you a iterator instead of a list. [e] * n gives you a list, but, depending on what you will do with those sequences, the itertools variant can be much more efficient.

Disable asp.net button after click to prevent double clicking

I like to disable the button and call a postback, this way the code behind still gets run after the button is disabled.

this is how i attach from code behind:

btnProcess.Attributes.Add("onclick", " this.disabled = true; __doPostBack('btnProcess', ''); return false;")

Then re-enable the button in code behind:

btnProcess.Enabled = True

"SMTP Error: Could not authenticate" in PHPMailer

I had the same problem with authentication. The fix was to set up 2-step verification and create an application specific password for the device ( error messages for blocking the device will appear in your account settings->"Notifications and alerts" if you problem is the same with mine)

How to replace an entire line in a text file by line number

in bash, replace N,M by the line numbers and xxx yyy by what you want

i=1
while read line;do
  if((i==N));then
    echo 'xxx'
  elif((i==M));then
    echo 'yyy'
  else
    echo "$line"
  fi
  ((i++))
done  < orig-file > new-file

EDIT

In fact in this solution there are some problems, with characters "\0" "\t" and "\"

"\t", can be solve by putting IFS= before read: "\", at end of line with -r

IFS= read -r line

but for "\0", the variable is truncated, there is no a solution in pure bash : Assign string containing null-character (\0) to a variable in Bash But in normal text file there is no nul character \0

perl would be a better choice

perl -ne 'if($.==N){print"xxx\n"}elsif($.==M){print"yyy\n"}else{print}' < orig-file > new-file

Center content in responsive bootstrap navbar

Use following html

<link rel="stylesheet" href="app/components/directives/navBar/navBar.scss"/>
<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
        <!-- Collect the nav links, forms, and other content for toggling -->
            <ul class="nav navbar-nav">
                <li><h5><a href="#/">Home</a></h5></li>
                <li>|</li>
                <li><h5><a href="#products">About</a></h5></li>
                <li>|</li>
                <li><h5><a href="#">Contacts</a></h5></li>
                <li>|</li>
                <li><h5><a href="#cart">Cart</a></h5></li>
            </ul>
    </div><!-- /.container-fluid -->
</nav>

And css

.navbar-nav {
  width: 100%;
  text-align: center;
}
.navbar-nav > li {
  float: none;
  display: inline-block;
}
.navbar-default {
  background-color: white;
  border-color: white;
}
.navbar-default .navbar-nav>.active>a, .navbar-default .navbar-nav>.active>a:hover, .navbar-default .navbar-nav>.active>a:focus{
  background-color:white;
}

Modify according to your needs

Creating a range of dates in Python

import datetime    
def date_generator():
    cur = base = datetime.date.today()
    end  = base + datetime.timedelta(days=100)
    delta = datetime.timedelta(days=1)
    while(end>base):
        base = base+delta
        print base

date_generator()

Chart.js - Formatting Y axis

Chart.js 2.X.X

I know this post is old. But if anyone is looking for more flexible solution, here it is

var options = {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    callback: function(label, index, labels) {
                        return Intl.NumberFormat().format(label);
                        // 1,350

                        return Intl.NumberFormat('hi', { 
                            style: 'currency', currency: 'INR', minimumFractionDigits: 0, 
                        }).format(label).replace(/^(\D+)/, '$1 ');
                        // ? 1,350

                        // return Intl.NumberFormat('hi', {
                            style: 'currency', currency: 'INR', currencyDisplay: 'symbol', minimumFractionDigits: 2 
                        }).format(label).replace(/^(\D+)/, '$1 ');
                        // ? 1,350.00
                    }
                }
            }]
        }
    }

'hi' is Hindi. Check here for other locales argument
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation#locales_argument

for more currency symbol
https://www.currency-iso.org/en/home/tables/table-a1.html

Send Email to multiple Recipients with MailMessage?

According to the Documentation :

MailMessage.To property - Returns MailAddressCollection that contains the list of recipients of this email message

Here MailAddressCollection has a in built method called

   public void Add(string addresses)

   1. Summary:
          Add a list of email addresses to the collection.

   2. Parameters:
          addresses: 
                *The email addresses to add to the System.Net.Mail.MailAddressCollection. Multiple
                *email addresses must be separated with a comma character (",").     

Therefore requirement in case of multiple recipients : Pass a string that contains email addresses separated by comma

In your case :

simply replace all the ; with ,

Msg.To.Add(toEmail.replace(";", ","));

For reference :

  1. https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage?view=netframework-4.8
  2. https://www.geeksforgeeks.org/c-sharp-replace-method/

How to completely uninstall python 2.7.13 on Ubuntu 16.04

How I do:

# Remove python2
sudo apt purge -y python2.7-minimal

# You already have Python3 but 
# don't care about the version 
sudo ln -s /usr/bin/python3 /usr/bin/python

# Same for pip
sudo apt install -y python3-pip
sudo ln -s /usr/bin/pip3 /usr/bin/pip

# Confirm the new version of Python: 3
python --version

Difference between arguments and parameters in Java

They are not. They're exactly the same.

However, some people say that parameters are placeholders in method signatures:

public void doMethod(String s, int i) {
  ..
}

String s and int i are sometimes said to be parameters. The arguments are the actual values/references:

myClassReference.doMethod("someString", 25);

"someString" and 25 are sometimes said to be the arguments.

VBA Check if variable is empty

For a number, it is tricky because if a numeric cell is empty VBA will assign a default value of 0 to it, so it is hard for your VBA code to tell the difference between an entered zero and a blank numeric cell.

The following check worked for me to see if there was an actual 0 entered into the cell:

If CStr(rng.value) = "0" then
    'your code here'
End If

How to copy a folder via cmd?

xcopy  e:\source_folder f:\destination_folder /e /i /h

The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.

Add property to an array of objects

With ES6 you can simply do:

 for(const element of Results) {
      element.Active = "false";
 }

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

On windows, use https://github.com/Zapotek/raw2vmdk to convert raw files created by dd or winhex to vmdk. raw2vmdk v0.1.3.2 has a bug - once the vmdk file is created, edit the vmdk file and fix the path to the raw file (in my case instead of D:\Temp\flash_16gb.raw (created by winhex) the generated path was D:Tempflash_16gb.raw). Then, open it in a vmware virtual machine version 6.5-7 (5.1 was refusing to attach the vmdk harddrive). howgh!

Unsupported Media Type in postman

Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.

With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.

How to make sure you don't get WCF Faulted state exception?

This error can also be caused by having zero methods tagged with the OperationContract attribute. This was my problem when building a new service and testing it a long the way.

How to access List elements

It's simple

y = [['vegas','London'],['US','UK']]

for x in y:
    for a in x:
        print(a)

How to increment an iterator by 2?

std::advance( iter, 2 );

This method will work for iterators that are not random-access iterators but it can still be specialized by the implementation to be no less efficient than iter += 2 when used with random-access iterators.

Project Links do not work on Wamp Server

You can follow all steps by @RiggsFolly thats is really good answer, If you do not want to create virtual host and want to use like previous localhost/example/ or something like that you can use answer by @Arunu

But if you still face problem please use this method,

  1. Locate your wamp folder (Eg. c:/Wamp/) where you have installed
  2. Goto Wamp/www/
  3. Open index.php file
  4. find this code $projectContents .= '<li><a href="'.($suppress_localhost ? 'http://' : '').$file.'">'.$file.'</a></li>';
  5. modify it add localhost after http:// $projectContents .= '<li><a href="'.($suppress_localhost ? 'http://localhost' : '').$file.'">'.$file.'</a></li>';
  6. Restart wamp server
  7. open localhost see the updated links

Hope you got your url like previous version of wamp server.

How do I make a newline after a twitter bootstrap element?

May be the solution could be use a padding property.

<div class="well span6" style="padding-top: 50px">
    <h3>I wish this appeared on the next line without having to 
        gratuitously use BR!
    </h3>
</div>

Bootstrap how to get text to vertical align in a div container

h2.text-left{
  position:relative;
  top:50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Explanation:

The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.

Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.

A possible fix for multiple lines would be to use a percentage slightly less than 50%.

How to embed small icon in UILabel

Swift 4.2:

let attachment = NSTextAttachment()        
attachment.image = UIImage(named: "yourIcon.png")
let attachmentString = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: price)
myString.append(attachmentString)
label.attributedText = myString

passing several arguments to FUN of lapply (and others *apply)

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

Center the content inside a column in Bootstrap 4

Add class text-center to your column:

<div class="col text-center">
I am centered
</div>

Having a UITextField in a UITableViewCell

I had been avoiding this by calling a method to run [cell.contentView bringSubviewToFront:textField] every time my cells appeared, but then I discovered this relatively simple technique:

cell.accessoryView = textField;

Doesn't seem to have the same background-overpasting issue, and it aligns itself on its own (somewhat). Also, the textLabel auto-truncates to avoid overflowing into (or under) it, which is handy.

How do I use PHP to get the current year?

use a PHP date() function.

and the format is just going to be Y. Capital Y is going to be a four digit year.

<?php echo date("Y"); ?>

How to get ER model of database from server with Workbench

I want to enhance Mr. Kamran Ali's answer with pictorial view.

Pictorial View is given step by step:

  1. Go to "Database" Menu option
  2. Select the "Reverse Engineer" option.

enter image description here

  1. A wizard will come. Select from "Stored Connection" and press "Next" button.

enter image description here

  1. Then "Next"..to.."Finish"

Enjoy :)

How to unload a package without restarting R

You can uncheck the checkbox button in RStudio (packages).

RStudio packages pane

How to use Jackson to deserialise an array of objects

I was unable to use this answer because my linter won't allow unchecked casts.

Here is an alternative you can use. I feel it is actually a cleaner solution.

public <T> List<T> parseJsonArray(String json, Class<T> clazz) throws JsonProcessingException {
  var tree = objectMapper.readTree(json);
  var list = new ArrayList<T>();
  for (JsonNode jsonNode : tree) {
    list.add(objectMapper.treeToValue(jsonNode, clazz));
  }
  return list;
}

How do I prevent a Gateway Timeout with FastCGI on Nginx

Proxy timeouts are well, for proxies, not for FastCGI...

The directives that affect FastCGI timeouts are client_header_timeout, client_body_timeout and send_timeout.

Edit: Considering what's found on nginx wiki, the send_timeout directive is responsible for setting general timeout of response (which was bit misleading). For FastCGI there's fastcgi_read_timeout which is affecting the fastcgi process response timeout.

HTH.

Find commit by hash SHA in Git

There are two ways to do this.

1. providing the SHA of the commit you want to see to git log

git log -p a2c25061

Where -p is short for patch

2. use git show

git show a2c25061

The output for both commands will be:

  • the commit
  • the author
  • the date
  • the commit message
  • the patch information

How do you build a Singleton in Dart?

Here is a comparison of several different ways to create a singleton in Dart.

1. Factory constructor

class SingletonOne {

  SingletonOne._privateConstructor();

  static final SingletonOne _instance = SingletonOne._privateConstructor();

  factory SingletonOne() {
    return _instance;
  }

}

2. Static field with getter

class SingletonTwo {

  SingletonTwo._privateConstructor();

  static final SingletonTwo _instance = SingletonTwo._privateConstructor();

  static SingletonTwo get instance => _instance;
  
}

3. Static field

class SingletonThree {

  SingletonThree._privateConstructor();

  static final SingletonThree instance = SingletonThree._privateConstructor();
  
}

How to instantiate

The above singletons are instantiated like this:

SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;

Note:

I originally asked this as a question, but discovered that all of the methods above are valid and the choice largely depends on personal preference.

PostgreSQL error 'Could not connect to server: No such file or directory'

This worked for me for the error you mentioned. Do one of these:

  1. Possibly change your default port specified in the postgres.conf file, if you have used something other than the default port 5432 while installing.

  2. Change the port number in postgresql.conf and restart the DB server.

  3. Instead of psql type the full command:

    psql -p 5432 -h localhost   
    
    • server name and the port no

How to deal with SQL column names that look like SQL keywords?

While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).

SELECT [from] AS TransferFrom -- Or something else more suitable
FROM TableName

error : expected unqualified-id before return in c++

Just for the sake of people who landed here for the same reason I did:

Don't use reserved keywords

I named a function in my class definition delete(), which is a reserved keyword and should not be used as a function name. Renaming it to deletion() (which also made sense semantically in my case) resolved the issue.

For a list of reserved keywords: http://en.cppreference.com/w/cpp/keyword

I quote: "Since they are used by the language, these keywords are not available for re-definition or overloading. "

HashMap allows duplicates?

Code example:

HashMap<Integer,String> h = new HashMap<Integer,String> ();

h.put(null,null);
h.put(null, "a");

System.out.println(h);

Output:

{null=a}

It overrides the value at key null.

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

Remove Duplicate objects from JSON Array

var standardsList = [
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Geometry"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Orders of Operation"},
    {"Grade": "Math 2", "Domain": "Geometry"},
    {"Grade": "Math 2", "Domain": "Geometry"}
];          

 function uniqurArray(array){
                         var a = array.concat();
                        for(var i=0; i<a.length; i++) {
                            for(var j=i+1; j<a.length; j++) {
                                if(a[i].Grade === a[j].Grade){
                                    a.splice(j--, 1);
                                }
                            }
                        }

                        return a;
                    }

    uniqurArray(standardsList) // put this js in console and you get uniq object in array

jQuery - Create hidden form element on the fly

$('#myformelement').append('<input type="hidden" name="myfieldname" value="myvalue" />');

Is it possible to convert char[] to char* in C?

Well, I'm not sure to understand your question...

In C, Char[] and Char* are the same thing.

Edit : thanks for this interesting link.

Is it possible to modify a registry entry via a .bat/.cmd script?

You can use the REG command. From http://www.ss64.com/nt/reg.html:

Syntax:

   REG QUERY [ROOT\]RegKey /v ValueName [/s]
   REG QUERY [ROOT\]RegKey /ve  --This returns the (default) value

   REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]
   REG ADD [ROOT\]RegKey /ve [/d Data] [/f]  -- Set the (default) value

   REG DELETE [ROOT\]RegKey /v ValueName [/f]
   REG DELETE [ROOT\]RegKey /ve [/f]  -- Remove the (default) value
   REG DELETE [ROOT\]RegKey /va [/f]  -- Delete all values under this key

   REG COPY  [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey

   REG EXPORT [ROOT\]RegKey FileName.reg
   REG IMPORT FileName.reg
   REG SAVE [ROOT\]RegKey FileName.hiv
   REG RESTORE \\MachineName\[ROOT]\KeyName FileName.hiv

   REG LOAD FileName KeyName
   REG UNLOAD KeyName

   REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s]
   REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]

Key:
   ROOT :
         HKLM = HKey_Local_machine (default)
         HKCU = HKey_current_user
         HKU  = HKey_users
         HKCR = HKey_classes_root

   ValueName : The value, under the selected RegKey, to edit.
               (default is all keys and values)

   /d Data   : The actual data to store as a "String", integer etc

   /f        : Force an update without prompting "Value exists, overwrite Y/N"

   \\Machine : Name of remote machine - omitting defaults to current machine.
                Only HKLM and HKU are available on remote machines.

   FileName  : The filename to save or restore a registry hive.

   KeyName   : A key name to load a hive file into. (Creating a new key)

   /S        : Query all subkeys and values.

   /S Separator : Character to use as the separator in REG_MULTI_SZ values
                  the default is "\0" 

   /t DataType  : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ

   Output    : /od (only differences) /os (only matches) /oa (all) /on (no output)

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

In WPF, you can write a fully functional Thumbnail View in a few XAML lines:

<ListBox ItemsSource={Binding MyItems}
         ScrollViewer.HorizontalScrollBarVisibility="Hidden">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Image Source={Binding FullPath} Width="50" />
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate><WrapPanel /></ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

This is, assuming you have a MyItems collection of items that contain a FullPath property that points to image files.

The magic comes from the ItemTemplate that transforms each list box item into an image, and the ItemsPanelTemplate that changes the default vertical stack panel to a wrap panel.

Print "hello world" every X seconds

Use java.util.Timer and Timer#schedule(TimerTask,delay,period) method will help you.

public class RemindTask extends TimerTask {
    public void run() {
      System.out.println(" Hello World!");
    }
    public static void main(String[] args){
       Timer timer = new Timer();
       timer.schedule(new RemindTask(), 3000,3000);
    }
  }

Create Generic method constraining T to an Enum

It should also be considered that since the release of C# 7.3 using Enum constraints is supported out-of-the-box without having to do additional checking and stuff.

So going forward and given you've changed the language version of your project to C# 7.3 the following code is going to work perfectly fine:

    private static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
    {
        // Your code goes here...
    }

In case you're don't know how to change the language version to C# 7.3 see the following screenshot: enter image description here

EDIT 1 - Required Visual Studio Version and considering ReSharper

For Visual Studio to recognize the new syntax you need at least version 15.7. You can find that also mentioned in Microsoft's release notes, see Visual Studio 2017 15.7 Release Notes. Thanks @MohamedElshawaf for pointing out this valid question.

Pls also note that in my case ReSharper 2018.1 as of writing this EDIT does not yet support C# 7.3. Having ReSharper activated it highlights the Enum constraint as an error telling me Cannot use 'System.Array', 'System.Delegate', 'System.Enum', 'System.ValueType', 'object' as type parameter constraint. ReSharper suggests as a quick fix to Remove 'Enum' constraint of type paramter T of method

However, if you turn off ReSharper temporarily under Tools -> Options -> ReSharper Ultimate -> General you'll see that the syntax is perfectly fine given that you use VS 15.7 or higher and C# 7.3 or higher.

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Use the login utility to create a login shell. Assume that the user you want to log in has the username Alice and that zsh is installed in /opt/local/bin/zsh (e.g., a more recent version installed via MacPorts). In iTerm 2, go to Preferences, Profiles, select the profile that you want to set up, and enter in Command:

login -pfq Alice /opt/local/bin/zsh

See man login for more details on the options.

How to change the interval time on bootstrap carousel?

The best way to get rid on it is adding or modifying the data-interval attribute like this:

<div data-ride="carousel" class="carousel slide" data-interval="10000" id="myCarousel">

It's specified on ms like it's usually on js, so 1000 = 1s, 3000 = 3s... 10000 = 10s.

By the way you can also specify it at 0 for not sliding automatically. It's useful when showing product images on mobile for example.

<div data-ride="carousel" class="carousel slide" data-interval="0" id="myCarousel">

Press enter in textbox to and execute button command

    private void textbox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            //cod for run
        }
    }

    private void buttonSearch_Click(object sender, EventArgs e)
    {
        textbox1_KeyDown(sender, new KeyEventArgs(Keys.Enter));
    }

100% Min Height CSS layout

First you should create a div with id='footer' after your content div and then simply do this.

Your HTML should look like this:

<html>
    <body>
        <div id="content">
            ...
        </div>
        <div id="footer"></div>
    </body>
</html>

And the CSS:

?html, body {
    height: 100%;   
}
#content {
    height: 100%;
}
#footer {
    clear: both;        
}

Calling another different view from the controller using ASP.NET MVC 4

You have to specify the name of the custom view and its related model in Controller Action method.

public ActionResult About()
{            
   return View("NameOfViewYouWantToReturn",Model); 
}

How to access property of anonymous type in C#?

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });

ExecuteNonQuery doesn't return results

Could you post the exact query? The ExecuteNonQuery method returns the @@ROWCOUNT Sql Server variable what ever it is after the last query has executed is what the ExecuteNonQuery method returns.

Convert pyspark string to date format

from datetime import datetime
from pyspark.sql.functions import col, udf
from pyspark.sql.types import DateType



# Creation of a dummy dataframe:
df1 = sqlContext.createDataFrame([("11/25/1991","11/24/1991","11/30/1991"), 
                            ("11/25/1391","11/24/1992","11/30/1992")], schema=['first', 'second', 'third'])

# Setting an user define function:
# This function converts the string cell into a date:
func =  udf (lambda x: datetime.strptime(x, '%m/%d/%Y'), DateType())

df = df1.withColumn('test', func(col('first')))

df.show()

df.printSchema()

Here is the output:

+----------+----------+----------+----------+
|     first|    second|     third|      test|
+----------+----------+----------+----------+
|11/25/1991|11/24/1991|11/30/1991|1991-01-25|
|11/25/1391|11/24/1992|11/30/1992|1391-01-17|
+----------+----------+----------+----------+

root
 |-- first: string (nullable = true)
 |-- second: string (nullable = true)
 |-- third: string (nullable = true)
 |-- test: date (nullable = true)

adb is not recognized as internal or external command on windows

If you go to your android-sdk/tools folder I think you'll find a message :

The adb tool has moved to platform-tools/

If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"

Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

So you should also add C:/android-sdk/platform-tools to you environment path. Also after you modify the PATH variable make sure that you start a new CommandPrompt window.

Combine GET and POST request methods in Spring

@RequestMapping(value = "/books", method = { RequestMethod.GET, 
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
     HttpServletRequest request) 
    throws ParseException {

//your code 
}

This will works for both GET and POST.

For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter

like below

public class BooksFilter{

private String parameter1;
private String parameter2;

   //getters and setters

URl should be like below

/books?parameter1=blah

Like this way u can use it for both GET and POST

Put buttons at bottom of screen with LinearLayout?

You can bundle your Button(s) within a RelativeLayout even if your Parent Layout is Linear. Make Sure the outer most parent has android:layout_height attribute set to match_parent. And in that Button tag add 'android:alignParentBottom="True" '

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

I think I've got it.

_x000D_
_x000D_
.wrapper {_x000D_
    background:#DDD;_x000D_
    display:inline-block;_x000D_
    padding: 10px;_x000D_
    height: 20px;_x000D_
    width:auto;_x000D_
}_x000D_
_x000D_
.label {_x000D_
    display: inline-block;_x000D_
    width: 1em;_x000D_
}_x000D_
_x000D_
.contents, .contents .inner {_x000D_
    display:inline-block;_x000D_
}_x000D_
_x000D_
.contents {_x000D_
    white-space:nowrap;_x000D_
    margin-left: -1em;_x000D_
    padding-left: 1em;_x000D_
}_x000D_
_x000D_
.contents .inner {_x000D_
    background:#c3c;_x000D_
    width:0%;_x000D_
    overflow:hidden;_x000D_
    -webkit-transition: width 1s ease-in-out;_x000D_
    -moz-transition: width 1s ease-in-out;_x000D_
    -o-transition: width 1s ease-in-out;_x000D_
    transition: width 1s ease-in-out;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
.wrapper:hover .contents .inner {_x000D_
   _x000D_
    width:100%;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <span class="label">+</span><div class="contents">_x000D_
        <div class="inner">_x000D_
            These are the contents of this div_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Animating to 100% causes it to wrap because the box is bigger than the available width (100% minus the + and the whitespace following it).

Instead, you can animate an inner element, whose 100% is the total width of .contents.

Twitter Bootstrap add active class to li

To activate the menus and submenus, even with params in the URL, use the code bellow:

// Highlight the active menu
$(document).ready(function () {
    var action = window.location.pathname.split('/')[1];

    // If there's no action, highlight the first menu item
    if (action == "") {
        $('ul.nav li:first').addClass('active');
    } else {
        // Highlight current menu
        $('ul.nav a[href="/' + action + '"]').parent().addClass('active');

        // Highlight parent menu item
        $('ul.nav a[href="/' + action + '"]').parents('li').addClass('active');
    }
});

This accepts URLs like:

/posts
/posts/1
/posts/1/edit