Programs & Examples On #Esoteric languages

Esoteric languages are languages designed to push the boundaries of accepted programming language design, either as a joke or as a proof of concept.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

find . -type f | 
sed -n "s/\(.*\)factory\.py$/& \1service\.py/p" | 
xargs -p -n 2 mv

eg will rename all files in the cwd with names ending in "factory.py" to be replaced with names ending in "service.py"

explanation:

1) in the sed cmd, the -n flag will suppress normal behavior of echoing input to output after the s/// command is applied, and the p option on s/// will force writing to output if a substitution is made. since a sub will only be made on match, sed will only have output for files ending in "factory.py"

2) in the s/// replacement string, we use "& " to interpolate the entire matching string, followed by a space character, into the replacement. because of this, it's vital that our RE matches the entire filename. after the space char, we use "\1service.py" to interpolate the string we gulped before "factory.py", followed by "service.py", replacing it. So for more complex transformations youll have to change the args to s/// (with an re still matching the entire filename)

example output:

foo_factory.py foo_service.py
bar_factory.py bar_service.py

3) we use xargs with -n 2 to consume the output of sed 2 delimited strings at a time, passing these to mv (i also put the -p option in there so you can feel safe when running this). voila.

How to replicate background-attachment fixed on iOS

It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.

wrapper div{
   image wrapper div{
       div for individual image{ <--- Fixed position
          image <--- relative position
       }
   }
   quote wrapper div{
       div for individual quote{
          quote
       }
   }
 }

How can I open a URL in Android's web browser from my application?

In 2.3, I had better luck with

final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url));
activity.startActivity(intent);

The difference being the use of Intent.ACTION_VIEW rather than the String "android.intent.action.VIEW"

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

Comparing date part only without comparing time in JavaScript

As I don't see here similar approach, and I'm not enjoying setting h/m/s/ms to 0, as it can cause problems with accurate transition to local time zone with changed date object (I presume so), let me introduce here this, written few moments ago, lil function:

+: Easy to use, makes a basic comparison operations done (comparing day, month and year without time.)
-: It seems that this is a complete opposite of "out of the box" thinking.

function datecompare(date1, sign, date2) {
    var day1 = date1.getDate();
    var mon1 = date1.getMonth();
    var year1 = date1.getFullYear();
    var day2 = date2.getDate();
    var mon2 = date2.getMonth();
    var year2 = date2.getFullYear();
    if (sign === '===') {
        if (day1 === day2 && mon1 === mon2 && year1 === year2) return true;
        else return false;
    }
    else if (sign === '>') {
        if (year1 > year2) return true;
        else if (year1 === year2 && mon1 > mon2) return true;
        else if (year1 === year2 && mon1 === mon2 && day1 > day2) return true;
        else return false;
    }    
}

Usage:

datecompare(date1, '===', date2) for equality check,
datecompare(date1, '>', date2) for greater check,
!datecompare(date1, '>', date2) for less or equal check

Also, obviously, you can switch date1 and date2 in places to achieve any other simple comparison.

What do >> and << mean in Python?

These are bitwise shift operators.

Quoting from the docs:

x << y

Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

x >> y

Returns x with the bits shifted to the right by y places. This is the same as dividing x by 2**y.

PHP GuzzleHttp. How to make a post request with params?

$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
    'body' => json_encode($dataArray)
]);
$response = $request->getBody();

Add

openssl.cafile in php.ini file

How to push changes to github after jenkins build completes?

The git checkout master of the answer by Woland isn't needed. Instead use the "Checkout to specific local branch" in the "Additional Behaviors" section to set the "Branch name" to master.

The git commit -am "blah" is still needed.

Now you can use the "Git Publisher" under "Post-build Actions" to push the changes. Be sure to specify the "Branches" to push ("Branch to push" = master, "Target remote name" = origin).

"Merge Results" isn't needed.

Performance of Java matrix math libraries?

You should add Apache Mahout to your shopping list.

How do I make an HTML button not reload the page

I can't comment yet, so I'm posting this as an answer. Best way to avoid reload is how @user2868288 said: using the onsubmit on the form tag.

From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page. For example:

<form id="frmData" onsubmit="return false">
 <input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
 <input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
 <input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
  $(document).ready(function(){
    $('#btnSubmit').click(function() {
        var tel = $("#txtTel").val();
        var email = $("#txtEmail").val();
        $.post("scripts/contact.php", {
            tel1: tel,
            email1: email
        })
        .done(function(data) {
            $('#lblEstatus').append(data); // Appends status
            if (data == "Received") {
                $("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
            }
        })
        .fail(function(xhr, textStatus, errorThrown) { 
            $('#lblEstatus').append("Error. Try later."); 
        });
     });
   }); 
</script>

Click a button programmatically - JS

When using JavaScript to access an HTML element, there is a good chance that the element is not on the page and therefore not in the dom as far as JavaScript is concerned, when the code to access that element runs.

This problem can occur even though you can visually see the HTML element in the browser window or have the code set to be called in the onload method.

I ran into this problem after writing code to repopulate specific div elements on a page after retrieving the cookies.

What is apparently happening is that even though the HTML has loaded and is outputted by the browser, the JavaScript code is running before the page has completed loading.

The solution to this problem which just may be a JavaScript bug, is to place the code you want to run within a timer that delays the code run by 400 milliseconds or so. You will need to test it to determine how quick you can run the code.

I also made a point to test for the element before attempting to assign values to it.

window.setTimeout(function() { if( document.getElementById("book") ) { // Code goes here }, 400 /* but after 400 ms */);

This may or may not help you solve your problem, but keep this in mind and understand that browsers do not always function as expected.

How to push to History in React Router v4?

Simplest way in React Router 4 is to use

this.props.history.push('/new/url');

But to use this method, your existing component should have access to history object. We can get access by

  1. If your component is linked to Route directly, then your component already has access to history object.

    eg:

    <Route path="/profile" component={ViewProfile}/>
    

    Here ViewProfile has access to history.

  2. If not connected to Route directly.

    eg:

    <Route path="/users" render={() => <ViewUsers/>}
    

    Then we have to use withRouter, a heigher order fuction to warp the existing component.

    Inside ViewUsers component

    • import { withRouter } from 'react-router-dom';

    • export default withRouter(ViewUsers);

    That's it now, your ViewUsers component has access to history object.

UPDATE

2- in this scenario, pass all route props to your component, and then we can access this.props.history from the component even without a HOC

eg:

<Route path="/users" render={props => <ViewUsers {...props} />}

What is PHPSESSID?

PHPSESSID reveals you are using PHP. If you don't want this you can easily change the name using the session.name in your php.ini file or using the session_name() function.

Send email using the GMail SMTP server from a PHP page

Gmail requires port 465, and also it's the code from phpmailer :)

Python if not == vs if !=

It's about your way of reading it. not operator is dynamic, that's why you are able to apply it in

if not x == 'val':

But != could be read in a better context as an operator which does the opposite of what == does.

Bootstrap change div order with pull-right, pull-left on 3 columns

Try this...

<div class="row">
    <div class="col-xs-3">
        Menu
    </div>
    <div class="col-xs-9">
        <div class="row">
          <div class="col-sm-4 col-sm-push-8">
          Right content
          </div>
          <div class="col-sm-8 col-sm-pull-4">
          Content
          </div>
       </div>
    </div>
</div>

Bootply

jsPDF multi page PDF with HTML renderer

Below is my code but the problem is that the document doesn't split to display the other part of the document in a new page.

Please improve this code.

<script type='text/javascript'>
$(document).on("click", "#btnExportToPDF", function () {
    var table1 =
    tableToJson($('#table1')[0]),
    cellWidth =42,
    rowCount = 0,
    cellContents,
    leftMargin = 2,
    topMargin = 12,
    topMarginTable =5,
    headerRowHeight = 13,
    rowHeight = 12,
    l = {
        orientation: 'p',
        unit: 'mm',
        format: 'a3',
        compress: true,
        fontSize: 11,
        lineHeight: 1,
        autoSize: false,
        printHeaders: true
    };

    var doc = new jsPDF(l,'pt', 'letter');

    doc.setProperties({
        title: 'Test PDF Document',
        subject: 'This is the subject',
        author: 'author',
        keywords: 'generated, javascript, web 2.0, ajax',
        creator: 'author'
    });
    doc.cellInitialize();

    $.each(table1, function (i, row)
    {
        rowCount++;

        $.each(row, function (j, cellContent) {

            if (rowCount == 1) {
                doc.margins = 1;
                doc.setFont("Times New Roman");
                doc.setFontType("bold");
                doc.setFontSize(11);

                doc.cell(leftMargin, topMargin, cellWidth, headerRowHeight, cellContent, i)
            }
            else if (rowCount == 2) {

                doc.margins = 1;
                doc.setFont("Times ");
                doc.setFontType("normal");
                // or for normal font type use ------ doc.setFontType("normal");

                doc.setFontSize(11);

                doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
            }
            else {

                doc.margins = 1;
                doc.setFont("Times  ");
                doc.setFontType("normal ");
                doc.setFontSize(11);
                doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
                // 1st=left margin    2nd parameter=top margin,     3rd=row cell width      4th=Row height
            }
        })
    })
    doc.save('sample Report.pdf');
});

function tableToJson(table) {

    var data = [];

    // first row needs to be headers
    var headers = [];

    for (var i=0; i<table.rows[0].cells.length; i++) {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }

    // go through cells
    for (var i=1; i<table.rows.length; i++) {

        var tableRow = table.rows[i];

        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {
            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
        }

        data.push(rowData);
    }

    return data;
}
</script>

How To Include CSS and jQuery in my WordPress plugin?

For styles wp_register_style( 'namespace', 'http://locationofcss.com/mycss.css' );

Then use: wp_enqueue_style('namespace'); wherever you want the css to load.

Scripts are as above but the quicker way for loading jquery is just to use enqueue loaded in an init for the page you want it to load on: wp_enqueue_script('jquery');

Unless of course you want to use the google repository for jquery.

You can also conditionally load the jquery library that your script is dependent on:

wp_enqueue_script('namespaceformyscript', 'http://locationofscript.com/myscript.js', array('jquery'));

Update Sept. 2017

I wrote this answer a while ago. I should clarify that the best place to enqueue your scripts and styles is within the wp_enqueue_scripts hook. So for example:

add_action('wp_enqueue_scripts', 'callback_for_setting_up_scripts');
function callback_for_setting_up_scripts() {
    wp_register_style( 'namespace', 'http://locationofcss.com/mycss.css' );
    wp_enqueue_style( 'namespace' );
    wp_enqueue_script( 'namespaceformyscript', 'http://locationofscript.com/myscript.js', array( 'jquery' ) );
}

The wp_enqueue_scripts action will set things up for the "frontend". You can use the admin_enqueue_scripts action for the backend (anywhere within wp-admin) and the login_enqueue_scripts action for the login page.

CSS performance relative to translateZ(0)

If you want implications, in some scenarios Google Chrome performance is horrible with hardware acceleration enabled. Oddly enough, changing the "trick" to -webkit-transform: rotateZ(360deg); worked just fine.

I don't believe we ever figured out why.

gcloud command not found - while installing Google Cloud SDK

sudo ./google-cloud-sdk/install.sh

I ran this in the root directory and it worked. I'm running macOS Mojave Version 10.14.3.

How to use npm with ASP.NET Core

Install the Bundler and Minifier into Visual Studio Extensions

Then you create a bundleconfig.json and enter the following like :

// Configure bundling and minification for the project.
// More info at https://go.microsoft.com/fwlink/?LinkId=808241
[
 {
    "outputFileName": "wwwroot/js/jquery.min.js",
    "inputFiles": [
      "node_modules/jquery/dist/jquery.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": false
    },
    // Optionally generate .map file
    "sourceMap": false
  }
]

So the bundler and minifier (gulp based) has access to the source files (which should be excluded from Visual Studio and also excluded from GIT) and puts them into the wwwroot as specified

only side effect every time you save it will run this (but you can set it to run it manually)

How to change theme for AlertDialog

Anyone trying to do this within a Fragment (using the support library i.e. pre API 11) should go with this:

public class LoadingDialogFragment extends DialogFragment {
    public static final String ID = "loadingDialog";

    public static LoadingDialogFragment newInstance() {
        LoadingDialogFragment f = new LoadingDialogFragment();

        return f;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        StyleAlertDialog adb = new StyleAlertDialog(getActivity(), R.style.Your_Style);
        adb.setView(getActivity().getLayoutInflater().inflate(R.layout.fragment_dialog_layout, null));
        return adb;
    }

    private class StyleAlertDialog extends AlertDialog {
        protected StyleAlertDialog(Context context, int theme) {
            super(context, theme);
        }
    }
}

@Rflexor gave me the nudge to extend AlertDialog and expose the constructor thanks

MySQL Query - Records between Today and Last 30 Days

For the current date activity and complete activity for previous 30 days use this, since the SYSDATE is variable in a day the previous 30th day will not have the whole data for that day.

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND SYSDATE()

How do you programmatically set an attribute?

let x be an object then you can do it two ways

x.attr_name = s 
setattr(x, 'attr_name', s)

how to loop through json array in jquery?

Try this:

for(var i = 0; i < data.length; i++){
    console.log(data[i].com)
}

Using ChildActionOnly in MVC

    public class HomeController : Controller  
    {  
        public ActionResult Index()  
        {  
            ViewBag.TempValue = "Index Action called at HomeController";  
            return View();  
        }  

        [ChildActionOnly]  
        public ActionResult ChildAction(string param)  
        {  
            ViewBag.Message = "Child Action called. " + param;  
            return View();  
        }  
    }  


The code is initially invoking an Index action that in turn returns two Index views and at the View level it calls the ChildAction named “ChildAction”.

    @{
        ViewBag.Title = "Index";    
    }    
    <h2>    
        Index    
    </h2>  

    <!DOCTYPE html>    
    <html>    
    <head>    
        <title>Error</title>    
    </head>    
    <body>    
        <ul>  
            <li>    
                @ViewBag.TempValue    
            </li>    
            <li>@ViewBag.OnExceptionError</li>    
            @*<li>@{Html.RenderAction("ChildAction", new { param = "first" });}</li>@**@    
            @Html.Action("ChildAction", "Home", new { param = "first" })    
        </ul>    
    </body>    
    </html>  


      Copy and paste the code to see the result .thanks 

take(1) vs first()

Tip: Only use first() if:

  • You consider zero items emitted to be an error condition (eg. completing before emitting) AND if there’s a greater than 0% chance of error you handling it gracefully
  • OR You know 100% that the source observable will emit 1+ items (so can never throw).

If there are zero emissions and you are not explicitly handling it (with catchError) then that error will get propagated up, possibly cause an unexpected problem somewhere else and can be quite tricky to track down - especially if it's coming from an end user.

You're safer off using take(1) for the most part provided that:

  • You're OK with take(1) not emitting anything if the source completes without an emission.
  • You don't need to use an inline predicate (eg. first(x => x > 10) )

Note: You can use a predicate with take(1) like this: .pipe( filter(x => x > 10), take(1) ). There is no error with this if nothing is ever greater than 10.

What about single()

If you want to be even stricter, and disallow two emissions you can use single() which errors if there are zero or 2+ emissions. Again you'd need to handle errors in that case.

Tip: Single can occasionally be useful if you want to ensure your observable chain isn't doing extra work like calling an http service twice and emitting two observables. Adding single to the end of the pipe will let you know if you made such a mistake. I'm using it in a 'task runner' where you pass in a task observable that should only emit one value, so I pass the response through single(), catchError() to guarantee good behavior.


Why not always use first() instead of take(1) ?

aka. How can first potentially cause more errors?

If you have an observable that takes something from a service and then pipes it through first() you should be fine most of the time. But if someone comes along to disable the service for whatever reason - and changes it to emit of(null) or NEVER then any downstream first() operators would start throwing errors.

Now I realize that might be exactly what you want - hence why this is just a tip. The operator first appealed to me because it sounded slightly less 'clumsy' than take(1) but you need to be careful about handling errors if there's ever a chance of the source not emitting. Will entirely depend on what you're doing though.


If you have a default value (constant):

Consider also .pipe(defaultIfEmpty(42), first()) if you have a default value that should be used if nothing is emitted. This would of course not raise an error because first would always receive a value.

Note that defaultIfEmpty is only triggered if the stream is empty, not if the value of what is emitted is null.

How I add Headers to http.get or http.post in Typescript and angular 2?

This way I was able to call MyService

private REST_API_SERVER = 'http://localhost:4040/abc';
public sendGetRequest() {
   var myFormData = { email: '[email protected]', password: '123' };
   const headers = new HttpHeaders();
   headers.append('Content-Type', 'application/json');
   //HTTP POST REQUEST
   this.httpClient
  .post(this.REST_API_SERVER, myFormData, {
    headers: headers,
   })
  .subscribe((data) => {
    console.log("i'm from service............", data, myFormData, headers);
    return data;
  });
}

div with dynamic min-height based on browser window height

No hack or js needed. Just apply the following rule to your root element:

min-height: 100%;
height: auto;

It will automatically choose the bigger one from the two as its height, which means if the content is longer than the browser, it will be the height of the content, otherwise, the height of the browser. This is standard css.

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

export IGNORE_WARNINGS=1

It does display warnings, but continues with the build

Replace Fragment inside a ViewPager

I found simple solution, which works fine even if you want add new fragments in the middle or replace current fragment. In my solution you should override getItemId() which should return unique id for each fragment. Not position as by default.

There is it:

public class DynamicPagerAdapter extends FragmentPagerAdapter {

private ArrayList<Page> mPages = new ArrayList<Page>();
private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();

public DynamicPagerAdapter(FragmentManager fm) {
    super(fm);
}

public void replacePage(int position, Page page) {
    mPages.set(position, page);
    notifyDataSetChanged();
}

public void setPages(ArrayList<Page> pages) {
    mPages = pages;
    notifyDataSetChanged();
}

@Override
public Fragment getItem(int position) {
    if (mPages.get(position).mPageType == PageType.FIRST) {
        return FirstFragment.newInstance(mPages.get(position));
    } else {
        return SecondFragment.newInstance(mPages.get(position));
    }
}

@Override
public int getCount() {
    return mPages.size();
}

@Override
public long getItemId(int position) {
    // return unique id
    return mPages.get(position).getId();
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = (Fragment) super.instantiateItem(container, position);
    while (mFragments.size() <= position) {
        mFragments.add(null);
    }
    mFragments.set(position, fragment);
    return fragment;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    super.destroyItem(container, position, object);
    mFragments.set(position, null);
}

@Override
public int getItemPosition(Object object) {
    PagerFragment pagerFragment = (PagerFragment) object;
    Page page = pagerFragment.getPage();
    int position = mFragments.indexOf(pagerFragment);
    if (page.equals(mPages.get(position))) {
        return POSITION_UNCHANGED;
    } else {
        return POSITION_NONE;
    }
}
}

Notice: In this example FirstFragment and SecondFragment extends abstract class PageFragment, which has method getPage().

Remove Blank option from Select Option with AngularJS

For reference : Why does angularjs include an empty option in select?

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.

In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.

Change your code like this

_x000D_
_x000D_
var MyApp=angular.module('MyApp1',[])
MyApp.controller('MyController', function($scope) {
  $scope.feed = {};

  //Configuration
  $scope.feed.configs = [
    {'name': 'Config 1',
     'value': 'config1'},
    {'name': 'Config 2',
     'value': 'config2'},
    {'name': 'Config 3',
     'value': 'config3'}
  ];
  //Setting first option as selected in configuration select
  $scope.feed.config = $scope.feed.configs[0].value;
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="MyApp1">
  <div ng-controller="MyController">
    <input type="text" ng-model="feed.name" placeholder="Name" />
    <!-- <select ng-model="feed.config">
<option ng-repeat="template in configs">{{template.name}}</option>
</select> -->
    <select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
    </select>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Working JSFiddle Demo

UPDATE (Dec 31, 2015)

If You don't want to set a default value and want to remove blank option,

<select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
      <option value="" selected="selected">Choose</option>
</select>

And in JS no need to initialize value.

$scope.feed.config = $scope.feed.configs[0].value;

How to sort an associative array by its values in Javascript?

Javascript doesn't have "associative arrays" the way you're thinking of them. Instead, you simply have the ability to set object properties using array-like syntax (as in your example), plus the ability to iterate over an object's properties.

The upshot of this is that there is no guarantee as to the order in which you iterate over the properties, so there is nothing like a sort for them. Instead, you'll need to convert your object properties into a "true" array (which does guarantee order). Here's a code snippet for converting an object into an array of two-tuples (two-element arrays), sorting it as you describe, then iterating over it:

var tuples = [];

for (var key in obj) tuples.push([key, obj[key]]);

tuples.sort(function(a, b) {
    a = a[1];
    b = b[1];

    return a < b ? -1 : (a > b ? 1 : 0);
});

for (var i = 0; i < tuples.length; i++) {
    var key = tuples[i][0];
    var value = tuples[i][1];

    // do something with key and value
}

You may find it more natural to wrap this in a function which takes a callback:

_x000D_
_x000D_
function bySortedValue(obj, callback, context) {_x000D_
  var tuples = [];_x000D_
_x000D_
  for (var key in obj) tuples.push([key, obj[key]]);_x000D_
_x000D_
  tuples.sort(function(a, b) {_x000D_
    return a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0_x000D_
  });_x000D_
_x000D_
  var length = tuples.length;_x000D_
  while (length--) callback.call(context, tuples[length][0], tuples[length][1]);_x000D_
}_x000D_
_x000D_
bySortedValue({_x000D_
  foo: 1,_x000D_
  bar: 7,_x000D_
  baz: 3_x000D_
}, function(key, value) {_x000D_
  document.getElementById('res').innerHTML += `${key}: ${value}<br>`_x000D_
});
_x000D_
<p id='res'>Result:<br/><br/><p>
_x000D_
_x000D_
_x000D_

Error creating bean with name

It looks like your Spring component scan Base is missing UserServiceImpl

<context:component-scan base-package="org.assessme.com.controller." />

$.ajax - dataType

jQuery Ajax loader is not working well when you call two APIs simultaneously. To resolve this problem you have to call the APIs one by one using the isAsync property in Ajax setting. You also need to make sure that there should not be any error in the setting. Otherwise, the loader will not work. E.g undefined content-type, data-type for POST/PUT/DELETE/GET call.

How can I get a web site's favicon?

You can use Getfv.co :

To retrieve a favicon you can hotlink it at... http://g.etfv.co/[URL]

Example for this page : http://g.etfv.co/https://stackoverflow.com/questions/5119041/how-can-i-get-a-web-sites-favicon

Download content and let's go !

Edit :

Getfv.co and fvicon.com look dead. If you want I found a non free alternative : grabicon.com.

How can I slice an ArrayList out of an ArrayList in Java?

This is how I solved it. I forgot that sublist was a direct reference to the elements in the original list, so it makes sense why it wouldn't work.

ArrayList<Integer> inputA = new ArrayList<Integer>(input.subList(0, input.size()/2));

Mod of negative number is melting my brain

Adding some understanding.

By Euclidean definition the mod result must be always positive.

Ex:

 int n = 5;
 int x = -3;

 int mod(int n, int x)
 {
     return ((n%x)+x)%x;
 }

Output:

 -1

Loading basic HTML in Node.js

This is a pretty old question...but if your use case here is to simply send a particular HTML page to the browser on an ad hoc basis, I would use something simple like this:

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

var server = http.createServer(function(req, res){
  var stream = fs.createReadStream('test.html');
  stream.pipe(res);
});
server.listen(7000);

Trying to retrieve first 5 characters from string in bash error?

You can try sed if you like -

[jaypal:~/Temp] TESTSTRINGONE="MOTEST"
[jaypal:~/Temp] sed 's/\(.\{5\}\).*/\1/' <<< "$TESTSTRINGONE"
MOTES

How do you obtain a Drawable object from a resource id in android package?

As of API 21, you could also use:

   ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);

Instead of ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

Input type "number" won't resize

Use an on onkeypress event. Example for a zip code box. It allows a maximum of 5 characters, and checks to make sure input is only numbers.

Nothing beats a server side validation of course, but this is a nifty way to go.

_x000D_
_x000D_
function validInput(e) {_x000D_
  e = (e) ? e : window.event;_x000D_
  a = document.getElementById('zip-code');_x000D_
  cPress = (e.which) ? e.which : e.keyCode;_x000D_
_x000D_
  if (cPress > 31 && (cPress < 48 || cPress > 57)) {_x000D_
    return false;_x000D_
  } else if (a.value.length >= 5) {_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  return true;_x000D_
}
_x000D_
#zip-code {_x000D_
  overflow: hidden;_x000D_
  width: 60px;_x000D_
}
_x000D_
<label for="zip-code">Zip Code:</label>_x000D_
<input type="number" id="zip-code" name="zip-code" onkeypress="return validInput(event);" required="required">
_x000D_
_x000D_
_x000D_

Remove pandas rows with duplicate indices

If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:

df3 = df3.query('~index.duplicated()')

This enables chaining statements like this:

df3.assign(C=2).query('~index.duplicated()').mean()

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

How to select multiple files with <input type="file">?

HTML5 has provided new attribute multiple for input element whose type attribute is file. So you can select multiple files and IE9 and previous versions does not support this.

NOTE: be carefull with the name of the input element. when you want to upload multiple file you should use array and not string as the value of the name attribute.

ex:

input type="file" name="myPhotos[]" multiple="multiple"

and if you are using php then you will get the data in $_FILES and use var_dump($_FILES) and see output and do processing Now you can iterate over and do the rest

What is the best way to implement constants in Java?

FWIW, a timeout in seconds value should probably be a configuration setting (read in from a properties file or through injection as in Spring) and not a constant.

git: How to ignore all present untracked files?

If you want to permanently ignore these files, a simple way to add them to .gitignore is:

  1. Change to the root of the git tree.
  2. git ls-files --others --exclude-standard >> .gitignore

This will enumerate all files inside untracked directories, which may or may not be what you want.

Class method differences in Python: bound, unbound and static

Methods in Python are a very, very simple thing once you understood the basics of the descriptor system. Imagine the following class:

class C(object):
    def foo(self):
        pass

Now let's have a look at that class in the shell:

>>> C.foo
<unbound method C.foo>
>>> C.__dict__['foo']
<function foo at 0x17d05b0>

As you can see if you access the foo attribute on the class you get back an unbound method, however inside the class storage (the dict) there is a function. Why's that? The reason for this is that the class of your class implements a __getattribute__ that resolves descriptors. Sounds complex, but is not. C.foo is roughly equivalent to this code in that special case:

>>> C.__dict__['foo'].__get__(None, C)
<unbound method C.foo>

That's because functions have a __get__ method which makes them descriptors. If you have an instance of a class it's nearly the same, just that None is the class instance:

>>> c = C()
>>> C.__dict__['foo'].__get__(c, C)
<bound method C.foo of <__main__.C object at 0x17bd4d0>>

Now why does Python do that? Because the method object binds the first parameter of a function to the instance of the class. That's where self comes from. Now sometimes you don't want your class to make a function a method, that's where staticmethod comes into play:

 class C(object):
  @staticmethod
  def foo():
   pass

The staticmethod decorator wraps your class and implements a dummy __get__ that returns the wrapped function as function and not as a method:

>>> C.__dict__['foo'].__get__(None, C)
<function foo at 0x17d0c30>

Hope that explains it.

jquery's append not working with svg element?

The accepted answer by Bobince is a short, portable solution. If you need to not only append SVG but also manipulate it, you could try the JavaScript library "Pablo" (I wrote it). It will feel familiar to jQuery users.

Your code example would then look like:

$(document).ready(function(){
    Pablo("svg").append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');
});

You can also create SVG elements on the fly, without specifying markup:

var circle = Pablo.circle({
    cx:100,
    cy:50,
    r:40
}).appendTo('svg');

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

You have mentioned "user" twice in your FROM clause. You must provide a table alias to at least one mention so each mention of user. can be pinned to one or the other instance:

FROM article INNER JOIN section
ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user **AS user1** ON article.author\_id = **user1**.id
LEFT JOIN user **AS user2** ON article.modified\_by = **user2**.id
WHERE article.id = '1'

(You may need something different - I guessed which user is which, but the SQL engine won't guess.)

Also, maybe you only needed one "user". Who knows?

Remove attribute "checked" of checkbox

You could try $(this):

$("#captureAudio").live("change", function() {
    if($(this).val() !== undefined) { /* IF THIS VALUE IS NOT UNDEFINED */
            navigator.device.capture.captureAudio(function(mediaFiles) {
            console.log("audio");
        }, function() {
            $(this).removeAttr('checked'); /* REMOVE checked ATTRIBUTE; */
            /* YOU CAN USE `$(this).prop("checked", false);` ALSO */
            _callback.error;
        }, {limit: 1});
    }
});

UICollectionView Self Sizing Cells with Auto Layout

contentView anchor mystery:

In one bizarre case this

    contentView.translatesAutoresizingMaskIntoConstraints = false

would not work. Added four explicit anchors to the contentView and it worked.

class AnnoyingCell: UICollectionViewCell {
    
    @IBOutlet var word: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame); common() }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder); common() }
    
    private func common() {
        contentView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            contentView.leftAnchor.constraint(equalTo: leftAnchor),
            contentView.rightAnchor.constraint(equalTo: rightAnchor),
            contentView.topAnchor.constraint(equalTo: topAnchor),
            contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }
}

and as usual

    estimatedItemSize = UICollectionViewFlowLayout.automaticSize

in YourLayout: UICollectionViewFlowLayout

Who knows? Might help someone.

Credit

https://www.vadimbulavin.com/collection-view-cells-self-sizing/

stumbled on to the tip there - never saw it anywhere else in all the 1000s articles on this.

Wampserver icon not going green fully, mysql services not starting up?

I have uninstalled the WampServer completelly, and deleted all files in /wamp folder, except www. This folder is preserved when uninstalling. After that I've installed it again and it works fine.

Important: This is helpful only in case when you already have your database backed up. All data from the database will be wiped out this way.

Python progression path - From apprentice to guru

Thoroughly Understand All Data Types and Structures

For every type and structure, write a series of demo programs that exercise every aspect of the type or data structure. If you do this, it might be worthwhile to blog notes on each one... it might be useful to lots of people!

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

How to check if a String contains any letter from a to z?

For a minimal change:

for(int i=0; i<str.Length; i++ )
   if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
      errorCount++;

You could use regular expressions, at least if speed is not an issue and you do not really need the actual exact count.

Nullable types: better way to check for null or zero in c#

You code sample will fail. If obj is null then the obj.ToString() will result in a null reference exception. I'd short cut the process and check for a null obj at the start of your helper function. As to your actual question, what's the type you're checking for null or zero? On String there's a great IsNullOrEmpty function, seems to me this would be a great use of extension methods to implement an IsNullOrZero method on the int? type.

Edit: Remember, the '?' is just compiler sugar for the INullable type, so you could probably take an INullable as the parm and then jsut compare it to null (parm == null) and if not null compare to zero.

Convert a string date into datetime in Oracle

You can use a cast to char to see the date results

_x000D_
_x000D_
 select to_char(to_date('17-MAR-17 06.04.54','dd-MON-yy hh24:mi:ss'), 'mm/dd/yyyy hh24:mi:ss') from dual;
_x000D_
_x000D_
_x000D_

Java 8 - Best way to transform a list: map or foreach?

There is a third option - using stream().toArray() - see comments under why didn't stream have a toList method. It turns out to be slower than forEach() or collect(), and less expressive. It might be optimised in later JDK builds, so adding it here just in case.

assuming List<String>

    myFinalList = Arrays.asList(
            myListToParse.stream()
                    .filter(Objects::nonNull)
                    .map(this::doSomething)
                    .toArray(String[]::new)
    );

with a micro-micro benchmark, 1M entries, 20% nulls and simple transform in doSomething()

private LongSummaryStatistics benchmark(final String testName, final Runnable methodToTest, int samples) {
    long[] timing = new long[samples];
    for (int i = 0; i < samples; i++) {
        long start = System.currentTimeMillis();
        methodToTest.run();
        timing[i] = System.currentTimeMillis() - start;
    }
    final LongSummaryStatistics stats = Arrays.stream(timing).summaryStatistics();
    System.out.println(testName + ": " + stats);
    return stats;
}

the results are

parallel:

toArray: LongSummaryStatistics{count=10, sum=3721, min=321, average=372,100000, max=535}
forEach: LongSummaryStatistics{count=10, sum=3502, min=249, average=350,200000, max=389}
collect: LongSummaryStatistics{count=10, sum=3325, min=265, average=332,500000, max=368}

sequential:

toArray: LongSummaryStatistics{count=10, sum=5493, min=517, average=549,300000, max=569}
forEach: LongSummaryStatistics{count=10, sum=5316, min=427, average=531,600000, max=571}
collect: LongSummaryStatistics{count=10, sum=5380, min=444, average=538,000000, max=557}

parallel without nulls and filter (so the stream is SIZED): toArrays has the best performance in such case, and .forEach() fails with "indexOutOfBounds" on the recepient ArrayList, had to replace with .forEachOrdered()

toArray: LongSummaryStatistics{count=100, sum=75566, min=707, average=755,660000, max=1107}
forEach: LongSummaryStatistics{count=100, sum=115802, min=992, average=1158,020000, max=1254}
collect: LongSummaryStatistics{count=100, sum=88415, min=732, average=884,150000, max=1014}

How to get Last record from Sqlite?

Another option is to use SQLites LAST_VALUE() function in the following way.

Given this table:

+--------+---------+-------+
| OBJECT |  STATUS |  TIME |
+--------+---------+-------+
|        |         |       |
| 1      |  ON     |  100  |
|        |         |       |
| 1      |  OFF    |  102  |
|        |         |       |
| 1      |  ON     |  103  |
|        |         |       |
| 2      |  ON     |  101  |
|        |         |       |
| 2      |  OFF    |  102  |
|        |         |       |
| 2      |  ON     |  103  |
|        |         |       |
| 3      |  OFF    |  102  |
|        |         |       |
| 3      |  ON     |  103  |
+--------+---------+-------+

You can get the last status of every object with the following query

SELECT                           
    DISTINCT OBJECT,             -- Only unique rows
    LAST_VALUE(STATUS) OVER (    -- The last value of the status column
        PARTITION BY OBJECT      -- Taking into account rows with the same value in the object column
        ORDER by time asc        -- "Last" when sorting the rows of every object by the time column in ascending order
        RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING    -- Take all rows in the patition
    ) as lastStatus
FROM
    TABLE

The result would look like:

+--------+--------------+
| OBJECT |  LAST_STATUS |
+--------+--------------+
|        |              |
| 1      |  ON          |
|        |              |
| 2      |  ON          |
|        |              |
| 3      |  ON          |
+--------+--------------+

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

I don't really see a way to do this as-is. I think you might need to remove the overflow:hidden from div#1 and add another div within div#1 (ie as a sibling to div#2) to hold your unspecified 'content' and add the overflow:hidden to that instead. I don't think that overflow can be (or should be able to be) over-ridden.

Changing navigation title programmatically

If you wanted to change the title from a child view controller of a Page View Controller that's embedded in a navigation controller, it would look like this:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.parent?.title = "some title"
}

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

ASP.NET Core configuration for .NET Core console application

If you use .netcore 3.1 the simplest way use new configuration system to call CreateDefaultBuilder method of static class Host and configure application

public class Program
{
    public static void Main(string[] args)
    {
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                IHostEnvironment env = context.HostingEnvironment;
                config.AddEnvironmentVariables()
                    // copy configuration files to output directory
                    .AddJsonFile("appsettings.json")
                    // default prefix for environment variables is DOTNET_
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddCommandLine(args);
            })
            .ConfigureServices(services =>
            {
                services.AddSingleton<IHostedService, MySimpleService>();
            })
            .Build()
            .Run();
    }
}

class MySimpleService : IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("StartAsync");
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("StopAsync");
        return Task.CompletedTask;
    }
}

You need set Copy to Output Directory = 'Copy if newer' for the files appsettings.json and appsettings.{environment}.json Also you can set environment variable {prefix}ENVIRONMENT (default prefix is DOTNET) to allow choose specific configuration parameters.

.csproj file:

<PropertyGroup>
  <OutputType>Exe</OutputType>
  <TargetFramework>netcoreapp3.1</TargetFramework>
  <RootNamespace>ConsoleApplication3</RootNamespace>
  <AssemblyName>ConsoleApplication3</AssemblyName>
</PropertyGroup>

<ItemGroup>
  <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.7" />
  <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.7" />
</ItemGroup>

<ItemGroup>
  <None Update="appsettings.Development.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
  <None Update="appsettings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

more details .NET Generic Host

How to remove not null constraint in sql server using query

Remove column constraint: not null to null

ALTER TABLE test ALTER COLUMN column_01 DROP NOT NULL;

Check if an element is present in an array

ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the problem, and so is now the preferred method.

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false (second parameter is the index position in this array at which to begin searching)

As of JULY 2018, this has been implemented in almost all major browsers, if you need to support an older browser a polyfill is available.

Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.

How to specify Memory & CPU limit in docker compose version 3

I know the topic is a bit old and seems stale, but anyway I was able to use these options:

    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M

when using 3.7 version of docker-compose

What helped in my case, was using this command:

docker-compose --compatibility up

--compatibility flag stands for (taken from the documentation):

If set, Compose will attempt to convert deploy keys in v3 files to their non-Swarm equivalent

Think it's great, that I don't have to revert my docker-compose file back to v2.

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

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

I can not add a comment to IonicBurger because I do not have "50 reputation" so I will add a new entry. My apologies. os.popen() is the best for multiple/complicated commands (my opinion) and also for getting the return value in addition to getting stdout like the following more complicated multiple commands:

import os
out = [ i.strip() for i in os.popen(r"ls *.py | grep -i '.*file' 2>/dev/null; echo $? ").readlines()]
print "     stdout: ", out[:-1]
print "returnValue: ", out[-1]

This will list all python files that have the word 'file' anywhere in their name. The [...] is a list comprehension to remove (strip) the newline character from each entry. The echo $? is a shell command to show the return status of the last command executed which will be the grep command and the last item of the list in this example. the 2>/dev/null says to print the stderr of the grep command to /dev/null so it does not show up in the output. The 'r' before the 'ls' command is to use the raw string so the shell will not interpret metacharacters like '*' incorrectly. This works in python 2.7. Here is the sample output:

      stdout:  ['fileFilter.py', 'fileProcess.py', 'file_access..py', 'myfile.py']
 returnValue:  0

Failed to install Python Cryptography package with PIP and setup.py

I noticed the original poster was clearly using a windows installation... and the best answers above are all for other OSs... so here goes. This assumes you have installed Python 2.7 which is the most widely supported (though old) version.

  1. Install the "Visual C++ Compiler for Python"
  2. Open an Administrative command prompt window
  3. Re-run pip install (package) e.g.

    cd C:\Python27\Scripts
    pip install cryptography  (or pycrypto, fabric, etc)
    

Twitter Bootstrap Modal Form Submit

Simple

<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" onclick="event.preventDefault();document.getElementById('your-form').submit();">Save changes</button>

How to set a value for a selectize.js input?

Answer by the user 'onlyblank' is correct. A small addition to that- You can set more than 1 default values if you want.

Instead of passing on id to the setValue(), pass an array. Example:

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
var yourDefaultIds = [1,2]; # find the ids using search as shown by the user onlyblank
selectize.setValue(defaultValueIds);

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

An example taken form here:

When an Employee entity object is removed, the remove operation is cascaded to the referenced Address entity object. In this regard, orphanRemoval=true and cascade=CascadeType.REMOVE are identical, and if orphanRemoval=true is specified, CascadeType.REMOVE is redundant.

The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null or to another Address object.

  • If orphanRemoval=true is specified the disconnected Address instance is automatically removed. This is useful for cleaning up dependent objects (e.g. Address) that should not exist without a reference from an owner object (e.g. Employee).

  • If only cascade=CascadeType.REMOVE is specified, no automatic action is taken since disconnecting a relationship is not a remove operation.

To avoid dangling references as a result of orphan removal, this feature should only be enabled for fields that hold private non shared dependent objects.

I hope this makes it more clear.

Non-invocable member cannot be used like a method?

It have happened because you are trying to use the property "OffenceBox.Text" like a method. Try to remove parenteses from OffenceBox.Text() and it'll work fine.

Remember that you cannot create a method and a property with the same name in a class.


By the way, some alias could confuse you, since sometimes it's method or property, e.g: "Count" alias:


Namespace: System.Linq

using System.Linq

namespace Teste
{
    public class TestLinq
    {
        public return Foo()
        {
            var listX = new List<int>();
            return listX.Count(x => x.Id == 1);
        }
    }
}


Namespace: System.Collections.Generic

using System.Collections.Generic

namespace Teste
{
    public class TestList
    {
        public int Foo()
        {
            var listX = new List<int>();
            return listX.Count;
        }
    }
}

Is a Java hashmap search really O(1)?

O(1+n/k) where k is the number of buckets.

If implementation sets k = n/alpha then it is O(1+alpha) = O(1) since alpha is a constant.

'was not declared in this scope' error

Here

{int y=((year-1)%100);int c=(year-1)/100;}

you declare and initialize the variables y, c, but you don't used them at all before they run out of scope. That's why you get the unused message.

Later in the function, y, c are undeclared, because the declarations you made only hold inside the block they were made in (the block between the braces {...}).

Submitting the value of a disabled input field

Input elements have a property called disabled. When the form submits, just run some code like this:

var myInput = document.getElementById('myInput');
myInput.disabled = true;

How do I vertically align text in a paragraph?

In my case margin auto works fine.

p {
    font: 22px/24px Ubuntu;
    margin:auto 0px;
}

Remove columns from DataTable in C#

To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.

DataTable dt;
int desiredSize = 10;

while (dt.Columns.Count > desiredSize)
{
   dt.Columns.RemoveAt(desiredSize);
}

How to delete file from public folder in laravel 5.1

this method worked for me
First, put the line below at the beginning of your controller:

use File;

below namespace in your php file Second:

 $destinationPath = 'your_path';
 File::delete($destinationPath.'/your_file');

$destinationPath --> the folder inside folder public.

How do I view the SSIS packages in SQL Server Management Studio?

When you start SSMS, it allows you to choose a Server Type and Server Name. In the server type dropdown, choose "Integration Services" and connect to the server.

Then you'll be able to see what packages are in the db.

Flutter Circle Design

You can use CustomMultiChildLayout to draw this kind of layouts. Here you can find a tutorial: How to Create Custom Layout Widgets in Flutter.

Rails: How do I create a default value for attributes in Rails activerecord's model?

The solution depends on a few things.

Is the default value dependent on other information available at creation time? Can you wipe the database with minimal consequences?

If you answered the first question yes, then you want to use Jim's solution

If you answered the second question yes, then you want to use Daniel's solution

If you answered no to both questions, you're probably better off adding and running a new migration.

class AddDefaultMigration < ActiveRecord::Migration
  def self.up
     change_column :tasks, :status, :string, :default => default_value, :null => false
  end
end

:string can be replaced with any type that ActiveRecord::Migration recognizes.

CPU is cheap so the redefinition of Task in Jim's solution isn't going to cause many problems. Especially in a production environment. This migration is proper way of doing it as it is loaded it and called much less often.

Handling NULL values in Hive

What is the datatype for column1 in your Hive table? Please note that if your column is STRING it won't be having a NULL value even though your external file does not have any data for that column.

How to append multiple items in one line in Python

use for loop. like this:

for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
    new_list.append(my_list[i + x])

Easiest way to develop simple GUI in Python

I prefer PyQT although it is pretty big. It has all the features that normal QT has, and that's why it's very usable. I think you can use QML with it too.

Send data from activity to fragment in Android

Very old post, still I dare to add a little explanation that would had been helpful for me.

Technically you can directly set members of any type in a fragment from activity.
So why Bundle?
The reason is very simple - Bundle provides uniform way to handle:
-- creating/opening fragment
-- reconfiguration (screen rotation) - just add initial/updated bundle to outState in onSaveInstanceState()
-- app restoration after being garbage collected in background (as with reconfiguration).

You can (if you like experiments) create a workaround in simple situations but Bundle-approach just doesn't see difference between one fragment and one thousand on a backstack - it stays simple and straightforward.
That's why the answer by @Elenasys is the most elegant and universal solution.
And that's why the answer given by @Martin has pitfalls

Windows equivalent to UNIX pwd

C:\Documents and Settings\Scripter>echo %cd%
C:\Documents and Settings\Scripter

C:\Documents and Settings\Scripter>

for Unix use pwd command

Current working directory

Angular IE Caching issue for $http

This only line helped me (Angular 1.4.8):

$httpProvider.defaults.headers.common['Pragma'] = 'no-cache';

UPD: The problem is IE11 does aggressive caching. When I was looking into Fiddler I noticed that in F12 mode requests are sending "Pragma=no-cache" and endpoint is requested every time I visit a page. But in normal mode endpoint was requested only once at the first time when I visited the page.

Fastest way to count exact number of rows in a very large table?

If you are using Oracle, how about this (assuming the table stats are updated):

select <TABLE_NAME>, num_rows, last_analyzed from user_tables

last_analyzed will show the time when stats were last gathered.

set background color: Android

By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:

android:background="#fff"

The FastCGI process exited unexpectedly

In my case I had wrong constellation of configurations:

  • error reporting disabled
  • typo error in the configuration

After enabling the error_reporting it was clear the session_path was pointed to a wrong folder.

"Sad but true"

Why does configure say no C compiler found when GCC is installed?

Maybe gcc is not in your path? Try finding gcc using which gcc and add it to your path if it's not already there.

How can I determine whether a specific file is open in Windows?

Use Process Explorer from the Sysinternals Suite, the Find Handle or DLL function will let you search for the process with that file open.

Batch Script to Run as Administrator

@echo off

 call :isAdmin

 if %errorlevel% == 0 (
    goto :run
 ) else (
    echo Requesting administrative privileges...
    goto :UACPrompt
 )

 exit /b

 :isAdmin
    fsutil dirty query %systemdrive% >nul
 exit /b

 :run
  <YOUR BATCH SCRIPT HERE>
 exit /b

 :UACPrompt
   echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
   echo UAC.ShellExecute "cmd.exe", "/c %~s0 %~1", "", "runas", 1 >> "%temp%\getadmin.vbs"

   "%temp%\getadmin.vbs"
   del "%temp%\getadmin.vbs"
  exit /B`

How get total sum from input box values using Javascript?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
_x000D_
  //iterate through each textboxes and add keyup_x000D_
  //handler to trigger sum event_x000D_
  $(".txt").each(function() {_x000D_
_x000D_
   $(this).keyup(function(){_x000D_
    calculateSum();_x000D_
   });_x000D_
  });_x000D_
_x000D_
 });_x000D_
_x000D_
 function calculateSum() {_x000D_
_x000D_
  var sum = 0;_x000D_
  //iterate through each textboxes and add the values_x000D_
  $(".txt").each(function() {_x000D_
_x000D_
   //add only if the value is number_x000D_
   if(!isNaN(this.value) && this.value.length!=0) {_x000D_
    sum += parseFloat(this.value);_x000D_
   }_x000D_
_x000D_
  });_x000D_
  //.toFixed() method will roundoff the final sum to 2 decimal places_x000D_
  $("#sum").html(sum.toFixed(2));_x000D_
 }
_x000D_
body {_x000D_
    font-family: sans-serif;_x000D_
   }_x000D_
   #summation {_x000D_
    font-size: 18px;_x000D_
    font-weight: bold;_x000D_
    color:#174C68;_x000D_
   }_x000D_
   .txt {_x000D_
    background-color: #FEFFB0;_x000D_
    font-weight: bold;_x000D_
    text-align: right;_x000D_
   }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">_x000D_
 <tr>_x000D_
  <td width="40px">1</td>_x000D_
  <td>Butter</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>2</td>_x000D_
  <td>Cheese</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>3</td>_x000D_
  <td>Eggs</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>4</td>_x000D_
  <td>Milk</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>5</td>_x000D_
  <td>Bread</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>6</td>_x000D_
  <td>Soap</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr id="summation">_x000D_
  <td>&nbsp;</td>_x000D_
  <td align="right">Sum :</td>_x000D_
  <td align="center"><span id="sum">0</span></td>_x000D_
 </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

If my interface must return Task what is the best way to have a no-operation implementation?

Recently encountered this and kept getting warnings/errors about the method being void.

We're in the business of placating the compiler and this clears it up:

    public async Task MyVoidAsyncMethod()
    {
        await Task.CompletedTask;
    }

This brings together the best of all the advice here so far. No return statement is necessary unless you're actually doing something in the method.

Is it good practice to make the constructor throw an exception?

This is totally valid, I do it all the time. I usually use IllegalArguemntException if it is a result of parameter checking.

In this case I wouldn't suggest asserts because they are turned off in a deployment build and you always want to stop this from happening, but they are valid if your group does ALL it's testing with asserts turned on and you think the chance of missing a parameter problem at runtime is more acceptable than throwing an exception that is maybe more likely to cause a runtime crash.

Also, an assert would be more difficult for the caller to trap, this is easy.

You probably want to list it as a "throws" in your method's javadocs along with the reason so that callers aren't surprised.

Get Table and Index storage size in sql server

with pages as (
    SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
            SUM (case 
                    when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
                    else lob_used_page_count + row_overflow_used_page_count
                 end) as pages
    FROM sys.dm_db_partition_stats
    group by object_id
), extra as (
    SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
    FROM sys.dm_db_partition_stats p, sys.internal_tables it
    WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
    group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
        pages * 8 as data_kb,
        (CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
        (CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id

Takes into account internal tables, such as those used for XML storage.

Edit: If you divide the data_kb and index_kb values by 1024.0, you will get the numbers you see in the GUI.

How do I truncate a .NET string?

Taking @CaffGeek and simplifying it:

public static string Truncate(this string value, int maxLength)
    {
        return string.IsNullOrEmpty(value) ? value : value.Substring(0, Math.Min(value.Length, maxLength));
    }

Detect Close windows event by jQuery

Combine the mousemove and window.onbeforeunload event :- I used for set TimeOut for Audit Table.

 $(document).ready(function () {
 var checkCloseX = 0;
        $(document).mousemove(function (e) {
            if (e.pageY <= 5) {
                checkCloseX = 1;
            }
            else { checkCloseX = 0; }
        });

        window.onbeforeunload = function (event) {
            if (event) {
                if (checkCloseX == 1) {

                    //alert('1111');
                    $.ajax({
                        type: "GET",
                        url: "Account/SetAuditHeaderTimeOut",
                        dataType: "json",
                        success: function (result) {
                            if (result != null) {
                            }
                        }
                    });
                }
            }
        };
  });

How do I create a crontab through a script

(I don't have enough reputation to comment, so I'm adding at as an answer: feel free to add it as as comment next to his answer)

Joe Casadonte's one-liner is perfect, except if you run with set -e, i.e. if your script is set to fail on error, and if there are no cronjobs yet. In that case, the one-liner will NOT create the cronjob, but will NOT stop the script. The silent failure can be very misleading.

The reason is that crontab -l returns with a 1 return code, causing the subsequent command (the echo) not to be executed... thus the cronjob is not created. But since they are executed as a subprocess (because of the parenthesis) they don't stop the script.

(Interestingly, if you run the same command again, it will work: once you have executed crontab - once, crontab -l still outputs nothing, but it doesn't return an error anymore (you don't get the no crontab for <user> message anymore). So the subsequent echo is executed and the crontab is created)

In any case, if you run with set -e, the line must be:

(crontab -l 2>/dev/null || true; echo "*/5 * * * * /path/to/job -with args") | crontab -

Java OCR implementation

If you are looking for a very extensible option or have a specific problem domain you could consider rolling your own using the Java Object Oriented Neural Engine. Another JOONE reference.

I used it successfully in a personal project to identify the letter from an image such as this, you can find all the source for the OCR component of my application on github, here.

'names' attribute must be the same length as the vector

Depending on what you're doing in the loop, the fact that the %in% operator returns a vector might be an issue; consider a simple example:

c1 <- c("one","two","three","more","more")
c2 <- c("seven","five","three")

if(c1%in%c2) {
    print("hello")
}

then the following warning is issued:

Warning message:
In if (c1 %in% c2) { :
  the condition has length > 1 and only the first element will be used

if something in your if statement is dependent on a specific number of elements, and they don't match, then it is possible to obtain the error you see

Hide keyboard in react-native

Below given two types of hiding keyboard.

Type: 1 if you are not using a scroll view then simply Import keyboard and Add Keyboard.dismiss(). this is the correct way of implementation.

Type: 2 if you are using a scroll view then simply

<ScrollView contentContainerStyle={{flex: 1}} keyboardShouldPersistTaps='handled'>
  <TextInput />
</ScrollView>

this is the correct way of implementation.

Firebase onMessageReceived not called when app in background

you can try this in your main Activity , when in the background

   if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                Object value = getIntent().getExtras().get(key);
                Log.d(TAG, "Key: " + key + " Value: " + value);
            }
        }

Check the following project as reference

"CSV file does not exist" for a filename with embedded quotes

Adnane's answer helped me.

Here's my full code on mac, hope this helps someone. All my csv files are saved in /Users/lionelyu/Documents/Python/Python Projects/

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')

path = '/Users/lionelyu/Documents/Python/Python Projects/'

aapl = pd.read_csv(path + 'AAPL_CLOSE.csv',index_col='Date',parse_dates=True)
cisco = pd.read_csv(path + 'CISCO_CLOSE.csv',index_col='Date',parse_dates=True)
ibm = pd.read_csv(path + 'IBM_CLOSE.csv',index_col='Date',parse_dates=True)
amzn = pd.read_csv(path + 'AMZN_CLOSE.csv',index_col='Date',parse_dates=True)

Can't start hostednetwork

The hosted network won't start if there are other active wifi adapters.

Disable the others whilst you're starting the hosted network.

SQL Server : How to test if a string has only digit characters

The selected answer does not work.

declare @str varchar(50)='79D136'
select 1 where @str NOT LIKE '%[^0-9]%'

I don't have a solution but know of this potential pitfall. The same goes if you substitute the letter 'D' for 'E' which is scientific notation.

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

How do I add a newline using printf?

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget

How to check if a file exists in the Documents directory in Swift?

Swift 4 example:

var filePath: String {
    //manager lets you examine contents of a files and folders in your app.
    let manager = FileManager.default

    //returns an array of urls from our documentDirectory and we take the first
    let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
    //print("this is the url path in the document directory \(String(describing: url))")

    //creates a new path component and creates a new file called "Data" where we store our data array
    return(url!.appendingPathComponent("Data").path)
}

I put the check in my loadData function which I called in viewDidLoad.

override func viewDidLoad() {
    super.viewDidLoad()

    loadData()
}

Then I defined loadData below.

func loadData() {
    let manager = FileManager.default

    if manager.fileExists(atPath: filePath) {
        print("The file exists!")

        //Do what you need with the file. 
        ourData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as! Array<DataObject>         
    } else {
        print("The file DOES NOT exist! Mournful trumpets sound...")
    }
}

Check if string contains only letters in javascript

With /^[a-zA-Z]/ you only check the first character:

  • ^: Assert position at the beginning of the string
  • [a-zA-Z]: Match a single character present in the list below:
    • a-z: A character in the range between "a" and "z"
    • A-Z: A character in the range between "A" and "Z"

If you want to check if all characters are letters, use this instead:

/^[a-zA-Z]+$/.test(str);
  • ^: Assert position at the beginning of the string
  • [a-zA-Z]: Match a single character present in the list below:
    • +: Between one and unlimited times, as many as possible, giving back as needed (greedy)
    • a-z: A character in the range between "a" and "z"
    • A-Z: A character in the range between "A" and "Z"
  • $: Assert position at the end of the string (or before the line break at the end of the string, if any)

Or, using the case-insensitive flag i, you could simplify it to

/^[a-z]+$/i.test(str);

Or, since you only want to test, and not match, you could check for the opposite, and negate it:

!/[^a-z]/i.test(str);

Connection to SQL Server Works Sometimes

Adding a response here, despite previously accepted answer. As my scenario was confirmed to be DNS. More specifically, a dns timeout during the pre-login handshake. By changing from a DNS name to an IP Address (or using Hosts file entry), you bypass the problem. Albeit at the cost of losing automatic ip resolution.

For example, even with a Connection String's timeout value set to 60 for a full minute, it still would happen within a couple seconds of the attempt. Which leads one to question why would it timeout before the specified timeout period? DNS.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

Where to get "UTF-8" string literal in Java?

Class org.apache.commons.lang3.CharEncoding.UTF_8 is deprecated after Java 7 introduced java.nio.charset.StandardCharsets

  • @see JRE character encoding names
  • @since 2.1
  • @deprecated Java 7 introduced {@link java.nio.charset.StandardCharsets}, which defines these constants as
  • {@link Charset} objects. Use {@link Charset#name()} to get the string values provided in this class.
  • This class will be removed in a future release.

How can I change the size of a Bootstrap checkbox?

<div id="rr-element">
   <label for="rr-1">
      <input type="checkbox" value="1" id="rr-1" name="rr[]">
      Value 1
   </label>
</div>
//do this on the css
div label input { margin-right:100px; }

How does one convert a grayscale image to RGB in OpenCV (Python)?

Try this:

import cv2
import cv

color_img = cv2.cvtColor(gray_img, cv.CV_GRAY2RGB)

I discovered, while using opencv, that some of the constants are defined in the cv2 module, and other in the cv module.

Create a new workspace in Eclipse

In Window->Preferences->General->Startup and Shutdown->Workspaces, make sure that 'Prompt for Workspace on startup' is checked.

Then close eclipse and reopen.

Then you'll be prompted for a workspace to open. You can create a new workspace from that dialogue.

Or File->Switch Workspace->Other...

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

If the new data could be an array or a scalar, and you want to prevent the new data to be nested if it was an array, the splat operator is awesome! It returns a scalar for a scalar, and an unpacked list of arguments for an array.

1.9.3-p551 :020 > a = [1, 2]
 => [1, 2] 
1.9.3-p551 :021 > b = [3, 4]
 => [3, 4] 
1.9.3-p551 :022 > c = 5
 => 5 
1.9.3-p551 :023 > a.object_id
 => 6617020 
1.9.3-p551 :024 > a.push *b
 => [1, 2, 3, 4] 
1.9.3-p551 :025 > a.object_id
 => 6617020 
1.9.3-p551 :026 > a.push *c
 => [1, 2, 3, 4, 5] 
1.9.3-p551 :027 > a.object_id
 => 6617020 

How can I build for release/distribution on the Xcode 4?

That part is now located under Schemes. If you edit your schemes you will see that you can set the debug/release/adhoc/distribution build config for each scheme.

GROUP BY without aggregate function

Let me give some examples.

Consider this data.

CREATE TABLE DATASET ( VAL1 CHAR ( 1 CHAR ),
                   VAL2 VARCHAR2 ( 10 CHAR ),
                   VAL3 NUMBER );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'b', 'b-details', 2 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'a', 'a-details', 1 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'c', 'c-details', 3 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'a', 'dup', 4 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'c', 'c-details', 5 );

COMMIT;

Whats there in table now

SELECT * FROM DATASET;

VAL1 VAL2             VAL3
---- ---------- ----------
b    b-details           2
a    a-details           1
c    c-details           3
a    dup                 4
c    c-details           5

5 rows selected.

--aggregate with group by

SELECT
      VAL1,
      COUNT ( * )
FROM
      DATASET A
GROUP BY
      VAL1;

VAL1   COUNT(*)
---- ----------
b             1
a             2
c             2

3 rows selected.

--aggregate with group by multiple columns but select partial column

SELECT
      VAL1,
      COUNT ( * )
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

VAL1  
---- 
b             
c             
a             
a             

4 rows selected.

--No aggregate with group by multiple columns

SELECT
      VAL1,
      VAL2
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

    VAL1  
    ---- 
    b    b-details
    c    c-details
    a    dup
    a    a-details

    4 rows selected.

--No aggregate with group by multiple columns

SELECT
      VAL1
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

    VAL1  
    ---- 
    b
    c
    a
    a

    4 rows selected.

You have N columns in select (excluding aggregations), then you should have N or N+x columns

How to change color in markdown cells ipython/jupyter notebook?

An alternative way to do that, is to enter a LaTeX environment within the notebook and change color from there (which is great if you are more fluent in LaTeX than in HTML). Example:

$\color{red}{\text{ciao}}$

would display ciao in red.

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

How to add multiple font files for the same font?

/*
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# dejavu sans
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
/*default version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans.ttf'); /* IE9 Compat Modes */
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'), /* Duplicated name with hyphen */
        url('dejavu/DejaVuSans.ttf') 
        format('truetype');
}
/*bold version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-Bold.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-Bold.ttf') 
        format('truetype');
    font-weight: bold;
}
/*italic version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-Oblique.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-Oblique.ttf') 
        format('truetype');
    font-style: italic;
}
/*bold italic version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-BoldOblique.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-BoldOblique.ttf') 
        format('truetype');
    font-weight: bold;
    font-style: italic;
}

Scroll RecyclerView to show selected item on top

If your LayoutManager is LinearLayoutManager you can use scrollToPositionWithOffset(position,0); on it and it will make your item the first visible item in the list. Otherwise, you can use smoothScrollToPosition on the RecyclerView directly.

I ended up using the below code.

 RecyclerView.LayoutManager layoutManager = mainList.getLayoutManager();
        if (layoutManager instanceof LinearLayoutManager) {
            // Scroll to item and make it the first visible item of the list.
            ((LinearLayoutManager) layoutManager).scrollToPositionWithOffset(position, 0);
        } else {
            mainList.smoothScrollToPosition(position);
        }

What’s the best way to reload / refresh an iframe?

Another solution.

const frame = document.getElementById("my-iframe");

frame.parentNode.replaceChild(frame.cloneNode(), frame);

What is the difference between an IntentService and a Service?

See Tejas Lagvankar's post about this subject. Below are some key differences between Service and IntentService and other components.

enter image description here

What's "tools:context" in Android layout files?

1.Description

tools: context = "activity name" it won't be packaged into the apk .Only ADT Layout Editor in your current Layout file set corresponding rendering context, show your current Layout in rendering the context is the activity name corresponds to the activity, if the activity in the manifest file set a Theme, then ADT Layout Editor will render your current Layout according to the Theme.Means that if you set the MainActivity set a Theme. The Light (the other), then you see in visual layout manager o background control of what should be the Theme. The Light looks like.Only to show you what you see is what you get results.

Some people see will understand some, some people see the also don't know, I'll add a few words of explanation:

2.Sample

Take a simple tools:text, for example, some more image, convenient to further understand the tools:context

<TextView
    android:id="@+id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="sample name1" />

<TextView
    android:id="@+id/text2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="sample name2" />

enter image description here

TextView1 adopted the android: text, and use the tools:text in the TextView2, on the right side of the Layout editor will display the sample name1, the sample name2 two font, if after you run the code to compile, generated apk, terminal display only the sample name1, does not show the sample name2 the words. You can try to run, see how the effect.

3.Specific description

1.The tools: context = "activity name" it won't be packaged into the apk(understanding: the equivalent of this is commented, the compiled no effect.)

2.Only ADT Layout Editor (i.e., for the above icon on the right side of the simulator) in the current Layout file set corresponding rendering context, the Layout of the current XML in rendering the context is the activity name corresponds to the activity, if the activity in the manifest file set a Theme, then ADT Layout Editor will render your current Layout according to the Theme.Means that if you set the MainActivity set a Theme. The Light can also be (other).(understand: you added tools: context = "activity name", the XML layout is rendering specified activity, establishes a Theme in the manifest file, pictured above right simulator Theme style will also follow changes corresponding to the Theme.)

4.summary

To sum up, these properties mainly aimed at above the right tools, the simulator debugging time display status, and compile doesn't work,

Difference between <input type='button' /> and <input type='submit' />

type='Submit' is set to forward & get the values on BACK-END (PHP, .NET etc). type='button' will reflect normal button behavior.

Calculating the sum of two variables in a batch script

You can solve any equation including adding with this code:

@echo off

title Richie's Calculator 3.0

:main

echo Welcome to Richie's Calculator 3.0

echo Press any key to begin calculating...

pause>nul

echo Enter An Equation

echo Example: 1+1

set /p 

set /a sum=%equation%

echo.

echo The Answer Is:

echo %sum%

echo.

echo Press any key to return to the main menu

pause>nul

cls

goto main

PLS-00103: Encountered the symbol "CREATE"

Run package declaration and body separately.

Java Singleton and Synchronization

Yes, you need to make getInstance() synchronized. If it's not there might arise a situation where multiple instances of the class can be made.

Consider the case where you have two threads that call getInstance() at the same time. Now imagine T1 executes just past the instance == null check, and then T2 runs. At this point in time the instance is not created or set, so T2 will pass the check and create the instance. Now imagine that execution switches back to T1. Now the singleton is created, but T1 has already done the check! It will proceed to make the object again! Making getInstance() synchronized prevents this problem.

There a few ways to make singletons thread-safe, but making getInstance() synchronized is probably the simplest.

Total size of the contents of all the files in a directory

Use du -sb:

du -sb DIR

Optionally, add the h option for more user-friendly output:

du -sbh DIR

Random record from MongoDB

If you have a simple id key, you could store all the id's in an array, and then pick a random id. (Ruby answer):

ids = @coll.find({},fields:{_id:1}).to_a
@coll.find(ids.sample).first

Install tkinter for Python

Tkinter is a GUI module for python. you can use it to make GUI based applications in python. Tkinter provides several GUI widgets like buttons,menu, canvas,text,frame,label etc. to develop desktop applications.Though Tkinter is very popular and is included with windows, macosx install of python, There are also alternative choices like pyQt, wxPython...

In this tutorial we will see how to install it on linux and use it with an example.

First, check if you have python installed and also check its version

Open up your terminal and type python. if its installed then it will show information like version, help... check your version (mine is python 2.7.9)

aman@vostro:~$ python Python 2.7.9 (default, Apr 2 2015, 15:33:21) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information.

If you don't have python then install it sudo apt-get install python

If you want to install python 3 then enter the following. If you are a newbie, I would recommend python 2 instead of python 3. Python 2 is still very popular and many apps are made on it. On ubuntu python2 is still the default sudo apt-get install python3

Finally, Install Tkinter

sudo apt-get install python-tk

for python 3

sudo apt-get install python3-tk

How to Use it

Now, lets check if Tkinter is working well with this little example

open your terminal and enter into your python shell. python

for python3 python3

if python was installed correctly you will get a >>> prompt. aman@vostro:~$ python

Python 2.7.9 (default, Apr  2 2015, 15:33:21)
[GCC 4.9.2] on linux2

Type "help", "copyright", "credits" or "license" for more information.
>>>

Now import Tkinter module. it wont show any error if it got imported correctly. NOTE: Make sure you type Tkinter (not tkinter) in python2 and tkinter (not Tkinter) in python3.

>>>import Tkinter

Now, just to check you can create an empty window using Tkinter.

>>>Tkinter.Tk()

android:drawableLeft margin and/or padding

Make your drawable resources.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <inset android:drawable="@drawable/small_m" android:insetLeft="10dp" android:insetTop="10dp" />
    </item>
    <item>
        <inset android:drawable="@drawable/small_p" android:insetLeft="10dp" android:insetTop="10dp" />
    </item>
</selector>

Replace all non-alphanumeric characters in a string

The pythonic way.

print "".join([ c if c.isalnum() else "*" for c in s ])

This doesn't deal with grouping multiple consecutive non-matching characters though, i.e.

"h^&i => "h**i not "h*i" as in the regex solutions.

Difference between style = "position:absolute" and style = "position:relative"

Relative positioning: The element creates its own coordinate axes, at a location offset from the viewport coordinate axis. It is Part of document flow but shifted.

Absolute positioning: An element searches for the nearest available coordinate axes among its parent elements. The element is then positioned by specifying offsets from this coordinate axis. It is removed from document normal flow.

enter image description here

Source

Background images: how to fill whole div if image is small and vice versa

Try below code segment, I've tried it myself before :

#your-div {
    background: url("your-image-link") no-repeat;
    background-size: cover;
    background-clip: border-box;
}

How does one set up the Visual Studio Code compiler/debugger to GCC?

You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.

This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

Getting the names of all files in a directory with PHP

I have smaller code todo this:

$path = "Pending2Post/";
$files = scandir($path);
foreach ($files as &$value) {
    echo "<a href='http://localhost/".$value."' target='_blank' >".$value."</a><br/><br/>";
}

How to get the week day name from a date?

To do this for oracle sql, the syntax would be:

,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field

for this example, I look for the second '-' and take the substring to the end

How to parse dates in multiple formats using SimpleDateFormat

You'll need to use a different SimpleDateFormat object for each different pattern. That said, you don't need that many different ones, thanks to this:

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

So, you'll need these formats:

  • "M/y" (that covers 9/09, 9/2009, and 09/2009)
  • "M/d/y" (that covers 9/1/2009)
  • "M-d-y" (that covers 9-1-2009)

So, my advice would be to write a method that works something like this (untested):

// ...
List<String> formatStrings = Arrays.asList("M/y", "M/d/y", "M-d-y");
// ...

Date tryParse(String dateString)
{
    for (String formatString : formatStrings)
    {
        try
        {
            return new SimpleDateFormat(formatString).parse(dateString);
        }
        catch (ParseException e) {}
    }

    return null;
}

How can I create a progress bar in Excel VBA?

Hi modified version of another post by Marecki. Has 4 styles

1. dots ....
2  10 to 1 count down
3. progress bar (default)
4. just percentage.

Before you ask why I didn't edit that post is I did and it got rejected was told to post a new answer.

Sub ShowProgress()

  Const x As Long = 150000
  Dim i&, PB$

  For i = 1 To x
  DoEvents
  UpdateProgress i, x
  Next i

  Application.StatusBar = ""
End Sub 'ShowProgress

Sub UpdateProgress(icurr As Long, imax As Long, Optional istyle As Integer = 3)
    Dim PB$
    PB = Format(icurr / imax, "00 %")
    If istyle = 1 Then ' text dots >>....    <<'
        Application.StatusBar = "Progress: " & PB & "  >>" & String(Val(PB), Chr(183)) & String(100 - Val(PB), Chr(32)) & "<<"
    ElseIf istyle = 2 Then ' 10 to 1 count down  (eight balls style)
        Application.StatusBar = "Progress: " & PB & "  " & ChrW$(10111 - Val(PB) / 11)
    ElseIf istyle = 3 Then ' solid progres bar (default)
        Application.StatusBar = "Progress: " & PB & "  " & String(100 - Val(PB), ChrW$(9608))
    Else ' just 00 %
        Application.StatusBar = "Progress: " & PB
    End If
End Sub

import httplib ImportError: No module named httplib

If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'

enter image description here

The maximum message size quota for incoming messages (65536) has been exceeded

For me, the settings in web.config / app.config were ignored. I ended up creating my binding manually, which solved the issue for me:

var httpBinding = new BasicHttpBinding()
{
    MaxBufferPoolSize = Int32.MaxValue,
    MaxBufferSize = Int32.MaxValue,
    MaxReceivedMessageSize = Int32.MaxValue,
    ReaderQuotas = new XmlDictionaryReaderQuotas()
    {
        MaxArrayLength = 200000000,
        MaxDepth = 32,
        MaxStringContentLength = 200000000
    }
};

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

Same error here, this worked for me:

sudo mongod --repair

followed by

sudo mongod

(forget about service and start)

Then on a different tab/terminal:

mongo

Convert a String representation of a Dictionary to a dictionary?

To summarize:

import ast, yaml, json, timeit

descs=['short string','long string']
strings=['{"809001":2,"848545":2,"565828":1}','{"2979":1,"30581":1,"7296":1,"127256":1,"18803":2,"41619":1,"41312":1,"16837":1,"7253":1,"70075":1,"3453":1,"4126":1,"23599":1,"11465":3,"19172":1,"4019":1,"4775":1,"64225":1,"3235":2,"15593":1,"7528":1,"176840":1,"40022":1,"152854":1,"9878":1,"16156":1,"6512":1,"4138":1,"11090":1,"12259":1,"4934":1,"65581":1,"9747":2,"18290":1,"107981":1,"459762":1,"23177":1,"23246":1,"3591":1,"3671":1,"5767":1,"3930":1,"89507":2,"19293":1,"92797":1,"32444":2,"70089":1,"46549":1,"30988":1,"4613":1,"14042":1,"26298":1,"222972":1,"2982":1,"3932":1,"11134":1,"3084":1,"6516":1,"486617":1,"14475":2,"2127":1,"51359":1,"2662":1,"4121":1,"53848":2,"552967":1,"204081":1,"5675":2,"32433":1,"92448":1}']
funcs=[json.loads,eval,ast.literal_eval,yaml.load]

for  desc,string in zip(descs,strings):
    print('***',desc,'***')
    print('')
    for  func in funcs:
        print(func.__module__+' '+func.__name__+':')
        %timeit func(string)        
    print('')

Results:

*** short string ***

json loads:
4.47 µs ± 33.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
builtins eval:
24.1 µs ± 163 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
ast literal_eval:
30.4 µs ± 299 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
yaml load:
504 µs ± 1.29 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

*** long string ***

json loads:
29.6 µs ± 230 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
builtins eval:
219 µs ± 3.92 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
ast literal_eval:
331 µs ± 1.89 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
yaml load:
9.02 ms ± 92.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Conclusion: prefer json.loads

What does "ulimit -s unlimited" do?

stack size can indeed be unlimited. _STK_LIM is the default, _STK_LIM_MAX is something that differs per architecture, as can be seen from include/asm-generic/resource.h:

/*
 * RLIMIT_STACK default maximum - some architectures override it:
 */
#ifndef _STK_LIM_MAX
# define _STK_LIM_MAX           RLIM_INFINITY
#endif

As can be seen from this example generic value is infinite, where RLIM_INFINITY is, again, in generic case defined as:

/*
 * SuS says limits have to be unsigned.
 * Which makes a ton more sense anyway.
 *
 * Some architectures override this (for compatibility reasons):
 */
#ifndef RLIM_INFINITY
# define RLIM_INFINITY          (~0UL)
#endif

So I guess the real answer is - stack size CAN be limited by some architecture, then unlimited stack trace will mean whatever _STK_LIM_MAX is defined to, and in case it's infinity - it is infinite. For details on what it means to set it to infinite and what implications it might have, refer to the other answer, it's way better than mine.

GUI Tool for PostgreSQL

There is a comprehensive list of tools on the PostgreSQL Wiki:

https://wiki.postgresql.org/wiki/PostgreSQL_Clients

And of course PostgreSQL itself comes with pgAdmin, a GUI tool for accessing Postgres databases.

How to check if an excel cell is empty using Apache POI?

First to avoid NullPointerException you have to add this

Row.MissingCellPolicy.CREATE_NULL_AS_BLANK

This will create a blank cell instead of giving you NPE then you can check to make sure nothing went wrong just like what @Gagravarr have said.

Cell cell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
    if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) 
        // do what you want

Android: How do I get string from resources using its name?

You can try this in an Activity:

getResources().getString(R.string.your string name);

In other situations like fragments,... use

getContext().getResources().getString(R.string.your string name);

e.printStackTrace equivalent in python

import traceback
traceback.print_exc()

When doing this inside an except ...: block it will automatically use the current exception. See http://docs.python.org/library/traceback.html for more information.

ReferenceError: document is not defined (in plain JavaScript)

try: window.document......

var body = window.document.getElementsByTagName("body")[0];

Chrome DevTools Devices does not detect device when plugged in

Had a nightmare with this today Samsung Galaxy Note 9 and a Windows 10 Laptop without Android Studio. Here are working steps to get debugging.

1) Enable developer mode on the phone in the usual manner and turn on "USB Debugging".

2) On your computer install the Samsung USB Drivers for Windows https://developer.samsung.com/galaxy/others/android-usb-driver-for-windows

3) Open Chrome on your Computer - bring up Remote Devices in dev console (at the moment it will say no devices detected).

4) Connect your phone to your computer via USB cable.

5) Accept any prompts for authorisation and wait until the computer says "your device is ready.." etc.

6) On your phone, swipe down the top menu and tap "P Android system" - select "MIDI" under "Use USB for".

7) Various setup notifications will appear on your PC, when they are finished you will get the authorisation prompt for debugging on your phone. Accept it! Wait a few more second and you will find the phone now appears in Chrome Dev tools on the computer, and will be connected in a few more seconds.

You're welcome.

How to search multiple columns in MySQL?

Here is a query which you can use to search for anything in from your database as a search result ,

SELECT * FROM tbl_customer 
    WHERE CustomerName LIKE '%".$search."%'
    OR Address LIKE '%".$search."%' 
    OR City LIKE '%".$search."%' 
    OR PostalCode LIKE '%".$search."%' 
    OR Country LIKE '%".$search."%'

Using this code will help you search in for multiple columns easily

How to do a non-greedy match in grep?

You're looking for a non-greedy (or lazy) match. To get a non-greedy match in regular expressions you need to use the modifier ? after the quantifier. For example you can change .* to .*?.

By default grep doesn't support non-greedy modifiers, but you can use grep -P to use the Perl syntax.

Change URL parameters

Would a viable alternative to String manipulation be to set up an html form and just modify the value of the rows element?

So, with html that is something like

<form id='myForm' target='site.fwx'>
    <input type='hidden' name='position' value='1'/>
    <input type='hidden' name='archiveid' value='5000'/>
    <input type='hidden' name='columns' value='5'/>
    <input type='hidden' name='rows' value='20'/>
    <input type='hidden' name='sorting' value='ModifiedTimeAsc'/>
</form>

With the following JavaScript to submit the form

var myForm = document.getElementById('myForm');
myForm.rows.value = yourNewValue;
myForm.submit();

Probably not suitable for all situations, but might be nicer than parsing the URL string.

How to get main window handle from process id?

As an extension to Hiale's solution, you could provide a different or modified version that supports processes that have multiple main windows.

First, amend the structure to allow storing of multiple handles:

struct handle_data {
    unsigned long process_id;
    std::vector<HWND> handles;
};

Second, amend the callback function:

BOOL CALLBACK enum_windows_callback(HWND handle, LPARAM lParam)
{
    handle_data& data = *(handle_data*)lParam;
    unsigned long process_id = 0;
    GetWindowThreadProcessId(handle, &process_id);
    if (data.process_id != process_id || !is_main_window(handle)) {
        return TRUE;
    }
    // change these 2 lines to allow storing of handle and loop again
    data.handles.push_back(handle);
    return TRUE;   
 }

Finally, amend the returns on the main function:

std::vector<HWD> find_main_window(unsigned long process_id)
{
    handle_data data;
    data.process_id = process_id;
    EnumWindows(enum_windows_callback, (LPARAM)&data);
    return data.handles;
}

How do I create a shortcut via command-line in Windows?

I present a small hybrid script [BAT/VBS] to create a desktop shortcut. And you can of course modifie it to your purpose.

@echo off
mode con cols=87 lines=5 & color 9B
Title Shortcut Creator for your batch and applications files by Hackoo 2015
Set MyFile=%~f0
Set ShorcutName=HackooTest
(
echo Call Shortcut("%MyFile%","%ShorcutName%"^)
echo ^'**********************************************************************************************^)
echo Sub Shortcut(ApplicationPath,Nom^)
echo    Dim objShell,DesktopPath,objShortCut,MyTab
echo    Set objShell = CreateObject("WScript.Shell"^)
echo    MyTab = Split(ApplicationPath,"\"^)
echo    If Nom = "" Then
echo    Nom = MyTab(UBound(MyTab^)^)
echo    End if
echo    DesktopPath = objShell.SpecialFolders("Desktop"^)
echo    Set objShortCut = objShell.CreateShortcut(DesktopPath ^& "\" ^& Nom ^& ".lnk"^)
echo    objShortCut.TargetPath = Dblquote(ApplicationPath^)
echo    ObjShortCut.IconLocation = "Winver.exe,0"
echo    objShortCut.Save
echo End Sub
echo ^'**********************************************************************************************
echo ^'Fonction pour ajouter les doubles quotes dans une variable
echo Function DblQuote(Str^)
echo    DblQuote = Chr(34^) ^& Str ^& Chr(34^)
echo End Function
echo ^'**********************************************************************************************
) > Shortcutme.vbs
Start /Wait Shortcutme.vbs
Del Shortcutme.vbs
::***************************************Main Batch*******************************************
cls
echo Done and your main batch goes here !
echo i am a test 
Pause > Nul
::********************************************************************************************

Can I run HTML files directly from GitHub, instead of just viewing their source?

raw.github.com/user/repository is no longer there

To link, href to source code in github, you have to use github link to raw source this way:

raw.githubusercontent.com/user/repository/master/file.extension

EXAMPLE

<html>
...
...
<head>    
<script src="https://raw.githubusercontent.com/amiahmadtouseef/tutorialhtmlfive/master/petdecider/script.js"></script>
...
</head>
<body>
...
</html>

Assign a class name to <img> tag instead of write it in css file?

Its depend. If you have more than two images in .column but you only need some images to have css applied then its better to add class to image directly instead of doing .column img{/*styling for image here*/}

In performance aspect i thing apply class to image is better because by doing so css will not look for possible child image.

Wait until page is loaded with Selenium WebDriver for Python

Here I did it using a rather simple form:

from selenium import webdriver
browser = webdriver.Firefox()
browser.get("url")
searchTxt=''
while not searchTxt:
    try:    
      searchTxt=browser.find_element_by_name('NAME OF ELEMENT')
      searchTxt.send_keys("USERNAME")
    except:continue

CURL Command Line URL Parameters

Felipsmartins is correct.

It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.

Which means you can do this:

curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'

Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.

I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.

curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros

This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)

Hope it helps.

Checking oracle sid and database name

The V$ views are mainly dynamic views of system metrics. They are used for performance tuning, session monitoring, etc. So access is limited to DBA users by default, which is why you're getting ORA-00942.

The easiest way of finding the database name is:

select * from global_name;

This view is granted to PUBLIC, so anybody can query it.

ListBox vs. ListView - how to choose for data binding

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

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

Get changes from master into branch in Git

There is no guarantee that the master bug fixes are not amongst other commits, hence you can't simply merge. Do

git checkout aq
git cherry-pick commit1
git cherry-pick commit2
git cherry-pick commit3
...

assuming those commits represent the bug fixes.

From now on though, keep bug fixes in a separate branch. You will be able to just

git merge hotfixes

when you want to roll them all into the regular dev branch.

How do I parse command line arguments in Bash?

If you are making scripts that are interchangeable with other utilities, below flexibility may be useful.

Either:

command -x=myfilename.ext --another_switch 

Or:

command -x myfilename.ext --another_switch

Here is the code:

STD_IN=0

prefix=""
key=""
value=""
for keyValue in "$@"
do
  case "${prefix}${keyValue}" in
    -i=*|--input_filename=*)  key="-i";     value="${keyValue#*=}";; 
    -ss=*|--seek_from=*)      key="-ss";    value="${keyValue#*=}";;
    -t=*|--play_seconds=*)    key="-t";     value="${keyValue#*=}";;
    -|--stdin)                key="-";      value=1;;
    *)                                      value=$keyValue;;
  esac
  case $key in
    -i) MOVIE=$(resolveMovie "${value}");  prefix=""; key="";;
    -ss) SEEK_FROM="${value}";          prefix=""; key="";;
    -t)  PLAY_SECONDS="${value}";           prefix=""; key="";;
    -)   STD_IN=${value};                   prefix=""; key="";; 
    *)   prefix="${keyValue}=";;
  esac
done

Assert that a method was called in a Python unit test

I use Mock (which is now unittest.mock on py3.3+) for this:

from mock import patch
from PyQt4 import Qt


@patch.object(Qt.QMessageBox, 'aboutQt')
def testShowAboutQt(self, mock):
    self.win.actionAboutQt.trigger()
    self.assertTrue(mock.called)

For your case, it could look like this:

import mock
from mock import patch


def testClearWasCalled(self):
   aw = aps.Request("nv1")
   with patch.object(aw, 'Clear') as mock:
       aw2 = aps.Request("nv2", aw)

   mock.assert_called_with(42) # or mock.assert_called_once_with(42)

Mock supports quite a few useful features, including ways to patch an object or module, as well as checking that the right thing was called, etc etc.

Caveat emptor! (Buyer beware!)

If you mistype assert_called_with (to assert_called_once or assert_called_wiht) your test may still run, as Mock will think this is a mocked function and happily go along, unless you use autospec=true. For more info read assert_called_once: Threat or Menace.

What size should TabBar images be?

According to my practice, I use the 40 x 40 for standard iPad tab bar item icon, 80 X 80 for retina.

From the Apple reference. https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/BarIcons.html#//apple_ref/doc/uid/TP40006556-CH21-SW1

If you want to create a bar icon that looks like it's related to the iOS 7 icon family, use a very thin stroke to draw it. Specifically, a 2-pixel stroke (high resolution) works well for detailed icons and a 3-pixel stroke works well for less detailed icons.

Regardless of the icon’s visual style, create a toolbar or navigation bar icon in the following sizes:

About 44 x 44 pixels About 22 x 22 pixels (standard resolution) Regardless of the icon’s visual style, create a tab bar icon in the following sizes:

About 50 x 50 pixels (96 x 64 pixels maximum) About 25 x 25 pixels (48 x 32 pixels maximum) for standard resolution

How to change Tkinter Button state from disabled to normal?

This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here's the winning combination for me, for some reason.. different than everyone else?

import tkinter

class App(object):
    def __init__(self):
        self.tree = None
        self._setup_widgets()

    def _setup_widgets(self):
        butts = tkinter.Button(text = "add line", state="disabled")
        butts.grid()

def main():  
    root = tkinter.Tk()
    app = App()
    root.mainloop()

if __name__ == "__main__":
    main()

Remove scrollbar from iframe

Add this in your css to hide just the horizontal scroll bar

iframe{
    overflow-x:hidden;
}

iPhone UITextField - Change placeholder text color

I had already faced this issue. In my case below code is correct.

Objective C

[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

For Swift 4.X

tf_mobile.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")

For iOS 13 Swift Code

tf_mobile.attributedPlaceholder = NSAttributedString(string:"PlaceHolder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])

You can also use below code for iOS 13

let iVar = class_getInstanceVariable(UITextField.self, "_placeholderLabel")!
let placeholderLabel = object_getIvar(tf_mobile, iVar) as! UILabel
placeholderLabel.textColor = .red

Hope, this may help you.

Pass connection string to code-first DbContext

I have a little solution example for that problem.

MyDBContext.cs

 public MyDBContext(DBConnectionType ConnectionType) //: base("ConnMain")
  {
      if(ConnectionType==DBConnectionType.MainConnection)
       {
         this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnMain"].ConnectionString;
       }
      else if(ConnectionType==DBConnectionType.BackupConnection)
       {
         this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnBackup"].ConnectionString;
       }
  }

MyClass.cs

public enum DBConnectionType
 {
    MainConnection=0,
    BackupConnection=1
 }

frmMyForm.cs

 MyDBContext db = new MyDBContext(DBConnectionType.MainConnection);
                               //or
//MyDBContext db = new MyDBContext(DBConnectionType.BackupConnection);

Nested or Inner Class in PHP

As per Xenon's comment to Anil Özselgin's answer, anonymous classes have been implemented in PHP 7.0, which is as close to nested classes as you'll get right now. Here are the relevant RFCs:

Nested Classes (status: withdrawn)

Anonymous Classes (status: implemented in PHP 7.0)

An example to the original post, this is what your code would look like:

<?php
    public class User {
        public $userid;
        public $username;
        private $password;

        public $profile;
        public $history;

        public function __construct() {
            $this->profile = new class {
                // Some code here for user profile
            }

            $this->history = new class {
                // Some code here for user history
            }
        }
    }
?>

This, though, comes with a very nasty caveat. If you use an IDE such as PHPStorm or NetBeans, and then add a method like this to the User class:

public function foo() {
  $this->profile->...
}

...bye bye auto-completion. This is the case even if you code to interfaces (the I in SOLID), using a pattern like this:

<?php
    public class User {
        public $profile;

        public function __construct() {
            $this->profile = new class implements UserProfileInterface {
                // Some code here for user profile
            }
        }
    }
?>

Unless your only calls to $this->profile are from the __construct() method (or whatever method $this->profile is defined in) then you won't get any sort of type hinting. Your property is essentially "hidden" to your IDE, making life very hard if you rely on your IDE for auto-completion, code smell sniffing, and refactoring.

Extracting specific columns from a data frame

Where df1 is your original data frame:

df2 <- subset(df1, select = c(1, 2, 5))

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

I wouldn't use StringTokenizer as it is one of classes in the JDK that's legacy.

The javadoc says:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Word wrap for a label in Windows Forms

If you really want to set the label width independent of the content, I find that the easiest way is this:

  • Set autosize true
  • Set maximum width to how you want it
  • Set minimum width identically

Now the label is of constant width, but it adapts its height automatically.

Then for dynamic text, decrease the font size. If necessary, use this snippet in the sub where the label text is set:

If Me.Size.Height - (Label12.Location.Y + Label12.Height) < 20 Then
    Dim naam As String = Label12.Font.Name
    Dim size As Single = Label12.Font.SizeInPoints - 1
    Label12.Font = New Font(naam, size)
End If

What does ':' (colon) do in JavaScript?

One stupid mistake I did awhile ago that might help some people.

Keep in mind that if you are using ":" in an event like this, the value will not change

var ondrag = (function(event, ui) {
            ...

            nub0x: event.target.offsetLeft + event.target.clientWidth/2;
            nub0y = event.target.offsetTop + event.target.clientHeight/2;

            ...
        });

So "nub0x" will initialize with the first event that happens and will never change its value. But "nub0y" will change during the next events.

vagrant login as root by default

Solution:
Add the following to your Vagrantfile:

config.ssh.username = 'root'
config.ssh.password = 'vagrant'
config.ssh.insert_key = 'true'

When you vagrant ssh henceforth, you will login as root and should expect the following:

==> mybox: Waiting for machine to boot. This may take a few minutes...
    mybox: SSH address: 127.0.0.1:2222
    mybox: SSH username: root
    mybox: SSH auth method: password
    mybox: Warning: Connection timeout. Retrying...
    mybox: Warning: Remote connection disconnect. Retrying...
==> mybox: Inserting Vagrant public key within guest...
==> mybox: Key inserted! Disconnecting and reconnecting using new SSH key...
==> mybox: Machine booted and ready!

Update 23-Jun-2015: This works for version 1.7.2 as well. Keying security has improved since 1.7.0; this technique overrides back to the previous method which uses a known private key. This solution is not intended to be used for a box that is accessible publicly without proper security measures done prior to publishing.

Reference:

Securing a password in a properties file

Actually, this is a duplicate of Encrypt Password in Configuration Files?.

The best solution I found so far is in this answert: https://stackoverflow.com/a/1133815/1549977

Pros: Password is saved a a char array, not as a string. It's still not good, but better than anything else.

how to delete all commit history in github?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D main

  5. Rename the current branch to main

    git branch -m main

  6. Finally, force update your repository

    git push -f origin main

PS: this will not keep your old commit history around

How to create a List with a dynamic object type

Just use dynamic as the argument:

var list = new List<dynamic>();

Proxy with urllib2

One can also use requests if we would like to access a web page using proxies. Python 3 code:

>>> import requests
>>> url = 'http://www.google.com'
>>> proxy = '169.50.87.252:80'
>>> requests.get(url, proxies={"http":proxy})
<Response [200]>

More than one proxies can also be added.

>>> proxy1 = '169.50.87.252:80'
>>> proxy2 = '89.34.97.132:8080'
>>> requests.get(url, proxies={"http":proxy1,"http":proxy2})
<Response [200]>

convert string array to string

I used this way to make my project faster:

RichTextBox rcbCatalyst = new RichTextBox()
{
    Lines = arrayString
};
string text = rcbCatalyst.Text;
rcbCatalyst.Dispose();

return text;

RichTextBox.Text will automatically convert your array to a multiline string!

C# - Fill a combo box with a DataTable

A few points:

1) "DataBind()" is only for web apps (not windows apps).

2) Your code looks very 'JAVAish' (not a bad thing, just an observation).

Try this:

mnuActionLanguage.ComboBox.DataSource = languages;

If that doesn't work... then I'm assuming that your datasource is being stepped on somewhere else in the code.

'innerText' works in IE, but not in Firefox

What about something like this?

//$elem is the jQuery object passed along.

var $currentText = $elem.context.firstChild.data.toUpperCase();

** I needed to make mine uppercase.

How do I install command line MySQL client on mac?

install MySQLWorkbench, then

export PATH=$PATH:/Applications/MySQLWorkbench.app/Contents/MacOS

How do I create a Linked List Data Structure in Java?

Use java.util.LinkedList. Like this:

list = new java.util.LinkedList()

Getting today's date in YYYY-MM-DD in Python?

Are you working with Pandas?

You can use pd.to_datetime from the pandas library. Here are various options, depending on what you want returned.

import pandas as pd

pd.to_datetime('today')  # pd.to_datetime('now')
# Timestamp('2019-03-27 00:00:10.958567')

As a python datetime object,

pd.to_datetime('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 50, 42, 587629)

As a formatted date string,

pd.to_datetime('today').isoformat()
# '2019-04-18T04:03:32.493337'

# Or, `strftime` for custom formats.
pd.to_datetime('today').strftime('%Y-%m-%d')
# '2019-03-27'

To get just the date from the timestamp, call Timestamp.date.

pd.to_datetime('today').date()
# datetime.date(2019, 3, 27)

Aside from to_datetime, you can directly instantiate a Timestamp object using,

pd.Timestamp('today')  # pd.Timestamp('now')
# Timestamp('2019-04-18 03:43:33.233093')

pd.Timestamp('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 53, 46, 220068)

If you want to make your Timestamp timezone aware, pass a timezone to the tz argument.

pd.Timestamp('now', tz='America/Los_Angeles')
# Timestamp('2019-04-18 03:59:02.647819-0700', tz='America/Los_Angeles')

Yet another date parser library: Pendulum

This one's good, I promise.

If you're working with pendulum, there are some interesting choices. You can get the current timestamp using now() or today's date using today().

import pendulum 

pendulum.now()
# DateTime(2019, 3, 27, 0, 2, 41, 452264, tzinfo=Timezone('America/Los_Angeles'))

pendulum.today()
# DateTime(2019, 3, 27, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

Additionally, you can also get tomorrow() or yesterday()'s date directly without having to do any additional timedelta arithmetic.

pendulum.yesterday()
# DateTime(2019, 3, 26, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

pendulum.tomorrow()
# DateTime(2019, 3, 28, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))

There are various formatting options available.

pendulum.now().to_date_string()
# '2019-03-27'

pendulum.now().to_formatted_date_string()
# 'Mar 27, 2019'

pendulum.now().to_day_datetime_string()
# 'Wed, Mar 27, 2019 12:04 AM'

Rationale for this answer

A lot of pandas users stumble upon this question because they believe it is a python question more than a pandas one. This answer aims to be useful to folks who are already using these libraries and would be interested to know that there are ways to achieve these results within the scope of the library itself.

If you are not working with pandas or pendulum already, I definitely do not recommend installing them just for the sake of running this code! These libraries are heavy and come with a lot of plumbing under the hood. It is not worth the trouble when you can use the standard library instead.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

What does LINQ return when the results are empty

Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.

Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.

How to hide/show more text within a certain length (like youtube)

$('#more').click(function(e) {
    e.stopPropagation();
    $('div').css({
        'height': 'auto'
    })
});

$(document).click(function() {
    $('div').css({
        'height': '40px'
    })
})

Check working example at http://jsfiddle.net/7Vv8u/4/

With Animation http://jsfiddle.net/7Vv8u/5/

Click on Read more to expand the text. Click outside to minimize it again.

Center a H1 tag inside a DIV

You could add padding to the h1:

#AlertDiv h1 {
  padding:15px 18px;
}

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement