Programs & Examples On #Navigator

The Navigator object contains information about the visitor's browser name, version, and more.

Flutter position stack widget in center

A Stack allows you to stack elements on top of each other, with the last element in the array taking the highest priority. You can use Align, Positioned, or Container to position the children of a stack.

Align

Widgets are moved by setting the alignment with Alignment, which has static properties like topCenter, bottomRight, and so on. Or you can take full control and set Alignment(1.0, -1.0), which takes x,y values ranging from 1.0 to -1.0, with (0,0) being the center of the screen.

  Stack(
      children: [
        Align(
          alignment: Alignment.topCenter,
          child: Container(
              height: 80,
              width: 80, color: Colors.blueAccent
          ),
        ),
        Align(
          alignment: Alignment.center,
          child: Container(
              height: 80,
              width: 80, color: Colors.deepPurple
          ),
        ),
        Container(
          alignment: Alignment.bottomCenter,
          // alignment: Alignment(1.0, -1.0),
          child: Container(
              height: 80,
              width: 80, color: Colors.amber
          ),
        )
      ]
  )

enter image description here

How to make flutter app responsive according to different screen size?

You can use responsive_helper package to make your app responsive.

It's a very easy method to make your app responsive. Just take a look at the example page and then you'll figure it out how to use it.

Tensorflow import error: No module named 'tensorflow'

In Anaconda Prompt (Anaconda 3), Type: conda install tensorflow command

This fix my issue in my Anaconda with Python 3.8.

Reference: https://panjeh.medium.com/modulenotfounderror-no-module-named-tensorflow-in-jupeter-1425afe23bd7

Anaconda Navigator won't launch (windows 10)

You need to update Anaconda using:

conda update

and

conda update anaconda-navigator

Try these commands on anaconda prompt and then try to launch navigator from the prompt itself using following command:

anaconda-navigator

If still the problem doesn't get solved, share the anaconda prompt logs here if they have any errors.

How do I update Anaconda?

If you are trying to update your Anaconda version to a new one, you'll notice that running the new installer wouldn't work, as it complains the installation directory is non-empty.

So you should use conda to upgrade as detailed by the official docs:

conda update conda
conda update anaconda


In Windows, if you made a "for all users" installation, it might be necessary to run from an Anaconda prompt with Administrator privileges.

Simply right click on Anaconda Prompt in the start menu

This prevents the error:

ERROR conda.core.link:_execute(502): An error occurred while uninstalling package 'defaults::conda-4.5.4-py36_0'. PermissionError(13, 'Access is denied')

flutter remove back button on appbar

If navigating to another page . Navigator.pushReplacement() can be used. It can be used If you're navigating from login to home screen. Or you can use .
AppBar(automaticallyImplyLeading: false)

Anaconda Installed but Cannot Launch Navigator

I also have the issue on windows when i am unable to find the anaconda-navigator in start menu. First you have to check anaconda-navigator.exe file in your anaconda folder if this file is present it means you have installed it properly otherwise there is some problem and you have to reinstall it.

Before reinstalling this points to be noticed 1) You have to uninstall all previous python folder 2) Check you environment variable and clear all previous python path

After this install anaconda your problem will be resolved if not tell me the full error i will try to solve it

Hide header in stack navigator React navigation

const CallStack = createStackNavigator({
  Calls: Calls,
  CallsScreen:CallsScreen,
}, {headerMode: 'none'});

CallStack.navigationOptions = {
  tabBarLabel: 'Calls',
  tabBarIcon: ({ focused }) => (
    <TabBarIcon
      focused={focused}
      name={Platform.OS === 'ios' ? 'ios-options' : 'md-options'}
    />
  ),

   header: null,

        headerVisible: false,

};

Anaconda-Navigator - Ubuntu16.04

add anaconda installation path to .bashrc

export PATH="$PATH:/home/username/anaconda3/bin"

load in terminal

$ source ~/.bashrc

run from terminal

$ anaconda-navigator

Disable back button in react navigation

1) To make the back button disappear in react-navigation v2 or newer:

navigationOptions:  {
    title: 'MyScreen',
    headerLeft: null
}

2) If you want to clean navigation stack:

Assuming you are on the screen from which you want to navigate from:

If you are using react-navigation version v5 or newer you can use navigation.reset or CommonActions.reset:

 // Replace current navigation state with a new one,
 // index value will be the current active route:

navigation.reset({
  index: 0,
  routes: [{ name: 'Profile' }],
});

Source and more info here: https://reactnavigation.org/docs/navigation-prop/#reset

Or:

navigation.dispatch(
  CommonActions.reset({
    index: 1,
    routes: [
      { name: 'Home' },
      {
        name: 'Profile',
        params: { user: 'jane' },
      },
    ],
  })
);

Source and more info here: https://reactnavigation.org/docs/navigation-actions/#reset

For older versions of react-navigation:

v2-v4 use StackActions.reset(...)

import { StackActions, NavigationActions } from 'react-navigation';

const resetAction = StackActions.reset({
  index: 0, // <-- currect active route from actions array
  actions: [
    NavigationActions.navigate({ routeName: 'myRouteWithDisabledBackFunctionality' }),
  ],
});

this.props.navigation.dispatch(resetAction);

v1 use NavigationActions.reset

3) For android you will also have to disable the hardware back button using the BackHandler:

http://reactnative.dev/docs/backhandler.html

or if you want to use hooks:

https://github.com/react-native-community/hooks#usebackhandler

otherwise the app will close at android hardware back button press if navigation stack is empty.

Unable to Resolve Module in React Native App

I had this error and then I realized that my package.json file was mostly empty. Make sure you have all the dependencies you have first.

use yarn add DEPENDENCY_NAME to add dependencies.

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

I also had this same problem.

I build .apk file of the project and installed it into mobile(android) and got it working

Conda environments not showing up in Jupyter Notebook

I don't think the other answers are working any more, as conda stopped automatically setting environments up as jupyter kernels. You need to manually add kernels for each environment in the following way:

source activate myenv
python -m ipykernel install --user --name myenv --display-name "Python (myenv)"

As documented here:http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernels-for-different-environments Also see this issue.

Addendum: You should be able to install the nb_conda_kernels package with conda install nb_conda_kernels to add all environments automatically, see https://github.com/Anaconda-Platform/nb_conda_kernels

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

"Have you tried turning it off and on again?" (Roy of The IT crowd)

This happened to me today, which is why I ended up to this page. Seeing that error was weird since, recently, I have not made any changes in my Python environment. Interestingly, I observed that if I open a new notebook and import pandas I would not get the same error message. So, I did shutdown the troublesome notebook and started it again and voila it is working again!

Even though this solved the problem (at least for me), I cannot readily come up with an explanation as to why it happened in the first place!

Method List in Visual Studio Code

There's no such feature today, the CTRL+SHIFT+O == CTRL+P @ doesn't work for all languages.

As a last resort you can use the search panel - although it is not so fast an easy to use as you'd like - you can enter this regex in the search panel to find all functions:

function\s([_A-Za-z0-9]+)\s*\(

setTimeout in React Native

Never call setState inside render method

You should never ever call setState inside the render method. Why? calling setState eventually fires the render method again. That means you are calling setState (mentioned in your render block) in a loop that would never end. The correct way to do that is by using componentDidMount hook in React, like so:

class CowtanApp extends Component {
  state = {
     timePassed: false
  }

  componentDidMount () {
     setTimeout(() => this.setState({timePassed: true}), 1000)
  }

  render () {
    return this.state.timePassed ? (
        <NavigatorIOS
          style = {styles.container}
          initialRoute = {{
            component: LoginPage,
            title: 'Sign In',
        }}/>
    ) : <LoadingPage/>
  }
}

PS Use ternary operators for cleaner, shorter and readable code.

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Use this snip : var IE = (navigator.userAgent.indexOf("Edge") > -1 || navigator.userAgent.indexOf("Trident/7.0") > -1) ? true : false;

AngularJS : ng-click not working

i tried using the same ng-click for two elements with same name showDetail2('abc')

it is working for me . can you check rest of the code which may be breaking you to move further.

here is the sample jsfiddle i tried:

#pragma mark in Swift?

Apple states in the latest version of Building Cocoa Apps,

The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, build configurations, and language features to accomplish the same functionality. For this reason, preprocessor directives are not imported in Swift.

The # character appears to still be how you work with various build configurations and things like that, but it looks like they're trying to cut back on your need for most preprocessing in the vein of pragma and forward you to other language features altogether. Perhaps this is to aid in the operation of the Playgrounds and the REPL behaving as close as possible to the fully compiled code.

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

One word answer: asynchronicity.

Forewords

This topic has been iterated at least a couple of thousands of times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:


The answer to the question at hand

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been canceled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, the asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

async code highlighted

In short, the callback functions are created synchronously but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs too inside the callback function would output the expected result, because the result is available at that point.

Implementing your own callback logic

Often you need to do more things with the result from an asynchronous function or do different things with the result depending on where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Code snippet of the above example:

_x000D_
_x000D_
// 1. Call helloCatAsync passing a callback function,_x000D_
//    which will be called receiving the result from the async operation_x000D_
console.log("1. function called...")_x000D_
helloCatAsync(function(result) {_x000D_
    // 5. Received the result from the async function,_x000D_
    //    now do whatever you want with it:_x000D_
    console.log("5. result is: ", result);_x000D_
});_x000D_
_x000D_
// 2. The "callback" parameter is a reference to the function which_x000D_
//    was passed as argument from the helloCatAsync call_x000D_
function helloCatAsync(callback) {_x000D_
    console.log("2. callback here is the function passed as argument above...")_x000D_
    // 3. Start async operation:_x000D_
    setTimeout(function() {_x000D_
    console.log("3. start async operation...")_x000D_
    console.log("4. finished async operation, calling the callback, passing the result...")_x000D_
        // 4. Finished async operation,_x000D_
        //    call the callback passing the result as argument_x000D_
        callback('Nya');_x000D_
    }, Math.random() * 2000);_x000D_
}
_x000D_
_x000D_
_x000D_

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Promises

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of the asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:


More reading material about JavaScript asynchronicity


Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputations can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

How to detect browser using angularjs?

You can easily use the "ng-device-detector" module.

https://github.com/srfrnk/ng-device-detector

var app = angular.module('myapp', ["ng.deviceDetector"]);
app.controller('DeviceCtrl', ["$scope","deviceDetector",function($scope,deviceDetector) {
      console.log("browser: ", deviceDetector.browser);
      console.log("browser version: ", deviceDetector.browser_version);
      console.log("device: ", deviceDetector.device);
}]);

Internet Explorer 11 detection

I found IE11 is giving more than one user agent strings in different environments.

Instead of relying on MSIE, and other approaches, It's better to rely on Trident version

const isIE11 = userAgent => userAgent.match(/Trident\/([\d.]+)/) ? +userAgent.match(/Trident\/([\d.]+)/)[1] >= 7;

Hope this helps :)

Console.log not working at all

You may have used the filter function in the console which will hide anything that doesn't match your query. Remove the query and your messages will display.

How can I detect browser type using jQuery?

My solution for ie detection:

if (navigator.userAgent.match(/msie/i) || navigator.userAgent.match(/trident/i) ){
    $("html").addClass("ie");
}

Jquery needed.

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

This works for me on all devices [ iOS, Android and Window Mobile 8.1 ].

Does not look like the best way by any means... but cannot be more simpler :)

<a href="bingmaps:?cp=18.551464~73.951399">
 <a href="http://maps.apple.com/maps?q=18.551464, 73.951399"> 
   Open Maps
 </a>
</a>

http://jsbin.com/dibeq

$apply already in progress error

You are getting this error because you are calling $apply inside an existing digestion cycle.

The big question is: why are you calling $apply? You shouldn't ever need to call $apply unless you are interfacing from a non-Angular event. The existence of $apply usually means I am doing something wrong (unless, again, the $apply happens from a non-Angular event).

If $apply really is appropriate here, consider using a "safe apply" approach:

https://coderwall.com/p/ngisma

HTML 5 video recording and storing a stream

Currently there is no production ready HTML5 only solution for recording video over the web. The current available solutions are as follows:

HTML Media Capture

Works on mobile devices and uses the OS' video capture app to capture video and upload/POST it to a web server. You will get .mov files on iOS (these are unplayable on Android I've tried) and .mp4 and .3gp on Android. At least the codecs will be the same: H.264 for video and AAC for audio in 99% of the devices.

HTML Media Capture

Image courtesy of https://addpipe.com/blog/the-new-video-recording-prompt-for-media-capture-in-ios9/

Flash and a media server on desktop.

Video recording in Flash works like this: audio and video data is captured from the webcam and microphone, it's encoded using Sorenson Spark or H.264 (video) and Nellymoser Asao or Speex (audio) then it's streamed (rtmp) to a media server (Red5, AMS, Wowza) where it is saved in .flv or .f4v files.

The MediaStream Recording proposal

The MediaStream Recording is a proposal by the the Media Capture Task Force (a joint task force between the WebRTC and Device APIs working groups) for a JS API who's purpose is to make basic video recording in the browser very simple.

Not supported by major browsers. When it'll get implemented (if it will) you will most probably end up with different filetypes (at least .ogg and .webm) and audio/video codecs depending on the browser.

Commercial solutions

There are a few saas and software solutions out there that will handle some or all of the above including addpipe.com, HDFVR, Nimbb and Cameratag.

Further reading:

Can someone explain how to implement the jQuery File Upload plugin?

Check out the Image drag and drop uploader with image preview using dropper jquery plugin.

HTML

<div class="target" width="78" height="100"><img /></div>

JS

$(".target").dropper({
    action: "upload.php",

}).on("start.dropper", onStart);
function onStart(e, files){
console.log(files[0]);

    image_preview(files[0].file).then(function(res){
$('.dropper-dropzone').empty();
//$('.dropper-dropzone').css("background-image",res.data);
 $('#imgPreview').remove();        
$('.dropper-dropzone').append('<img id="imgPreview"/><span style="display:none">Drag and drop files or click to select</span>');
var widthImg=$('.dropper-dropzone').attr('width');
        $('#imgPreview').attr({width:widthImg});
    $('#imgPreview').attr({src:res.data});

    })

}

function image_preview(file){
    var def = new $.Deferred();
    var imgURL = '';
    if (file.type.match('image.*')) {
        //create object url support
        var URL = window.URL || window.webkitURL;
        if (URL !== undefined) {
            imgURL = URL.createObjectURL(file);
            URL.revokeObjectURL(file);
            def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
        }
        //file reader support
        else if(window.File && window.FileReader)
        {
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function () {
                imgURL = reader.result;
                def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
            }
        }
        else {
            def.reject({status: 1001, message: 'File uploader not supported', data:imgURL, error: {}});
        }
    }
    else
        def.reject({status: 1002, message: 'File type not supported', error: {}});
    return def.promise();
}

$('.dropper-dropzone').mouseenter(function() {
 $( '.dropper-dropzone>span' ).css("display", "block");
});

$('.dropper-dropzone').mouseleave(function() {
 $( '.dropper-dropzone>span' ).css("display", "none");
});

CSS

.dropper-dropzone{
    width:78px;
padding:3px;
    height:100px;
position: relative;
}
.dropper-dropzone>img{
    width:78px;
    height:100px;
margin-top=0;
}

.dropper-dropzone>span {
    position: absolute;
    right: 10px;
    top: 20px;
color:#ccc;


}

.dropper .dropper-dropzone{

padding:3px !important    
}

Demo Jsfiddle

How to detect IE11?

Get IE Version from the User-Agent

var ie = 0;
try { ie = navigator.userAgent.match( /(MSIE |Trident.*rv[ :])([0-9]+)/ )[ 2 ]; }
catch(e){}

How it works: The user-agent string for all IE versions includes a portion "MSIE space version" or "Trident other-text rv space-or-colon version". Knowing this, we grab the version number from a String.match() regular expression. A try-catch block is used to shorten the code, otherwise we'd need to test the array bounds for non-IE browsers.

Note: The user-agent can be spoofed or omitted, sometimes unintentionally if the user has set their browser to a "compatibility mode". Though this doesn't seem like much of an issue in practice.


Get IE Version without the User-Agent

var d = document, w = window;
var ie = ( !!w.MSInputMethodContext ? 11 : !d.all ? 99 : w.atob ? 10 : 
d.addEventListener ? 9 : d.querySelector ? 8 : w.XMLHttpRequest ? 7 : 
d.compatMode ? 6 : w.attachEvent ? 5 : 1 );

How it works: Each version of IE adds support for additional features not found in previous versions. So we can test for the features in a top-down manner. A ternary sequence is used here for brevity, though if-then and switch statements would work just as well. The variable ie is set to an integer 5-11, or 1 for older, or 99 for newer/non-IE. You can set it to 0 if you just want to test for IE 1-11 exactly.

Note: Object detection may break if your code is run on a page with third-party scripts that add polyfills for things like document.addEventListener. In such situations the user-agent is the best option.


Detect if the Browser is Modern

If you're only interested in whether or not a browser supports most HTML 5 and CSS 3 standards, you can reasonably assume that IE 8 and lower remain the primary problem apps. Testing for window.getComputedStyle will give you a fairly good mix of modern browsers, as well (IE 9, FF 4, Chrome 11, Safari 5, Opera 11.5). IE 9 greatly improves on standards support, but native CSS animation requires IE 10.

var isModernBrowser = ( !document.all || ( document.all && document.addEventListener ) ); 

HTML5 record audio to file

The code shown below is copyrighted to Matt Diamond and available for use under MIT license. The original files are here:

Save this files and use

_x000D_
_x000D_
(function(window){_x000D_
_x000D_
      var WORKER_PATH = 'recorderWorker.js';_x000D_
      var Recorder = function(source, cfg){_x000D_
        var config = cfg || {};_x000D_
        var bufferLen = config.bufferLen || 4096;_x000D_
        this.context = source.context;_x000D_
        this.node = this.context.createScriptProcessor(bufferLen, 2, 2);_x000D_
        var worker = new Worker(config.workerPath || WORKER_PATH);_x000D_
        worker.postMessage({_x000D_
          command: 'init',_x000D_
          config: {_x000D_
            sampleRate: this.context.sampleRate_x000D_
          }_x000D_
        });_x000D_
        var recording = false,_x000D_
          currCallback;_x000D_
_x000D_
        this.node.onaudioprocess = function(e){_x000D_
          if (!recording) return;_x000D_
          worker.postMessage({_x000D_
            command: 'record',_x000D_
            buffer: [_x000D_
              e.inputBuffer.getChannelData(0),_x000D_
              e.inputBuffer.getChannelData(1)_x000D_
            ]_x000D_
          });_x000D_
        }_x000D_
_x000D_
        this.configure = function(cfg){_x000D_
          for (var prop in cfg){_x000D_
            if (cfg.hasOwnProperty(prop)){_x000D_
              config[prop] = cfg[prop];_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
_x000D_
        this.record = function(){_x000D_
       _x000D_
          recording = true;_x000D_
        }_x000D_
_x000D_
        this.stop = function(){_x000D_
        _x000D_
          recording = false;_x000D_
        }_x000D_
_x000D_
        this.clear = function(){_x000D_
          worker.postMessage({ command: 'clear' });_x000D_
        }_x000D_
_x000D_
        this.getBuffer = function(cb) {_x000D_
          currCallback = cb || config.callback;_x000D_
          worker.postMessage({ command: 'getBuffer' })_x000D_
        }_x000D_
_x000D_
        this.exportWAV = function(cb, type){_x000D_
          currCallback = cb || config.callback;_x000D_
          type = type || config.type || 'audio/wav';_x000D_
          if (!currCallback) throw new Error('Callback not set');_x000D_
          worker.postMessage({_x000D_
            command: 'exportWAV',_x000D_
            type: type_x000D_
          });_x000D_
        }_x000D_
_x000D_
        worker.onmessage = function(e){_x000D_
          var blob = e.data;_x000D_
          currCallback(blob);_x000D_
        }_x000D_
_x000D_
        source.connect(this.node);_x000D_
        this.node.connect(this.context.destination);    //this should not be necessary_x000D_
      };_x000D_
_x000D_
      Recorder.forceDownload = function(blob, filename){_x000D_
        var url = (window.URL || window.webkitURL).createObjectURL(blob);_x000D_
        var link = window.document.createElement('a');_x000D_
        link.href = url;_x000D_
        link.download = filename || 'output.wav';_x000D_
        var click = document.createEvent("Event");_x000D_
        click.initEvent("click", true, true);_x000D_
        link.dispatchEvent(click);_x000D_
      }_x000D_
_x000D_
      window.Recorder = Recorder;_x000D_
_x000D_
    })(window);_x000D_
_x000D_
    //ADDITIONAL JS recorderWorker.js_x000D_
    var recLength = 0,_x000D_
      recBuffersL = [],_x000D_
      recBuffersR = [],_x000D_
      sampleRate;_x000D_
    this.onmessage = function(e){_x000D_
      switch(e.data.command){_x000D_
        case 'init':_x000D_
          init(e.data.config);_x000D_
          break;_x000D_
        case 'record':_x000D_
          record(e.data.buffer);_x000D_
          break;_x000D_
        case 'exportWAV':_x000D_
          exportWAV(e.data.type);_x000D_
          break;_x000D_
        case 'getBuffer':_x000D_
          getBuffer();_x000D_
          break;_x000D_
        case 'clear':_x000D_
          clear();_x000D_
          break;_x000D_
      }_x000D_
    };_x000D_
_x000D_
    function init(config){_x000D_
      sampleRate = config.sampleRate;_x000D_
    }_x000D_
_x000D_
    function record(inputBuffer){_x000D_
_x000D_
      recBuffersL.push(inputBuffer[0]);_x000D_
      recBuffersR.push(inputBuffer[1]);_x000D_
      recLength += inputBuffer[0].length;_x000D_
    }_x000D_
_x000D_
    function exportWAV(type){_x000D_
      var bufferL = mergeBuffers(recBuffersL, recLength);_x000D_
      var bufferR = mergeBuffers(recBuffersR, recLength);_x000D_
      var interleaved = interleave(bufferL, bufferR);_x000D_
      var dataview = encodeWAV(interleaved);_x000D_
      var audioBlob = new Blob([dataview], { type: type });_x000D_
_x000D_
      this.postMessage(audioBlob);_x000D_
    }_x000D_
_x000D_
    function getBuffer() {_x000D_
      var buffers = [];_x000D_
      buffers.push( mergeBuffers(recBuffersL, recLength) );_x000D_
      buffers.push( mergeBuffers(recBuffersR, recLength) );_x000D_
      this.postMessage(buffers);_x000D_
    }_x000D_
_x000D_
    function clear(){_x000D_
      recLength = 0;_x000D_
      recBuffersL = [];_x000D_
      recBuffersR = [];_x000D_
    }_x000D_
_x000D_
    function mergeBuffers(recBuffers, recLength){_x000D_
      var result = new Float32Array(recLength);_x000D_
      var offset = 0;_x000D_
      for (var i = 0; i < recBuffers.length; i++){_x000D_
        result.set(recBuffers[i], offset);_x000D_
        offset += recBuffers[i].length;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function interleave(inputL, inputR){_x000D_
      var length = inputL.length + inputR.length;_x000D_
      var result = new Float32Array(length);_x000D_
_x000D_
      var index = 0,_x000D_
        inputIndex = 0;_x000D_
_x000D_
      while (index < length){_x000D_
        result[index++] = inputL[inputIndex];_x000D_
        result[index++] = inputR[inputIndex];_x000D_
        inputIndex++;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function floatTo16BitPCM(output, offset, input){_x000D_
      for (var i = 0; i < input.length; i++, offset+=2){_x000D_
        var s = Math.max(-1, Math.min(1, input[i]));_x000D_
        output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function writeString(view, offset, string){_x000D_
      for (var i = 0; i < string.length; i++){_x000D_
        view.setUint8(offset + i, string.charCodeAt(i));_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function encodeWAV(samples){_x000D_
      var buffer = new ArrayBuffer(44 + samples.length * 2);_x000D_
      var view = new DataView(buffer);_x000D_
_x000D_
      /* RIFF identifier */_x000D_
      writeString(view, 0, 'RIFF');_x000D_
      /* file length */_x000D_
      view.setUint32(4, 32 + samples.length * 2, true);_x000D_
      /* RIFF type */_x000D_
      writeString(view, 8, 'WAVE');_x000D_
      /* format chunk identifier */_x000D_
      writeString(view, 12, 'fmt ');_x000D_
      /* format chunk length */_x000D_
      view.setUint32(16, 16, true);_x000D_
      /* sample format (raw) */_x000D_
      view.setUint16(20, 1, true);_x000D_
      /* channel count */_x000D_
      view.setUint16(22, 2, true);_x000D_
      /* sample rate */_x000D_
      view.setUint32(24, sampleRate, true);_x000D_
      /* byte rate (sample rate * block align) */_x000D_
      view.setUint32(28, sampleRate * 4, true);_x000D_
      /* block align (channel count * bytes per sample) */_x000D_
      view.setUint16(32, 4, true);_x000D_
      /* bits per sample */_x000D_
      view.setUint16(34, 16, true);_x000D_
      /* data chunk identifier */_x000D_
      writeString(view, 36, 'data');_x000D_
      /* data chunk length */_x000D_
      view.setUint32(40, samples.length * 2, true);_x000D_
_x000D_
      floatTo16BitPCM(view, 44, samples);_x000D_
_x000D_
      return view;_x000D_
    }
_x000D_
<html>_x000D_
     <body>_x000D_
      <audio controls autoplay></audio>_x000D_
      <script type="text/javascript" src="recorder.js"> </script>_x000D_
                    <fieldset><legend>RECORD AUDIO</legend>_x000D_
      <input onclick="startRecording()" type="button" value="start recording" />_x000D_
      <input onclick="stopRecording()" type="button" value="stop recording and play" />_x000D_
                    </fieldset>_x000D_
      <script>_x000D_
       var onFail = function(e) {_x000D_
        console.log('Rejected!', e);_x000D_
       };_x000D_
_x000D_
       var onSuccess = function(s) {_x000D_
        var context = new webkitAudioContext();_x000D_
        var mediaStreamSource = context.createMediaStreamSource(s);_x000D_
        recorder = new Recorder(mediaStreamSource);_x000D_
        recorder.record();_x000D_
_x000D_
        // audio loopback_x000D_
        // mediaStreamSource.connect(context.destination);_x000D_
       }_x000D_
_x000D_
       window.URL = window.URL || window.webkitURL;_x000D_
       navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;_x000D_
_x000D_
       var recorder;_x000D_
       var audio = document.querySelector('audio');_x000D_
_x000D_
       function startRecording() {_x000D_
        if (navigator.getUserMedia) {_x000D_
         navigator.getUserMedia({audio: true}, onSuccess, onFail);_x000D_
        } else {_x000D_
         console.log('navigator.getUserMedia not present');_x000D_
        }_x000D_
       }_x000D_
_x000D_
       function stopRecording() {_x000D_
        recorder.stop();_x000D_
        recorder.exportWAV(function(s) {_x000D_
                                _x000D_
                                  audio.src = window.URL.createObjectURL(s);_x000D_
        });_x000D_
       }_x000D_
      </script>_x000D_
     </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Export to CSV using jQuery and html

I am not sure if the above CSV generation code is so great as it appears to skip th cells and also did not appear to allow for commas in the value. So here is my CSV generation code that might be useful.

It does assume you have the $table variable which is a jQuery object (eg. var $table = $('#yourtable');)

$rows = $table.find('tr');

var csvData = "";

for(var i=0;i<$rows.length;i++){
                var $cells = $($rows[i]).children('th,td'); //header or content cells

                for(var y=0;y<$cells.length;y++){
                    if(y>0){
                      csvData += ",";
                    }
                    var txt = ($($cells[y]).text()).toString().trim();
                    if(txt.indexOf(',')>=0 || txt.indexOf('\"')>=0 || txt.indexOf('\n')>=0){
                        txt = "\"" + txt.replace(/\"/g, "\"\"") + "\"";
                    }
                    csvData += txt;
                }
                csvData += '\n';
 }

Running Python on Windows for Node.js dependencies

TL;DR Make a copy or alias of your python.exe with name python2.7.exe

My python 2.7 was installed as

D:\app\Python27\python.exe

I always got this error no matter how I set (and verified) PYTHON env variable:

gyp ERR! stack Error: Can't find Python executable "python2.7", you can set the PYTHON env variable.
gyp ERR! stack     at failNoPython (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:103:14)

The reason for this was that in node-gyp's configure.js the python executable was resolved like:

var python = gyp.opts.python || process.env.PYTHON || 'python'

And it turned out that gyp.opts.python had value 'python2.7' thus overriding process.env.PYTHON.

I resolved this by creating an alias for python.exe executable with name node-gyp was looking for:

D:\app\Python27>mklink python2.7.exe python.exe

You need admin rights for this operation.

Remove attribute "checked" of checkbox

using .removeAttr() on a boolean attribute such as checked, selected, or readonly would also set the corresponding named property to false.

Hence removed this checked attribute

$("#IdName option:checked").removeAttr("checked");

How does HTTP_USER_AGENT work?

http://www.useragentstring.com/

Visit that page, it'll give you a good explanation of each element of your user agent.

Mozilla:

MozillaProductSlice. Claims to be a Mozilla based user agent, which is only true for Gecko browsers like Firefox and Netscape. For all other user agents it means 'Mozilla-compatible'. In modern browsers, this is only used for historical reasons. It has no real meaning anymore

Exit from app when click button in android phonegap?

navigator.app.exitApp();

add this line where you want you exit the application.

How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
    a.Fill(t1);
}
return t1;
}

and now can be used like this:

table = GetDataTable();

How to change column width in DataGridView?

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

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

The following code worked for me:

public vidOff() {

      let stream = this.video.nativeElement.srcObject;
      let tracks = stream.getTracks();

      tracks.forEach(function (track) {
          track.stop();
      });

      this.video.nativeElement.srcObject = null;
      this.video.nativeElement.stop();
  }

Detecting a mobile browser

According to MDN's article on Browser detection using the user agent, it is encouraged to avoid this approach if possible and suggest other avenues such as feature detection.

However, if one must use the user agent as a means to detect if the device is mobile, they suggest:

In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.

Therefore, this one-liner will suffice:

const isMobileDevice = window.navigator.userAgent.toLowerCase().includes("mobi");

[UPDATE]:

As @zenw0lf suggests in the comments, using a Regular Expression would be better:

const isMobileDevice = /Mobi/i.test(window.navigator.userAgent)

How to detect my browser version and operating system using JavaScript?

To detect operating system using JavaScript it is better to use navigator.userAgent instead of navigator.appVersion

_x000D_
_x000D_
{_x000D_
  var OSName = "Unknown OS";_x000D_
  if (navigator.userAgent.indexOf("Win") != -1) OSName = "Windows";_x000D_
  if (navigator.userAgent.indexOf("Mac") != -1) OSName = "Macintosh";_x000D_
  if (navigator.userAgent.indexOf("Linux") != -1) OSName = "Linux";_x000D_
  if (navigator.userAgent.indexOf("Android") != -1) OSName = "Android";_x000D_
  if (navigator.userAgent.indexOf("like Mac") != -1) OSName = "iOS";_x000D_
  console.log('Your OS: ' + OSName);_x000D_
}
_x000D_
_x000D_
_x000D_

Detect IE version (prior to v9) in JavaScript

Conditional comments are no longer supported in IE as of Version 10 as noted on the Microsoft reference page.

_x000D_
_x000D_
var ieDetector = function() {_x000D_
  var browser = { // browser object_x000D_
_x000D_
      verIE: null,_x000D_
      docModeIE: null,_x000D_
      verIEtrue: null,_x000D_
      verIE_ua: null_x000D_
_x000D_
    },_x000D_
    tmp;_x000D_
_x000D_
  tmp = document.documentMode;_x000D_
  try {_x000D_
    document.documentMode = "";_x000D_
  } catch (e) {};_x000D_
_x000D_
  browser.isIE = typeof document.documentMode == "number" || eval("/*@cc_on!@*/!1");_x000D_
  try {_x000D_
    document.documentMode = tmp;_x000D_
  } catch (e) {};_x000D_
_x000D_
  // We only let IE run this code._x000D_
  if (browser.isIE) {_x000D_
    browser.verIE_ua =_x000D_
      (/^(?:.*?[^a-zA-Z])??(?:MSIE|rv\s*\:)\s*(\d+\.?\d*)/i).test(navigator.userAgent || "") ?_x000D_
      parseFloat(RegExp.$1, 10) : null;_x000D_
_x000D_
    var e, verTrueFloat, x,_x000D_
      obj = document.createElement("div"),_x000D_
_x000D_
      CLASSID = [_x000D_
        "{45EA75A0-A269-11D1-B5BF-0000F8051515}", // Internet Explorer Help_x000D_
        "{3AF36230-A269-11D1-B5BF-0000F8051515}", // Offline Browsing Pack_x000D_
        "{89820200-ECBD-11CF-8B85-00AA005B4383}"_x000D_
      ];_x000D_
_x000D_
    try {_x000D_
      obj.style.behavior = "url(#default#clientcaps)"_x000D_
    } catch (e) {};_x000D_
_x000D_
    for (x = 0; x < CLASSID.length; x++) {_x000D_
      try {_x000D_
        browser.verIEtrue = obj.getComponentVersion(CLASSID[x], "componentid").replace(/,/g, ".");_x000D_
      } catch (e) {};_x000D_
_x000D_
      if (browser.verIEtrue) break;_x000D_
_x000D_
    };_x000D_
    verTrueFloat = parseFloat(browser.verIEtrue || "0", 10);_x000D_
    browser.docModeIE = document.documentMode ||_x000D_
      ((/back/i).test(document.compatMode || "") ? 5 : verTrueFloat) ||_x000D_
      browser.verIE_ua;_x000D_
    browser.verIE = verTrueFloat || browser.docModeIE;_x000D_
  };_x000D_
_x000D_
  return {_x000D_
    isIE: browser.isIE,_x000D_
    Version: browser.verIE_x000D_
  };_x000D_
_x000D_
}();_x000D_
_x000D_
document.write('isIE: ' + ieDetector.isIE + "<br />");_x000D_
document.write('IE Version Number: ' + ieDetector.Version);
_x000D_
_x000D_
_x000D_

then use:

if((ieDetector.isIE) && (ieDetector.Version <= 9))
{

}

How to remove MySQL completely with config and library files?

With the command:

sudo apt-get remove --purge mysql\*

you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).

You can list all installed mysql packages with the command:

sudo dpkg -l | grep -i mysql

For more cleanup of the package cache, you can use the command:

sudo apt-get clean

Also, remember to use the command:

sudo updatedb

Otherwise the "locate" command will display old data.

To install mysql again, use the following command:

sudo apt-get install libmysqlclient-dev mysql-client

This will install the mysql client, libmysql and its headers files.

To install the mysql server, use the command:

sudo apt-get install mysql-server

How to get user agent in PHP

You could also use the php native funcion get_browser()

IMPORTANT NOTE: You should have a browscap.ini file.

Detect Safari browser

This code is used to detect only safari browser

if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) 
{
   alert("Browser is Safari");          
}

Jquery click not working with ipad

We have a similar problem: the click event on a button doesn't work, as long as the user has not scrolled the page. The bug appears only on iOS.

We solved it by scrolling the page a little bit:

$('#modal-window').animate({scrollTop:$("#next-page-button-anchor").offset().top}, 500);

(It doesn't answer the ultimate cause, though. Maybe some kind of bug in Safari mobile ?)

Get city name using geolocation

geolocator.js can do that. (I'm the author).

Getting City Name (Limited Address)

geolocator.locateByIP(options, function (err, location) {
    console.log(location.address.city);
});

Getting Full Address Information

Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.

var options = {
    enableHighAccuracy: true,
    fallbackToIP: true, // fallback to IP if Geolocation fails or rejected
    addressLookup: true
};
geolocator.locate(options, function (err, location) {
    console.log(location.address.city);
});

This uses Google APIs internally (for address lookup). So before this call, you should configure geolocator with your Google API key.

geolocator.config({
    language: "en",
    google: {
        version: "3",
        key: "YOUR-GOOGLE-API-KEY"
    }
});

Geolocator supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and a lot more features...

Google Gson - deserialize list<class> object? (generic type)

Since Gson 2.8, we can create util function like

public <T> List<T> getList(String jsonArray, Class<T> clazz) {
    Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
    return new Gson().fromJson(jsonArray, typeOfT);
}

Example using

String jsonArray = ...
List<User> user = getList(jsonArray, User.class);

HTML 5 Geo Location Prompt in Chrome

None of the above helped me.

After a little research I found that as of M50 (April 2016) - Chrome now requires a secure origin (such as HTTPS) for Geolocation.

Deprecated Features on Insecure Origins

The host "localhost" is special b/c its "potentially secure". You may not see errors during development if you are deploying to your development machine.

Apple Mach-O Linker Error when compiling for device

The problem was that in XCode 4, the dependencies do not assume the architecture settings of the main project, as they previously did in XCode 3. I had to go through all of my dependencies setting them for the correct architecture.

changing source on html5 video tag

Try moving the OGG source to the top. I've noticed Firefox sometimes gets confused and stops the player when the one it wants to play, OGG, isn't first.

Worth a try.

If Browser is Internet Explorer: run an alternative script instead

You can do something like this to include IE-specific javascript:

<!--[IF IE]>
    <script type="text/javascript">
        // IE stuff
    </script>
<![endif]-->

How to get visitor's location (i.e. country) using geolocation?

For developers looking for a full-featured geolocation utility, you can have a look at geolocator.js (I'm the author).

Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.

var options = {
    enableHighAccuracy: true,
    timeout: 6000,
    maximumAge: 0,
    desiredAccuracy: 30,
    fallbackToIP: true, // if HTML5 geolocation fails or rejected
    addressLookup: true, // get detailed address information
    timezone: true, 
    map: "my-map" // this will even create a map for you
};

geolocator.locate(options, function (err, location) {
    console.log(err || location);
});

It supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and more...

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

I noticed this problem recently myself, and I'm not sure how it comes about but it would appear sometimes firefox gets stuck on something loaded in cache. After clearing cache and restarting firefox it appears to function again.

Use tnsnames.ora in Oracle SQL Developer

I had the same problem, tnsnames.ora worked fine for all other tools but SQL Developer would not use it. I tried all the suggestions on the web I could find, including the solutions on the link provided here.
Nothing worked.

It turns out that the database was caching backup copies of tnsnames.ora like tnsnames.ora.bk2, tnsnames09042811AM4501.bak, tnsnames.ora.bk etc. These files were not readable by the average user.

I suspect sqldeveloper is pattern matching for the name and it was trying to read one of these backup copies and couldn't. So it just fails gracefully and shows nothing in drop down list.

The solution is to make all the files readable or delete or move the backup copies out of the Admin directory.

Is there an Eclipse plugin to run system shell in the Console?

... just a little bit late :) you might give a try at http://code.google.com/p/tarlog-plugins/. It gives you options like open shell and open explorer from Project Explorer context menu.

There's also http://sourceforge.net/projects/explorerplugin/ but it seems kind of stuck at 2009.

JavaScript for detecting browser language preference

I've been using Hamid's answer for a while, but it in cases where the languages array is like ["en", "en-GB", "en-US", "fr-FR", "fr", "en-ZA"] it will return "en", when "en-GB" would be a better match.

My update (below) will return the first long format code e.g. "en-GB", otherwise it will return the first short code e.g. "en", otherwise it will return null.

_x000D_
_x000D_
function getFirstBrowserLanguage() {_x000D_
        var nav = window.navigator,_x000D_
            browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],_x000D_
            i,_x000D_
            language,_x000D_
            len,_x000D_
            shortLanguage = null;_x000D_
_x000D_
        // support for HTML 5.1 "navigator.languages"_x000D_
        if (Array.isArray(nav.languages)) {_x000D_
            for (i = 0; i < nav.languages.length; i++) {_x000D_
                language = nav.languages[i];_x000D_
                len = language.length;_x000D_
                if (!shortLanguage && len) {_x000D_
                    shortLanguage = language;_x000D_
                }_x000D_
                if (language && len>2) {_x000D_
                    return language;_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
_x000D_
        // support for other well known properties in browsers_x000D_
        for (i = 0; i < browserLanguagePropertyKeys.length; i++) {_x000D_
            language = nav[browserLanguagePropertyKeys[i]];_x000D_
            //skip this loop iteration if property is null/undefined.  IE11 fix._x000D_
            if (language == null) { continue; } _x000D_
            len = language.length;_x000D_
            if (!shortLanguage && len) {_x000D_
                shortLanguage = language;_x000D_
            }_x000D_
            if (language && len > 2) {_x000D_
                return language;_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return shortLanguage;_x000D_
    }_x000D_
_x000D_
console.log(getFirstBrowserLanguage());
_x000D_
_x000D_
_x000D_

Update: IE11 was erroring when some properties were undefined. Added a check to skip those properties.

How to check if function exists in JavaScript?

This will verify if the function exists, if so it will be executed

me.onChange && me.onChange(str);

Thus the error TypeError: me.onChange is not a function is prevent.

Vue.JS: How to call function after page loaded?

You can use the mounted() Vue Lifecycle Hook. This will allow you to call a method before the page loads.

This is an implementation example:

HTML:

<div id="app">
  <h1>Welcome our site {{ name }}</h1>
</div>

JS:

var app = new Vue ({
    el: '#app',
    data: {
        name: ''
    },
    mounted: function() {
        this.askName() // Calls the method before page loads
    },
    methods: {
        // Declares the method
        askName: function(){
            this.name = prompt(`What's your name?`)
        }
    }
})

This will get the prompt method's value, insert it in the variable name and output in the DOM after the page loads. You can check the code sample here.

You can read more about Lifecycle Hooks here.

Count frequency of words in a list and sort by frequency

Using Counter would be the best way, but if you don't want to do that, you can implement it yourself this way.

# The list you already have
word_list = ['words', ..., 'other', 'words']
# Get a set of unique words from the list
word_set = set(word_list)
# create your frequency dictionary
freq = {}
# iterate through them, once per unique word.
for word in word_set:
    freq[word] = word_list.count(word) / float(len(word_list))

freq will end up with the frequency of each word in the list you already have.

You need float in there to convert one of the integers to a float, so the resulting value will be a float.

Edit:

If you can't use a dict or set, here is another less efficient way:

# The list you already have
word_list = ['words', ..., 'other', 'words']
unique_words = []
for word in word_list:
    if word not in unique_words:
        unique_words += [word]
word_frequencies = []
for word in unique_words:
    word_frequencies += [float(word_list.count(word)) / len(word_list)]
for i in range(len(unique_words)):
    print(unique_words[i] + ": " + word_frequencies[i])

The indicies of unique_words and word_frequencies will match.

C++ where to initialize static const

Static members need to be initialized in a .cpp translation unit at file scope or in the appropriate namespace:

const string foo::s( "my foo");

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I had this issue on Android 10,

Changed targetSdkVersion 29 to targetSdkVersion 28 issue resolved. Not sure what is the actual problem.

I think not a good practice, but it worked.

before:

compileSdkVersion 29

minSdkVersion 14

targetSdkVersion 29

Now:

compileSdkVersion 29

minSdkVersion 14

targetSdkVersion 28

For each row in an R dataframe

You can use the by() function:

by(dataFrame, seq_len(nrow(dataFrame)), function(row) dostuff)

But iterating over the rows directly like this is rarely what you want to; you should try to vectorize instead. Can I ask what the actual work in the loop is doing?

How to assign string to bytes array

Arrays are values... slices are more like pointers. That is [n]type is not compatible with []type as they are fundamentally two different things. You can get a slice that points to an array by using arr[:] which returns a slice that has arr as it's backing storage.

One way to convert a slice of for example []byte to [20]byte is to actually allocate a [20]byte which you can do by using var [20]byte (as it's a value... no make needed) and then copy data into it:

buf := make([]byte, 10)
var arr [10]byte
copy(arr[:], buf)

Essentially what a lot of other answers get wrong is that []type is NOT an array.

[n]T and []T are completely different things!

When using reflect []T is not of kind Array but of kind Slice and [n]T is of kind Array.

You also can't use map[[]byte]T but you can use map[[n]byte]T.

This can sometimes be cumbersome because a lot of functions operate for example on []byte whereas some functions return [n]byte (most notably the hash functions in crypto/*). A sha256 hash for example is [32]byte and not []byte so when beginners try to write it to a file for example:

sum := sha256.Sum256(data)
w.Write(sum)

they will get an error. The correct way of is to use

w.Write(sum[:])

However, what is it that you want? Just accessing the string bytewise? You can easily convert a string to []byte using:

bytes := []byte(str)

but this isn't an array, it's a slice. Also, byte != rune. In case you want to operate on "characters" you need to use rune... not byte.

Alternative to the HTML Bold tag

<b> is a last resort

You can use <b>, but only as a last resort. There are a variety of elements that work as good alternatives to <b>, here they are in order of most usefulness:

More useful alternatives

  • For important text: <strong>
  • For stress emphasized text: <em>
  • For headings, not just page headings but paragraph headings and others of all kinds: <h1> through <h6>

The practical edge case for use of <b>

The only case where I would advocate using <b> is if

  1. you have styled <strong> in a different way that you don't want displaying for the text that you have in mind,

  2. you don't want italic emphasis or a heading, and

  3. you are about to use an inline span or a span with a class just for bolding text. (For example: <span class='bold'>)

Then it's reasonable to use <b> instead, because in that case it'll probably be cleaner/shorter and more semantic than an unsemantic span, and terceness/readability is a good reason for making that choice, since b has been redefined for use as an element denoting printed emphasis.

Simulate user input in bash script

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

As @idleberg mentions, on Mac OS, it is best to install rbenv to avoid permissions errors when using manually installed ruby.

Installation

$ brew update
$ brew install rbenv

Add the following in .bashrc file:

eval "$(rbenv init -)"

Now, we can look at the list of ruby versions available for install

$ rbenv install -l

Install version 2.3.8 for example

$ rbenv install 2.3.8

Now we can use this ruby version globally

$ rbenv global 2.3.8

Finally run

$ rbenv rehash
$ which ruby
/Users/myuser/.rbenv/shims/ruby
$ ruby -v
ruby 2.3.7p456 (2018-03-28 revision 63024) [x86_64-darwin17]

Go for it

Now install bundler

$ gem install bundler

All done!

Spring @Value is not resolving to value from property file

Problem is due to problem in my applicationContext.xml vs spring-servlet.xml - it was scoping issue between the beans.

pedjaradenkovic kindly pointed me to an existing resource: Spring @Value annotation in @Controller class not evaluating to value inside properties file and Spring 3.0.5 doesn't evaluate @Value annotation from properties

SQLite - getting number of rows in a database

Extension of VolkerK's answer, to make code a little more readable, you can use AS to reference the count, example below:

SELECT COUNT(*) AS c from profile

This makes for much easier reading in some frameworks, for example, i'm using Exponent's (React Native) Sqlite integration, and without the AS statement, the code is pretty ugly.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

How does the Java 'for each' loop work?

The Java "for-each" loop construct will allow iteration over two types of objects:

  • T[] (arrays of any type)
  • java.lang.Iterable<T>

The Iterable<T> interface has only one method: Iterator<T> iterator(). This works on objects of type Collection<T> because the Collection<T> interface extends Iterable<T>.

NGINX - No input file specified. - php Fast/CGI

Simply restarting my php-fpm solved the issue. As i understand it's mostly a php-fpm issue than nginx.

How do I add one month to current date in Java?

Calendar cal = Calendar.getInstance(); 
cal.add(Calendar.MONTH, 1);
java.util.Date dt = cal.getTime();

How do I set up cron to run a file just once at a specific time?

Your comment suggests you're trying to call this from a programming language. If that's the case, can your program fork a child process that calls sleep then does the work?

What about having your program calculate the number of seconds until the desired runtime, and have it call shell_exec("sleep ${secondsToWait) ; myCommandToRun");

PHP String to Float

you can follow this link to know more about How to convert a string/number into number/float/decimal in PHP. HERE IS WHAT THIS LINK SAYS...

Method 1: Using number_format() Function. The number_format() function is used to convert a string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure.

$num = "1000.314"; 

//Convert string in number using  
//number_format(), function 
echo number_format($num), "\n"; 

//Convert string in number using  
//number_format(), function 
echo number_format($num, 2); 

Method 2: Using type casting: Typecasting can directly convert a string into a float, double, or integer primitive type. This is the best way to convert a string into a number without any function.

// Number in string format 
$num = "1000.314"; 

// Type cast using int 
echo (int)$num, "\n"; 

// Type cast using float 
echo (float)$num, "\n"; 

// Type cast using double 
echo (double)$num; 

Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively.

// Number in string format 
$num = "1000.314"; 

// intval() function to convert  
// string into integer 
echo intval($num), "\n"; 

// floatval() function to convert 
// string to float 
echo floatval($num); 

Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly.

// Number into string format 
$num = "1000.314"; 

// Performing mathematical operation  
// to implicitly type conversion 
echo $num + 0, "\n"; 

// Performing mathematical operation  
// to implicitly type conversion 
echo $num + 0.0, "\n"; 

// Performing mathematical operation  
// to implicitly type conversion 
echo $num + 0.1;

Unable to load DLL 'SQLite.Interop.dll'

I ran across this problem, in a solution with a WebAPI/MVC5 web project and a Feature Test project, that both drew off of the same data access (or, 'Core') project. I, like so many others here, am using a copy downloaded via NuGet in Visual Studio 2013.

What I did, was in Visual Studio added a x86 and x64 solution folder to the Feature Test and Web Projects. I then did a Right Click | Add Existing Item..., and added the appropriate SQLite.interop.dll library from ..\SolutionFolder\packages\System.Data.SQLite.Core.1.0.94.0\build\net451\[appropriate architecture] for each of those folders. I then did a Right Click | Properties, and set Copy to Output Directory to Always Copy. The next time I needed to run my feature tests, the tests ran successfully.

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

How to center body on a page?

You have to specify the width to the body for it to center on the page.

Or put all the content in the div and center it.

<body>
    <div>
    jhfgdfjh
    </div>
</body>?

div {
    margin: 0px auto;
    width:400px;
}

?

SQL Server Regular expressions in T-SQL

If you are using SQL Server 2016 or above, you can use sp_execute_external_script along with R. It has functions for Regular Expression searches, such as grep and grepl.

Here's an example for email addresses. I'll query some "people" via the SQL Server database engine, pass the data for those people to R, let R decide which people have invalid email addresses, and have R pass back that subset of people to SQL Server. The "people" are from the [Application].[People] table in the [WideWorldImporters] sample database. They get passed to the R engine as a dataframe named InputDataSet. R uses the grepl function with the "not" operator (exclamation point!) to find which people have email addresses that don't match the RegEx string search pattern.

EXEC sp_execute_external_script 
 @language = N'R',
 @script = N' RegexWithR <- InputDataSet;
OutputDataSet <- RegexWithR[!grepl("([_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4}))", RegexWithR$EmailAddress), ];',
 @input_data_1 = N'SELECT PersonID, FullName, EmailAddress FROM Application.People'
 WITH RESULT SETS (([PersonID] INT, [FullName] NVARCHAR(50), [EmailAddress] NVARCHAR(256)))

Note that the appropriate features must be installed on the SQL Server host. For SQL Server 2016, it is called "SQL Server R Services". For SQL Server 2017, it was renamed to "SQL Server Machine Learning Services".

Closing Thoughts Microsoft's implementation of SQL (T-SQL) doesn't have native support for RegEx. This proposed solution may not be any more desirable to the OP than the use of a CLR stored procedure. But it does offer an additional way to approach the problem.

functional way to iterate over range (ES6/7)

ES7 Proposal

Warning: Unfortunately I believe most popular platforms have dropped support for comprehensions. See below for the well-supported ES6 method

You can always use something like:

[for (i of Array(7).keys()) i*i];

Running this code on Firefox:

[ 0, 1, 4, 9, 16, 25, 36 ]

This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.

This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:

var range = (u, l = 0) => [ for( i of Array(u - l).keys() ) i + l ]

Then you can do:

[for (i of range(5)) i*i] // 0, 1, 4, 9, 16, 25
[for (i of range(5,3)) i*i] // 9, 16, 25

ES6

A nice way to do this any of:

[...Array(7).keys()].map(i => i * i);
Array(7).fill().map((_,i) => i*i);
[...Array(7)].map((_,i) => i*i);

This will output:

[ 0, 1, 4, 9, 16, 25, 36 ]

How do you 'redo' changes after 'undo' with Emacs?

By default, redo in Emacs requires pressing C-g, then undo.

However it's possible use Emacs built-in undo to implement a redo command too.

The package undo-fu, uses Emacs built-in undo functionality to expose both undo and redo.

How to store Node.js deployment settings/configuration files?

Just use npm module config (more than 300000 downloads)

https://www.npmjs.com/package/config

Node-config organizes hierarchical configurations for your app deployments.

It lets you define a set of default parameters, and extend them for different deployment environments (development, qa, staging, production, etc.).

$ npm install config
$ mkdir config
$ vi config/default.json


{
      // Customer module configs
      "Customer": {
        "dbConfig": {
          "host": "localhost",
          "port": 5984,
          "dbName": "customers"
        },
        "credit": {
          "initialLimit": 100,
          // Set low for development
          "initialDays": 1
        }
      }
}



$ vi config/production.json

{
  "Customer": {
    "dbConfig": {
      "host": "prod-db-server"
    },
    "credit": {
      "initialDays": 30
    }
  }
}



$ vi index.js

var config = require('config');
//...
var dbConfig = config.get('Customer.dbConfig');
db.connect(dbConfig, ...);

if (config.has('optionalFeature.detail')) {
  var detail = config.get('optionalFeature.detail');
  //...
}


$ export NODE_ENV=production
$ node index.js

Check existence of directory and create if doesn't exist

Here's the simple check, and creates the dir if doesn't exists:

## Provide the dir name(i.e sub dir) that you want to create under main dir:
output_dir <- file.path(main_dir, sub_dir)

if (!dir.exists(output_dir)){
dir.create(output_dir)
} else {
    print("Dir already exists!")
}

Deny all, allow only one IP through htaccess

If you want to use mod_rewrite for access control you can use condition like user agent, http referrer, remote addr etc.

Example

RewriteCond %{REMOTE_ADDR} !=*.*.*.* #you ip address
RewriteRule ^$ - [F]

Refrences:

How to make a Div appear on top of everything else on the screen?

you should use position:fixed to make z-index values to apply to your div

How to insert default values in SQL table?

If your columns should not contain NULL values, you need to define the columns as NOT NULL as well, otherwise the passed in NULL will be used instead of the default and not produce an error.

If you don't pass in any value to these fields (which requires you to specify the fields that you do want to use), the defaults will be used:

INSERT INTO 
  table1 (field1, field3) 
VALUES   (5,10)

Changing Underline color

There's now a new css3 property for this: text-decoration-color

So you can now have text in one color and a text-decoration underline - in a different color... without needing an extra 'wrap' element

_x000D_
_x000D_
p {_x000D_
  text-decoration: underline;_x000D_
  -webkit-text-decoration-color: red; /* safari still uses vendor prefix */_x000D_
  text-decoration-color: red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
_x000D_
_x000D_

Codepen

NB:

1) Browser Support is limited at the moment to Firefox and Chrome (fully supported as of V57) and Safari

2) You could also use the text-decoration shorthand property which looks like this:

<text-decoration-line> || <text-decoration-style> || <text-decoration-color>

...so using the text-decoration shorthand - the example above would simply be:

p {
  text-decoration: underline red;
}

_x000D_
_x000D_
p {_x000D_
  text-decoration: underline red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
_x000D_
_x000D_

JavaScript checking for null vs. undefined and difference between == and ===

If your (logical) check is for a negation (!) and you want to capture both JS null and undefined (as different Browsers will give you different results) you would use the less restrictive comparison: e.g.:

var ItemID = Item.get_id();
if (ItemID != null)
{
 //do stuff
}

This will capture both null and undefined

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

You don't need to prevent this error message!
Error messages are your friends!
Without error message you'd never know what is happened.
It's all right! Any working code supposed to throw out error messages.

Though error messages needs proper handling. Usually you don't have to to take any special actions to avoid such an error messages. Just leave your code intact. But if you don't want this error message to be shown to the user, just turn it off. Not error message itself but daislaying it to the user.

ini_set('display_errors',0);
ini_set('log_errors',1);

or even better at .htaccess/php.ini level
And user will never see any error messages. While you will be able still see it in the error log.
Please note that error_reporting should be at max in both cases.

To prevent this message you can check mysql_query result and run fetch_assoc only on success.
But usually nobody uses it as it may require too many nested if's.
But there can be solution too - exceptions!

But it is still not necessary. You can leave your code as is, because it is supposed to work without errors when done.

Using return is another method to avoid nested error messages. Here is a snippet from my database handling function:

  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbget: ".mysql_error()." in ".$query);
    return false;
  }
  if (!mysql_num_rows($res)) return NULL;

  //fetching goes here
  //if there was no errors only

Detect and exclude outliers in Pandas data frame

If you like method chaining, you can get your boolean condition for all numeric columns like this:

df.sub(df.mean()).div(df.std()).abs().lt(3)

Each value of each column will be converted to True/False based on whether its less than three standard deviations away from the mean or not.

VBA collection: list of keys

You can snoop around in your memory using RTLMoveMemory and retrieve the desired information directly from there:

32-Bit:

Option Explicit

'Provide direct memory access:
Public Declare Sub MemCopy Lib "kernel32" Alias "RtlMoveMemory" ( _
    ByVal Destination As Long, _
    ByVal Source As Long, _
    ByVal Length As Long)


Function CollectionKeys(oColl As Collection) As String()

    'Declare Pointer- / Memory-Address-Variables
    Dim CollPtr As Long
    Dim KeyPtr As Long
    Dim ItemPtr As Long

    'Get MemoryAddress of Collection Object
    CollPtr = VBA.ObjPtr(oColl)

    'Peek ElementCount
    Dim ElementCount As Long
    ElementCount = PeekLong(CollPtr + 16)

        'Verify ElementCount
        If ElementCount <> oColl.Count Then
            'Something's wrong!
            Stop
        End If

    'Declare Simple Counter
    Dim index As Long

    'Declare Temporary Array to hold our keys
    Dim Temp() As String
    ReDim Temp(ElementCount)

    'Get MemoryAddress of first CollectionItem
    ItemPtr = PeekLong(CollPtr + 24)

    'Loop through all CollectionItems in Chain
    While Not ItemPtr = 0 And index < ElementCount

        'increment Index
        index = index + 1

        'Get MemoryAddress of Element-Key
        KeyPtr = PeekLong(ItemPtr + 16)

        'Peek Key and add to temporary array (if present)
        If KeyPtr <> 0 Then
           Temp(index) = PeekBSTR(KeyPtr)
        End If

        'Get MemoryAddress of next Element in Chain
        ItemPtr = PeekLong(ItemPtr + 24)

    Wend

    'Assign temporary array as Return-Value
    CollectionKeys = Temp

End Function


'Peek Long from given MemoryAddress
Public Function PeekLong(Address As Long) As Long

  If Address = 0 Then Stop
  Call MemCopy(VBA.VarPtr(PeekLong), Address, 4&)

End Function

'Peek String from given MemoryAddress
Public Function PeekBSTR(Address As Long) As String

    Dim Length As Long

    If Address = 0 Then Stop
    Length = PeekLong(Address - 4)

    PeekBSTR = Space(Length \ 2)
    Call MemCopy(VBA.StrPtr(PeekBSTR), Address, Length)

End Function

64-Bit:

Option Explicit

'Provide direct memory access:
Public Declare PtrSafe Sub MemCopy Lib "kernel32" Alias "RtlMoveMemory" ( _
     ByVal Destination As LongPtr, _
     ByVal Source As LongPtr, _
     ByVal Length As LongPtr)



Function CollectionKeys(oColl As Collection) As String()

    'Declare Pointer- / Memory-Address-Variables
    Dim CollPtr As LongPtr
    Dim KeyPtr As LongPtr
    Dim ItemPtr As LongPtr

    'Get MemoryAddress of Collection Object
    CollPtr = VBA.ObjPtr(oColl)

    'Peek ElementCount
    Dim ElementCount As Long
    ElementCount = PeekLong(CollPtr + 28)

        'Verify ElementCount
        If ElementCount <> oColl.Count Then
            'Something's wrong!
            Stop
        End If

    'Declare Simple Counter
    Dim index As Long

    'Declare Temporary Array to hold our keys
    Dim Temp() As String
    ReDim Temp(ElementCount)

    'Get MemoryAddress of first CollectionItem
    ItemPtr = PeekLongLong(CollPtr + 40)

    'Loop through all CollectionItems in Chain
    While Not ItemPtr = 0 And index < ElementCount

        'increment Index
        index = index + 1

        'Get MemoryAddress of Element-Key
        KeyPtr = PeekLongLong(ItemPtr + 24)

        'Peek Key and add to temporary array (if present)
        If KeyPtr <> 0 Then
           Temp(index) = PeekBSTR(KeyPtr)
        End If

        'Get MemoryAddress of next Element in Chain
        ItemPtr = PeekLongLong(ItemPtr + 40)

    Wend

    'Assign temporary array as Return-Value
    CollectionKeys = Temp

End Function


'Peek Long from given Memory-Address
Public Function PeekLong(Address As LongPtr) As Long

  If Address = 0 Then Stop
  Call MemCopy(VBA.VarPtr(PeekLong), Address, 4^)

End Function

'Peek LongLong from given Memory Address
Public Function PeekLongLong(Address As LongPtr) As LongLong

  If Address = 0 Then Stop
  Call MemCopy(VBA.VarPtr(PeekLongLong), Address, 8^)

End Function

'Peek String from given MemoryAddress
Public Function PeekBSTR(Address As LongPtr) As String

    Dim Length As Long

    If Address = 0 Then Stop
    Length = PeekLong(Address - 4)

    PeekBSTR = Space(Length \ 2)
    Call MemCopy(VBA.StrPtr(PeekBSTR), Address, CLngLng(Length))

End Function

Creating SolidColorBrush from hex color value

If you don't want to deal with the pain of the conversion every time simply create an extension method.

public static class Extensions
{
    public static SolidColorBrush ToBrush(this string HexColorString)
    {
        return (SolidColorBrush)(new BrushConverter().ConvertFrom(HexColorString));
    }    
}

Then use like this: BackColor = "#FFADD8E6".ToBrush()

Alternately if you could provide a method to do the same thing.

public SolidColorBrush BrushFromHex(string hexColorString)
{
    return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexColorString));
}

BackColor = BrushFromHex("#FFADD8E6");

How to show/hide if variable is null

<div ng-hide="myvar == null"></div>

or

<div ng-show="myvar != null"></div>

How to automatically insert a blank row after a group of data

  1. Insert a column at the left of the table 'Control'
  2. Number the data as 1 to 1000 (assuming there are 1000 rows)
  3. Copy the key field to another sheet and remove duplicates
  4. Copy the unique row items to the main sheet, after 1000th record
  5. In the 'Control' column, add number 1001 to all unique records
  6. Sort the data (including the added records), first on key field and then on 'Control'
  7. A blank line (with data in key field and 'Control') is added

React-router urls don't work when refreshing or writing manually

Its pretty simple when you got cannot get 403 error after refresh dom component. just add this one line in your web pack config, 'historyApiFallback: true '. this savez my whole day.

Aligning textviews on the left and right edges in Android layout

Dave Webb's answer did work for me. Thanks! Here my code, hope this helps someone!

<RelativeLayout
    android:background="#FFFFFF"
    android:layout_width="match_parent"
    android:minHeight="30dp"
    android:layout_height="wrap_content">
    <TextView
        android:height="25dp"
        android:layout_width="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="ABA Type"
        android:padding="3dip"
        android:layout_gravity="center_vertical"
        android:gravity="left|center_vertical"
        android:layout_height="match_parent" />
    <TextView
        android:background="@color/blue"
        android:minWidth="30px"
        android:minHeight="30px"
        android:layout_column="1"
        android:id="@+id/txtABAType"
        android:singleLine="false"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="20dp"
        android:layout_width="wrap_content" />
</RelativeLayout>

Image: Image

Calculating a directory's size using Python?

It is handy:

import os
import stat

size = 0
path_ = ""
def calculate(path=os.environ["SYSTEMROOT"]):
    global size, path_
    size = 0
    path_ = path

    for x, y, z in os.walk(path):
        for i in z:
            size += os.path.getsize(x + os.sep + i)

def cevir(x):
    global path_
    print(path_, x, "Byte")
    print(path_, x/1024, "Kilobyte")
    print(path_, x/1048576, "Megabyte")
    print(path_, x/1073741824, "Gigabyte")

calculate("C:\Users\Jundullah\Desktop")
cevir(size)

Output:
C:\Users\Jundullah\Desktop 87874712211 Byte
C:\Users\Jundullah\Desktop 85815148.64355469 Kilobyte
C:\Users\Jundullah\Desktop 83803.85609722137 Megabyte
C:\Users\Jundullah\Desktop 81.83970321994275 Gigabyte

Tree implementation in Java (root, parents and children)

In answer ,it creates circular dependency.This can be avoided by removing parent inside Child nodes. i.e,

public class MyTreeNode<T>{     


    private T data = null;
    private List<MyTreeNode> children = new ArrayList<>();


    public MyTreeNode(T data) {
        this.data = data;

    }

    public void addChild(MyTreeNode child) {
        this.children.add(child);
    }

    public void addChild(T data) {
        MyTreeNode<T> newChild = new MyTreeNode<>(data);
        children.add(newChild);
    }

    public void addChildren(List<MyTreeNode> children) {
        this.children.addAll(children);
    }

    public List<MyTreeNode> getChildren() {
        return children;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }


}

Using the same example specified above,the output will be like this:

{ "data": "Root", "children": [ { "data": "Child1", "children": [ { "data": "Grandchild1", "children": [] }, { "data": "Grandchild2", "children": [] } ] }, { "data": "Child2", "children": [ { "data": "Grandchild3", "children": [] } ] }, { "data": "Child3", "children": [] }, { "data": "Child4", "children": [] }, { "data": "Child5", "children": [] }, { "data": "Child6", "children": [] } ] }

HttpWebRequest using Basic authentication

I finally got it!

string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
WebRequest request = WebRequest.Create(url);
request.Credentials = GetCredential();
request.PreAuthenticate = true;

and this is GetCredential()

private CredentialCache GetCredential()
{
    string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
    CredentialCache credentialCache = new CredentialCache();
    credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["ead_username"], ConfigurationManager.AppSettings["ead_password"]));
    return credentialCache;
}

YAY!

PHP Composer behind http proxy

Try this:

export HTTPS_PROXY_REQUEST_FULLURI=false

solved this issue for me working behind a proxy at a company few weeks ago.

Force “landscape” orientation mode

I use some css like this (based on css tricks):

@media screen and (min-width: 320px) and (max-width: 767px) and (orientation: portrait) {
  html {
    transform: rotate(-90deg);
    transform-origin: left top;
    width: 100vh;
    height: 100vw;
    overflow-x: hidden;
    position: absolute;
    top: 100%;
    left: 0;
  }
}

How to create <input type=“text”/> dynamically

You could do something like this in a loop based on the number of text fields they enter.

$('<input/>').attr({type:'text',name:'text'+i}).appendTo('#myform');

But for better performance I'd create all the html first and inject it into the DOM only once.

var count = 20;
var html = [];
while(count--) {
  html.push("<input type='text' name='name", count, "'>");
}
$('#myform').append(html.join(''));

Edit this example uses jQuery to append the html, but you could easily modify it to use innerHTML as well.

Location for session files in Apache/PHP

I believe its in /tmp/. Check your phpinfo function though, it should say session.save_path in there somewhere.

Disable arrow key scrolling in users browser

Summary

Simply prevent the default browser action:

window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if([32, 37, 38, 39, 40].indexOf(e.code) > -1) {
        e.preventDefault();
    }
}, false);

If you need to support Internet Explorer or other older browsers, use e.keyCode instead of e.code, but keep in mind that keyCode is deprecated.

Original answer

I used the following function in my own game:

var keys = {};
window.addEventListener("keydown",
    function(e){
        keys[e.code] = true;
        switch(e.code){
            case 37: case 39: case 38:  case 40: // Arrow keys
            case 32: e.preventDefault(); break; // Space
            default: break; // do not block other keys
        }
    },
false);
window.addEventListener('keyup',
    function(e){
        keys[e.code] = false;
    },
false);

The magic happens in e.preventDefault();. This will block the default action of the event, in this case moving the viewpoint of the browser.

If you don't need the current button states you can simply drop keys and just discard the default action on the arrow keys:

var arrow_keys_handler = function(e) {
    switch(e.code){
        case 37: case 39: case 38:  case 40: // Arrow keys
        case 32: e.preventDefault(); break; // Space
        default: break; // do not block other keys
    }
};
window.addEventListener("keydown", arrow_keys_handler, false);

Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:

window.removeEventListener("keydown", arrow_keys_handler, false);

References

How can I get a JavaScript stack trace when I throw an exception?

This will give a stack trace (as array of strings) for modern Chrome, Opera, Firefox and IE10+

function getStackTrace () {

  var stack;

  try {
    throw new Error('');
  }
  catch (error) {
    stack = error.stack || '';
  }

  stack = stack.split('\n').map(function (line) { return line.trim(); });
  return stack.splice(stack[0] == 'Error' ? 2 : 1);
}

Usage:

console.log(getStackTrace().join('\n'));

It excludes from the stack its own call as well as title "Error" that is used by Chrome and Firefox (but not IE).

It shouldn't crash on older browsers but just return empty array. If you need more universal solution look at stacktrace.js. Its list of supported browsers is really impressive but to my mind it is very big for that small task it is intended for: 37Kb of minified text including all dependencies.

Django: TemplateSyntaxError: Could not parse the remainder

also happens when you use jinja templates (which have different syntax for calling object methods) and you forget to set it in settings.py

getMinutes() 0-9 - How to display two digit numbers?

I usually use this piece of code :

var start = new Date(timestamp),
    startMinutes = start.getMinutes() < 10 ? '0' + start.getMinutes() : start.getMinutes();

It is quite similar to the @ogur accepted answer but does not concatenate an empty string in the case that 0 is not needed. Not sure it is better. Just an other way to do it !

ViewBag, ViewData and TempData

void Keep()

Calling this method with in the current action ensures that all the items in TempData are not removed at the end of the current request.

    @model MyProject.Models.EmpModel;
    @{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "About";
    var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
    TempData.Keep(); // retains all strings values
    } 

void Keep(string key)

Calling this method with in the current action ensures that specific item in TempData is not removed at the end of the current request.

    @model MyProject.Models.EmpModel;
    @{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "About";
    var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
    TempData.Keep("emp"); // retains only "emp" string values
    } 

How to get the primary IP address of the local machine on Linux and OS X?

This works on Linux and OSX

This will get the interface associated to the default route

NET_IF=`netstat -rn | awk '/^0.0.0.0/ {thif=substr($0,74,10); print thif;} /^default.*UG/ {thif=substr($0,65,10); print thif;}'`

Using the interface discovered above, get the ip address.

NET_IP=`ifconfig ${NET_IF} | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'`

OSX

uname -a

Darwin laptop 14.4.0 Darwin Kernel Version 14.4.0: Thu May 28 11:35:04 PDT 2015; root:xnu-2782.30.5~1/RELEASE_X86_64 x86_64

echo $NET_IF

en5

echo $NET_IP

192.168.0.130

CentOS Linux

uname -a

Linux dev-cil.medfx.local 2.6.18-164.el5xen 1 SMP Thu Sep 3 04:03:03 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux

echo $NET_IF

eth0

echo $NET_IP

192.168.46.10

Pandas read_csv from url

url = "https://github.com/cs109/2014_data/blob/master/countries.csv"
c = pd.read_csv(url, sep = "\t")

What is the reason for a red exclamation mark next to my project in Eclipse?

There can be several reasons. Most of the times it may be some of the below reasons ,

  1. You have deleted some of the .jar files from your /lib folder
  2. You have added new .jar files
  3. you have added new .jar files which may be conflict with others

So what to do is we have to resolve those missing / updating / newly_added jar files.

  1. right click on the project and go to properties
  2. Select Java Build Path
  3. go to the Libraries tab
  4. Remove the references of the jar files which you have removed already. There will be a red mark near them so you can identify them easily.
  5. Add the references to the newly added .jar files by using Add JARs
  6. Refresh the project

This will solve the problem if it's because one of the above reasons.

Bitbucket git credentials if signed up with Google

You should do a one-time setup of creating an "App password" in Bitbucket web UI with permissions to at least read your repositories and then use it in the command line.

How-to:

  1. Login to Bitbucket
  2. Click on your profile image on the right (now on the bottom left)
  3. Choose Bitbucket settings (now Personal settings)
  4. Under Access management section look for the App passwords option (https://bitbucket.org/account/settings/app-passwords/)
  5. Create an app password with permissions at least to Read under Repositories section. A password will be generated for you. Remember to save it, it will be shown only once!
  6. The username will be your Google username.

Using underscores in Java variables and method names

Here's a link to Sun's recommendations for Java. Not that you have to use these or even that their library code follows all of them, but it's a good start if you're going from scratch. Tool like Eclipse have built in formatters and cleanup tools that can help you conform to these conventions (or others that you define).

For me, '_' are too hard to type :)

phpMyAdmin - Error > Incorrect format parameter?

This error is caused by the fact that the maximum upload size is (Max: 2,048KiB). If your file is bigger than this, you will get an error. Zip the file and upload it again, you will not get the error.

SyntaxError: multiple statements found while compiling a single statement

In the shell, you can't execute more than one statement at a time:

>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement

You need to execute them one by one:

>>> x = 5
>>> y = 6
>>>

When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.

Split page vertically using CSS

Here is the flex-box approach:

CSS

 .parent {
  display:flex;
  height:100vh;
  }
  .child{
    flex-grow:1;
  }
  .left{
    background:#ddd;
  }
  .center{
    background:#666;
  }

  .right{
    background:#999;
  }

HTML

<div class="parent">
    <div class="child left">Left</div>
    <div class="child center">Center</div>
    <div class="child right">Right</div>
</div>

You can try the same in js fiddle.

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

You might use one of our plugins: the JQL enhancement functions - check out https://plugins.atlassian.com/plugin/details/22514

There is no interval on day, but we might add it in a next iteration, if you think it is usefull.

Francis.

How to convert byte array to string and vice versa?

While base64 encoding is safe and one could argue "the right answer", I arrived here looking for a way to convert a Java byte array to/from a Java String as-is. That is, where each member of the byte array remains intact in its String counterpart, with no extra space required for encoding/transport.

This answer describing 8bit transparent encodings was very helpful for me. I used ISO-8859-1 on terabytes of binary data to convert back and forth successfully (binary <-> String) without the inflated space requirements needed for a base64 encoding, so is safe for my use-case - YMMV.

This was also helpful in explaining when/if you should experiment.

How do you get a query string on Flask?

If the request if GET and we passed some query parameters then,

fro`enter code here`m flask import request
@app.route('/')
@app.route('/data')
def data():
   if request.method == 'GET':
      # Get the parameters by key
      arg1 = request.args.get('arg1')
      arg2 = request.args.get('arg2')
      # Generate the query string
      query_string="?arg1={0}&arg2={1}".format(arg1, arg2)
      return render_template("data.html", query_string=query_string)

History or log of commands executed in Git

I found out that in my version of git bash "2.24.0.windows.2" in my "home" folder under windows users, there will be a file called ".bash-history" with no file extension in that folder. It's only created after you exit from bash.

Here's my workflow:

  1. before exiting bash type "history >> history.txt" [ENTER]
  2. exit the bash prompt
  3. hold Win+R to open the Run command box
  4. enter shell:profile
  5. open "history.txt" to confirm that my text was added
  6. On a new line press [F5] to enter a timestamp
  7. save and close the history textfile
  8. Delete the ".bash-history" file so the next session will create a new history

If you really want points I guess you could make a batch file to do all this but this is good enough for me. Hope it helps someone.

IllegalArgumentException or NullPointerException for a null parameter?

As a subjective question this should be closed, but as it's still open:

This is part of the internal policy used at my previous place of employment and it worked really well. This is all from memory so I can't remember the exact wording. It's worth noting that they did not use checked exceptions, but that is beyond the scope of the question. The unchecked exceptions they did use fell into 3 main categories.

NullPointerException: Do not throw intentionally. NPEs are to be thrown only by the VM when dereferencing a null reference. All possible effort is to be made to ensure that these are never thrown. @Nullable and @NotNull should be used in conjunction with code analysis tools to find these errors.

IllegalArgumentException: Thrown when an argument to a function does not conform to the public documentation, such that the error can be identified and described in terms of the arguments passed in. The OP's situation would fall into this category.

IllegalStateException: Thrown when a function is called and its arguments are either unexpected at the time they are passed or incompatible with the state of the object the method is a member of.

For example, there were two internal versions of the IndexOutOfBoundsException used in things that had a length. One a sub-class of IllegalStateException, used if the index was larger than the length. The other a subclass of IllegalArgumentException, used if the index was negative. This was because you could add more items to the object and the argument would be valid, while a negative number is never valid.

As I said, this system works really well, and it took someone to explain why the distinction is there: "Depending on the type of error it is quite straightforward for you to figure out what to do. Even if you can't actually figure out what went wrong you can figure out where to catch that error and create additional debugging information."

NullPointerException: Handle the Null case or put in an assertion so that the NPE is not thrown. If you put in an assertion is just one of the other two types. If possible, continue debugging as if the assertion was there in the first place.

IllegalArgumentException: you have something wrong at your call site. If the values being passed in are from another function, find out why you are receiving an incorrect value. If you are passing in one of your arguments propagate the error checks up the call stack until you find the function that is not returning what you expect.

IllegalStateException: You have not called your functions in the correct order. If you are using one of your arguments, check them and throw an IllegalArgumentException describing the issue. You can then propagate the cheeks up against the stack until you find the issue.

Anyway, his point was that you can only copy the IllegalArgumentAssertions up the stack. There is no way for you to propagate the IllegalStateExceptions or NullPointerExceptions up the stack because they had something to do with your function.

c# foreach (property in object)... Is there a simple way of doing this?

Use Reflection to do this

SomeClass A = SomeClass(...)
PropertyInfo[] properties = A.GetType().GetProperties();

Sending HTTP POST with System.Net.WebClient

WebClient doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using

How do I convert a Django QuerySet into list of dicts?

If you need native data types for some reason (e.g. JSON serialization) this is my quick 'n' dirty way to do it:

data = [{'id': blog.pk, 'name': blog.name} for blog in blogs]

As you can see building the dict inside the list is not really DRY so if somebody knows a better way ...

Creation timestamp and last update timestamp with Hibernate and MySQL

You can just use @CreationTimestamp and @UpdateTimestamp:

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_date")
private Date createDate;

@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modify_date")
private Date modifyDate;

In which case do you use the JPA @JoinTable annotation?

It lets you handle Many to Many relationship. Example:

Table 1: post

post has following columns
____________________
|  ID     |  DATE   |
|_________|_________|
|         |         |
|_________|_________|

Table 2: user

user has the following columns:

____________________
|     ID  |NAME     |
|_________|_________|
|         |         |
|_________|_________|

Join Table lets you create a mapping using:

@JoinTable(
  name="USER_POST",
  joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="ID"),
  inverseJoinColumns=@JoinColumn(name="POST_ID", referencedColumnName="ID"))

will create a table:

____________________
|  USER_ID| POST_ID |
|_________|_________|
|         |         |
|_________|_________|

How to remove an element from an array in Swift

For Swift4:

list = list.filter{$0 != "your Value"}

How to reset Jenkins security settings from the command line?

step-1 : go to the directory cd .jenkins/secrets then you will get a 'initialAdminPassword'.

step-2 : nano initialAdminPassword

you will get a password

Argparse optional positional arguments?

Use nargs='?' (or nargs='*' if you need more than one dir)

parser.add_argument('dir', nargs='?', default=os.getcwd())

extended example:

>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]

positional arguments:
  dir

optional arguments:
  -h, --help  show this help message and exit
  -v

How do I get a Date without time in Java?

Prefer not to use third-party libraries as much as possible. I know that this way is mentioned before, but here is a nice clean way:

  /*
    Return values:
    -1:    Date1 < Date2
     0:    Date1 == Date2
     1:    Date1 > Date2

    -2:    Error
*/
public int compareDates(Date date1, Date date2)
{
    SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");

    try
    {
        date1 = sdf.parse(sdf.format(date1));
        date2 = sdf.parse(sdf.format(date2));
    }
    catch (ParseException e) {
        e.printStackTrace();
        return -2;
    }

    Calendar cal1 = new GregorianCalendar();
    Calendar cal2 = new GregorianCalendar();

    cal1.setTime(date1);
    cal2.setTime(date2);

    if(cal1.equals(cal2))
    {
        return 0;
    }
    else if(cal1.after(cal2))
    {
        return 1;
    }
    else if(cal1.before(cal2))
    {
        return -1;
    }

    return -2;
}

Well, not using GregorianCalendar is maybe an option!

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

I love jQuery's method chaining. Simply do...

    var value = $("#text").val().replace('.',':');

    //Or if you want to return the value:
    return $("#text").val().replace('.',':');

Writing MemoryStream to Response Object

I tried all variants of end, close, flush, and System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest() and none of them worked.

Then I added the content length to the header: Response.AddHeader("Content-Length", asset.File_Size.ToString());

In this example asset is a class that has a Int32 called File_Size

This worked for me and nothing else did.

How to import spring-config.xml of one project into spring-config.xml of another project?

<import resource="classpath*:spring-config.xml" /> 

This is the most suitable one for class path configuration. Particularly when you are searching for the .xml files in a different project which is in your class path.

HTML-Tooltip position relative to mouse pointer

We can achieve the same using "Directive" in Angularjs.

            //Bind mousemove event to the element which will show tooltip
            $("#tooltip").mousemove(function(e) {
                //find X & Y coodrinates
                x = e.clientX,
                y = e.clientY;

                //Set tooltip position according to mouse position
                tooltipSpan.style.top = (y + 20) + 'px';
                tooltipSpan.style.left = (x + 20) + 'px';
            });

You can check this post for further details. http://www.ufthelp.com/2014/12/Tooltip-Directive-AngularJS.html

How do I fix the indentation of an entire file in Vi?

You can use tidy application/utility to indent HTML & XML files and it works pretty well in indenting those files.

Prettify an XML file

:!tidy -mi -xml %

Prettify an HTML file

:!tidy -mi -html %

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

The easiest way is to change imdb.py setting allow_pickle=True to np.load at the line where imdb.py throws error.

Convert array values from string to int?

Keep it simple...

$intArray = array ();
$strArray = explode(',', $string);
foreach ($strArray as $value)
$intArray [] = intval ($value);

Why are you looking for other ways? Looping does the job without pain. If performance is your concern, you can go with json_decode (). People have posted how to use that, so I am not including it here.

Note: When using == operator instead of === , your string values are automatically converted into numbers (e.g. integer or double) if they form a valid number without quotes. For example:

$str = '1';
($str == 1) // true but
($str === 1) //false

Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.

how to display a div triggered by onclick event

You'll have to give an ID to the div you want to show/hide, then use this code:

html:

<div id="one">
    <div id="tow">
        This is text
    </div>
    <button onclick="javascript:showDiv();">Click to show div</button>
</div>

javascript:

function showDiv() {
    div = document.getElementById('tow');
    div.style.display = "block";
}

CSS:

?#tow { display: none; }?

Fiddle: http://jsfiddle.net/xkdNa/

C/C++ line number

C++20 offers a new way to achieve this by using std::source_location. This is currently accessible in gcc an clang as std::experimental::source_location with #include <experimental/source_location>.

The problem with macros like __LINE__ is that if you want to create for example a logging function that outputs the current line number along with a message, you always have to pass __LINE__ as a function argument, because it is expanded at the call site. Something like this:

void log(const std::string msg) {
    std::cout << __LINE__ << " " << msg << std::endl;
}

Will always output the line of the function declaration and not the line where log was actually called from. On the other hand, with std::source_location you can write something like this:

#include <experimental/source_location>
using std::experimental::source_location;

void log(const std::string msg, const source_location loc = source_location::current())
{
    std::cout << loc.line() << " " << msg << std::endl;
}

Here, loc is initialized with the line number pointing to the location where log was called. You can try it online here.

Property 'catch' does not exist on type 'Observable<any>'

With RxJS 5.5+, the catch operator is now deprecated. You should now use the catchError operator in conjunction with pipe.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including catchError you should now import from 'rxjs/operators' and use the pipe operator.

Example of catching error for an Http request Observable

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.request(method, url, options).pipe(
      catchError((err: HttpErrorResponse) => {
        ...
      }
    )
  }
  ...
}

Notice here that catch is replaced with catchError and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.


See the rxjs documentation on pipable (previously known as lettable) operators for more info.

get index of DataTable column with name

I wrote an extension method of DataRow which gets me the object via the column name.

public static object Column(this DataRow source, string columnName)
{
    var c = source.Table.Columns[columnName];
    if (c != null)
    {
        return source.ItemArray[c.Ordinal];
    }

    throw new ObjectNotFoundException(string.Format("The column '{0}' was not found in this table", columnName));
}

And its called like this:

DataTable data = LoadDataTable();
foreach (DataRow row in data.Rows)
{        
    var obj = row.Column("YourColumnName");
    Console.WriteLine(obj);
}

How do I get a button to open another activity?

If you declared your button in the xml file similar to this:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="next activity"
        android:onClick="goToActivity2"
        />

then you can use it to change the activity by putting this at the java file:

public void goToActivity2 (View view){
    Intent intent = new Intent (this, Main2Activity.class);
    startActivity(intent);
}

Note that my second activity is called "Main2Activity"

Django DoesNotExist

I have found the solution to this issue using ObjectDoesNotExist on this way

from django.core.exceptions import ObjectDoesNotExist
......

try:
  # try something
except ObjectDoesNotExist:
  # do something

After this, my code works as I need

Thanks any way, your post help me to solve my issue

How to delete empty folders using windows command prompt?

If you want to use Varun's ROBOCOPY command line in the Explorer context menu (i.e. right-click) here is a Windows registry import. I tried adding this as a comment to his answer, but the inline markup wasn't feasible.

I've tested this on my own Windows 10 PC, but use at your own risk. It will open a new command prompt, run the command, and pause so you can see the output.

  1. Copy into a new text file:

    Windows Registry Editor Version 5.00

    [HKEY_CURRENT_USER\Software\Classes\directory\Background\shell\Delete Empty Folders\command] @="C:\Windows\System32\Cmd.exe /C \"C:\Windows\System32\Robocopy.exe \"%V\" \"%V\" /s /move\" && PAUSE"

    [HKEY_CURRENT_USER\Software\Classes\directory\shell\Delete Empty Folders\command] @="C:\Windows\System32\Cmd.exe /C \"C:\Windows\System32\Robocopy.exe \"%V\" \"%V\" /s /move\" && PAUSE"

  2. Rename the .txt extension to .reg

  3. Double click to import.

MISCONF Redis is configured to save RDB snapshots

in case you are working on a linux machine, also recheck the file and folder permissions of the database.

The db and the path to it can be obtained via:

in redis-cli:

CONFIG GET dir

CONFIG GET dbfilename

and in the commandline ls -l. The permissions for the directory should be 755, and those for the file should be 644. Also, normally redis-server executes as the user redis, therefore its also nice to give the user redis the ownership of the folder by executing sudo chown -R redis:redis /path/to/rdb/folder. This has been elaborated in the answer here.

Error: No module named psycopg2.extensions

I installed it successfully using these commands:

sudo apt-get install libpq-dev python-dev
pip install psycopg2

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

This is specific for each site. So if you type that once, you will only get through that site and all other sites will need a similar type-through.

It is also remembered for that site and you have to click on the padlock to reset it (so you can type it again):

enter image description here

Needless to say use of this "feature" is a bad idea and is unsafe - hence the name.

You should find out why the site is showing the error and/or stop using it until they fix it. HSTS specifically adds protections for bad certs to prevent you clicking through them. The fact it's needed suggests there is something wrong with the https connection - like the site or your connection to it has been hacked.

The chrome developers also do change this periodically. They changed it recently from badidea to thisisunsafe so everyone using badidea, suddenly stopped being able to use it. You should not depend on it. As Steffen pointed out in the comments below, it is available in the code should it change again though they now base64 encode it to make it more obscure. The last time they changed they put this comment in the commit:

Rotate the interstitial bypass keyword

The security interstitial bypass keyword hasn't changed in two years and awareness of the bypass has been increased in blogs and social media. Rotate the keyword to help prevent misuse.

I think the message from the Chrome team is clear - you should not use it. It would not surprise me if they removed it completely in future.

If you are using this when using a self-signed certificate for local testing then why not just add your self-signed certificate certificate to your computer's certificate store so you get a green padlock and do not have to type this? Note Chrome insists on a SAN field in certificates now so if just using the old subject field then even adding it to the certificate store will not result in a green padlock.

If you leave the certificate untrusted then certain things do not work. Caching for example is completely ignored for untrusted certificates. As is HTTP/2 Push.

HTTPS is here to stay and we need to get used to using it properly - and not bypassing the warnings with a hack that is liable to change and doesn't work the same as a full HTTPS solution.

ArrayBuffer to base64 encoded string

function _arrayBufferToBase64(uarr) {
    var strings = [], chunksize = 0xffff;
    var len = uarr.length;

    for (var i = 0; i * chunksize < len; i++){
        strings.push(String.fromCharCode.apply(null, uarr.subarray(i * chunksize, (i + 1) * chunksize)));
    }

    return strings.join("");
}

This is better, if you use JSZip for unpack archive from string

Correct modification of state arrays in React.js

Option one is using

this.setState(prevState => ({
  arrayvar: [...prevState.arrayvar, newelement]
}))

Option 2:

this.setState({ 
  arrayvar: this.state.arrayvar.concat([newelement])
})

Javascript to Select Multiple options

Based on @Peter Baley answer, I created a more generic function:

   @objectId: HTML object ID
   @values: can be a string or an array. String is less "secure" (should not contain repeated value).
   function checkMultiValues(objectId, values){
        selectMultiObject=document.getElementById(objectId);
        for ( var i = 0, l = selectMultiObject.options.length, o; i < l; i++ )
        {
          o = selectMultiObject.options[i];
          if ( values.indexOf( o.value ) != -1 )
          {
            o.selected = true;
          } else {
            o.selected = false;
          }
        }
    }

Example: checkMultiValues('thisMultiHTMLObject','a,b,c,d');

How to find a value in an array of objects in JavaScript?

If You want to find a specific object via search function just try something like this:

    function findArray(value){

        let countLayer = dataLayer.length;
        for(var x = 0 ; x < countLayer ; x++){

            if(dataLayer[x].user){
                let newArr = dataLayer[x].user;
                let data = newArr[value];
                return data;
            }

        }

        return null;

    }

    findArray("id");

This is an example object:

layerObj = {
    0: { gtm.start :1232542, event: "gtm.js"},
    1: { event: "gtm.dom", gtm.uniqueEventId: 52},
    2: { visitor id: "abcdef2345"},
    3: { user: { id: "29857239", verified: "Null", user_profile: "Personal", billing_subscription: "True", partners_user: "adobe"}
}

Code will iterate and find the "user" array and will search for the object You seek inside.

My problem was when the array index changed every window refresh and it was either in 3rd or second array, but it does not matter.

Worked like a charm for Me!

In Your example it is a bit shorter:

function findArray(value){

    let countLayer = Object.length;
    for(var x = 0 ; x < countLayer ; x++){

        if(Object[x].dinner === value){
            return Object[x];
        }

    }

    return null;

}

findArray('sushi');

Bootstrap select dropdown list placeholder

<option value="" defaultValue disabled> Something </option>

you can replace defaultValue with selected but that would give warning.

Embed image in a <button> element

Add new folder with name of Images in your project. Put some images into Images folder. Then it will work fine.

<input type="image" src="~/Images/Desert.jpg" alt="Submit" width="48" height="48">

Remove empty lines in a text file via grep

Simplest Answer -----------------------------------------

[root@node1 ~]# cat /etc/sudoers | grep -v -e ^# -e ^$
Defaults   !visiblepw
Defaults    always_set_home
Defaults    match_group_by_gid
Defaults    always_query_group_plugin
Defaults    env_reset
Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
Defaults    env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults    env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults    env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults    env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin
root    ALL=(ALL)       ALL
%wheel  ALL=(ALL)       ALL
[root@node1 ~]#

How to remove decimal part from a number in C#

Use Math.Round

int d = (int) Math.Round(a, 0);

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

Answers suggesting to disable CURLOPT_SSL_VERIFYPEER should not be accepted. The question is "Why doesn't it work with cURL", and as correctly pointed out by Martijn Hols, it is dangerous.

The error is probably caused by not having an up-to-date bundle of CA root certificates. This is typically a text file with a bunch of cryptographic signatures that curl uses to verify a host’s SSL certificate.

You need to make sure that your installation of PHP has one of these files, and that it’s up to date (otherwise download one here: http://curl.haxx.se/docs/caextract.html).

Then set in php.ini:

curl.cainfo = <absolute_path_to> cacert.pem

If you are setting it at runtime, use:

curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");

changing the language of error message in required field in html5 contact form

_x000D_
_x000D_
<form>
  <input
    type="text"
    name="company_name"
    oninvalid="this.setCustomValidity('Lütfen isaretli yerleri doldurunuz')"
    required
  /><input type="submit" />
</form>
_x000D_
_x000D_
_x000D_

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

Open window in JavaScript with HTML inserted

I would not recomend you to use document.write as others suggest, because if you will open such window twice your HTML will be duplicated 2 times (or more).

Use innerHTML instead

var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";

What jsf component can render a div tag?

You can create a DIV component using the <h:panelGroup/>. By default, the <h:panelGroup/> will generate a SPAN in the HTML code.

However, if you specify layout="block", then the component will be a DIV in the generated HTML code.

<h:panelGroup layout="block"/>

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

it is very simple....

[in make file]

==== 1 ===================

OBJS = ....\

version.o <<== add to your obj lists

==== 2 ===================

DATE = $(shell date +'char szVersionStr[20] = "%Y-%m-%d %H:%M:%S";') <<== add

all:version $(ProgramID) <<== version add at first

version: <<== add

echo '$(DATE)' > version.c  <== add ( create version.c file)

[in program]

=====3 =============

extern char szVersionStr[20];

[ using ]

=== 4 ====

printf( "Version: %s\n", szVersionStr );

Example on ToggleButton

Move this

 btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
     editString = ed.getText().toString();

inside onClick

Also you change the state of the toogle button whether its 0 or 1

http://developer.android.com/guide/topics/ui/controls/togglebutton.html

Example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dp"
        android:text="Button" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="51dp"
        android:text="Switch" />

    <ToggleButton
        android:id="@+id/togglebutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/switch1"
        android:layout_marginTop="58dp"
        android:onClick="onToggleClicked"
        android:textOff="Vibrate off"
        android:textOn="Vibrate on" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity implements OnClickListener {

    EditText ed;
    Switch sb;
    ToggleButton tb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed = (EditText) findViewById(R.id.editText1);
        Button b = (Button) findViewById(R.id.button1);
        sb = (Switch)findViewById(R.id.switch1);
        tb = (ToggleButton)findViewById(R.id.togglebutton);
        b.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        String s = ed.getText().toString();
         if(s.equals("1")){

             tb.setText("TOGGLE ON");
             tb.setActivated(true);
             sb.setChecked(true);

         }
         else if(s.equals("0")){

             tb.setText("TOGGLE OFF");
             tb.setActivated(false);
             sb.setChecked(false);

    }

    }
     }

Snaps

enter image description here

enter image description here

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Here it is as a single formula:

=(RIGHT(D2,3))+(MID(D2,7,2)*1000)+(MID(D2,4,2)*60000)+(LEFT(D2,2)*3600000)

Determine the process pid listening on a certain port

netstat -nlp should tell you the PID of what's listening on which port.

Case insensitive string as HashMap key

Based on other answers, there are basically two approaches: subclassing HashMap or wrapping String. The first one requires a little more work. In fact, if you want to do it correctly, you must override almost all methods (containsKey, entrySet, get, put, putAll and remove).

Anyway, it has a problem. If you want to avoid future problems, you must specify a Locale in String case operations. So you would create new methods (get(String, Locale), ...). Everything is easier and clearer wrapping String:

public final class CaseInsensitiveString {

    private final String s;

    public CaseInsensitiveString(String s, Locale locale) {
        this.s = s.toUpperCase(locale);
    }

    // equals, hashCode & toString, no need for memoizing hashCode
}

And well, about your worries on performance: premature optimization is the root of all evil :)

How can I get the number of records affected by a stored procedure?

For Microsoft SQL Server you can return the @@ROWCOUNT variable to return the number of rows affected by the last statement in the stored procedure.

Efficient way to return a std::vector in c++

As nice as "return by value" might be, it's the kind of code that can lead one into error. Consider the following program:

    #include <string>
    #include <vector>
    #include <iostream>
    using namespace std;
    static std::vector<std::string> strings;
    std::vector<std::string> vecFunc(void) { return strings; };
    int main(int argc, char * argv[]){
      // set up the vector of strings to hold however
      // many strings the user provides on the command line
      for(int idx=1; (idx<argc); ++idx){
         strings.push_back(argv[idx]);
      }

      // now, iterate the strings and print them using the vector function
      // as accessor
      for(std::vector<std::string>::interator idx=vecFunc().begin(); (idx!=vecFunc().end()); ++idx){
         cout << "Addr: " << idx->c_str() << std::endl;
         cout << "Val:  " << *idx << std::endl;
      }
    return 0;
    };
  • Q: What will happen when the above is executed? A: A coredump.
  • Q: Why didn't the compiler catch the mistake? A: Because the program is syntactically, although not semantically, correct.
  • Q: What happens if you modify vecFunc() to return a reference? A: The program runs to completion and produces the expected result.
  • Q: What is the difference? A: The compiler does not have to create and manage anonymous objects. The programmer has instructed the compiler to use exactly one object for the iterator and for endpoint determination, rather than two different objects as the broken example does.

The above erroneous program will indicate no errors even if one uses the GNU g++ reporting options -Wall -Wextra -Weffc++

If you must produce a value, then the following would work in place of calling vecFunc() twice:

   std::vector<std::string> lclvec(vecFunc());
   for(std::vector<std::string>::iterator idx=lclvec.begin(); (idx!=lclvec.end()); ++idx)...

The above also produces no anonymous objects during iteration of the loop, but requires a possible copy operation (which, as some note, might be optimized away under some circumstances. But the reference method guarantees that no copy will be produced. Believing the compiler will perform RVO is no substitute for trying to build the most efficient code you can. If you can moot the need for the compiler to do RVO, you are ahead of the game.

Keeping it simple and how to do multiple CTE in a query

You can have multiple CTEs in one query, as well as reuse a CTE:

WITH    cte1 AS
        (
        SELECT  1 AS id
        ),
        cte2 AS
        (
        SELECT  2 AS id
        )
SELECT  *
FROM    cte1
UNION ALL
SELECT  *
FROM    cte2
UNION ALL
SELECT  *
FROM    cte1

Note, however, that SQL Server may reevaluate the CTE each time it is accessed, so if you are using values like RAND(), NEWID() etc., they may change between the CTE calls.

Multiple distinct pages in one HTML file

This is kind of overriding the thing of one page, but... You could use iframes in HTML.

<html>
<body>
<iframe src="page1.html" border="0"></iframe>
</body>
</html>

And page1.html would be your base page. Your still making multiple pages, but your browser just doesn't move. So lets say thats your index.html. You have tabs, you click page 2, your url wont change, but the page will. All in iframes. The only thing different, is that you can view the frame source as well.

How to delete all data from solr and hbase

If you want to delete all of the data in Solr via SolrJ do something like this.

public static void deleteAllSolrData() {
    HttpSolrServer solr = new HttpSolrServer("http://localhost:8080/solr/core/");
    try {
      solr.deleteByQuery("*:*");
    } catch (SolrServerException e) {
      throw new RuntimeException("Failed to delete data in Solr. "
          + e.getMessage(), e);
    } catch (IOException e) {
      throw new RuntimeException("Failed to delete data in Solr. "
          + e.getMessage(), e);
    }
}

If you want to delete all of the data in HBase do something like this.

public static void deleteHBaseTable(String tableName, Configuration conf) {
    HBaseAdmin admin = null;    
    try {
        admin = new HBaseAdmin(conf);
        admin.disableTable(tableName);
        admin.deleteTable(tableName);
    } catch (MasterNotRunningException e) {
        throw new RuntimeException("Unable to delete the table " + tableName
        + ". The actual exception is: " + e.getMessage(), e);
    } catch (ZooKeeperConnectionException e) {
        throw new RuntimeException("Unable to delete the table " + tableName
        + ". The actual exception is: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException("Unable to delete the table " + tableName
        + ". The actual exception is: " + e.getMessage(), e);
    } finally {
        close(admin);
    }
 }

Run a Docker image as a container

$ docker images
REPOSITORY                TAG                 IMAGE ID            CREATED            
jamesmedice/marketplace   latest              e78c49b5f380        2 days ago          
jamesmedice/marketplace   v1.0.0              *e78c49b5f380*        2 days ago          


$ docker run -p 6001:8585 *e78c49b5f380*

How do you execute SQL from within a bash script?

Maybe you can pipe SQL query to sqlplus. It works for mysql:

echo "SELECT * FROM table" | mysql --user=username database

How do I replace all line breaks in a string with <br /> elements?

It will replace all new line with break

str = str.replace(/\n/g, '<br>')

If you want to replace all new line with single break line

str = str.replace(/\n*\n/g, '<br>')

Read more about Regex : https://dl.icewarp.com/online_help/203030104.htm this will help you everytime.

Take a list of numbers and return the average

Simple math..

def average(n):
    result = 0
    for i in n:
      result += i
      ave_num = result / len(n)
    return ave_num

input -> [1,2,3,4,5]
output -> 3.0

Turn off enclosing <p> tags in CKEditor 3.0

In VS2015, this worked to turn the Enter key into <br>

myCKEControl.EnterMode = CKEditor.NET.EnterMode.BR

Personally, I don't care if my resulting text only has <br> and not <p>. It renders perfectly fine and it looks the way I want it to. In the end, it works.

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

How to represent matrices in python

If you are not going to use the NumPy library, you can use the nested list. This is code to implement the dynamic nested list (2-dimensional lists).

Let r is the number of rows

let r=3

m=[]
for i in range(r):
    m.append([int(x) for x in raw_input().split()])

Any time you can append a row using

m.append([int(x) for x in raw_input().split()])

Above, you have to enter the matrix row-wise. To insert a column:

for i in m:
    i.append(x) # x is the value to be added in column

To print the matrix:

print m       # all in single row

for i in m:
    print i   # each row in a different line

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

you could use the font style Like:

     <font color="white"><h1>Header Content</h1></font>

Example of a strong and weak entity types

First Strong/Weak Reference types are introduced in ARC. In Non ARC assign/retain are being used. A strong reference means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you points to it with a strong reference. Only once you set the property to nil, the object get destroyed.

A weak reference means you signify that you don't want to have control over the object's lifetime or don't want to "own" object. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil. The most frequent use cases of weak references in iOS are for IBOutlets, Delegates etc.

For more info Refer : http://www.informit.com/articles/article.aspx?p=1856389&seqNum=5

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

I wrapped @smileyborg's iOS7 solution in a category

I decided to wrap this clever solution by @smileyborg into a UICollectionViewCell+AutoLayoutDynamicHeightCalculation category.

The category also rectifies the issues outlined in @wildmonkey's answer (loading a cell from a nib and systemLayoutSizeFittingSize: returning CGRectZero)

It doesn't take into account any caching but suits my needs right now. Feel free to copy, paste and hack at it.

UICollectionViewCell+AutoLayoutDynamicHeightCalculation.h

#import <UIKit/UIKit.h>

typedef void (^UICollectionViewCellAutoLayoutRenderBlock)(void);

/**
 *  A category on UICollectionViewCell to aid calculating dynamic heights based on AutoLayout contraints.
 *
 *  Many thanks to @smileyborg and @wildmonkey
 *
 *  @see stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights
 */
@interface UICollectionViewCell (AutoLayoutDynamicHeightCalculation)

/**
 *  Grab an instance of the receiving type to use in order to calculate AutoLayout contraint driven dynamic height. The method pulls the cell from a nib file and moves any Interface Builder defined contrainsts to the content view.
 *
 *  @param name Name of the nib file.
 *
 *  @return collection view cell for using to calculate content based height
 */
+ (instancetype)heightCalculationCellFromNibWithName:(NSString *)name;

/**
 *  Returns the height of the receiver after rendering with your model data and applying an AutoLayout pass
 *
 *  @param block Render the model data to your UI elements in this block
 *
 *  @return Calculated constraint derived height
 */
- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block collectionViewWidth:(CGFloat)width;

/**
 *  Directly calls `heightAfterAutoLayoutPassAndRenderingWithBlock:collectionViewWidth` assuming a collection view width spanning the [UIScreen mainScreen] bounds
 */
- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block;

@end

UICollectionViewCell+AutoLayoutDynamicHeightCalculation.m

#import "UICollectionViewCell+AutoLayout.h"

@implementation UICollectionViewCell (AutoLayout)

#pragma mark Dummy Cell Generator

+ (instancetype)heightCalculationCellFromNibWithName:(NSString *)name
{
    UICollectionViewCell *heightCalculationCell = [[[NSBundle mainBundle] loadNibNamed:name owner:self options:nil] lastObject];
    [heightCalculationCell moveInterfaceBuilderLayoutConstraintsToContentView];
    return heightCalculationCell;
}

#pragma mark Moving Constraints

- (void)moveInterfaceBuilderLayoutConstraintsToContentView
{
    [self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
        [self removeConstraint:constraint];
        id firstItem = constraint.firstItem == self ? self.contentView : constraint.firstItem;
        id secondItem = constraint.secondItem == self ? self.contentView : constraint.secondItem;
        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:firstItem
                                                                     attribute:constraint.firstAttribute
                                                                     relatedBy:constraint.relation
                                                                        toItem:secondItem
                                                                     attribute:constraint.secondAttribute
                                                                    multiplier:constraint.multiplier
                                                                      constant:constraint.constant]];
    }];
}

#pragma mark Height

- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block
{
    return [self heightAfterAutoLayoutPassAndRenderingWithBlock:block
                                            collectionViewWidth:CGRectGetWidth([[UIScreen mainScreen] bounds])];
}

- (CGFloat)heightAfterAutoLayoutPassAndRenderingWithBlock:(UICollectionViewCellAutoLayoutRenderBlock)block collectionViewWidth:(CGFloat)width
{
    NSParameterAssert(block);

    block();

    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];

    self.bounds = CGRectMake(0.0f, 0.0f, width, CGRectGetHeight(self.bounds));

    [self setNeedsLayout];
    [self layoutIfNeeded];

    CGSize calculatedSize = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

    return calculatedSize.height;

}

@end

Usage example:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MYSweetCell *cell = [MYSweetCell heightCalculationCellFromNibWithName:NSStringFromClass([MYSweetCell class])];
    CGFloat height = [cell heightAfterAutoLayoutPassAndRenderingWithBlock:^{
        [(id<MYSweetCellRenderProtocol>)cell renderWithModel:someModel];
    }];
    return CGSizeMake(CGRectGetWidth(self.collectionView.bounds), height);
}

Thankfully we won't have to do this jazz in iOS8, but there it is for now!

Docker: Multiple Dockerfiles in project

In newer versions(>=1.8.0) of docker, you can do this

docker build -f Dockerfile.db .
docker build -f Dockerfile.web .

A big save.

EDIT: update versions per raksja's comment

EDIT: comment from @vsevolod: it's possible to get syntax highlighting in VS code by giving files .Dockerfile extension(instead of name) e.g. Prod.Dockerfile, Test.Dockerfile etc.

How to properly and completely close/reset a TcpClient connection?

Closes a socket connection and allows for re-use of the socket:

tcpClient.Client.Disconnect(false);

Simulator or Emulator? What is the difference?

Simulation = For analysis and study

Emulation = For usage as a substitute

A simulator is an environment which models but an emulator is one that replicates the usage as on the original device or system.

Simulator mimics the activity of something that it is simulating. It "appears"(a lot can go with this "appears", depending on the context) to be the same as the thing being simulated. For example the flight simulator "appears" to be a real flight to the user, although it does not transport you from one place to another.

Emulator, on the other hand, actually "does" what the thing being emulated does, and in doing so it too "appears to be doing the same thing". An emulator may use different set of protocols for mimicking the thing being emulated, but the result/outcome is always the same as the original object. For example, EMU8086 emulates the 8086 microprocessor on your computer, which obviously is not running on 8086 (= different protocols), but the output it gives is what a real 8086 would give.

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).


A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

Nested jQuery.each() - continue/break

You can break the $.each() loop at a particular iteration by making the callback function return false.

Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Unfortunately MyApp has stopped. How can I solve this?

If you don't have any kind of interesting log in your terminal (or they are not directly related to your app), maybe your problem is due to a native library. In that case, you should check for the "tombstone" files within your terminal.

The default location for the tombstone files depends on every device, but if that's the case, you will have a log telling: Tombstone written to: /data/tombstones/tombstone_06

For more information, check on https://source.android.com/devices/tech/debug.

Asp.net MVC ModelState.Clear

I had an instance where I wanted to update the model of a sumitted form, and did not want to 'Redirect To Action' for performanace reason. Previous values of hidden fields were being retained on my updated model - causing allsorts of issues!.

A few lines of code soon identified the elements within ModelState that I wanted to remove (after validation), so the new values were used in the form:-

while (ModelState.FirstOrDefault(ms => ms.Key.ToString().StartsWith("SearchResult")).Value != null)
{
    ModelState.Remove(ModelState.FirstOrDefault(ms => ms.Key.ToString().StartsWith("SearchResult")));
}

GCC -fPIC option

Position Independent Code means that the generated machine code is not dependent on being located at a specific address in order to work.

E.g. jumps would be generated as relative rather than absolute.

Pseudo-assembly:

PIC: This would work whether the code was at address 100 or 1000

100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL CURRENT+10
...
111: NOP

Non-PIC: This will only work if the code is at address 100

100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL 111
...
111: NOP

EDIT: In response to comment.

If your code is compiled with -fPIC, it's suitable for inclusion in a library - the library must be able to be relocated from its preferred location in memory to another address, there could be another already loaded library at the address your library prefers.

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

I added TO_DATE and it resolved issue.

Before modification - due to below condition i got this error

record_update_dt>='05-May-2017'

After modification - after adding to_date, issue got resolved.

record_update_dt>=to_date('05-May-2017','DD-Mon-YYYY')

PHP Unset Session Variable

// set
$_SESSION['test'] = 1;

// destroy
unset($_SESSION['test']);

Can't operator == be applied to generic types in C#?

It appears that without the class constraint:

bool Compare<T> (T x, T y) where T: class
{
    return x == y;
}

One should realize that while class constrained Equals in the == operator inherits from Object.Equals, while that of a struct overrides ValueType.Equals.

Note that:

bool Compare<T> (T x, T y) where T: struct
{
    return x == y;
}

also gives out the same compiler error.

As yet I do not understand why having a value type equality operator comparison is rejected by the compiler. I do know for a fact though, that this works:

bool Compare<T> (T x, T y)
{
    return x.Equals(y);
}

Running windows shell commands with python

You would use the os module system method.

You just put in the string form of the command, the return value is the windows enrivonment variable COMSPEC

For example:

os.system('python') opens up the windows command prompt and runs the python interpreter

os.system('python') example

Append value to empty vector in R?

You have a few options:

  • c(vector, values)

  • append(vector, values)

  • vector[(length(vector) + 1):(length(vector) + length(values))] <- values

The first one is the standard approach. The second one gives you the option to append someplace other than the end. The last one is a bit contorted but has the advantage of modifying vector (though really, you could just as easily do vector <- c(vector, values).

Notice that in R you don't need to cycle through vectors. You can just operate on them in whole.

Also, this is fairly basic stuff, so you should go through some of the references.

Some more options based on OP feedback:

for(i in values) vector <- c(vector, i)

Hibernate: flush() and commit()

flush(); Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory. It will update or insert into your tables in the running transaction, but it may not commit those changes.

You need to flush in batch processing otherwise it may give OutOfMemoryException.

Commit(); Commit will make the database commit. When you have a persisted object and you change a value on it, it becomes dirty and hibernate needs to flush these changes to your persistence layer. So, you should commit but it also ends the unit of work (transaction.commit()).

Connect to Oracle DB using sqlplus

try this: sqlplus USER/PW@//hostname:1521/SID

Difference between a Structure and a Union

Non technically speaking means :

Assumption: chair = memory block , people = variable

Structure : If there are 3 people they can sit in chair of their size correspondingly .

Union : If there are 3 people only one chair will be there to sit , all need to use the same chair when they want to sit .

Technically speaking means :

The below mentioned program gives a deep dive into structure and union together .

struct MAIN_STRUCT
{
UINT64 bufferaddr;   
union {
    UINT32 data;
    struct INNER_STRUCT{
        UINT16 length;  
        UINT8 cso;  
        UINT8 cmd;  
           } flags;
     } data1;
};

Total MAIN_STRUCT size =sizeof(UINT64) for bufferaddr + sizeof(UNIT32) for union + 32 bit for padding(depends on processor architecture) = 128 bits . For structure all the members get the memory block contiguously .

Union gets one memory block of the max size member(Here its 32 bit) . Inside union one more structure lies(INNER_STRUCT) its members get a memory block of total size 32 bits(16+8+8) . In union either INNER_STRUCT(32 bit) member or data(32 bit) can be accessed .

How to pass a vector to a function?

If you use random instead of * random your code not give any error

How do I add items to an array in jQuery?

Hope this will help you..

var list = [];
    $(document).ready(function () {
        $('#test').click(function () {
            var oRows = $('#MainContent_Table1 tr').length;
            $('#MainContent_Table1 tr').each(function (index) {
                list.push(this.cells[0].innerHTML);
            });
        });
    });

How do you right-justify text in an HTML textbox?

Using inline styles:

<input type="text" style="text-align: right"/>

or, put it in a style sheet, like so:

<style>
   .rightJustified {
        text-align: right;
    }
</style>

and reference the class:

<input type="text" class="rightJustified"/>

spark submit add multiple jars in classpath

if you are using properties file you can add following line there:

spark.jars=jars/your_jar1.jar,...

assuming that

<your root from where you run spark-submit>
  |
  |-jars
      |-your_jar1.jar

What is an optional value in Swift?

An optional means that Swift is not entirely sure if the value corresponds to the type: for example, Int? means that Swift is not entirely sure whether the number is an Int.

To remove it, there are three methods you could employ.

1) If you are absolutely sure of the type, you can use an exclamation mark to force unwrap it, like this:

// Here is an optional variable:

var age: Int?

// Here is how you would force unwrap it:

var unwrappedAge = age!

If you do force unwrap an optional and it is equal to nil, you may encounter this crash error:

enter image description here

This is not necessarily safe, so here's a method that might prevent crashing in case you are not certain of the type and value:

Methods 2 and three safeguard against this problem.

2) The Implicitly Unwrapped Optional

 if let unwrappedAge = age {

 // continue in here

 }

Note that the unwrapped type is now Int, rather than Int?.

3) The guard statement

 guard let unwrappedAge = age else { 
   // continue in here
 }

From here, you can go ahead and use the unwrapped variable. Make sure only to force unwrap (with an !), if you are sure of the type of the variable.

Good luck with your project!

Remove duplicated rows using dplyr

For completeness’ sake, the following also works:

df %>% group_by(x) %>% filter (! duplicated(y))

However, I prefer the solution using distinct, and I suspect it’s faster, too.

Applying an ellipsis to multiline text

I took a look at how YouTube solves it on their homepage and simplified it:

.multine-ellipsis {
  -webkit-box-orient: vertical;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}

This will allow 2 lines of code and then append an ellipsis.

Gist: https://gist.github.com/eddybrando/386d3350c0b794ea87a2082bf4ab014b

How to print VARCHAR(MAX) using Print Statement?

I know it's an old question, but what I did is not mentioned here.

For me the following worked.

DECLARE @info NVARCHAR(MAX)

--SET @info to something big

PRINT CAST(@info AS NTEXT)

Bootstrap 4 File Input

Bootstrap 4.4:

Show a choose file bar. After a file is chosen show the file name along with its extension

<div class="custom-file">
    <input type="file" class="custom-file-input" id="idEditUploadVideo"
     onchange="$('#idFileName').html(this.files[0].name)">
    <label class="custom-file-label" id="idFileName" for="idEditUploadVideo">Choose file</label>
</div>

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

Use jQuery. Keep your checkbox elements hidden and create a list like this:

<ul id="list">
    <li><a href="javascript:void(0)" id="link1">Happy face</a></li>
    <li><a href="javascript:void(0)" id="link2">Sad face</a></li>
</ul>

<form action="file.php" method="post">
    <!-- More code -->
    <input type="radio" id="option1" name="radio1" value="happy" style="display:none"/>
    <input type="radio" id="option2" name="radio1" value="sad" style="display:none"/>
    <!-- More code -->
</form>

<script type="text/javascript">
$("#list li a").click(function() {
    $('#list .active').removeClass("active");
    var id = this.id;
    var newselect = id.replace('link', 'option');
    $('#'+newselect).attr('checked', true);
    $(this).addClass("active").parent().addClass("active");
    return false;
});
</script>

This code would add the checked attribute to your radio inputs in the background and assign class active to your list elements. Do not use inline styles of course, don't forget to include jQuery and everything should run out of the box after you customize it.

Cheers!

Convenient way to parse incoming multipart/form-data parameters in a Servlet

multipart/form-data encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded encoding. When using a different encoding, the request.getParameter() calls will all return null. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts() instead. Also see this blog for extended examples.

Prior to Servlet 3.0, a de facto standard to parse multipart/form-data requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).

Hamcrest compare collections

List<Long> actual = Arrays.asList(1L, 2L);
List<Long> expected = Arrays.asList(2L, 1L);
assertThat(actual, containsInAnyOrder(expected.toArray()));

Shorter version of @Joe's answer without redundant parameters.

How to enable GZIP compression in IIS 7.5

Global Gzip in HttpModule

If you don't have access to shared hosting - the final IIS instance. You can create a HttpModule that gets added this code to every HttpApplication.Begin_Request event:-

HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

How to deep copy a list?

I believe a lot of programmers have run into one or two interview problems where they are asked to deep copy a linked list, however this problem is harder than it sounds!

in python, there is a module called "copy" with two useful functions

import copy
copy.copy()
copy.deepcopy()

copy() is a shallow copy function, if the given argument is a compound data structure, for instance a list, then python will create another object of the same type (in this case, a new list) but for everything inside old list, only their reference is copied

# think of it like
newList = [elem for elem in oldlist]

Intuitively, we could assume that deepcopy() would follow the same paradigm, and the only difference is that for each elem we will recursively call deepcopy, (just like the answer of mbcoder)

but this is wrong!

deepcopy() actually preserve the graphical structure of the original compound data:

a = [1,2]
b = [a,a] # there's only 1 object a
c = deepcopy(b)

# check the result
c[0] is a # return False, a new object a' is created
c[0] is c[1] # return True, c is [a',a'] not [a',a'']

this is the tricky part, during the process of deepcopy() a hashtable(dictionary in python) is used to map: "old_object ref onto new_object ref", this prevent unnecessary duplicates and thus preserve the structure of the copied compound data

official doc

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

How can I make a CSS table fit the screen width?

Set font-size in viewport-width-related units, e.g.:

table { font-size: 0.9vw; }

This will make font unreadable when page is too narrow, but sometimes this is acceptable.

Creating Unicode character from its number

The other answers here either only support unicode up to U+FFFF (the answers dealing with just one instance of char) or don't tell how to get to the actual symbol (the answers stopping at Character.toChars() or using incorrect method after that), so adding my answer here, too.

To support supplementary code points also, this is what needs to be done:

// this character:
// http://www.isthisthingon.org/unicode/index.php?page=1F&subpage=4&glyph=1F495
// using code points here, not U+n notation
// for equivalence with U+n, below would be 0xnnnn
int codePoint = 128149;
// converting to char[] pair
char[] charPair = Character.toChars(codePoint);
// and to String, containing the character we want
String symbol = new String(charPair);

// we now have str with the desired character as the first item
// confirm that we indeed have character with code point 128149
System.out.println("First code point: " + symbol.codePointAt(0));

I also did a quick test as to which conversion methods work and which don't

int codePoint = 128149;
char[] charPair = Character.toChars(codePoint);

System.out.println(new String(charPair, 0, 2).codePointAt(0)); // 128149, worked
System.out.println(charPair.toString().codePointAt(0));        // 91, didn't work
System.out.println(new String(charPair).codePointAt(0));       // 128149, worked
System.out.println(String.valueOf(codePoint).codePointAt(0));  // 49, didn't work
System.out.println(new String(new int[] {codePoint}, 0, 1).codePointAt(0));
                                                               // 128149, worked

Word-wrap in an HTML table

You can try this if it suits you...

Put a textarea inside your td and disable it with background color white and define its number of rows.

<table style="width: 100%;">
  <tr>
    <td>
        <textarea rows="4" style="background-color:white;border: none;" disabled>      Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word
      </textarea>
    </td>
    <td><span style="display: inline;">Short word</span></td>
  </tr>
</table>

Which is faster: multiple single INSERTs or one multiple-row INSERT?

A major factor will be whether you're using a transactional engine and whether you have autocommit on.

Autocommit is on by default and you probably want to leave it on; therefore, each insert that you do does its own transaction. This means that if you do one insert per row, you're going to be committing a transaction for each row.

Assuming a single thread, that means that the server needs to sync some data to disc for EVERY ROW. It needs to wait for the data to reach a persistent storage location (hopefully the battery-backed ram in your RAID controller). This is inherently rather slow and will probably become the limiting factor in these cases.

I'm of course assuming that you're using a transactional engine (usually innodb) AND that you haven't tweaked the settings to reduce durability.

I'm also assuming that you're using a single thread to do these inserts. Using multiple threads muddies things a bit because some versions of MySQL have working group-commit in innodb - this means that multiple threads doing their own commits can share a single write to the transaction log, which is good because it means fewer syncs to persistent storage.

On the other hand, the upshot is, that you REALLY WANT TO USE multi-row inserts.

There is a limit over which it gets counter-productive, but in most cases it's at least 10,000 rows. So if you batch them up to 1,000 rows, you're probably safe.

If you're using MyISAM, there's a whole other load of things, but I'll not bore you with those. Peace.

VBA copy cells value and format

Following on from jpw it might be good to encapsulate his solution in a small subroutine to save on having lots of lines of code:

Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
  If Worksheets(1).Cells(i, 3) <> "" Then
    call copValuesAndFormat(i,3,a,15)        
    call copValuesAndFormat(i,5,a,17) 
    call copValuesAndFormat(i,6,a,18) 
    call copValuesAndFormat(i,7,a,19) 
    call copValuesAndFormat(i,8,a,20) 
    call copValuesAndFormat(i,9,a,21) 
    a = a + 1
  End If
Next i
end sub

sub copValuesAndFormat(x1 as integer, y1 as integer, x2 as integer, y2 as integer)
  Worksheets(1).Cells(x1, y1).Copy
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteFormats
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteValues
end sub

(I do not have Excel in current location so please excuse bugs as not tested)

What is an unhandled promise rejection?

I had faced a similar issue with NodeJS, where the culprit was a forEach loop. Note that forEach is a synchronous function (NOT Asynchronous). Therefore it just ignores the promise returned. The solution was to use a for-of loop instead: Code where I got the error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

is as follows:

permissionOrders.forEach( async(order) => {
        const requestPermissionOrder = new RequestPermissionOrderSchema({
            item: order.item,
            item_desc: order.item_desc,
            quantity: order.quantity,
            unit_price: order.unit_price,
            total_cost: order.total_cost,
            status: order.status,
            priority: order.priority,
            directOrder: order.directOrder
        });

        try {
            const dat_order = await requestPermissionOrder.save();
            res.json(dat_order);
        } catch(err){
            res.json({ message : err});
        }
    });

Solution for the above issue is as follows:

for (let order of permissionOrders){
        const requestPermissionOrder = new RequestPermissionOrderSchema({
            item: order.item,
            item_desc: order.item_desc,
            quantity: order.quantity,
            unit_price: order.unit_price,
            total_cost: order.total_cost,
            status: order.status,
            priority: order.priority,
            directOrder: order.directOrder
        });

        try {
            const dat_order = await requestPermissionOrder.save();
            res.json(dat_order);
        } catch(err){
            res.json({ message : err});
        }
    };

Default Xmxsize in Java 8 (max heap size)

Like you have mentioned, The default -Xmxsize (Maximum HeapSize) depends on your system configuration.

Java8 client takes Larger of 1/64th of your physical memory for your Xmssize (Minimum HeapSize) and Smaller of 1/4th of your physical memory for your -Xmxsize (Maximum HeapSize).

Which means if you have a physical memory of 8GB RAM, you will have Xmssize as Larger of 8*(1/6) and Smaller of -Xmxsizeas 8*(1/4).

You can Check your default HeapSize with

In Windows:

java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"

In Linux:

java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

These default values can also be overrided to your desired amount.

Build Maven Project Without Running Unit Tests

If you want to skip running and compiling tests:

mvn -Dmaven.test.skip=true install

If you want to compile but not run tests:

mvn install -DskipTests

How to unset a JavaScript variable?

@scunlife's answer will work, but technically it ought to be

delete window.some_var; 

delete is supposed to be a no-op when the target isn't an object property. e.g.,

(function() {
   var foo = 123;
   delete foo; // wont do anything, foo is still 123
   var bar = { foo: 123 };
   delete bar.foo; // foo is gone
}());

But since global variables are actually members of the window object, it works.

When prototype chains are involved, using delete gets more complex because it only removes the property from the target object, and not the prototype. e.g.,

function Foo() {}
Foo.prototype = { bar: 123 };
var foo = new Foo();
// foo.bar is 123
foo.bar = 456;
// foo.bar is now 456
delete foo.bar;
// foo.bar is 123 again.

So be careful.

EDIT: My answer is somewhat inaccurate (see "Misconceptions" at the end). The link explains all the gory details, but the summary is that there can be big differences between browsers and depending on the object you are deleting from. delete object.someProp should generally be safe as long as object !== window. I still wouldn't use it to delete variables declared with var although you can under the right circumstances.

Regular expression to match a word or its prefix

[ ] defines a character class. So every character you set there, will match. [012] will match 0 or 1 or 2 and [0-2] behaves the same.

What you want is groupings to define a or-statement. Use (s|season) for your issue.

Btw. you have to watch out. Metacharacters in normal regex (or inside a grouping) are different from character class. A character class is like a sub-language. [$A] will only match $ or A, nothing else. No escaping here for the dollar.

Horizontal list items

Here you can find a working example, with some more suggestions about dynamic resizing of the list.

I've used display:inline-block and a percentage padding so that the parent list can dynamically change size:

display:inline-block;
padding:10px 1%;
width: 30%

plus two more rules to remove padding for the first and last items.

ul#menuItems li:first-child{padding-left:0;}
ul#menuItems li:last-child{padding-right:0;}

jQuery select by attribute using AND and OR operators

JQuery uses CSS selectors to select elements, so you just need to use more than one rule by separating them with commas, as so:

a=$('[myc="blue"], [myid="1"], [myid="3"]');

Edit:

Sorry, you wanted blue and 1 or 3. How about:

a=$('[myc="blue"][myid="1"],  [myid="3"]');

Putting the two attribute selectors together gives you AND, using a comma gives you OR.

jQuery loop over JSON result from AJAX Success?

you can remove the outer loop and replace this with data.data:

$.each(data.data, function(k, v) {
    /// do stuff
});

You were close:

$.each(data, function() {
  $.each(this, function(k, v) {
    /// do stuff
  });
});

You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.

Where is Maven's settings.xml located on Mac OS?

It doesn't exist at first. You have to create it in your home folder, /Users/usename/.m2/ (or ~/.m2)

For example :

alt text

What is the difference between a URI, a URL and a URN?

Identity = Name with Location

Every URL(Uniform Resource Locator) is a URI(Uniform Resource Identifier), abstractly speaking, but every URI is not a URL. There is another subcategory of URI is URN (Uniform Resource Name), which is a named resource but do not specify how to locate them, like mailto, news, ISBN is URIs. Source

enter image description here

URN:

  • URN Format : urn:[namespace identifier]:[namespace specific string]
  • urn: and : stand for themselves.
  • Examples:
    • urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66
    • urn:ISSN:0167-6423
    • urn:isbn:096139210x
    • Amazon Resource Names (ARNs) is a uniquely identify AWS resources.
      • ARN Format : arn:partition:service:region:account-id:resource

URL:

  • URL Format : [scheme]://[Domain][Port]/[path]?[queryString]#[fragmentId]
  • :,//,? and # stand for themselves.
  • schemes are https,ftp,gopher,mailto,news,telnet,file,man,info,whatis,ldap...
  • Examples:

Analogy:
To reach a person: Driving(protocol others SMS, email, phone), Address(hostname other phone-number, emailid) and person name(object name with a relative path).

Where can I find the .apk file on my device, when I download any app and install?

There is an app in google play known as MyAppSharer. Open the app, search for the app that you have installed, check apk and select share. The app would take some time and build the apk. You can then close the app. The apk of the file is located in /sdcard/MyAppSharer

This does not require rooting your phone and works only for apps that are currently installed on your phone

How do I install soap extension?

In Ubuntu with php7.3:

sudo apt install php7.3-soap 
sudo service apache2 restart

Making custom right-click context menus for my web-app

here is an example for right click context menu in javascript: Right Click Context Menu

Used raw javasScript Code for context menu functionality. Can you please check this, hope this will help you.

Live Code:

_x000D_
_x000D_
(function() {_x000D_
  _x000D_
  "use strict";_x000D_
_x000D_
_x000D_
  /*********************************************** Context Menu Function Only ********************************/_x000D_
  function clickInsideElement( e, className ) {_x000D_
    var el = e.srcElement || e.target;_x000D_
    if ( el.classList.contains(className) ) {_x000D_
      return el;_x000D_
    } else {_x000D_
      while ( el = el.parentNode ) {_x000D_
        if ( el.classList && el.classList.contains(className) ) {_x000D_
          return el;_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  function getPosition(e) {_x000D_
    var posx = 0, posy = 0;_x000D_
    if (!e) var e = window.event;_x000D_
    if (e.pageX || e.pageY) {_x000D_
      posx = e.pageX;_x000D_
      posy = e.pageY;_x000D_
    } else if (e.clientX || e.clientY) {_x000D_
      posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;_x000D_
      posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;_x000D_
    }_x000D_
    return {_x000D_
      x: posx,_x000D_
      y: posy_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Your Menu Class Name_x000D_
  var taskItemClassName = "thumb";_x000D_
  var contextMenuClassName = "context-menu",contextMenuItemClassName = "context-menu__item",contextMenuLinkClassName = "context-menu__link", contextMenuActive = "context-menu--active";_x000D_
  var taskItemInContext, clickCoords, clickCoordsX, clickCoordsY, menu = document.querySelector("#context-menu"), menuItems = menu.querySelectorAll(".context-menu__item");_x000D_
  var menuState = 0, menuWidth, menuHeight, menuPosition, menuPositionX, menuPositionY, windowWidth, windowHeight;_x000D_
_x000D_
  function initMenuFunction() {_x000D_
    contextListener();_x000D_
    clickListener();_x000D_
    keyupListener();_x000D_
    resizeListener();_x000D_
  }_x000D_
_x000D_
  /**_x000D_
   * Listens for contextmenu events._x000D_
   */_x000D_
  function contextListener() {_x000D_
    document.addEventListener( "contextmenu", function(e) {_x000D_
      taskItemInContext = clickInsideElement( e, taskItemClassName );_x000D_
_x000D_
      if ( taskItemInContext ) {_x000D_
        e.preventDefault();_x000D_
        toggleMenuOn();_x000D_
        positionMenu(e);_x000D_
      } else {_x000D_
        taskItemInContext = null;_x000D_
        toggleMenuOff();_x000D_
      }_x000D_
    });_x000D_
  }_x000D_
_x000D_
  /**_x000D_
   * Listens for click events._x000D_
   */_x000D_
  function clickListener() {_x000D_
    document.addEventListener( "click", function(e) {_x000D_
      var clickeElIsLink = clickInsideElement( e, contextMenuLinkClassName );_x000D_
_x000D_
      if ( clickeElIsLink ) {_x000D_
        e.preventDefault();_x000D_
        menuItemListener( clickeElIsLink );_x000D_
      } else {_x000D_
        var button = e.which || e.button;_x000D_
        if ( button === 1 ) {_x000D_
          toggleMenuOff();_x000D_
        }_x000D_
      }_x000D_
    });_x000D_
  }_x000D_
_x000D_
  /**_x000D_
   * Listens for keyup events._x000D_
   */_x000D_
  function keyupListener() {_x000D_
    window.onkeyup = function(e) {_x000D_
      if ( e.keyCode === 27 ) {_x000D_
        toggleMenuOff();_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
_x000D_
  /**_x000D_
   * Window resize event listener_x000D_
   */_x000D_
  function resizeListener() {_x000D_
    window.onresize = function(e) {_x000D_
      toggleMenuOff();_x000D_
    };_x000D_
  }_x000D_
_x000D_
  /**_x000D_
   * Turns the custom context menu on._x000D_
   */_x000D_
  function toggleMenuOn() {_x000D_
    if ( menuState !== 1 ) {_x000D_
      menuState = 1;_x000D_
      menu.classList.add( contextMenuActive );_x000D_
    }_x000D_
  }_x000D_
_x000D_
  /**_x000D_
   * Turns the custom context menu off._x000D_
   */_x000D_
  function toggleMenuOff() {_x000D_
    if ( menuState !== 0 ) {_x000D_
      menuState = 0;_x000D_
      menu.classList.remove( contextMenuActive );_x000D_
    }_x000D_
  }_x000D_
_x000D_
  function positionMenu(e) {_x000D_
    clickCoords = getPosition(e);_x000D_
    clickCoordsX = clickCoords.x;_x000D_
    clickCoordsY = clickCoords.y;_x000D_
    menuWidth = menu.offsetWidth + 4;_x000D_
    menuHeight = menu.offsetHeight + 4;_x000D_
_x000D_
    windowWidth = window.innerWidth;_x000D_
    windowHeight = window.innerHeight;_x000D_
_x000D_
    if ( (windowWidth - clickCoordsX) < menuWidth ) {_x000D_
      menu.style.left = (windowWidth - menuWidth)-0 + "px";_x000D_
    } else {_x000D_
      menu.style.left = clickCoordsX-0 + "px";_x000D_
    }_x000D_
_x000D_
    // menu.style.top = clickCoordsY + "px";_x000D_
_x000D_
    if ( Math.abs(windowHeight - clickCoordsY) < menuHeight ) {_x000D_
      menu.style.top = (windowHeight - menuHeight)-0 + "px";_x000D_
    } else {_x000D_
      menu.style.top = clickCoordsY-0 + "px";_x000D_
    }_x000D_
  }_x000D_
_x000D_
_x000D_
  function menuItemListener( link ) {_x000D_
    var menuSelectedPhotoId = taskItemInContext.getAttribute("data-id");_x000D_
    console.log('Your Selected Photo: '+menuSelectedPhotoId)_x000D_
    var moveToAlbumSelectedId = link.getAttribute("data-action");_x000D_
    if(moveToAlbumSelectedId == 'remove'){_x000D_
      console.log('You Clicked the remove button')_x000D_
    }else if(moveToAlbumSelectedId && moveToAlbumSelectedId.length > 7){_x000D_
      console.log('Clicked Album Name: '+moveToAlbumSelectedId);_x000D_
    }_x000D_
    toggleMenuOff();_x000D_
  }_x000D_
  initMenuFunction();_x000D_
_x000D_
})();
_x000D_
/* For Body Padding and content */_x000D_
body { padding-top: 70px; }_x000D_
li a { text-decoration: none !important; }_x000D_
_x000D_
/* Thumbnail only */_x000D_
.thumb {_x000D_
  margin-bottom: 30px;_x000D_
}_x000D_
.thumb:hover a, .thumb:active a, .thumb:focus a {_x000D_
  border: 1px solid purple;_x000D_
}_x000D_
_x000D_
/************** For Context menu ***********/_x000D_
/* context menu */_x000D_
.context-menu {  display: none;  position: absolute;  z-index: 9999;  padding: 12px 0;  width: 200px;  background-color: #fff;  border: solid 1px #dfdfdf;  box-shadow: 1px 1px 2px #cfcfcf;  }_x000D_
.context-menu--active {  display: block;  }_x000D_
_x000D_
.context-menu__items { list-style: none;  margin: 0;  padding: 0;  }_x000D_
.context-menu__item { display: block;  margin-bottom: 4px;  }_x000D_
.context-menu__item:last-child {  margin-bottom: 0;  }_x000D_
.context-menu__link {  display: block;  padding: 4px 12px;  color: #0066aa;  text-decoration: none;  }_x000D_
.context-menu__link:hover {  color: #fff;  background-color: #0066aa;  }_x000D_
.context-menu__items ul {  position: absolute;  white-space: nowrap;  z-index: 1;  left: -99999em;}_x000D_
.context-menu__items > li:hover > ul {  left: auto;  padding-top: 5px  ;  min-width: 100%;  }_x000D_
.context-menu__items > li li ul {  border-left:1px solid #fff;}_x000D_
.context-menu__items > li li:hover > ul {  left: 100%;  top: -1px;  }_x000D_
.context-menu__item ul { background-color: #ffffff; padding: 7px 11px;  list-style-type: none;  text-decoration: none; margin-left: 40px; }_x000D_
.page-media .context-menu__items ul li { display: block; }_x000D_
/************** For Context menu ***********/
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
    <!-- Page Content -->_x000D_
    <div class="container">_x000D_
_x000D_
        <div class="row">_x000D_
_x000D_
            <div class="col-lg-12">_x000D_
                <h1 class="page-header">Thumbnail Gallery <small>(Right click to see the context menu)</small></h1>_x000D_
            </div>_x000D_
_x000D_
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
                <a class="thumbnail" href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
                </a>_x000D_
            </div>_x000D_
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
                <a class="thumbnail" href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
                </a>_x000D_
            </div>_x000D_
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
                <a class="thumbnail" href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
                </a>_x000D_
            </div>_x000D_
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
                <a class="thumbnail" href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
                </a>_x000D_
            </div>_x000D_
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
                <a class="thumbnail" href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
                </a>_x000D_
            </div>_x000D_
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
                <a class="thumbnail" href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
                </a>_x000D_
            </div>_x000D_
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
                <a class="thumbnail" href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
                </a>_x000D_
            </div>_x000D_
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
                <a class="thumbnail" href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
                </a>_x000D_
            </div>_x000D_
_x000D_
        </div>_x000D_
_x000D_
        <hr>_x000D_
_x000D_
_x000D_
    </div>_x000D_
    <!-- /.container -->_x000D_
_x000D_
_x000D_
    <!-- / The Context Menu -->_x000D_
    <nav id="context-menu" class="context-menu">_x000D_
        <ul class="context-menu__items">_x000D_
            <li class="context-menu__item">_x000D_
                <a href="#" class="context-menu__link" data-action="Delete This Photo"><i class="fa fa-empire"></i> Delete This Photo</a>_x000D_
            </li>_x000D_
            <li class="context-menu__item">_x000D_
                <a href="#" class="context-menu__link" data-action="Photo Option 2"><i class="fa fa-envira"></i> Photo Option 2</a>_x000D_
            </li>_x000D_
            <li class="context-menu__item">_x000D_
                <a href="#" class="context-menu__link" data-action="Photo Option 3"><i class="fa fa-first-order"></i> Photo Option 3</a>_x000D_
            </li>_x000D_
            <li class="context-menu__item">_x000D_
                <a href="#" class="context-menu__link" data-action="Photo Option 4"><i class="fa fa-gitlab"></i> Photo Option 4</a>_x000D_
            </li>_x000D_
            <li class="context-menu__item">_x000D_
                <a href="#" class="context-menu__link" data-action="Photo Option 5"><i class="fa fa-ioxhost"></i> Photo Option 5</a>_x000D_
            </li>_x000D_
            <li class="context-menu__item">_x000D_
                <a href="#" class="context-menu__link"><i class="fa fa-arrow-right"></i> Add Photo to</a>_x000D_
                <ul>_x000D_
                    <li><a href="#!" class="context-menu__link" data-action="album-one"><i class="fa fa-camera-retro"></i> Album One</a></li>_x000D_
                    <li><a href="#!" class="context-menu__link" data-action="album-two"><i class="fa fa-camera-retro"></i> Album Two</a></li>_x000D_
                    <li><a href="#!" class="context-menu__link" data-action="album-three"><i class="fa fa-camera-retro"></i> Album Three</a></li>_x000D_
                    <li><a href="#!" class="context-menu__link" data-action="album-four"><i class="fa fa-camera-retro"></i> Album Four</a></li>_x000D_
                </ul>_x000D_
            </li>_x000D_
        </ul>_x000D_
    </nav>_x000D_
_x000D_
    <!-- End # Context Menu -->_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

REST API using POST instead of GET

It is nice that REST brings meaning to HTTP verbs (as they defined) but I prefer to agree with Scott Peal.

Here is also item from WIKI's extended explanation on POST request:

There are times when HTTP GET is less suitable even for data retrieval. An example of this is when a great deal of data would need to be specified in the URL. Browsers and web servers can have limits on the length of the URL that they will handle without truncation or error. Percent-encoding of reserved characters in URLs and query strings can significantly increase their length, and while Apache HTTP Server can handle up to 4,000 characters in a URL,[5] Microsoft Internet Explorer is limited to 2,048 characters in any URL.[6] Equally, HTTP GET should not be used where sensitive information, such as user names and passwords, have to be submitted along with other data for the request to complete. Even if HTTPS is used, preventing the data from being intercepted in transit, the browser history and the web server's logs will likely contain the full URL in plaintext, which may be exposed if either system is hacked. In these cases, HTTP POST should be used.[7]

I could only suggest to REST team to consider more secure use of HTTP protocol to avoid making consumers struggle with non-secure "good practice".

Make Https call using HttpClient

For error:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

I think that you need to accept certificate unconditionally with following code

ServicePointManager.ServerCertificateValidationCallback += 
    (sender, cert, chain, sslPolicyErrors) => true;

as Oppositional wrote in his answer to question .NET client connecting to ssl Web API.

Delete directories recursively in Java

One-liner solution (Java8) to delete all files and directories recursively including starting directory:

Files.walk(Paths.get("c:/dir_to_delete/"))
                .map(Path::toFile)
                .sorted((o1, o2) -> -o1.compareTo(o2))
                .forEach(File::delete);

We use a comparator for reversed order, otherwise File::delete won't be able to delete possibly non-empty directory. So, if you want to keep directories and only delete files just remove the comparator in sorted() or remove sorting completely and add files filter:

Files.walk(Paths.get("c:/dir_to_delete/"))
                .filter(Files::isRegularFile)
                .map(Path::toFile)
                .forEach(File::delete);

How to set up datasource with Spring for HikariCP?

May this also can help using configuration file like java class way.

@Configuration
@PropertySource("classpath:application.properties")
public class DataSourceConfig {
    @Autowired
    JdbcConfigProperties jdbc;


    @Bean(name = "hikariDataSource")
    public DataSource hikariDataSource() {
        HikariConfig config = new HikariConfig();
        HikariDataSource dataSource;

        config.setJdbcUrl(jdbc.getUrl());
        config.setUsername(jdbc.getUser());
        config.setPassword(jdbc.getPassword());
        // optional: Property setting depends on database vendor
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        dataSource = new HikariDataSource(config);

        return dataSource;
    }
}

How to use it:

@Component
public class Car implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(AptSommering.class);


    @Autowired
    @Qualifier("hikariDataSource")
    private DataSource hikariDataSource;


}

Getting a timestamp for today at midnight?

$midnight = strtotime('midnight'); is valid
You can also try out strtotime('12am') or strtotime('[input any time you wish to here. e.g noon, 6pm, 3pm, 8pm, etc]'). I skipped adding today before midnight because the default is today.

Remove rows with all or some NAs (missing values) in data.frame

tidyr has a new function drop_na:

library(tidyr)
df %>% drop_na()
#              gene hsap mmul mmus rnor cfam
# 2 ENSG00000199674    0    2    2    2    2
# 6 ENSG00000221312    0    1    2    3    2
df %>% drop_na(rnor, cfam)
#              gene hsap mmul mmus rnor cfam
# 2 ENSG00000199674    0    2    2    2    2
# 4 ENSG00000207604    0   NA   NA    1    2
# 6 ENSG00000221312    0    1    2    3    2

Executing periodic actions in Python

Surprised to not find a solution using a generator for timing. I just designed this one for my own purposes.

This solution: single threaded, no object instantiation each period, uses generator for times, rock solid on timing down to precision of the time module (unlike several of the solutions I've tried from stack exchange).

Note: for Python 2.x, replace next(g) below with g.next().

import time

def do_every(period,f,*args):
    def g_tick():
        t = time.time()
        while True:
            t += period
            yield max(t - time.time(),0)
    g = g_tick()
    while True:
        time.sleep(next(g))
        f(*args)

def hello(s):
    print('hello {} ({:.4f})'.format(s,time.time()))
    time.sleep(.3)

do_every(1,hello,'foo')

Results in, for example:

hello foo (1421705487.5811)
hello foo (1421705488.5811)
hello foo (1421705489.5809)
hello foo (1421705490.5830)
hello foo (1421705491.5803)
hello foo (1421705492.5808)
hello foo (1421705493.5811)
hello foo (1421705494.5811)
hello foo (1421705495.5810)
hello foo (1421705496.5811)
hello foo (1421705497.5810)
hello foo (1421705498.5810)
hello foo (1421705499.5809)
hello foo (1421705500.5811)
hello foo (1421705501.5811)
hello foo (1421705502.5811)
hello foo (1421705503.5810)

Note that this example includes a simulation of the cpu doing something else for .3 seconds each period. If you changed it to be random each time it wouldn't matter. The max in the yield line serves to protect sleep from negative numbers in case the function being called takes longer than the period specified. In that case it would execute immediately and make up the lost time in the timing of the next execution.

How to return only the Date from a SQL Server DateTime datatype

I think this would work in your case:

CONVERT(VARCHAR(10),Person.DateOfBirth,111) AS BirthDate
//here date is obtained as 1990/09/25

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

This is not the correct answer for the question but still I would like to share this...

Using just document.createElement('div') and skipping JQuery will improve the performance a lot when you want to make lot of elements on the fly and append to DOM.

Java Reflection: How to get the name of a variable?

(Edit: two previous answers removed, one for answering the question as it stood before edits and one for being, if not absolutely wrong, at least close to it.)

If you compile with debug information on (javac -g), the names of local variables are kept in the .class file. For example, take this simple class:

class TestLocalVarNames {
    public String aMethod(int arg) {
        String local1 = "a string";
        StringBuilder local2 = new StringBuilder();
        return local2.append(local1).append(arg).toString();
    }
}

After compiling with javac -g:vars TestLocalVarNames.java, the names of local variables are now in the .class file. javap's -l flag ("Print line number and local variable tables") can show them.

javap -l -c TestLocalVarNames shows:

class TestLocalVarNames extends java.lang.Object{
TestLocalVarNames();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

  LocalVariableTable:
   Start  Length  Slot  Name   Signature
   0      5      0    this       LTestLocalVarNames;

public java.lang.String aMethod(int);
  Code:
   0:   ldc     #2; //String a string
   2:   astore_2
   3:   new     #3; //class java/lang/StringBuilder
   6:   dup
   7:   invokespecial   #4; //Method java/lang/StringBuilder."<init>":()V
   10:  astore_3
   11:  aload_3
   12:  aload_2
   13:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   16:  iload_1
   17:  invokevirtual   #6; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
   20:  invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   23:  areturn

  LocalVariableTable:
   Start  Length  Slot  Name   Signature
   0      24      0    this       LTestLocalVarNames;
   0      24      1    arg       I
   3      21      2    local1       Ljava/lang/String;
   11      13      3    local2       Ljava/lang/StringBuilder;
}

The VM spec explains what we're seeing here:

§4.7.9 The LocalVariableTable Attribute:

The LocalVariableTable attribute is an optional variable-length attribute of a Code (§4.7.3) attribute. It may be used by debuggers to determine the value of a given local variable during the execution of a method.

The LocalVariableTable stores the names and types of the variables in each slot, so it is possible to match them up with the bytecode. This is how debuggers can do "Evaluate expression".

As erickson said, though, there's no way to access this table through normal reflection. If you're still determined to do this, I believe the Java Platform Debugger Architecture (JPDA) will help (but I've never used it myself).

Regular Expression to get a string between parentheses in Javascript

To match a substring inside parentheses excluding any inner parentheses you may use

\(([^()]*)\)

pattern. See the regex demo.

In JavaScript, use it like

var rx = /\(([^()]*)\)/g;

Pattern details

  • \( - a ( char
  • ([^()]*) - Capturing group 1: a negated character class matching any 0 or more chars other than ( and )
  • \) - a ) char.

To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value.

Most up-to-date JavaScript code demo (using matchAll):

_x000D_
_x000D_
const strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
const rx = /\(([^()]*)\)/g;
strs.forEach(x => {
  const matches = [...x.matchAll(rx)];
  console.log( Array.from(matches, m => m[0]) ); // All full match values
  console.log( Array.from(matches, m => m[1]) ); // All Group 1 values
});
_x000D_
_x000D_
_x000D_

Legacy JavaScript code demo (ES5 compliant):

_x000D_
_x000D_
var strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
var rx = /\(([^()]*)\)/g;


for (var i=0;i<strs.length;i++) {
  console.log(strs[i]);

  // Grab Group 1 values:
  var res=[], m;
  while(m=rx.exec(strs[i])) {
    res.push(m[1]);
  }
  console.log("Group 1: ", res);

  // Grab whole values
  console.log("Whole matches: ", strs[i].match(rx));
}
_x000D_
_x000D_
_x000D_

You should not use <Link> outside a <Router>

For JEST users

if you use Jest for testing and this error happen just wrap your component with <BrowserRouter>

describe('Test suits for MyComponentWithLink', () => {
it('should match with snapshot', () => {
const tree = renderer
  .create(
    <BrowserRouter>
      <MyComponentWithLink/>
    </BrowserRouter>
  )
  .toJSON();
 expect(tree).toMatchSnapshot();
 });
});

How to use if statements in underscore.js templates?

Here is a simple if/else check in underscore.js, if you need to include a null check.

<div class="editor-label">
    <label>First Name : </label>
</div>
<div class="editor-field">
    <% if(FirstName == null) { %>
        <input type="text" id="txtFirstName" value="" />
    <% } else { %>
        <input type="text" id="txtFirstName" value="<%=FirstName%>" />
    <% } %>
</div>

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

I realize this is a little old, but, yes it can be done. Some javascript to get you started:

viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0');

Just change the parts you need and Mobile Safari will respect the new settings.

Update:

If you don't already have the meta viewport tag in the source, you can append it directly with something like this:

var metaTag=document.createElement('meta');
metaTag.name = "viewport"
metaTag.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
document.getElementsByTagName('head')[0].appendChild(metaTag);

Or if you're using jQuery:

$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">');

How to get column by number in Pandas?

The following is taken from http://pandas.pydata.org/pandas-docs/dev/indexing.html. There are a few more examples... you have to scroll down a little

In [816]: df1

           0         2         4         6
0   0.569605  0.875906 -2.211372  0.974466
2  -2.006747 -0.410001 -0.078638  0.545952
4  -1.219217 -1.226825  0.769804 -1.281247
6  -0.727707 -0.121306 -0.097883  0.695775
8   0.341734  0.959726 -1.110336 -0.619976
10  0.149748 -0.732339  0.687738  0.176444

Select via integer slicing

In [817]: df1.iloc[:3]

          0         2         4         6
0  0.569605  0.875906 -2.211372  0.974466
2 -2.006747 -0.410001 -0.078638  0.545952
4 -1.219217 -1.226825  0.769804 -1.281247

In [818]: df1.iloc[1:5,2:4]

          4         6
2 -0.078638  0.545952
4  0.769804 -1.281247
6 -0.097883  0.695775
8 -1.110336 -0.619976

Select via integer list

In [819]: df1.iloc[[1,3,5],[1,3]]

           2         6
2  -0.410001  0.545952
6  -0.121306  0.695775
10 -0.732339  0.176444

Sleep Command in T-SQL?

Here is a very simple piece of C# code to test the CommandTimeout with. It creates a new command which will wait for 2 seconds. Set the CommandTimeout to 1 second and you will see an exception when running it. Setting the CommandTimeout to either 0 or something higher than 2 will run fine. By the way, the default CommandTimeout is 30 seconds.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data.SqlClient;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var builder = new SqlConnectionStringBuilder();
      builder.DataSource = "localhost";
      builder.IntegratedSecurity = true;
      builder.InitialCatalog = "master";

      var connectionString = builder.ConnectionString;

      using (var connection = new SqlConnection(connectionString))
      {
        connection.Open();

        using (var command = connection.CreateCommand())
        {
          command.CommandText = "WAITFOR DELAY '00:00:02'";
          command.CommandTimeout = 1;

          command.ExecuteNonQuery();
        }
      }
    }
  }
}

Django set default form values

As explained in Django docs, initial is not default.

  • The initial value of a field is intended to be displayed in an HTML . But if the user delete this value, and finally send back a blank value for this field, the initial value is lost. So you do not obtain what is expected by a default behaviour.

  • The default behaviour is : the value that validation process will take if data argument do not contain any value for the field.

To implement that, a straightforward way is to combine initial and clean_<field>():

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

    (...)

    def clean_tank(self):
        if not self['tank'].html_name in self.data:
            return self.fields['tank'].initial
        return self.cleaned_data['tank']

Only variable references should be returned by reference - Codeigniter

Edit filename: core/Common.php, line number: 257

Before

return $_config[0] =& $config; 

After

$_config[0] =& $config;
return $_config[0]; 

Update

Added by NikiC

In PHP assignment expressions always return the assigned value. So $_config[0] =& $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).

Update

This fix has been merged into CI 2.2.1 (https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3). It's better to upgrade rather than modifying core framework files.

Finding common rows (intersection) in two Pandas dataframes

If I understand you correctly, you can use a combination of Series.isin() and DataFrame.append():

In [80]: df1
Out[80]:
   rating  user_id
0       2  0x21abL
1       1  0x21abL
2       1   0xdafL
3       0  0x21abL
4       4  0x1d14L
5       2  0x21abL
6       1  0x21abL
7       0   0xdafL
8       4  0x1d14L
9       1  0x21abL

In [81]: df2
Out[81]:
   rating      user_id
0       2      0x1d14L
1       1    0xdbdcad7
2       1      0x21abL
3       3      0x21abL
4       3      0x21abL
5       1  0x5734a81e2
6       2      0x1d14L
7       0       0xdafL
8       0      0x1d14L
9       4  0x5734a81e2

In [82]: ind = df2.user_id.isin(df1.user_id) & df1.user_id.isin(df2.user_id)

In [83]: ind
Out[83]:
0     True
1    False
2     True
3     True
4     True
5    False
6     True
7     True
8     True
9    False
Name: user_id, dtype: bool

In [84]: df1[ind].append(df2[ind])
Out[84]:
   rating  user_id
0       2  0x21abL
2       1   0xdafL
3       0  0x21abL
4       4  0x1d14L
6       1  0x21abL
7       0   0xdafL
8       4  0x1d14L
0       2  0x1d14L
2       1  0x21abL
3       3  0x21abL
4       3  0x21abL
6       2  0x1d14L
7       0   0xdafL
8       0  0x1d14L

This is essentially the algorithm you described as "clunky", using idiomatic pandas methods. Note the duplicate row indices. Also, note that this won't give you the expected output if df1 and df2 have no overlapping row indices, i.e., if

In [93]: df1.index & df2.index
Out[93]: Int64Index([], dtype='int64')

In fact, it won't give the expected output if their row indices are not equal.

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

Parse date without timezone javascript

Date in javascript is just keeping it simple inside. so the date-time data is stored in UTC unix epoch (milliseconds or ms).

If you want to have a "fixed" time that doesn't change in whatever timezone you are on the earth, you can adjust the time in UTC to match your current local timezone and save it. And when retreiving it, in whatever your local timezone you are in, it will show the adjusted UTC time based on the one who saved it and the add the local timezone offset to get the "fixed" time.

To save date (in ms)

toUTC(datetime) {
  const myDate = (typeof datetime === 'number')
    ? new Date(datetime)
    : datetime;

  if (!myDate || (typeof myDate.getTime !== 'function')) {
    return 0;
  }

  const getUTC = myDate.getTime();
  const offset = myDate.getTimezoneOffset() * 60000; // It's in minutes so convert to ms
  return getUTC - offset; // UTC - OFFSET
}

To retreive/show date (in ms)

fromUTC(datetime) {
  const myDate = (typeof datetime === 'number')
    ? new Date(datetime)
    : datetime;

  if (!myDate || (typeof myDate.getTime !== 'function')) {
    return 0;
  }

  const getUTC = myDate.getTime();
  const offset = myDate.getTimezoneOffset() * 60000; // It's in minutes so convert to ms
  return getUTC + offset; // UTC + OFFSET
}

Then you can:

const saveTime = new Date(toUTC(Date.parse("2005-07-08T00:00:00+0000")));
// SEND TO DB....

// FROM DB...
const showTime = new Date(fromUTC(saveTime));

Comparing chars in Java

One way to do it using a List<Character> constructed using overloaded convenience factory methods in is as :

if(List.of('A','B','C','D','E').contains(symbol) {
    // do something
}

Input type=password, don't let browser remember the password

<input type="password" autocomplete="off" />

I'd just like to add that as a user I think this is very annoying and a hassle to overcome. I strongly recommend against using this as it will more than likely aggravate your users.

Passwords are already not stored in the MRU, and correctly configured public machines will not even save the username.

Generating Random Passwords

I created this method similar to the available in the membership provider. This is usefull if you don't want to add the web reference in some applications.

It works great.

public static string GeneratePassword(int Length, int NonAlphaNumericChars)
    {
        string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
        string allowedNonAlphaNum = "!@#$%^&*()_-+=[{]};:<>|./?";
        Random rd = new Random();

        if (NonAlphaNumericChars > Length || Length <= 0 || NonAlphaNumericChars < 0)
            throw new ArgumentOutOfRangeException();

            char[] pass = new char[Length];
            int[] pos = new int[Length];
            int i = 0, j = 0, temp = 0;
            bool flag = false;

            //Random the position values of the pos array for the string Pass
            while (i < Length - 1)
            {
                j = 0;
                flag = false;
                temp = rd.Next(0, Length);
                for (j = 0; j < Length; j++)
                    if (temp == pos[j])
                    {
                        flag = true;
                        j = Length;
                    }

                if (!flag)
                {
                    pos[i] = temp;
                    i++;
                }
            }

            //Random the AlphaNumericChars
            for (i = 0; i < Length - NonAlphaNumericChars; i++)
                pass[i] = allowedChars[rd.Next(0, allowedChars.Length)];

            //Random the NonAlphaNumericChars
            for (i = Length - NonAlphaNumericChars; i < Length; i++)
                pass[i] = allowedNonAlphaNum[rd.Next(0, allowedNonAlphaNum.Length)];

            //Set the sorted array values by the pos array for the rigth posistion
            char[] sorted = new char[Length];
            for (i = 0; i < Length; i++)
                sorted[i] = pass[pos[i]];

            string Pass = new String(sorted);

            return Pass;
    }

How do I execute a command and get the output of the command within C++ using POSIX?

C++ stream implemention of waqas's answer:

#include <istream>
#include <streambuf>
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>

class execbuf : public std::streambuf {
    protected:
        std::string output;
        int_type underflow(int_type character) {
            if (gptr() < egptr()) return traits_type::to_int_type(*gptr());
            return traits_type::eof();
        }
    public:
        execbuf(const char* command) {
            std::array<char, 128> buffer;
            std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(command, "r"), pclose);
            if (!pipe) {
                throw std::runtime_error("popen() failed!");
            }
            while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
                this->output += buffer.data();
            }
            setg((char*)this->output.data(), (char*)this->output.data(), (char*)(this->output.data() + this->output.size()));
        }
};

class exec : public std::istream {
    protected:
        execbuf buffer;
    public:
        exec(char* command) : std::istream(nullptr), buffer(command, fd) {
            this->rdbuf(&buffer);
        }
};

This code catches all output through stdout . If you want to catch only stderr then pass your command like this:

sh -c '<your-command>' 2>&1 > /dev/null

If you want to catch both stdout and stderr then the command should be like this:

sh -c '<your-command>' 2>&1

How to connect to mysql with laravel?

It's also much more better to not modify the app/config/database.php file itself... otherwise modify .env file and put your DB info there. (.env file is available in Laravel 5, not sure if it was there in previous versions...)

NOTE: Of course you should have already set mysql as your default database connection in the app/config/database.php file.

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

I've ported Grant Burton's PHP code to an ASP.Net static method callable against the HttpRequestBase. It will optionally skip through any private IP ranges.

public static class ClientIP
{
    // based on http://www.grantburton.com/2008/11/30/fix-for-incorrect-ip-addresses-in-wordpress-comments/
    public static string ClientIPFromRequest(this HttpRequestBase request, bool skipPrivate)
    {
        foreach (var item in s_HeaderItems)
        {
            var ipString = request.Headers[item.Key];

        if (String.IsNullOrEmpty(ipString))
            continue;

        if (item.Split)
        {
            foreach (var ip in ipString.Split(','))
                if (ValidIP(ip, skipPrivate))
                    return ip;
        }
        else
        {
            if (ValidIP(ipString, skipPrivate))
                return ipString;
        }
    }

    return request.UserHostAddress;
}

private static bool ValidIP(string ip, bool skipPrivate)
{
    IPAddress ipAddr;

    ip = ip == null ? String.Empty : ip.Trim();

    if (0 == ip.Length
        || false == IPAddress.TryParse(ip, out ipAddr)
        || (ipAddr.AddressFamily != AddressFamily.InterNetwork
            && ipAddr.AddressFamily != AddressFamily.InterNetworkV6))
        return false;

    if (skipPrivate && ipAddr.AddressFamily == AddressFamily.InterNetwork)
    {
        var addr = IpRange.AddrToUInt64(ipAddr);
        foreach (var range in s_PrivateRanges)
        {
            if (range.Encompasses(addr))
                return false;
        }
    }

    return true;
}

/// <summary>
/// Provides a simple class that understands how to parse and
/// compare IP addresses (IPV4) ranges.
/// </summary>
private sealed class IpRange
{
    private readonly UInt64 _start;
    private readonly UInt64 _end;

    public IpRange(string startStr, string endStr)
    {
        _start = ParseToUInt64(startStr);
        _end = ParseToUInt64(endStr);
    }

    public static UInt64 AddrToUInt64(IPAddress ip)
    {
        var ipBytes = ip.GetAddressBytes();
        UInt64 value = 0;

        foreach (var abyte in ipBytes)
        {
            value <<= 8;    // shift
            value += abyte;
        }

        return value;
    }

    public static UInt64 ParseToUInt64(string ipStr)
    {
        var ip = IPAddress.Parse(ipStr);
        return AddrToUInt64(ip);
    }

    public bool Encompasses(UInt64 addrValue)
    {
        return _start <= addrValue && addrValue <= _end;
    }

    public bool Encompasses(IPAddress addr)
    {
        var value = AddrToUInt64(addr);
        return Encompasses(value);
    }
};

private static readonly IpRange[] s_PrivateRanges =
    new IpRange[] { 
            new IpRange("0.0.0.0","2.255.255.255"),
            new IpRange("10.0.0.0","10.255.255.255"),
            new IpRange("127.0.0.0","127.255.255.255"),
            new IpRange("169.254.0.0","169.254.255.255"),
            new IpRange("172.16.0.0","172.31.255.255"),
            new IpRange("192.0.2.0","192.0.2.255"),
            new IpRange("192.168.0.0","192.168.255.255"),
            new IpRange("255.255.255.0","255.255.255.255")
    };


/// <summary>
/// Describes a header item (key) and if it is expected to be 
/// a comma-delimited string
/// </summary>
private sealed class HeaderItem
{
    public readonly string Key;
    public readonly bool Split;

    public HeaderItem(string key, bool split)
    {
        Key = key;
        Split = split;
    }
}

// order is in trust/use order top to bottom
private static readonly HeaderItem[] s_HeaderItems =
    new HeaderItem[] { 
            new HeaderItem("HTTP_CLIENT_IP",false),
            new HeaderItem("HTTP_X_FORWARDED_FOR",true),
            new HeaderItem("HTTP_X_FORWARDED",false),
            new HeaderItem("HTTP_X_CLUSTER_CLIENT_IP",false),
            new HeaderItem("HTTP_FORWARDED_FOR",false),
            new HeaderItem("HTTP_FORWARDED",false),
            new HeaderItem("HTTP_VIA",false),
            new HeaderItem("REMOTE_ADDR",false)
    };
}