Programs & Examples On #Mediawiki

MediaWiki is a free software wiki package written in PHP, originally for use on Wikipedia. It is now used by several other projects hosted by the non-profit Wikimedia Foundation and by many other wikis.

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

The error message says that getComputedStyle requires the parameter to be Element type. You receive it because the parameter has an incorrect type.

The most common case is that you try to pass an element that doesn't exist as an argument:

my_element = document.querySelector(#non_existing_id);

Now that element is null, this will result in mentioned error:

my_style = window.getComputedStyle(my_element);

If it's not possible to always get element correctly, you can, for example, use the following to end function if querySelector didn't find any match:

if (my_element === null) return;

Equivalent of .bat in mac os

May be you can find answer here? Equivalent of double-clickable .sh and .bat on Mac?

Usually you can create bash script for Mac OS, where you put similar commands as in batch file. For your case create bash file and put same command, but change back-slashes with regular ones.

Your file will look something like:

#! /bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;./supportlibraries/Framework_DataTable.jar;./supportlibraries/Framework_Reporting.jar;./supportlibraries/Framework_Utilities.jar;./supportlibraries/poi-3.8-20120326.jar;PATH_TO_YOUR_SELENIUM_SERVER_FOLDER/selenium-server-standalone-2.19.0.jar" allocator.testTrack

Change folders in path above to relevant one.

Then make this script executable: open terminal and navigate to folder with your script. Then change read-write-execute rights for this file running command:

chmod 755 scriptname.sh

Then you can run it like any other regular script: ./scriptname.sh

or you can run it passing file to bash:

bash scriptname.sh

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

The key point is referencing right version in your config file.

Steps;

1- look at what is the version of your Newtonsoft.Json.dll in the project reference property what ever the version in your package folder (For example mine is 7.0.1 and the reference Version is 7.0.0.0)

2- look at what the project expect from you in the exception (mine is 6.0.0.0)

3- Add dependent assembly to your config file as it should be..

  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json"  publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="7.0.0.0"/>
  </dependentAssembly>

Matplotlib: "Unknown projection '3d'" error

First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib.

Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib."__version__")

I'm guessing you're running version 0.99, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib.

If you're running version 0.99, try doing this instead of using using the projection keyword argument:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization! 
fig = plt.figure()

ax = Axes3D(fig) #<-- Note the difference from your original code...

X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()

This should work in matplotlib 1.0.x, as well, not just 0.99.

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Try this

SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID=@id", con);
cmd.Parameters.AddWithValue("id", id.Text);

How do I undo the most recent local commits in Git?

In my case I accidentally committed some files I did not want to. So I did the following and it worked:

git reset --soft HEAD^
git rm --cached [files you do not need]
git add [files you need]
git commit -c ORIG_HEAD

Verify the results with gitk or git log --stat

Converting a string to JSON object

var Data=[{"id": "name2", "label": "Quantity"}]

Pass the string variable into Json parse :

Objdata= Json.parse(Data);

Add JsonArray to JsonObject

I'm starting to learn about this myself, being very new to android development and I found this video very helpful.

https://www.youtube.com/watch?v=qcotbMLjlA4

It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.

Code from the video for JSONArray to JSONObject:

JSONArray queryArray = quoteJSONObject.names();

ArrayList<String> list = new ArrayList<String>();

for(int i = 0; i < queryArray.length(); i++){
    list.add(queryArray.getString(i));
}

for(String item : list){
    Log.v("JSON ARRAY ITEMS ", item);
}

How can I check for existence of element in std::vector, in one line?

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

Define the selected option with the old input in Laravel / Blade

Also, you can use the ? operator to avoid having to use @if @else @endif syntax. Change:

@if (Input::old('title') == $key)
      <option value="{{ $key }}" selected>{{ $val }}</option>
@else
      <option value="{{ $key }}">{{ $val }}</option>
@endif

Simply to:

<option value="{{ $key }}" {{ (Input::old("title") == $key ? "selected":"") }}>{{ $val }}</option>

Redirect to external URL with return in laravel

For Laravel 8 you can also use

Route::redirect('/here', '/there');
//or
Route::permanentRedirect('/here', '/there');

This also works with external URLs

See: https://austencam.com/posts/setting-up-an-m1-mac-for-laravel-development-with-homebrew-php-mysql-valet-and-redis

What does ^M character mean in Vim?

This is the only thing that worked in my case:

:e ++ff=dos

:wq

How to use underscore.js as a template engine?

Everything you need to know about underscore template is here. Only 3 things to keep in mind:

  1. <% %> - to execute some code
  2. <%= %> - to print some value in template
  3. <%- %> - to print some values HTML escaped

That's all about it.

Simple example:

var tpl = _.template("<h1>Some text: <%= foo %></h1>");

then tpl({foo: "blahblah"}) would be rendered to the string <h1>Some text: blahblah</h1>

npm check and update package if needed

Check outdated packages

npm outdated

Check and pick packages to update

npx npm-check -u

npm oudated img

npx npm-check -u img

Merge a Branch into Trunk

If your working directory points to the trunk, then you should be able to merge your branch with:

svn merge https://HOST/repository/branches/branch_1

be sure to be to issue this command in the root directory of your trunk

How do I change JPanel inside a JFrame on the fly?

I was having exactly the same problem!! Increadible!! The solution I found was:

  1. Adding all the components (JPanels) to the container;
  2. Using the setVisible(false) method to all of them;
  3. On user action, setting setVisible(true) to the panel I wanted to show.
// Hiding all components (JPanels) added to a container (ex: another JPanel)
for (Component component : this.container.getComponents()) {
      component.setVisible(false);
}
// Showing only the selected JPanel, the one user wants to see
panel.setVisible(true);

No revalidate(), no validate(), no CardLayout needed.

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

I've had same problem with docker-compose:

  1. Killed docker-proxy processe .
  2. Restart docker
  3. Start docker-compose again.

What is bootstrapping?

"Bootstrapping" comes from the term "pulling yourself up by your own bootstraps." That much you can get from Wikipedia.

In computing, a bootstrap loader is the first piece of code that runs when a machine starts, and is responsible for loading the rest of the operating system. In modern computers it's stored in ROM, but I recall the bootstrap process on the PDP-11, where you would poke bits via the front-panel switches to load a particular disk segment into memory, and then run it. Needless to say, the bootstrap loader is normally pretty small.

"Bootstrapping" is also used as a term for building a system using itself -- or more correctly, a predecessor version. For example, ANTLR version 3 is written using a parser developed in ANTLR version 2.

Removing unwanted table cell borders with CSS

Set the cellspacing attribute of the table to 0.

You can also use the CSS style, border-spacing: 0, but only if you don't need to support older versions of IE.

How to exclude property from Json Serialization

If you are using Json.Net attribute [JsonIgnore] will simply ignore the field/property while serializing or deserialising.

public class Car
{
  // included in JSON
  public string Model { get; set; }
  public DateTime Year { get; set; }
  public List<string> Features { get; set; }

  // ignored
  [JsonIgnore]
  public DateTime LastModified { get; set; }
}

Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.

[DataContract]
public class Computer
{
  // included in JSON
  [DataMember]
  public string Name { get; set; }
  [DataMember]
  public decimal SalePrice { get; set; }

  // ignored
  public string Manufacture { get; set; }
  public int StockCount { get; set; }
  public decimal WholeSalePrice { get; set; }
  public DateTime NextShipmentDate { get; set; }
}

Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details

git pull from master into the development branch

Scenario:

I have master updating and my branch updating, I want my branch to keep track of master with rebasing, to keep all history tracked properly, let's call my branch Mybranch

Solution:

git checkout master    
git pull --rebase    
git checkout Mybranch    
git rebase master
git push -f origin Mybranch
  • need to resolve all conflicts with git mergetool &, git rebase --continue, git rebase --skip, git add -u, according to situation and git hints, till all is solved

(correction to last stage, in courtesy of Tzachi Cohen, using "-f" forces git to "update history" at server)

now branch should be aligned with master and rebased, also with remote updated, so at git log there are no "behind" or "ahead", just need to remove all local conflict *.orig files to keep folder "clean"

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I finally found the problem. The error was not the good one.

Apparently, Ole DB source have a bug that might make it crash and throw that error. I replaced the OLE DB destination with a OLE DB Command with the insert statement in it and it fixed it.

The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

Strange Bug, Hope it will help other people.

Static image src in Vue.js template

This is how i solve it.:

      items: [
        { title: 'Dashboard', icon: require('@/assets/icons/sidebar/dashboard.svg') },
        { title: 'Projects',  icon: require('@/assets/icons/sidebar/projects.svg') },
        { title: 'Clients', icon: require('@/assets/icons/sidebar/clients.svg') },
      ],

And on the template part:

<img :src="item.icon" />

See it in action here

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

How to get city name from latitude and longitude coordinates in Google Maps?

try using this api :

URL ": http://maps.googleapis.com/maps/api/geocode/json?latlng="+String.valueOf(yout_lattitude)+","+String.valueOf(your_longitude)

How to run SQL in shell script

Maybe it's too late for answering but, there's a working code:

sqlplus -s "/ as sysdba" << EOF
    SET HEADING OFF
    SET FEEDBACK OFF
    SET LINESIZE 3800
    SET TRIMSPOOL ON
    SET TERMOUT OFF
    SET SPACE 0
    SET PAGESIZE 0
    select (select instance_name from v\$instance) as DB_NAME,
           file_name
      from dba_data_files
     order by 2;

MySQL user DB does not have password columns - Installing MySQL on OSX

It only worked with me when I "flushed" after the commands mentioned here. Here's the full list of commands I used:

Previous answers might not work for later mysql versions. Try these steps if previous answers did not work for you:

1- Click on the wamp icon > mysql > mysql console

2- write following commands, one by one

use mysql;
update user set authentication_string=password('your_password') where user='root';
FLUSH PRIVILEGES;
quit

How to get a jqGrid selected row cells value

You can use in this manner also

var rowId =$("#list").jqGrid('getGridParam','selrow');  
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId'];   // perticuler Column name of jqgrid that you want to access

How to float 3 divs side by side using CSS?

I prefer this method, floats are poorly supported in older versions of IE (really?...)

.column-left{ position:absolute; left: 0px; width: 33.3%; background: red; }
.column-right{position:absolute; left:66.6%; width: 33.3%; background: green; }
.column-center{ position:absolute; left:33.3%; width: 33.3%; background: yellow; }

UPDATED : Of course, to use this technique and due to the absolute positioning you need to enclose the divs on a container and do a postprocessing to define the height of if, something like this:

jQuery(document).ready(function(){ 
    jQuery('.main').height( Math.max (
        jQuery('.column-left').height(),
        jQuery('.column??-right').height(),
        jQuery('.column-center').height())
    ); 
});

Not the most amazing thing in the world, but at least doesn't break on older IEs.

How to include a font .ttf using CSS?

Only providing .ttf file for webfont won't be good enough for cross-browser support. The best possible combination at present is using the combination as :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff') format('woff'), /* Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

This code assumes you have .eot , .woff , .ttf and svg format for you webfont. To automate all this process , you can use : Transfonter.org.

Also , modern browsers are shifting towards .woff font , so you can probably do this too : :

@font-face {
  font-family: 'MyWebFont';
  src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
   url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */
}  

Read more here : http://css-tricks.com/snippets/css/using-font-face/


Look for browser support : Can I Use fontface

Reset textbox value in javascript

this is might be a possible solution

void 0 != document.getElementById("ad") &&       (document.getElementById("ad").onclick =function(){
 var a = $("#client_id").val();
 var b = $("#contact").val();
 var c = $("#message").val();
 var Qdata = { client_id: a, contact:b, message:c }
 var respo='';
     $("#message").html('');

return $.ajax({

    url: applicationPath ,
    type: "POST",
    data: Qdata,
    success: function(e) {
         $("#mcg").html("msg send successfully");

    }

})

});

Pass array to where in Codeigniter Active Record

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,

$this->db->where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate

$this->db->or_where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

What exactly is the 'react-scripts start' command?

As Sagiv b.g. pointed out, the npm start command is a shortcut for npm run start. I just wanted to add a real-life example to clarify it a bit more.

The setup below comes from the create-react-app github repo. The package.json defines a bunch of scripts which define the actual flow.

"scripts": {
  "start": "npm-run-all -p watch-css start-js",
  "build": "npm run build-css && react-scripts build",
  "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
  "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
  "start-js": "react-scripts start"
},

For clarity, I added a diagram. enter image description here

The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name> command. But as you can see, actually there are only 2 practical flows:

  • npm run start
  • npm run build

The grey boxes are commands which can be executed from the command line.

So, for instance, if you run npm start (or npm run start) that actually translate to the npm-run-all -p watch-css start-js command, which is executed from the commandline.

In my case, I have this special npm-run-all command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2> switch. So, here it executes 2 scripts, i.e. watch-css and start-js. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)

  • The watch-css makes sure that the *.scss files are translated to *.cssfiles, and looks for future updates.

  • The start-js points to the react-scripts start which hosts the website in a development mode.

In conclusion, the npm start command is configurable. If you want to know what it does, then you have to check the package.json file. (and you may want to make a little diagram when things get complicated).

Visual Studio Error: (407: Proxy Authentication Required)

My case is when using two factor auth, outlook account and VS12.

I found out I have to

  • open IE (my corporate default browser)
  • log in to visual studio online account (including two factor auth)
  • connect again in VS12 (do the auth again for some reason)

show all tags in git log

Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:

Make sure you study this thread, as overriding a signed tag is not as easy:

  • if you already pushed a tag, the git tag man page seriously advised against a simple git tag -f B to replace a tag name "A"
  • don't try to recreate a signed tag with git tag -f (see the thread extract below)

    (it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):

Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:

  • in the tag object itself as a contents of 'tag' header (you can see it in output of "git show <tag>" and also in output of "git cat-file -p <tag>", where <tag> is heavyweight tag, e.g. v1.6.3 in git.git repository),
  • and also is default name of tag reference (reference in "refs/tags/*" namespace) pointing to a tag object.
    Note that the tag reference (appropriate reference in the "refs/tags/*" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3', other can have in 'refs/tags/sub/v0.1.3' for example.

So when you create signed tag 'A', you have the following situation (assuming that it points at some commit)

  35805ce   <--- 5b7b4ead  <=== refs/tags/A
  (commit)       tag A
                 (tag)

Please also note that "git tag -f A A" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.

If you do "git tag -f -s A A": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of -s / -a / -m options is used to force annotated tag (creation of tag object), you will get the following situation

  35805ce   <--- 5b7b4ea  <--- ada8ddc  <=== refs/tags/A
  (commit)       tag A         tag A
                 (tag)         (tag)

Note also that "git show A" would show the whole chain down to the non-tag object...

Get/pick an image from Android's built-in Gallery app programmatically

Please find the answer for the selecting single image from gallery

import android.app.Activity;
import android.net.Uri;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class PickImage extends Activity {

    Button btnOpen, btnGet, btnPick;
    TextView textInfo1, textInfo2;
    ImageView imageView;

    private static final int RQS_OPEN_IMAGE = 1;
    private static final int RQS_GET_IMAGE = 2;
    private static final int RQS_PICK_IMAGE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_pick);
        btnOpen = (Button)findViewById(R.id.open);
        btnGet = (Button)findViewById(R.id.get);
        btnPick = (Button)findViewById(R.id.pick);
        textInfo1 = (TextView)findViewById(R.id.info1);
        textInfo2 = (TextView)findViewById(R.id.info2);
        imageView = (ImageView) findViewById(R.id.image);

        btnOpen.setOnClickListener(btnOpenOnClickListener);
        btnGet.setOnClickListener(btnGetOnClickListener);
        btnPick.setOnClickListener(btnPickOnClickListener);
    }

    View.OnClickListener btnOpenOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");

            startActivityForResult(intent, RQS_OPEN_IMAGE);
        }
    };

    View.OnClickListener btnGetOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");

            startActivityForResult(intent, RQS_OPEN_IMAGE);
        }
    };

    View.OnClickListener btnPickOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, RQS_PICK_IMAGE);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {


            if (requestCode == RQS_OPEN_IMAGE ||
                    requestCode == RQS_GET_IMAGE ||
                    requestCode == RQS_PICK_IMAGE) {

                imageView.setImageBitmap(null);
                textInfo1.setText("");
                textInfo2.setText("");

                Uri mediaUri = data.getData();
                textInfo1.setText(mediaUri.toString());
                String mediaPath = mediaUri.getPath();
                textInfo2.setText(mediaPath);

                //display the image
                try {
                    InputStream inputStream = getBaseContext().getContentResolver().openInputStream(mediaUri);
                    Bitmap bm = BitmapFactory.decodeStream(inputStream);

                   ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    byte[] byteArray = stream.toByteArray();

                    imageView.setImageBitmap(bm);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

how to check if input field is empty

if you are using jquery-validate.js in your application then use below expression.

if($("#spa").is(":blank"))
{
  //code
}

Send data from javascript to a mysql database

You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".

Virtual member call in a constructor

I think that ignoring the warning might be legitimate if you want to give the child class the ability to set or override a property that the parent constructor will use right away:

internal class Parent
{
    public Parent()
    {
        Console.WriteLine("Parent ctor");
        Console.WriteLine(Something);
    }

    protected virtual string Something { get; } = "Parent";
}

internal class Child : Parent
{
    public Child()
    {
        Console.WriteLine("Child ctor");
        Console.WriteLine(Something);
    }

    protected override string Something { get; } = "Child";
}

The risk here would be for the child class to set the property from its constructor in which case the change in the value would occur after the base class constructor has been called.

My use case is that I want the child class to provide a specific value or a utility class such as a converter and I don't want to have to call an initialization method on the base.

The output of the above when instantiating the child class is:

Parent ctor
Child
Child ctor
Child

Returning Promises from Vuex actions

actions.js

const axios = require('axios');
const types = require('./types');

export const actions = {
  GET_CONTENT({commit}){
    axios.get(`${URL}`)
      .then(doc =>{
        const content = doc.data;
        commit(types.SET_CONTENT , content);
        setTimeout(() =>{
          commit(types.IS_LOADING , false);
        } , 1000);
      }).catch(err =>{
        console.log(err);
    });
  },
}

home.vue

<script>
  import {value , onCreated} from "vue-function-api";
  import {useState, useStore} from "@u3u/vue-hooks";

  export default {
    name: 'home',

    setup(){
      const store = useStore();
      const state = {
        ...useState(["content" , "isLoading"])
      };
      onCreated(() =>{
        store.value.dispatch("GET_CONTENT" );
      });

      return{
        ...state,
      }
    }
  };
</script>

What's the best/easiest GUI Library for Ruby?

wxWidgets is worth checking out. It is well supported on Ruby via wxRuby. For an example app, have a look at wxRIDE. See it compared to other toolkits. You might also want to check out Anvil, which is a sort of Rails-ish framework for working with wx. It looks moribund now, though.

WPF MVVM: How to close a window

You could rephrase the question, and by doing so - coming up with another solution. How can I enable communication between views, viewmodels and whatnot in an MVVM environment? You could use the Mediator pattern. It's basically a notification system. For the actual Mediator implementation, google for it or ask me and I can email it.

Make a Command whose purpose is to close the view.

public void Execute( object parameter )
{
    this.viewModel.DisposeMyStuff();
    Mediator.NotifyColleagues(Mediator.Token.ConfigWindowShouldClose);
}

The Mediator will raise a notification (a token)

Listen to this notification (token) like this in the View codebehind constructor:

public ClientConfigView()
{
    InitializeComponent();
    Mediator.ListenOn(Mediator.Token.ConfigWindowShouldClose, callback => this.Close() );
}

How to set the default value for radio buttons in AngularJS?

Set a default value for people with ngInit

<div ng-app>
    <div ng-init="people=1" />
        <input type="radio" ng-model="people" value="1"><label>1</label>
        <input type="radio" ng-model="people" value="2"><label>2</label>
        <input type="radio" ng-model="people" value="3"><label>3</label>
    <ul>
        <li>{{10*people}}€</li>
        <li>{{8*people}}€</li>
        <li>{{30*people}}€</li>
    </ul>
</div>

Demo: Fiddle

AngularJS - pass function to directive

To call a controller function in parent scope from inside an isolate scope directive, use dash-separated attribute names in the HTML like the OP said.

Also if you want to send a parameter to your function, call the function by passing an object:

<test color1="color1" update-fn="updateFn(msg)"></test>

JS

var app = angular.module('dr', []);

app.controller("testCtrl", function($scope) {
    $scope.color1 = "color";
    $scope.updateFn = function(msg) {        
        alert(msg);
    }
});

app.directive('test', function() {
    return {
        restrict: 'E',
        scope: {
            color1: '=',
            updateFn: '&'
        },
        // object is passed while making the call
        template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>
            Click</button>",
        replace: true,        
        link: function(scope, elm, attrs) {             
        }
    }
});

Fiddle

how to create 100% vertical line in css

<!DOCTYPE html>
<html>
<title>Welcome</title>
<style type="text/css">
    .head1 {
        width:300px;
        border-right:1px solid #333;
        float:left;
        height:500px;
    }
   .head2 {
       float:left;
       padding-left:100PX;
       padding-top:10PX;
   }
</style>
<body>
   <h1 class="head1">Ramya</h1>
   <h2 class="head2">Reddy</h2>
</body>
</html>

How to start automatic download of a file in Internet Explorer?

I think this will work for you. But visitors are easy if they got something in seconds without spending more time and hence they will also again visit your site. <a href="file.zip" onclick="if (event.button==0) setTimeout(function(){document.body.innerHTML='thanks!'},500)"> Start automatic download! </a>

How do you check "if not null" with Eloquent?

We can use

Model::whereNotNull('sent_at');

Or

Model::whereRaw('sent_at is not null');

"End of script output before headers" error in Apache

For future reference:

This is typically an error that occurs when you are unable to view or execute the file, the reason for which is generally a permissions error. I would start by following @Renning 's suggestion and running chmod 755 test.cgi (obviously replace test.cgi with the name of your cgi script here).

If that doesn't work there are a couple other things you can try. I once got this error when I created test.cgi as root in another user's home. The fix there was to run chmod user:user test.cgi where user is the name of the user who's home you're in.

The last thing I can think of is making sure that your cgi script is returning the proper headers. In my ruby script I did it by putting puts "Content-type: text/html" before I actually outputted anything to the page.

Happy coding!

Best way to combine two or more byte arrays in C#

Many of the answers seem to me to be ignoring the stated requirements:

  • The result should be a byte array
  • It should be as efficient as possible

These two together rule out a LINQ sequence of bytes - anything with yield is going to make it impossible to get the final size without iterating through the whole sequence.

If those aren't the real requirements of course, LINQ could be a perfectly good solution (or the IList<T> implementation). However, I'll assume that Superdumbell knows what he wants.

(EDIT: I've just had another thought. There's a big semantic difference between making a copy of the arrays and reading them lazily. Consider what happens if you change the data in one of the "source" arrays after calling the Combine (or whatever) method but before using the result - with lazy evaluation, that change will be visible. With an immediate copy, it won't. Different situations will call for different behaviour - just something to be aware of.)

Here are my proposed methods - which are very similar to those contained in some of the other answers, certainly :)

public static byte[] Combine(byte[] first, byte[] second)
{
    byte[] ret = new byte[first.Length + second.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    return ret;
}

public static byte[] Combine(byte[] first, byte[] second, byte[] third)
{
    byte[] ret = new byte[first.Length + second.Length + third.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    Buffer.BlockCopy(third, 0, ret, first.Length + second.Length,
                     third.Length);
    return ret;
}

public static byte[] Combine(params byte[][] arrays)
{
    byte[] ret = new byte[arrays.Sum(x => x.Length)];
    int offset = 0;
    foreach (byte[] data in arrays)
    {
        Buffer.BlockCopy(data, 0, ret, offset, data.Length);
        offset += data.Length;
    }
    return ret;
}

Of course the "params" version requires creating an array of the byte arrays first, which introduces extra inefficiency.

Reverse / invert a dictionary mapping

I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":

class SymDict:
    def __init__(self):
        self.aToB = {}
        self.bToA = {}

    def assocAB(self, a, b):
        # Stores and returns a tuple (a,b) of overwritten bindings
        currB = None
        if a in self.aToB: currB = self.bToA[a]
        currA = None
        if b in self.bToA: currA = self.aToB[b]

        self.aToB[a] = b
        self.bToA[b] = a
        return (currA, currB)

    def lookupA(self, a):
        if a in self.aToB:
            return self.aToB[a]
        return None

    def lookupB(self, b):
        if b in self.bToA:
            return self.bToA[b]
        return None

Deletion and iteration methods are easy enough to implement if they're needed.

This implementation is way more efficient than inverting an entire dictionary (which seems to be the most popular solution on this page). Not to mention, you can add or remove values from your SymDict as much as you want, and your inverse-dictionary will always stay valid -- this isn't true if you simply reverse the entire dictionary once.

How do I get the position selected in a RecyclerView?

Personally, the simplest way that I have found and works great for me is as follows:

Create an interface inside your "RecycleAdapter" Class (Subclass)

public interface ClickCallback {
    void onItemClick(int position);
}

Add a variable of the interface as a parameter in the Constructor.

private String[] items;
private ClickCallback callback;

public RecyclerAdapter(String[] items, ClickCallback clickCallback) {
    this.items = items;
    this.callback = clickCallback;
}

Set a Click listener in the ViewHolder (another subclass) and pass the 'position' to through the interface

    AwesomeViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.onItemClick(getAdapterPosition());
            }
        });
        mTextView = (TextView) itemView.findViewById(R.id.mTextView);
    }

Now, when initializing the recycler adapter in an activity/fragment, just Create a new 'ClickCallback' (interface)

String[] values = {"Hello","World"};
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(values, new RecyclerAdapter.ClickCallback() {
    @Override
    public void onItemClick(int position) {
         // Do anything with the item position
    }
});

That's it for me. :)

Search for a string in all tables, rows and columns of a DB

To "find where the data I get comes from", you can start SQL Profiler, start your report or application, and you will see all the queries issued against your database.

What is the string length of a GUID?

22 bytes, if you do it like this:

System.Guid guid = System.Guid.NewGuid();
byte[] guidbytes = guid.ToByteArray();
string uuid = Convert.ToBase64String(guidbytes).Trim('=');

How to update the value of a key in a dictionary in Python?

Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.

>>> books = {}
>>> books['book'] = 3       
>>> books['book'] -= 1   
>>> books   
{'book': 2}   

In your case:

book_shop[ch1] -= 1

How to run Conda?

Temporary solution:

$anaconda/bin/conda create -n py33 python=3.3 anaconda

How to list files in a directory in a C program?

Here is a complete program how to recursively list folder's contents:

#include <dirent.h> 
#include <stdio.h> 
#include <string.h>

#define NORMAL_COLOR  "\x1B[0m"
#define GREEN  "\x1B[32m"
#define BLUE  "\x1B[34m"



/* let us make a recursive function to print the content of a given folder */

void show_dir_content(char * path)
{
  DIR * d = opendir(path); // open the path
  if(d==NULL) return; // if was not able return
  struct dirent * dir; // for the directory entries
  while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
    {
      if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
        printf("%s%s\n",BLUE, dir->d_name);
      else
      if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
      {
        printf("%s%s\n",GREEN, dir->d_name); // print its name in green
        char d_path[255]; // here I am using sprintf which is safer than strcat
        sprintf(d_path, "%s/%s", path, dir->d_name);
        show_dir_content(d_path); // recall with the new path
      }
    }
    closedir(d); // finally close the directory
}

int main(int argc, char **argv)
{

  printf("%s\n", NORMAL_COLOR);

    show_dir_content(argv[1]);

  printf("%s\n", NORMAL_COLOR);
  return(0);
}

How to make Toolbar transparent?

All you need to is to define theme which hide action bar, define action bar style with transparent background and set this style to the toolbar widget. Please note that toolbar should be drawen as last view (over all view tree)

<style name="Theme.Custom" parent="@android:style/Theme.AppCompat">
    <item name="windowActionBar">false</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="android:windowActionBarOverlay">true</item>
</style>

<style name="CustomActionBar" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:windowActionBarOverlay">true</item>
    <!-- Support library compatibility -->
    <item name="windowActionBarOverlay">true</item>
</style>

Layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Toolbar should be above content-->
    <include layout="@layout/toolbar" />

</RelativeLayout>

Toolbar layout:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:theme="@style/CustomActionBar"/>

Non-static method requires a target

I've found this issue to be prevalent in Entity Framework when we instantiate an Entity manually rather than through DBContext which will resolve all the Navigation Properties. If there are Foreign Key references (Navigation Properties) between tables and you use those references in your lambda (e.g. ProductDetail.Products.ID) then that "Products" context remains null if you manually created the Entity.

Fix height of a table row in HTML Table

my css

TR.gray-t {background:#949494;}
h3{
    padding-top:3px;
    font:bold 12px/2px Arial;
}

my html

<TR class='gray-t'>
<TD colspan='3'><h3>KAJANG</h3>

I decrease the 2nd size in font.

padding-top is used to fix the size in IE7.

Deleting Elements in an Array if Element is a Certain value VBA

I know this is old, but here's the solution I came up with when I didn't like the ones I found.

-Loop through the array (Variant) adding each element and some divider to a string, unless it matches the one you want to remove -Then split the string on the divider

tmpString=""
For Each arrElem in GlobalArray
   If CStr(arrElem) = "removeThis" Then
      GoTo SkipElem
   Else
      tmpString =tmpString & ":-:" & CStr(arrElem)
   End If
SkipElem:
Next
GlobalArray = Split(tmpString, ":-:")

Obviously the use of strings creates some limitations, like needing to be sure of the information already in the array, and as-is this code makes the first array element blank, but it does what I need and with a little more work it could be more versatile.

Extract / Identify Tables from PDF python

You should definitely have a look at this answer of mine:

and also have a look at all the links included therein.

Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.

How to work on UAC when installing XAMPP

Basically there's three things you can do

  1. Ensure that your user account has administrator privilege.
  2. Disable User Account Control (UAC).
  3. Install in C://xampp.

I've just writen an answer to a very similar answer here where I explain how you can disable UAC since Windows 8.

How do I get a decimal value when using the division operator in Python?

Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:

>>> 0.4/100.
0.0040000000000000001

If you actually want a decimal value, do this:

>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")

That will give you an object that properly knows that 4 / 100 in base 10 is "0.04". Floating-point numbers are actually in base 2, i.e. binary, not decimal.

How do I check whether a checkbox is checked in jQuery?

I believe you could do this:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}

How do you clear Apache Maven's cache?

I've had this same problem, and I wrote a one-liner in shell to do it.

rm -rf $(mvn help:evaluate -Dexpression=settings.localRepository\
                       -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN -B \
                       -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn | grep -vF '[INFO]')/*

I did it as a one-liner because I wanted to have a Jenkins-project to simply run this whenever I needed, so I wouldn't have to log on to stuff, etc. If you allow yourself a shell-script for it, you can write it cleaner:

#!/usr/bin/env bash
REPOSITORY=$(mvn help:evaluate \
  -Dexpression=settings.localRepository \
  -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
  -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn \
  --batch-mode \
  | grep -vF '[INFO]')

rm -rf $REPOSITORY/*

Should work, but I have not tested all of that script. (I've tested the first command, but not the whole script.) This approach has the downside of running a large complicated command first. It is idempotent, so you can test it out for yourself. The deletion is its own command afterwards, and this lets you try it all out and check that it does what you think it does, because you shouldn't trust deletion commands without verification. However, it is smart for one good reason: It's portable. It respects your settings.xml file. If you're running this command, and tell maven to use a specific xml file (the -s or --settings argument), this will still work. So you don't have to fiddle with making sure everything is the same everywhere.

It's a bit wieldy, but it's a decent way of doing business, IMO.

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

They can be considered as equivalent. The limits in size are the same:

  • Maximum length of CLOB (in bytes or OCTETS)) 2 147 483 647
  • Maximum length of BLOB (in bytes) 2 147 483 647

There is also the DBCLOBs, for double byte characters.

References:

How to multiply individual elements of a list with a number?

You can use built-in map function:

result = map(lambda x: x * P, S)

or list comprehensions that is a bit more pythonic:

result = [x * P for x in S]

Remove Rows From Data Frame where a Row matches a String

Just use the == with the negation symbol (!). If dtfm is the name of your data.frame:

dtfm[!dtfm$C == "Foo", ]

Or, to move the negation in the comparison:

dtfm[dtfm$C != "Foo", ]

Or, even shorter using subset():

subset(dtfm, C!="Foo")

How to get Text BOLD in Alert or Confirm box?

The alert() dialog is not rendered in HTML, and thus the HTML you have embedded is meaningless.

You'd need to use a custom modal to achieve that.

Changing directory in Google colab (breaking out of the python interpreter)

If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate

.

!ls    # to find the directory you're in ,
%cd ./samplefolder  #if you wanna go into a folder (say samplefolder)

or if you wanna go out of the current folder

%cd ../      

and then navigate to the required folder/file accordingly

How to access custom attributes from event object in React?

I do not know about React, but in the general case you can pass custom attributes like this:

1) define inside an html-tag a new attribute with data- prefix

data-mydatafield = "asdasdasdaad"

2) get from javascript with

e.target.attributes.getNamedItem("data-mydatafield").value 

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

I normally use this statement:

ALTER TABLE `table_name`
  CHANGE COLUMN `col_name` `col_name` VARCHAR(10000);

But, I think SET will work too, never have tried it. :)

How to write an ArrayList of Strings into a text file?

import java.io.FileWriter;
...
FileWriter writer = new FileWriter("output.txt"); 
for(String str: arr) {
  writer.write(str + System.lineSeparator());
}
writer.close();

How to loop through all but the last item of a list?

If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module).

from itertools import tee, izip, chain

def pairwise(seq):
    a,b = tee(seq)
    b.next()
    return izip(a,b)

for current_item, next_item in pairwise(y):
    if compare(current_item, next_item):
        # do what you have to do

If you need to compare the last value to some special value, chain that value to the end

for current, next_item in pairwise(chain(y, [None])):

Delete forked repo from GitHub

Select repo->Settings->(scroll down)Delete repo

Where do I configure log4j in a JUnit test class?

I use system properties in log4j.xml:

...
<param name="File" value="${catalina.home}/logs/root.log"/>
...

and start tests with:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
    <configuration>
        <systemProperties>
            <property>
                <name>catalina.home</name>
                <value>${project.build.directory}</value>
            </property>
        </systemProperties>
    </configuration>
</plugin>

Passing a URL with brackets to curl

Never mind, I found it in the docs:

-g/--globoff
              This  option  switches  off  the "URL globbing parser". When you set this option, you can
              specify URLs that contain the letters {}[] without having them being interpreted by  curl
              itself.  Note  that  these  letters  are not normal legal URL contents but they should be
              encoded according to the URI standard.

How do I query between two dates using MySQL?

Your query should have date as

select * from table between `lowerdate` and `upperdate`

try

SELECT * FROM `objects` 
WHERE  (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')

How to search contents of multiple pdf files?

There is another utility called ripgrep-all, which is based on ripgrep.

It can handle more than just PDF documents, like Office documents and movies, and the author claims it is faster than pdfgrep.

Command syntax for recursively searching the current directory, and the second one limits to PDF files only:

rga 'pattern' .
rga --type pdf 'pattern' .

Send password when using scp to copy files from one server to another

You should use better authentication with open keys. In these case you need no password and no expect.

If you want it with expect, use this script (see answer Automate scp file transfer using a shell script ):

#!/usr/bin/expect -f

# connect via scp
    spawn scp "[email protected]:/home/santhosh/file.dmp" /u01/dumps/file.dmp
#######################
expect {
-re ".*es.*o.*" {
    exp_send "yes\r"
    exp_continue
}
-re ".*sword.*" {
    exp_send "PASSWORD\r"
}
}
interact

Also, you can use pexpect (python module):

def doScp(user,password, host, path, files):
 fNames = ' '.join(files)
 print fNames
 child = pexpect.spawn('scp %s %s@%s:%s' % (fNames, user, host,path))
 print 'scp %s %s@%s:%s' % (fNames, user, host,path)
    i = child.expect(['assword:', r"yes/no"], timeout=30)
    if i == 0:
        child.sendline(password)
    elif i == 1:
        child.sendline("yes")
        child.expect("assword:", timeout=30)
        child.sendline(password)
    data = child.read()
    print data
    child.close()

equivalent of vbCrLf in c#

You are looking for System.Environment.NewLine.

On Windows, this is equivalent to \r\n though it could be different under another .NET implementation, such as Mono on Linux, for example.

Open Source Alternatives to Reflector?

2 options I know of.

  • CCI
  • Mono Cecil

These wont give you C# though.

How do I detect whether a Python variable is a function?

Following previous replies, I came up with this:

from pprint import pprint

def print_callables_of(obj):
    li = []
    for name in dir(obj):
        attr = getattr(obj, name)
        if hasattr(attr, '__call__'):
            li.append(name)
    pprint(li)

How to style a div to be a responsive square?

To achieve what you are looking for you can use the viewport-percentage length vw.

Here is a quick example I made on jsfiddle.

HTML:

<div class="square">
    <h1>This is a Square</h1>
</div>

CSS:

.square {
    background: #000;
    width: 50vw;
    height: 50vw;
}
.square h1 {
    color: #fff;
}

I am sure there are many other ways to do this but this way seemed the best to me.

Parallel.ForEach vs Task.Factory.StartNew

The first is a much better option.

Parallel.ForEach, internally, uses a Partitioner<T> to distribute your collection into work items. It will not do one task per item, but rather batch this to lower the overhead involved.

The second option will schedule a single Task per item in your collection. While the results will be (nearly) the same, this will introduce far more overhead than necessary, especially for large collections, and cause the overall runtimes to be slower.

FYI - The Partitioner used can be controlled by using the appropriate overloads to Parallel.ForEach, if so desired. For details, see Custom Partitioners on MSDN.

The main difference, at runtime, is the second will act asynchronous. This can be duplicated using Parallel.ForEach by doing:

Task.Factory.StartNew( () => Parallel.ForEach<Item>(items, item => DoSomething(item)));

By doing this, you still take advantage of the partitioners, but don't block until the operation is complete.

Does file_get_contents() have a timeout setting?

For me work when i change my php.ini in my host:

; Default timeout for socket based streams (seconds)
default_socket_timeout = 300

c++ boost split string

The problem is somewhere else in your code, because this works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;    
for (size_t i = 0; i < strs.size(); i++)
    cout << strs[i] << endl;

and testing your approach, which uses a vector iterator also works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
    cout << *it << endl;
}

Again, your problem is somewhere else. Maybe what you think is a \t character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.

Output:

* size of the vector: 3
test
test2
test3

java SSL and cert keystore

System.setProperty("javax.net.ssl.trustStore", path_to_your_jks_file);

Run JavaScript code on window close or page refresh?

There is both window.onbeforeunload and window.onunload, which are used differently depending on the browser. You can assign them either by setting the window properties to functions, or using the .addEventListener:

window.onbeforeunload = function(){
   // Do something
}
// OR
window.addEventListener("beforeunload", function(e){
   // Do something
}, false);
   

Usually, onbeforeunload is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunload isn't supported by Opera, as far as I know, but you could always set both.

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

ASP.NET Version:4.0.30319.18408 belongs to .Net4.5 and System.Web.Http Version=4.0.0.0 is compatible for .NET4.0. So the versions that you have are not compatible. You should update you System.Web.Http to version 5.0.0.0, which is compatible with .Net4.5

Row numbers in query result using Microsoft Access

MS-Access doesn't support ROW_NUMBER(). Use TOP 1:

SELECT TOP 1 *
FROM [MyTable]
ORDER BY [MyIdentityCOlumn]

If you need the 15th row - MS-Access has no simple, built-in, way to do this. You can simulate the rownumber by using reverse nested ordering to get this:

SELECT TOP 1 *
FROM (
  SELECT TOP 15 *
  FROM [MyTable]
  ORDER BY [MyIdentityColumn] ) t
ORDER BY [MyIdentityColumn] DESC

fileReader.readAsBinaryString to upload files

(Following is a late but complete answer)

FileReader methods support


FileReader.readAsBinaryString() is deprecated. Don't use it! It's no longer in the W3C File API working draft:

void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);

NB: Note that File is a kind of extended Blob structure.

Mozilla still implements readAsBinaryString() and describes it in MDN FileApi documentation:

void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);

The reason behind readAsBinaryString() deprecation is in my opinion the following: the standard for JavaScript strings are DOMString which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.

We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob and typed arrays (ArrayBuffer and the not-yet-implemented but not necessary StringView) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.

XMLHttpRequest upload support


XMLHttpRequest.send() has the following invocations options:

void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);

XMLHttpRequest.sendAsBinary() has the following invocations options:

void sendAsBinary(   in DOMString body );

sendAsBinary() is NOT a standard and may not be supported in Chrome.

Solutions


So you have several options:

  1. send() the FileReader.result of FileReader.readAsArrayBuffer ( fileObject ). It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.
  2. send() the FileReader.result of FileReader.readAsDataURL( fileObject ). It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.
  3. Being non-standard and sendAsBinary() the FileReader.result of FileReader.readAsBinaryString( fileObject )

MDN states that:

The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.

Can I give the col-md-1.5 in bootstrap?

Create new classes to overwrite the width. See jFiddle for working code.

<div class="row">
  <div class="col-xs-1 col-xs-1-5">
    <div class="box">
      box 1
    </div>
  </div>
  <div class="col-xs-3 col-xs-3-5">
    <div class="box">
      box 2
    </div>
  </div>
  <div class="col-xs-3 col-xs-3-5">
    <div class="box">
      box 3
    </div>
  </div>
  <div class="col-xs-3 col-xs-3-5">
    <div class="box">
      box 4
    </div>
  </div>
</div>

.col-xs-1-5 {
  width: 12.49995%;
}
.col-xs-3-5 {
  width: 29.16655%;
}
.box {
  border: 1px solid #000;
  text-align: center;
}

How to determine the IP address of a Solaris system

The following shell script gives a nice tabular result of interfaces and IP addresses (excluding the loopback interface) It has been tested on a Solaris box

/usr/sbin/ifconfig -a | awk '/flags/ {printf $1" "} /inet/ {print $2}' | grep -v lo

ce0: 10.106.106.108
ce0:1: 10.106.106.23
ce0:2: 10.106.106.96
ce1: 10.106.106.109

Get Element value with minidom with Python

It should just be

name[0].firstChild.nodeValue

Reading the selected value from asp:RadioButtonList using jQuery

According to me it'll be working fine...

Just try with this

   var GetValue=$('#radiobuttonListId').find(":checked").val();

The Radiobuttonlist value to be stored on GetValue(Variable).

What is correct media query for IPad Pro?

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

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

warning: control reaches end of non-void function [-Wreturn-type]

You just need to return from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.

  /* .... */
  if (Date1 == Date2)  
     fprintf (stderr , "Indicating that the first date is equal to second date.\n"); 

  return 0;
}

How to find if a given key exists in a C++ std::map

map <int , char>::iterator itr;
    for(itr = MyMap.begin() ; itr!= MyMap.end() ; itr++)
    {
        if (itr->second == 'c')
        {
            cout<<itr->first<<endl;
        }
    }

HTML Upload MAX_FILE_SIZE does not appear to work

There IS A POINT in introducing MAX_FILE_SIZE client side hidden form field.

php.ini can limit uploaded file size. So, while your script honors the limit imposed by php.ini, different HTML forms can further limit an uploaded file size. So, when uploading video, form may limit* maximum size to 10MB, and while uploading photos, forms may put a limit of just 1mb. And at the same time, the maximum limit can be set in php.ini to suppose 10mb to allow all this.

Although this is not a fool proof way of telling the server what to do, yet it can be helpful.

  • HTML does'nt limit anything. It just forwards the server all form variable including MAX_FILE_SIZE and its value.

Hope it helped someone.

How to debug a referenced dll (having pdb)

I had the *.pdb files in the same folder and used the options from Arindam, but it still didn't work. Turns out I needed to enable Enable native code debugging which can be found under Project properties > Debug.

How to launch Safari and open URL from iOS app

Here's what I did:

  1. I created an IBAction in the header .h files as follows:

    - (IBAction)openDaleDietrichDotCom:(id)sender;
    
  2. I added a UIButton on the Settings page containing the text that I want to link to.

  3. I connected the button to IBAction in File Owner appropriately.

  4. Then implement the following:

Objective-C

- (IBAction)openDaleDietrichDotCom:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.daledietrich.com"]];
}

Swift

(IBAction in viewController, rather than header file)

if let link = URL(string: "https://yoursite.com") {
  UIApplication.shared.open(link)
}

How can I control Chromedriver open window size?

Use Dimension Class for controlling window size.

Dimension d = new Dimension(1200,800);  //(x,y coordinators in pixels) 
driver.manage().window().setSize(d);

Importing a CSV file into a sqlite3 database table using Python

With this you can do joins on CSVs as well:

import sqlite3
import os
import pandas as pd
from typing import List

class CSVDriver:
    def __init__(self, table_dir_path: str):
        self.table_dir_path = table_dir_path  # where tables (ie. csv files) are located
        self._con = None

    @property
    def con(self) -> sqlite3.Connection:
        """Make a singleton connection to an in-memory SQLite database"""
        if not self._con:
            self._con = sqlite3.connect(":memory:")
        return self._con
    
    def _exists(self, table: str) -> bool:
        query = """
        SELECT name
        FROM sqlite_master 
        WHERE type ='table'
        AND name NOT LIKE 'sqlite_%';
        """
        tables = self.con.execute(query).fetchall()
        return table in tables

    def _load_table_to_mem(self, table: str, sep: str = None) -> None:
        """
        Load a CSV into an in-memory SQLite database
        sep is set to None in order to force pandas to auto-detect the delimiter
        """
        if self._exists(table):
            return
        file_name = table + ".csv"
        path = os.path.join(self.table_dir_path, file_name)
        if not os.path.exists(path):
            raise ValueError(f"CSV table {table} does not exist in {self.table_dir_path}")
        df = pd.read_csv(path, sep=sep, engine="python")  # set engine to python to skip pandas' warning
        df.to_sql(table, self.con, if_exists='replace', index=False, chunksize=10000)

    def query(self, query: str) -> List[tuple]:
        """
        Run an SQL query on CSV file(s). 
        Tables are loaded from table_dir_path
        """
        tables = extract_tables(query)
        for table in tables:
            self._load_table_to_mem(table)
        cursor = self.con.cursor()
        cursor.execute(query)
        records = cursor.fetchall()
        return records

extract_tables():

import sqlparse
from sqlparse.sql import IdentifierList, Identifier,  Function
from sqlparse.tokens import Keyword, DML
from collections import namedtuple
import itertools

class Reference(namedtuple('Reference', ['schema', 'name', 'alias', 'is_function'])):
    __slots__ = ()

    def has_alias(self):
        return self.alias is not None

    @property
    def is_query_alias(self):
        return self.name is None and self.alias is not None

    @property
    def is_table_alias(self):
        return self.name is not None and self.alias is not None and not self.is_function

    @property
    def full_name(self):
        if self.schema is None:
            return self.name
        else:
            return self.schema + '.' + self.name

def _is_subselect(parsed):
    if not parsed.is_group:
        return False
    for item in parsed.tokens:
        if item.ttype is DML and item.value.upper() in ('SELECT', 'INSERT',
                                                        'UPDATE', 'CREATE', 'DELETE'):
            return True
    return False


def _identifier_is_function(identifier):
    return any(isinstance(t, Function) for t in identifier.tokens)


def _extract_from_part(parsed):
    tbl_prefix_seen = False
    for item in parsed.tokens:
        if item.is_group:
            for x in _extract_from_part(item):
                yield x
        if tbl_prefix_seen:
            if _is_subselect(item):
                for x in _extract_from_part(item):
                    yield x
            # An incomplete nested select won't be recognized correctly as a
            # sub-select. eg: 'SELECT * FROM (SELECT id FROM user'. This causes
            # the second FROM to trigger this elif condition resulting in a
            # StopIteration. So we need to ignore the keyword if the keyword
            # FROM.
            # Also 'SELECT * FROM abc JOIN def' will trigger this elif
            # condition. So we need to ignore the keyword JOIN and its variants
            # INNER JOIN, FULL OUTER JOIN, etc.
            elif item.ttype is Keyword and (
                    not item.value.upper() == 'FROM') and (
                    not item.value.upper().endswith('JOIN')):
                tbl_prefix_seen = False
            else:
                yield item
        elif item.ttype is Keyword or item.ttype is Keyword.DML:
            item_val = item.value.upper()
            if (item_val in ('COPY', 'FROM', 'INTO', 'UPDATE', 'TABLE') or
                    item_val.endswith('JOIN')):
                tbl_prefix_seen = True
        # 'SELECT a, FROM abc' will detect FROM as part of the column list.
        # So this check here is necessary.
        elif isinstance(item, IdentifierList):
            for identifier in item.get_identifiers():
                if (identifier.ttype is Keyword and
                        identifier.value.upper() == 'FROM'):
                    tbl_prefix_seen = True
                    break


def _extract_table_identifiers(token_stream):
    for item in token_stream:
        if isinstance(item, IdentifierList):
            for ident in item.get_identifiers():
                try:
                    alias = ident.get_alias()
                    schema_name = ident.get_parent_name()
                    real_name = ident.get_real_name()
                except AttributeError:
                    continue
                if real_name:
                    yield Reference(schema_name, real_name,
                                    alias, _identifier_is_function(ident))
        elif isinstance(item, Identifier):
            yield Reference(item.get_parent_name(), item.get_real_name(),
                            item.get_alias(), _identifier_is_function(item))
        elif isinstance(item, Function):
            yield Reference(item.get_parent_name(), item.get_real_name(),
                            item.get_alias(), _identifier_is_function(item))


def extract_tables(sql):
    # let's handle multiple statements in one sql string
    extracted_tables = []
    statements = list(sqlparse.parse(sql))
    for statement in statements:
        stream = _extract_from_part(statement)
        extracted_tables.append([ref.name for ref in _extract_table_identifiers(stream)])
    return list(itertools.chain(*extracted_tables))

Example (assuming account.csv and tojoin.csv exist in /path/to/files):

db_path = r"/path/to/files"
driver = CSVDriver(db_path)
query = """
SELECT tojoin.col_to_join 
FROM account
LEFT JOIN tojoin
ON account.a = tojoin.a
"""
driver.query(query)

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

How to "crop" a rectangular image into a square with CSS?

object-fit: cover will do exactly what you need.

But it might not work on IE/Edge. Follow as shown below to fix it with just CSS to work on all browsers.

The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Once it is in the centre, I give to the image,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

This makes the image get the effect of Object-fit:cover.


Here is a demonstration of the above logic.

https://jsfiddle.net/furqan_694/s3xLe1gp/

This logic works in all browsers.


Original Image
Original Image

Vertically Cropped
Vertically Cropped Image

Horizontally Cropped
Horizontally Cropped Image


How to compare two dates?

Other answers using datetime and comparisons also work for time only, without a date.

For example, to check if right now it is more or less than 8:00 a.m., we can use:

import datetime

eight_am = datetime.time( 8,0,0 ) # Time, without a date

And later compare with:

datetime.datetime.now().time() > eight_am  

which will return True

What is the &#xA; character?

That would be an HTML Encoded Line Feed character (using the hexadecimal value).

The decimal value would be &#10;

How to prevent Right Click option using jquery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script>
 $(document).ready(function(){
  $(document).bind("contextmenu",function(e){
  return false;
  });
});
</script>
</head>
<body>

<p>Right click is disabled on this page.</p>

</body>
</html>

Visual Studio 2015 Update 3 Offline Installer (ISO)

[UPDATE]
As per March 7, 2017, Visual Studio 2017 was released for general availability.

You can refer to Mehdi Dehghani answer for the direct download links or the old-fashioned ways using the website, vibs2006 answer
And you can also combine it with ray pixar answer to make it a complete full standalone offline installer.


Note:
I don't condone any illegal use of the offline installer.
Please stop piracy and follow the EULA.

The community edition is free even for commercial use, under some condition.
You can see the EULA in this link below.
https://www.visualstudio.com/support/legal/mt171547
Thank you.


Instruction for official offline installer:

  1. Open this link

    https://www.visualstudio.com/downloads/

  2. Scroll Down (DO NOT FORGET!)

  3. Click on "Visual Studio 2015" panel heading
  4. Choose the edition that you want

    These menu should be available in that panel:

    • Community 2015
    • Enterprise 2015
    • Professional 2015
    • Enterprise 2015
    • Visual Studio 2015 Update
    • Visual Studio 2015 Language Pack
    • Visual Studio Test Professional 2015 Language Pack
    • Test Professional 2015
    • Express 2015 for Desktop
    • Express 2015 for Windows 10


  1. Choose the language that you want in the drop-down menu (above the Download button)

    The language drop-down menu should be like this:

    • English for English
    • Deutsch for German
    • Español for Spanish
    • Français for French
    • Italiano for Italian
    • ??????? for Russian
    • ??? for Japanese
    • ???? for Chinese (Simplified)
    • ???? for Chinese (Traditional)
    • ??? for Korean


  1. Check on "ISO" in radio-button menu (on the left side of the Download button)

    The radio-button menu should be like this:

    • Web installer
    • ISO
  2. Click the Download button

EditText, clear focus on touch outside

You've probably found the answer to this problem already but I've been looking on how to solve this and still can't really find exactly what I was looking for so I figured I'd post it here.

What I did was the following (this is very generalized, purpose is to give you an idea of how to proceed, copying and pasting all the code will not work O:D ):

First have the EditText and any other views you want in your program wrapped by a single view. In my case I used a LinearLayout to wrap everything.

<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/mainLinearLayout">
 <EditText
  android:id="@+id/editText"/>
 <ImageView
  android:id="@+id/imageView"/>
 <TextView
  android:id="@+id/textView"/>
 </LinearLayout>

Then in your code you have to set a Touch Listener to your main LinearLayout.

final EditText searchEditText = (EditText) findViewById(R.id.editText);
mainLinearLayout.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if(searchEditText.isFocused()){
                if(event.getY() >= 72){
                    //Will only enter this if the EditText already has focus
                    //And if a touch event happens outside of the EditText
                    //Which in my case is at the top of my layout
                    //and 72 pixels long
                    searchEditText.clearFocus();
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
            return false;
        }
    });

I hope this helps some people. Or at least helps them start solving their problem.

Setting Custom ActionBar Title from Fragment

Use the following:

getActivity().setTitle("YOUR_TITLE");

How do I check if a variable exists?

catch is called except in Python. other than that it's fine for such simple cases. There's the AttributeError that can be used to check if an object has an attribute.

What is the best way to modify a list in a 'foreach' loop?

I have written one easy step, but because of this performance will be degraded

Here is my code snippet:-

for (int tempReg = 0; tempReg < reg.Matches(lines).Count; tempReg++)
                            {
                                foreach (Match match in reg.Matches(lines))
                                {
                                    var aStringBuilder = new StringBuilder(lines);
                                    aStringBuilder.Insert(startIndex, match.ToString().Replace(",", " ");
                                    lines[k] = aStringBuilder.ToString();
                                    tempReg = 0;
                                    break;
                                }
                            }

How do I set a fixed background image for a PHP file?

It's not a good coding to put PHP code into CSS

body
{
    background-image:url('bg.png');
}

that's it

Accessing the logged-in user in a template

You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user.

Now, you can access every property of the user. For example, you can access the username like that : app.user.username.

Warning, if the user is not logged, the app.user is null.

If you want to check if the user is logged, you can use the is_granted twig function. For example, if you want to check if the user has ROLE_ADMIN, you just have to do is_granted("ROLE_ADMIN").

So, in every of your pages you can do :

{% if is_granted("ROLE") %}
    Hi {{ app.user.username }}
{% endif %}

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

Angular2, what is the correct way to disable an anchor element?

Specifying pointer-events: none in CSS disables mouse input but doesn't disable keyboard input. For example, the user can still tab to the link and "click" it by pressing the Enter key or (in Windows) the ? Menu key. You could disable specific keystrokes by intercepting the keydown event, but this would likely confuse users relying on assistive technologies.

Probably the best way to disable a link is to remove its href attribute, making it a non-link. You can do this dynamically with a conditional href attribute binding:

<a *ngFor="let link of links"
   [attr.href]="isDisabled(link) ? null : '#'"
   [class.disabled]="isDisabled(link)"
   (click)="!isDisabled(link) && onClick(link)">
   {{ link.name }}
</a>

Or, as in Günter Zöchbauer's answer, you can create two links, one normal and one disabled, and use *ngIf to show one or the other:

<ng-template ngFor #link [ngForOf]="links">
    <a *ngIf="!isDisabled(link)" href="#" (click)="onClick(link)">{{ link.name }}</a>
    <a *ngIf="isDisabled(link)" class="disabled">{{ link.name }}</a>
</ng-template>

Here's some CSS to make the link look disabled:

a.disabled {
    color: gray;
    cursor: not-allowed;
    text-decoration: underline;
}

How can I get Apache gzip compression to work?

First of all go to apache/bin/conf/httpd.conf and make sure that mod_deflate.so is enabled.

Then go to the .htaccess file and add this line:

SetOutputFilter DEFLATE

This should output all the content served as gzipped, i have tried it and it works.

Initialize/reset struct to zero/null

Define a const static instance of the struct with the initial values and then simply assign this value to your variable whenever you want to reset it.

For example:

static const struct x EmptyStruct;

Here I am relying on static initialization to set my initial values, but you could use a struct initializer if you want different initial values.

Then, each time round the loop you can write:

myStructVariable = EmptyStruct;

Real differences between "java -server" and "java -client"?

IIRC, it involves garbage collection strategies. The theory is that a client and server will be different in terms of short-lived objects, which is important for modern GC algorithms.

Here is a link on server mode. Alas, they don't mention client mode.

Here is a very thorough link on GC in general; this is a more basic article. Not sure if either address -server vs -client but this is relevant material.

At No Fluff Just Stuff, both Ken Sipe and Glenn Vandenburg do great talks on this kind of thing.

Hibernate: flush() and commit()

session.flush() is synchronise method means to insert data in to database sequentially.if we use this method data will not store in database but it will store in cache,if any exception will rise in middle we can handle it. But commit() it will store data in database,if we are storing more amount of data then ,there may be chance to get out Of Memory Exception,As like in JDBC program in Save point topic

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

Failed to install *.apk on device 'emulator-5554': EOF

I solved The problem by restart Eclipse then Project -> build all

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

Not in bash (that I know of), but:

cp `ls | grep -v Music` /target_directory

I know this is not exactly what you were looking for, but it will solve your example.

python for increment inner loop

You might just be better of using while loops rather than for loops for this. I translated your code directly from the java code.

str1 = "ababa"
str2 = "aba"
i = 0

while i < len(str1):
  j = 0
  while j < len(str2):
    if not str1[i+j] == str1[j]:
      break
    if j == (len(str2) -1):
      i += len(str2)
    j+=1  
  i+=1

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

I tried below line as per @Andrie answer but didn't work,

op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

so after hunting more, I did work around to get it work successfully.

Here is my code snip.

AFHTTPRequestOperationManager *operation = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    AFJSONResponseSerializer *jsonResponseSerializer = [AFJSONResponseSerializer serializer];

    NSMutableSet *jsonAcceptableContentTypes = [NSMutableSet setWithSet:jsonResponseSerializer.acceptableContentTypes];
    [jsonAcceptableContentTypes addObject:@"text/plain"];
    jsonResponseSerializer.acceptableContentTypes = jsonAcceptableContentTypes;
    operation.responseSerializer = jsonResponseSerializer;

Hope this will help someone out there.

DataTables fixed headers misaligned with columns in wide tables

Trigger DataTable search function after initializing DataTable with a blank string in it. It will automatically adjust misalignment of thead with tbody.

$( document ).ready(function()
{

    $('#monitor_data_voyage').DataTable( {
        scrollY:150,
        bSort:false,
        bPaginate:false,
        sScrollX: "100%",
        scrollX: true,
    } );

    setTimeout( function(){
       $('#monitor_data_voyage').DataTable().search( '' ).draw();
    }, 10 );

});

jquery find closest previous sibling with class

Try

$('li.current_sub').prev('.par_cat').[do stuff];

MAVEN_HOME, MVN_HOME or M2_HOME

$M2_HOMEis used sometimes, for example, to install Takari Extensions for Apache Maven

One way to find $M2_HOME value is to search for mvn:

sudo find / -name "mvn" 2>/dev/null

And, probably it will be: /opt/maven/

A regular expression to exclude a word/string

Here's yet another way (using a negative look-ahead):

^/(?!ignoreme|ignoreme2|ignoremeN)([a-z0-9]+)$ 

Note: There's only one capturing expression: ([a-z0-9]+).

Selenium Webdriver: Entering text into text field

It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:

  1. either check for the valid string-input in the text-box.
  2. or set a loop against that text box to enter the value until you post the form/request.
String barcode="0000000047166";

WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));
strLocator.sendKeys(barcode);

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

You can use like the following

string result = null;
object value = cmd.ExecuteScalar();
 if (value != null)
 {
    result = value.ToString();
 }     
 conn.Close();
return result;

What's a good, free serial port monitor for reverse-engineering?

Portmon from sysinternals (now MSFT) is probably the best monitor.

I haven't found a good free tool that will emulate a port and record/replay comms. The commercial ones were expensive and either so limited or so complex if you want to respond to commands that I ended up using expect and python on a second machine.

Skip first line(field) in loop using CSV file?

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

with open(filename, 'r') as f:
    next(f)
    for line in f:

and:

with open(filename,'r') as f:
    lines = f.readlines()[1:]

How to Get True Size of MySQL Database?

None of the answers include the overhead size and the metadata sizes of tables.

Here is a more accurate estimation of the "disk space" allocated by a database.

SELECT ROUND((SUM(data_length+index_length+data_free) + (COUNT(*) * 300 * 1024))/1048576+150, 2) AS MegaBytes FROM information_schema.TABLES WHERE table_schema = 'DATABASE-NAME'

Django error - matching query does not exist

Maybe you have no Comments record with such primary key, then you should use this code:

try:
    comment = Comment.objects.get(pk=comment_id)
except Comment.DoesNotExist:
    comment = None

How to save an image locally using Python whose URL address I already know?

Something fresh for Python 3 using Requests:

Comments in the code. Ready to use function.


import requests
from os import path

def get_image(image_url):
    """
    Get image based on url.
    :return: Image name if everything OK, False otherwise
    """
    image_name = path.split(image_url)[1]
    try:
        image = requests.get(image_url)
    except OSError:  # Little too wide, but work OK, no additional imports needed. Catch all conection problems
        return False
    if image.status_code == 200:  # we could have retrieved error page
        base_dir = path.join(path.dirname(path.realpath(__file__)), "images") # Use your own path or "" to use current working directory. Folder must exist.
        with open(path.join(base_dir, image_name), "wb") as f:
            f.write(image.content)
        return image_name

get_image("https://apod.nasddfda.gov/apod/image/2003/S106_Mishra_1947.jpg")

How to check type of object in Python?

use isinstance(v, type_name) or type(v) is type_name or type(v) == type_name,

where type_name can be one of the following:

  • None
  • bool
  • int
  • float
  • complex
  • str
  • list
  • tuple
  • set
  • dict

and, of course,

  • custom types (classes)

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

Assume you have the following Home route definition

<Route exact path="/" render={routeProps => (
   <Home routeProps={routeProps}/>
)}/>

{/*optional catch-all router */}
<Route render={routeProps => (
       <div><h4>404 not found</h4></div>
)}/>

At your Home component, you can intercept the request at ComponentWillMount event,

const searchPath = this.props.routeProps.location.search;

if (searchPath){
    this.props.routeProps.history.push("/" + searchPath.replace("?",""));
}
else{
    /*.... originally Home event */
}

Now, instead of calling /joblist at url, you can request /?joblist, and the Component will auto redirect the request to /joblist (take note the extra question mark in the path)

In Javascript, how to conditionally add a member to an object?

Using lodash library, you can use _.omitBy

var a = _.omitBy({
    b: conditionB ? 4 : undefined,
    c: conditionC ? 5 : undefined,
}, _.IsUndefined)

This results handy when you have requests that are optional

var a = _.omitBy({
    b: req.body.optionalA,  //if undefined, will be removed
    c: req.body.optionalB,
}, _.IsUndefined)

How can I color Python logging output?

This is another Python3 variant of airmind's example. I wanted some specific features I didn't see in the other examples

  • use colors for the terminal but do not write non-printable characters in the file handlers (I defined 2 formatters for this)
  • ability to override the color for a specific log message
  • configure the logger from a file (yaml in this case)

Notes: I used colorama but you could modify this so it is not required. Also for my testing I was just running python file so my class is in module __main__ You would have to change (): __main__.ColoredFormatter to whatever your module is.

pip install colorama pyyaml

logging.yaml

---
version: 1
disable_existing_loggers: False
formatters:
  simple:
    format: "%(threadName)s - %(name)s - %(levelname)s - %(message)s"
  color:
    format: "%(threadName)s - %(name)s - %(levelname)s - %(message)s"
    (): __main__.ColoredFormatter
    use_color: true

handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: color
    stream: ext://sys.stdout

  info_file_handler:
    class: logging.handlers.RotatingFileHandler
    level: INFO
    formatter: simple
    filename: app.log
    maxBytes: 20971520 
    backupCount: 20
    encoding: utf8

  error_file_handler:
    class: logging.handlers.RotatingFileHandler
    level: ERROR
    formatter: simple
    filename: errors.log
    maxBytes: 10485760 
    backupCount: 20
    encoding: utf8

root:
  level: DEBUG
  handlers: [console, info_file_handler, error_file_handler]

main.py

import logging
import logging.config
import os
from logging import Logger

import colorama
import yaml
from colorama import Back, Fore, Style

COLORS = {
    "WARNING": Fore.YELLOW,
    "INFO": Fore.CYAN,
    "DEBUG": Fore.BLUE,
    "CRITICAL": Fore.YELLOW,
    "ERROR": Fore.RED,
}


class ColoredFormatter(logging.Formatter):
    def __init__(self, *, format, use_color):
        logging.Formatter.__init__(self, fmt=format)
        self.use_color = use_color

    def format(self, record):
        msg = super().format(record)
        if self.use_color:
            levelname = record.levelname
            if hasattr(record, "color"):
                return f"{record.color}{msg}{Style.RESET_ALL}"
            if levelname in COLORS:
                return f"{COLORS[levelname]}{msg}{Style.RESET_ALL}"
        return msg


with open("logging.yaml", "rt") as f:
    config = yaml.safe_load(f.read())
    logging.config.dictConfig(config)

logger: Logger = logging.getLogger(__name__)
logger.info("Test INFO", extra={"color": Back.RED})
logger.info("Test INFO", extra={"color": f"{Style.BRIGHT}{Back.RED}"})
logger.info("Test INFO")
logger.debug("Test DEBUG")
logger.warning("Test WARN")

output:

output

Removing object properties with Lodash

To select (or remove) object properties that satisfy a given condition deeply, you can use something like this:

function pickByDeep(object, condition, arraysToo=false) {
  return _.transform(object, (acc, val, key) => {
    if (_.isPlainObject(val) || arraysToo && _.isArray(val)) {
      acc[key] = pickByDeep(val, condition, arraysToo);
    } else if (condition(val, key, object)) {
      acc[key] = val;
    }
  });
}

https://codepen.io/aercolino/pen/MWgjyjm

Print PDF directly from JavaScript

Here is a function to print a PDF from an iframe.

You just need to pass the URL of the PDF to the function. It will create an iframe and trigger print once the PDF is load.

Note that the function doesn't destroy the iframe. Instead, it reuses it each time the function is call. It's hard to destroy the iframe because it is needed until the printing is done, and the print method doesn't has callback support (as far as I know).

printPdf = function (url) {
  var iframe = this._printIframe;
  if (!this._printIframe) {
    iframe = this._printIframe = document.createElement('iframe');
    document.body.appendChild(iframe);

    iframe.style.display = 'none';
    iframe.onload = function() {
      setTimeout(function() {
        iframe.focus();
        iframe.contentWindow.print();
      }, 1);
    };
  }

  iframe.src = url;
}

C++ Convert string (or char*) to wstring (or wchar_t*)

using Boost.Locale:

ws = boost::locale::conv::utf_to_utf<wchar_t>(s);

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

function:

function print_call_stack(err) {
    var stack = err.stack;
    console.error(stack);
}

use case:

     try{
         aaa.bbb;//error throw here
     }
     catch (err){
         print_call_stack(err); 
     }

jQuery: go to URL with target="_blank"

The .ready function is used to insert the attribute once the page has finished loading.

$(document).ready(function() {
     $("class name or id a.your class name").attr({"target" : "_blank"})
})

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

Compile error: package javax.servlet does not exist

In a linux environment the soft link apparently does not work. you must use the physical path. for instance on my machine I have a softlink at /usr/share/tomacat7/lib/servlet-api.jar and using this as my classpath argument led to a failed compile with the same error. instead I had to use /usr/share/java/tomcat-servlet-api-3.0.jar which is the file that the soft link pointed to.

Writing unit tests in Python: How do I start?

If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test rather than the default unittest module.

Consider these two examples, which do the same thing:

Example 1 (unittest):

import unittest

class LearningCase(unittest.TestCase):
    def test_starting_out(self):
        self.assertEqual(1, 1)

def main():
    unittest.main()

if __name__ == "__main__":
    main()

Example 2 (pytest):

def test_starting_out():
    assert 1 == 1

Assuming that both files are named test_unittesting.py, how do we run the tests?

Example 1 (unittest):

cd /path/to/dir/
python test_unittesting.py

Example 2 (pytest):

cd /path/to/dir/
py.test

The SQL OVER() clause - when and why is it useful?

The OVER clause is powerful in that you can have aggregates over different ranges ("windowing"), whether you use a GROUP BY or not

Example: get count per SalesOrderID and count of all

SELECT
    SalesOrderID, ProductID, OrderQty
    ,COUNT(OrderQty) AS 'Count'
    ,COUNT(*) OVER () AS 'CountAll'
FROM Sales.SalesOrderDetail 
WHERE
     SalesOrderID IN(43659,43664)
GROUP BY
     SalesOrderID, ProductID, OrderQty

Get different COUNTs, no GROUP BY

SELECT
    SalesOrderID, ProductID, OrderQty
    ,COUNT(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'CountQtyPerOrder'
    ,COUNT(OrderQty) OVER(PARTITION BY ProductID) AS 'CountQtyPerProduct',
    ,COUNT(*) OVER () AS 'CountAllAgain'
FROM Sales.SalesOrderDetail 
WHERE
     SalesOrderID IN(43659,43664)

Postgres: How to do Composite keys?

Your compound PRIMARY KEY specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT (already implied), too:

 CREATE TABLE tags
      (
               question_id INTEGER NOT NULL,
               tag_id SERIAL NOT NULL,
               tag1 VARCHAR(20),
               tag2 VARCHAR(20),
               tag3 VARCHAR(20),
               PRIMARY KEY(question_id, tag_id)
      );

NOTICE:  CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
    NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
    CREATE TABLE
    pg=> \d tags
                                         Table "public.tags"
       Column    |         Type          |                       Modifiers       
    -------------+-----------------------+-------------------------------------------------------
     question_id | integer               | not null
     tag_id      | integer               | not null default nextval('tags_tag_id_seq'::regclass)
     tag1        | character varying(20) |
     tag2        | character varying(20) |
     tag3        | character varying(20) |
    Indexes:
        "tags_pkey" PRIMARY KEY, btree (question_id, tag_id)

Adding new line of data to TextBox

C# - serialData is ReceivedEventHandler in TextBox.

SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();

serialData.Invoke(new Action(() => serialData.Text = String.Concat(recvData)));

Now Visual Studio drops my lines. TextBox, of course, had all the correct options on.

Serial:

Serial.print(rnd);
Serial.( '\n' );  //carriage return

close vs shutdown socket?

This is explained in Beej's networking guide. shutdown is a flexible way to block communication in one or both directions. When the second parameter is SHUT_RDWR, it will block both sending and receiving (like close). However, close is the way to actually destroy a socket.

With shutdown, you will still be able to receive pending data the peer already sent (thanks to Joey Adams for noting this).

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

Keep only date part when using pandas.to_datetime

While I upvoted EdChum's answer, which is the most direct answer to the question the OP posed, it does not really solve the performance problem (it still relies on python datetime objects, and hence any operation on them will be not vectorized - that is, it will be slow).

A better performing alternative is to use df['dates'].dt.floor('d'). Strictly speaking, it does not "keep only date part", since it just sets the time to 00:00:00. But it does work as desired by the OP when, for instance:

  • printing to screen
  • saving to csv
  • using the column to groupby

... and it is much more efficient, since the operation is vectorized.

EDIT: in fact, the answer the OP's would have preferred is probably "recent versions of pandas do not write the time to csv if it is 00:00:00 for all observations".

How to get all values from python enum class?

You can use IntEnum:

from enum import IntEnum

class Color(IntEnum):
   RED = 1
   BLUE = 2


print(int(Color.RED))   # prints 1

To get list of the ints:

enum_list = list(map(int, Color))
print(enum_list) # prints [1, 2]

Rails: Default sort order for a rails model?

A quick update to Michael's excellent answer above.

For Rails 4.0+ you need to put your sort in a block like this:

class Book < ActiveRecord::Base
  default_scope { order('created_at DESC') }
end

Notice that the order statement is placed in a block denoted by the curly braces.

They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:

Support for calling #default_scope without a block is removed. For example instead of default_scope where(color: 'red'), please use default_scope { where(color: 'red') }. (Alternatively you can just redefine self.default_scope.)

As @Dan mentions in his comment below, you can do a more rubyish syntax like this:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

or with multiple columns:

class Book < ActiveRecord::Base
  default_scope { order({begin_date: :desc}, :name) }
end

Thanks @Dan!

How to fix "Attempted relative import in non-package" even with __init__.py

As Paolo said, we have 2 invocation methods:

1) python -m tests.core_test
2) python tests/core_test.py

One difference between them is sys.path[0] string. Since the interpret will search sys.path when doing import, we can do with tests/core_test.py:

if __name__ == '__main__':
    import sys
    from pathlib import Path
    sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
    from components import core
    <other stuff>

And more after this, we can run core_test.py with other methods:

cd tests
python core_test.py
python -m core_test
...

Note, py36 tested only.

Detecting Enter keypress on VB.NET

Make sure the form KeyPreview property is set to true.

Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
    If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
        SendKeys.Send("{TAB}")
        e.Handled = True
    End If

End Sub

Play a Sound with Python

wxPython has support for playing wav files on Windows and Unix - I am not sure if this includes Macs. However it only support wav files as far as I can tell - it does not support other common formats such as mp3 or ogg.

CSS Disabled scrolling

Try using the following code snippet. This should solve your issue.

body, html { 
    overflow-x: hidden; 
    overflow-y: auto;
}

How to print the value of a Tensor object in TensorFlow?

No, you can not see the content of the tensor without running the graph (doing session.run()). The only things you can see are:

  • the dimensionality of the tensor (but I assume it is not hard to calculate it for the list of the operations that TF has)
  • type of the operation that will be used to generate the tensor (transpose_1:0, random_uniform:0)
  • type of elements in the tensor (float32)

I have not found this in documentation, but I believe that the values of the variables (and some of the constants are not calculated at the time of assignment).


Take a look at this example:

import tensorflow as tf
from datetime import datetime
dim = 7000

The first example where I just initiate a constant Tensor of random numbers run approximately the same time irrespectibly of dim (0:00:00.003261)

startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
print datetime.now() - startTime

In the second case, where the constant is actually gets evaluated and the values are assigned, the time clearly depends on dim (0:00:01.244642)

startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
sess = tf.Session()
sess.run(m1)
print datetime.now() - startTime

And you can make it more clear by calculating something (d = tf.matrix_determinant(m1), keeping in mind that the time will run in O(dim^2.8))

P.S. I found were it is explained in documentation:

A Tensor object is a symbolic handle to the result of an operation, but does not actually hold the values of the operation's output.

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

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

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

Stretch child div height to fill parent that has dynamic height

Use display: flex to stretch your divs:

div#container {
    padding:20px;
    background:#F1F1F1;
    display: flex;
}

.content {
    width:150px;
    background:#ddd;
    padding:10px;
    margin-left: 10px;
}

JSFIDDLE

DataGridView checkbox column - value and functionality

If you have a gridview containing more than one checkbox .... you should try this ....

Object[] o=new Object[6];

for (int i = 0; i < dgverlist.RowCount; i++)
{
    for (int j = 2; j < dgverlist.ColumnCount; j++)
    {
        DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
        ch1 = (DataGridViewCheckBoxCell)dgverlist.Rows[i].Cells[j];

        if (ch1.Value != null)
        {
           o[i] = ch1.OwningColumn.HeaderText.ToString();

            MessageBox.Show(o[i].ToString());
        }
    }
}

Overriding a JavaScript function while referencing the original

I had some code written by someone else and wanted to add a line to a function which i could not find in the code. So as a workaround I wanted to override it.

None of the solutions worked for me though.

Here is what worked in my case:

if (typeof originalFunction === "undefined") {
    originalFunction = targetFunction;
    targetFunction = function(x, y) {
        //Your code
        originalFunction(a, b);
        //Your Code
    };  
}

Grep for beginning and end of line?

are you parsing output of ls -l?

If you are, and you just want to get the file name

find . -iname "*[0-9]" 

If you have no choice because usrLog.txt is created by something/someone else and you absolutely must use this file, other options include

awk '/^[-d].*[0-9]$/' file

Ruby(1.9+)

ruby -ne 'print if /^[-d].*[0-9]$/' file

Bash

while read -r line ; do  case $line in [-d]*[0-9] ) echo $line;  esac; done < file

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

This answer assumes you understand implementing the perfect algorithm for P1 and discusses how to achieve a win in conditions against ordinary human players, who will make some mistakes more commonly than others.

The game of course should end in a draw if both players play optimally. At a human level, P1 playing in a corner produces wins far more often. For whatever psychological reason, P2 is baited into thinking that playing in the center is not that important, which is unfortunate for them, since it's the only response that does not create a winning game for P1.

If P2 does correctly block in the center, P1 should play the opposite corner, because again, for whatever psychological reason, P2 will prefer the symmetry of playing a corner, which again produces a losing board for them.

For any move P1 may make for the starting move, there is a move P2 may make that will create a win for P1 if both players play optimally thereafter. In that sense P1 may play wherever. The edge moves are weakest in the sense that the largest fraction of possible responses to this move produce a draw, but there are still responses that will create a win for P1.

Empirically (more precisely, anecdotally) the best P1 starting moves seem to be first corner, second center, and last edge.

The next challenge you can add, in person or via a GUI, is not to display the board. A human can definitely remember all the state but the added challenge leads to a preference for symmetric boards, which take less effort to remember, leading to the mistake I outlined in the first branch.

I'm a lot of fun at parties, I know.

How to get the current location latitude and longitude in android

**The activity should implements LocationListener

In onCreate(), write the following code **

  Boolean network = haveNetworkConnection();
    Log.e("network", "---------->" + network);
    if (!network) {
        Toast.makeText(getApplicationContext(), "Network is not available",
                3000).show();

    }

    SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.googleMap);
    googleMap = supportMapFragment.getMap();
    googleMap.setMyLocationEnabled(true);


    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);




        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            && !locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {



         TextView title = new TextView(context);
         title.setText("Location Services Not Active");
            title.setBackgroundColor(Color.BLACK);
            title.setPadding(10, 15, 15, 10);
            title.setGravity(Gravity.CENTER);
            title.setTextColor(Color.WHITE);
            title.setTextSize(22);


            AlertDialog.Builder builder = new AlertDialog.Builder(this);




        builder.setCustomTitle(title);


        // builder.setTitle("Location Services Not Active");
        builder.setMessage("Please enable Location Services and GPS");

        builder.setPositiveButton("Turn on",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface,
                            int i) {
                        // Show location settings when the user acknowledges
                        // the alert dialog
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);

                        startActivity(intent);
                        finish();
                    }
                });

        builder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel();
                    }
                });

        builder.show();

    }

    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(bestProvider);

    if (location == null) {
        Toast.makeText(getApplicationContext(), "GPS signal not found",
                3000).show();
    }
    if (location != null) {
        Log.e("locatin", "location--" + location);

        Log.e("latitude at beginning",
                "@@@@@@@@@@@@@@@" + location.getLatitude());
        onLocationChanged(location);
    }

Write a method haveNetworkConnection

private boolean haveNetworkConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}



@Override
public void onLocationChanged(Location location) {


    LatLng latLng = new LatLng(latitude, longitude);
    googleMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title("Current LOC")
            .icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_RED)));

    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));


}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}

YouTube API to fetch all videos on a channel

Sample solution in Python. Help taken from this video: video Like many other answers, upload id is to be retrieved from the channel id first.

import urllib.request
import json

key = "YOUR_YOUTUBE_API_v3_BROWSER_KEY"

#List of channels : mention if you are pasting channel id or username - "id" or "forUsername"
ytids = [["bbcnews","forUsername"],["UCjq4pjKj9X4W9i7UnYShpVg","id"]]

newstitles = []
for ytid,ytparam in ytids:
    urld = "https://www.googleapis.com/youtube/v3/channels?part=contentDetails&"+ytparam+"="+ytid+"&key="+key
    with urllib.request.urlopen(urld) as url:
        datad = json.loads(url.read())
    uploadsdet = datad['items']
    #get upload id from channel id
    uploadid = uploadsdet[0]['contentDetails']['relatedPlaylists']['uploads']

    #retrieve list
    urld = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId="+uploadid+"&key="+key
    with urllib.request.urlopen(urld) as url:
        datad = json.loads(url.read())

    for data in datad['items']:
        ntitle =  data['snippet']['title']
        nlink = data['contentDetails']['videoId']
        newstitles.append([nlink,ntitle])

for link,title in newstitles:
    print(link, title)

input type=file show only button

Hide the input-file element and create a visible button that will trigger the click event of that input-file.

Try this:

CSS

#file { width:0; height:0; } 

HTML:

<input type='file' id='file' name='file' />
<button id='btn-upload'>Upload</button>

JAVASCRIPT(jQuery):

$(function(){
    $('#btn-upload').click(function(e){
        e.preventDefault();
        $('#file').click();}
    );
});

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

Change the color of a bullet in a html list?

<ul style="color: red;">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
  • One
  • Two
  • Three
  • Difference between "char" and "String" in Java

    In string we can store multiple char. e.g. char ch='a';

    String s="a";
    

    String s1="aaaa";

    Is ASCII code 7-bit or 8-bit?

    The original ASCII table is encoded on 7 bits therefore it has 128 characters.

    Nowadays most readers/editors use an "extended" ASCII table (from ISO 8859-1), which is encoded on 8 bits and enjoys 256 characters (including Á, Ä, Œ, é, è and other characters useful for european languages as well as mathematical glyphs and other symbols).

    While UTF-8 uses the same encoding as the basic ASCII table (meaning 0x41 is A in both codes), it does not share the same encoding for the "Latin Extended-A" block. Which sometimes causes weird characters to appear in words like à la carte or piñata.

    displayname attribute vs display attribute

    I think the current answers are neglecting to highlight the actual important and significant differences and what that means for the intended usage. While they might both work in certain situations because the implementer built in support for both, they have different usage scenarios. Both can annotate properties and methods but here are some important differences:

    DisplayAttribute

    • defined in the System.ComponentModel.DataAnnotations namespace in the System.ComponentModel.DataAnnotations.dll assembly
    • can be used on parameters and fields
    • lets you set additional properties like Description or ShortName
    • can be localized with resources

    DisplayNameAttribute

    • DisplayName is in the System.ComponentModel namespace in System.dll
    • can be used on classes and events
    • cannot be localized with resources

    The assembly and namespace speaks to the intended usage and localization support is the big kicker. DisplayNameAttribute has been around since .NET 2 and seems to have been intended more for naming of developer components and properties in the legacy property grid, not so much for things visible to end users that may need localization and such.

    DisplayAttribute was introduced later in .NET 4 and seems to be designed specifically for labeling members of data classes that will be end-user visible, so it is more suitable for DTOs, entities, and other things of that sort. I find it rather unfortunate that they limited it so it can't be used on classes though.

    EDIT: Looks like latest .NET Core source allows DisplayAttribute to be used on classes now as well.

    I'm getting Key error in python

    I fully agree with the Key error comments. You could also use the dictionary's get() method as well to avoid the exceptions. This could also be used to give a default path rather than None as shown below.

    >>> d = {"a":1, "b":2}
    >>> x = d.get("A",None)
    >>> print x
    None
    

    Extract elements of list at odd positions

    list_ = list(range(9)) print(list_[1::2])

    Compiling and Running Java Code in Sublime Text 2

    Refer the solution at: http://www.compilr.org/compile-and-run-java-programs/

    Hope that solves, for both compiling and running the classes within sublime..... You can see my script in the comments section to try it out in case of mac...

    EDIT: Unfortunately, the above link is broken now. It detailed all the steps required for comiling and running java within sublime text. Anyways, for mac or linux systems, the below should work:

    modify javac.sublime-build file to:


    #!/bin/sh
    
    classesDir="/Users/$USER/Desktop/java/classes/"
    codeDir="/Users/$USER/Desktop/java/code/"
    [ -f "$classesDir/$1.class" ] && rm $classesDir/$1.class
    for file in $1.java
    do
    echo "Compiling $file........"
    javac -d $classesDir $codeDir/$file
    done
    if [ -f "$classesDir/$1.class" ]
    then
    echo "-----------OUTPUT-----------"
    java -cp $classesDir $1
    else
    echo " "
    fi
    

    Here, I have made a folder named "java" on the Desktop and subfolders "classes" and "code" for maintaining the .class and .java files respectively, you can modify in your own way.

    Get viewport/window height in ReactJS

    I found a simple combo of QoP and speckledcarp's answer using React Hooks and resizing features, with slightly less lines of code:

    const [width, setWidth]   = useState(window.innerWidth);
    const [height, setHeight] = useState(window.innerHeight);
    const updateDimensions = () => {
        setWidth(window.innerWidth);
        setHeight(window.innerHeight);
    }
    useEffect(() => {
        window.addEventListener("resize", updateDimensions);
        return () => window.removeEventListener("resize", updateDimensions);
    }, []);
    

    Oh yeah make sure that the resize event is in double quotes, not single. That one got me for a bit ;)

    Calling an API from SQL Server stored procedure

    I worked so much, I hope my effort might help you out.

    Just paste this into your SSMS and press F5:

    Declare @Object as Int;
    DECLARE @hr  int
    Declare @json as table(Json_Table nvarchar(max))
    
    Exec @hr=sp_OACreate 'MSXML2.ServerXMLHTTP.6.0', @Object OUT;
    IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
    Exec @hr=sp_OAMethod @Object, 'open', NULL, 'get',
                     'http://overpass-api.de/api/interpreter?data=[out:json];area[name=%22Auckland%22]-%3E.a;(node(area.a)[amenity=cinema];way(area.a)[amenity=cinema];rel(area.a)[amenity=cinema];);out;', --Your Web Service Url (invoked)
                     'false'
    IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
    Exec @hr=sp_OAMethod @Object, 'send'
    IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
    Exec @hr=sp_OAMethod @Object, 'responseText', @json OUTPUT
    IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
    
    INSERT into @json (Json_Table) exec sp_OAGetProperty @Object, 'responseText'
    -- select the JSON string
    select * from @json
    -- Parse the JSON string
    SELECT * FROM OPENJSON((select * from @json), N'$.elements')
    WITH (   
          [type] nvarchar(max) N'$.type'   ,
          [id]   nvarchar(max) N'$.id',
          [lat]   nvarchar(max) N'$.lat',
          [lon]   nvarchar(max) N'$.lon',
          [amenity]   nvarchar(max) N'$.tags.amenity',
          [name]   nvarchar(max) N'$.tags.name'     
    )
    EXEC sp_OADestroy @Object
    

    This query will give you 3 results:

    1. Catch the error in case something goes wrong (don't panic, it will always show you an error above 4000 characters because NVARCHAR(MAX) can only store till 4000 characters)

    2. Put the JSON into a string (which is what we want)

    3. BONUS: parse the JSON and nicely store the data into a table (how cool is that?)

    enter image description here

    Automatically creating directories with file output

    The os.makedirs function does this. Try the following:

    import os
    import errno
    
    filename = "/foo/bar/baz.txt"
    if not os.path.exists(os.path.dirname(filename)):
        try:
            os.makedirs(os.path.dirname(filename))
        except OSError as exc: # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise
    
    with open(filename, "w") as f:
        f.write("FOOBAR")
    
    

    The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


    In Python 3.2+, there is a more elegant way that avoids the race condition above:

    import os
    
    filename = "/foo/bar/baz.txt"
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    with open(filename, "w") as f:
        f.write("FOOBAR")
    
    

    String delimiter in string.split method

    Double quotes are interpreted as literals in regex; they are not special characters. You are trying to match a literal "||".

    Just use Pattern.quote(delimiter):

    As requested, here's a line of code (same as Sanjay's)

    final String[] tokens = line.split(Pattern.quote(delimiter));
    

    If that doesn't work, you're not passing in the correct delimiter.

    How to use regex with find command?

    The -regex find expression matches the whole name, including the relative path from the current directory. For find . this always starts with ./, then any directories.

    Also, these are emacs regular expressions, which have other escaping rules than the usual egrep regular expressions.

    If these are all directly in the current directory, then

    find . -regex '\./[a-f0-9\-]\{36\}\.jpg'
    

    should work. (I'm not really sure - I can't get the counted repetition to work here.) You can switch to egrep expressions by -regextype posix-egrep:

    find . -regextype posix-egrep -regex '\./[a-f0-9\-]{36}\.jpg'
    

    (Note that everything said here is for GNU find, I don't know anything about the BSD one which is also the default on Mac.)

    Android: Vertical alignment for multi line EditText (Text area)

    I think you can use layout:weight = 5 instead android:lines = 5 because when you port your app to smaller device - it does it nicely.. well, both attributes will accomplish your job..

    How to call JavaScript function instead of href in HTML

    Your should also separate the javascript from the HTML.
    HTML:

    <a href="#" id="function-click"><img title="next page" alt="next page" src="/themes/me/img/arrn.png"></a>
    

    javascript:

    myLink = document.getElementById('function-click');
    myLink.onclick = ShowOld(2367,146986,2);
    

    Just make sure the last line in the ShowOld function is:

    return false;
    

    as this will stop the link from opening in the browser.

    AngularJS : Custom filters and ng-repeat

    You can call more of 1 function filters in the same ng-repeat filter

    <article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">
    

    Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

    Following is the solution which worked for me. The files which I updated are as follows:

    1. config.xml (Full Path: /config.xml)
    2. network_security_config.xml (Full Path: /resources/android/xml/network_security_config.xml)

    Changes in the corresponding files are as follows:

    1. config.xml

    I have added <application android:usesCleartextTraffic="true" /> tag within <edit-config> tag in the config.xml file

    <platform name="android">
        <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
            <application android:usesCleartextTraffic="true" />
            <application android:networkSecurityConfig="@xml/network_security_config" />
        </edit-config>
        ...
    <platform name="android">
    

    2. network_security_config.xml

    In this file I have added 2 <domain> tag within <domain-config> tag, the main domain and a sub domain as per my project requirement

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">mywebsite.in</domain>
            <domain includeSubdomains="true">api.mywebsite.in</domain>
        </domain-config>
    </network-security-config>
    

    Thanks @Ashutosh for the providing the help.

    Hope it helps.

    How to store Configuration file and read it using React

    If you used Create React App, you can set an environment variable using a .env file. The documentation is here:

    https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

    Basically do something like this in the .env file at the project root.

    REACT_APP_NOT_SECRET_CODE=abcdef
    

    Note that the variable name must start with REACT_APP_

    You can access it from your component with

    process.env.REACT_APP_NOT_SECRET_CODE
    

    How to delete/truncate tables from Hadoop-Hive?

    You can use drop command to delete meta data and actual data from HDFS.

    And just to delete data and keep the table structure, use truncate command.

    For further help regarding hive ql, check language manual of hive.

    How do I measure request and response times at once using cURL?

    Another option that is perhaps the simplest one in terms of the command line is adding the built-in --trace-time option:

    curl -X POST -d @file server:port --trace-time
    

    Even though it technically does not output the timings of the various steps as requested by the OP, it does display the timestamps for all steps of the request as shown below. Using this, you can (fairly easily) calculate how long each step has taken.

    $ curl https://www.google.com --trace-time -v -o /dev/null
    13:29:11.148734 * Rebuilt URL to: https://www.google.com/
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
      0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     013:29:11.149958 *   Trying 172.217.20.36...
    13:29:11.149993 * TCP_NODELAY set
    13:29:11.163177 * Connected to www.google.com (172.217.20.36) port 443 (#0)
    13:29:11.164768 * ALPN, offering h2
    13:29:11.164804 * ALPN, offering http/1.1
    13:29:11.164833 * successfully set certificate verify locations:
    13:29:11.164863 *   CAfile: none
      CApath: /etc/ssl/certs
    13:29:11.165046 } [5 bytes data]
    13:29:11.165099 * (304) (OUT), TLS handshake, Client hello (1):
    13:29:11.165128 } [512 bytes data]
    13:29:11.189518 * (304) (IN), TLS handshake, Server hello (2):
    13:29:11.189537 { [100 bytes data]
    13:29:11.189628 * TLSv1.2 (IN), TLS handshake, Certificate (11):
    13:29:11.189658 { [2104 bytes data]
    13:29:11.190243 * TLSv1.2 (IN), TLS handshake, Server key exchange (12):
    13:29:11.190277 { [115 bytes data]
    13:29:11.190507 * TLSv1.2 (IN), TLS handshake, Server finished (14):
    13:29:11.190539 { [4 bytes data]
    13:29:11.190770 * TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
    13:29:11.190797 } [37 bytes data]
    13:29:11.190890 * TLSv1.2 (OUT), TLS change cipher, Client hello (1):
    13:29:11.190915 } [1 bytes data]
    13:29:11.191023 * TLSv1.2 (OUT), TLS handshake, Finished (20):
    13:29:11.191053 } [16 bytes data]
    13:29:11.204324 * TLSv1.2 (IN), TLS handshake, Finished (20):
    13:29:11.204358 { [16 bytes data]
    13:29:11.204417 * SSL connection using TLSv1.2 / ECDHE-ECDSA-CHACHA20-POLY1305
    13:29:11.204451 * ALPN, server accepted to use h2
    13:29:11.204483 * Server certificate:
    13:29:11.204520 *  subject: C=US; ST=California; L=Mountain View; O=Google LLC; CN=www.google.com
    13:29:11.204555 *  start date: Oct  2 07:29:00 2018 GMT
    13:29:11.204585 *  expire date: Dec 25 07:29:00 2018 GMT
    13:29:11.204623 *  subjectAltName: host "www.google.com" matched cert's "www.google.com"
    13:29:11.204663 *  issuer: C=US; O=Google Trust Services; CN=Google Internet Authority G3
    13:29:11.204701 *  SSL certificate verify ok.
    13:29:11.204754 * Using HTTP2, server supports multi-use
    13:29:11.204795 * Connection state changed (HTTP/2 confirmed)
    13:29:11.204840 * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
    13:29:11.204881 } [5 bytes data]
    13:29:11.204983 * Using Stream ID: 1 (easy handle 0x55846ef24520)
    13:29:11.205034 } [5 bytes data]
    13:29:11.205104 > GET / HTTP/2
    13:29:11.205104 > Host: www.google.com
    13:29:11.205104 > User-Agent: curl/7.61.0
    13:29:11.205104 > Accept: */*
    13:29:11.205104 > 
    13:29:11.218116 { [5 bytes data]
    13:29:11.218173 * Connection state changed (MAX_CONCURRENT_STREAMS == 100)!
    13:29:11.218211 } [5 bytes data]
    13:29:11.251936 < HTTP/2 200 
    13:29:11.251962 < date: Fri, 19 Oct 2018 10:29:11 GMT
    13:29:11.251998 < expires: -1
    13:29:11.252046 < cache-control: private, max-age=0
    13:29:11.252085 < content-type: text/html; charset=ISO-8859-1
    13:29:11.252119 < p3p: CP="This is not a P3P policy! See g.co/p3phelp for more info."
    13:29:11.252160 < server: gws
    13:29:11.252198 < x-xss-protection: 1; mode=block
    13:29:11.252228 < x-frame-options: SAMEORIGIN
    13:29:11.252262 < set-cookie: 1P_JAR=2018-10-19-10; expires=Sun, 18-Nov-2018 10:29:11 GMT; path=/; domain=.google.com
    13:29:11.252297 < set-cookie: NID=141=pzXxp1jrJmLwFVl9bLMPFdGCtG8ySQKxB2rlDWgerrKJeXxfdmB1HhJ1UXzX-OaFQcnR1A9LKYxi__PWMigjMBQHmI3xkU53LI_TsYRbkMNJNdxs-caQQ7fEcDGE694S; expires=Sat, 20-Apr-2019 10:29:11 GMT; path=/; domain=.google.com; HttpOnly
    13:29:11.252336 < alt-svc: quic=":443"; ma=2592000; v="44,43,39,35"
    13:29:11.252368 < accept-ranges: none
    13:29:11.252408 < vary: Accept-Encoding
    13:29:11.252438 < 
    13:29:11.252473 { [5 bytes data]
    100 12215    0 12215    0     0   112k      0 --:--:-- --:--:-- --:--:--  112k
    13:29:11.255674 * Connection #0 to host www.google.com left intact
    

    How to debug external class library projects in visual studio?

    I run two instances of visual studio--one for the external dll and one for the main application.
    In the project properties of the external dll, set the following:

    Build Events:

    • copy /y "$(TargetDir)$(TargetName).dll" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).dll"

    • copy /y "$(TargetDir)$(TargetName).pdb" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).pdb"

    Debug:

    • Start external program: C:\<path-to-main>\bin\debug\<AppName>.exe

    • Working Directory C:\<path-to-main>\bin\debug

    This way, whenever I build the external dll, it gets updated in the main application's directory. If I hit debug from the external dll's project--the main application runs, but the debugger only hits breakpoints in the external dll. If I hit debug from the main project, the main application runs with the most recently built external dll, but now the debugger only hits breakpoints in the main project.

    I realize one debugger will do the job for both, but I find it easier to keep the two straight this way.

    Importing the private-key/public-certificate pair in the Java KeyStore

    A keystore needs a keystore file. The KeyStore class needs a FileInputStream. But if you supply null (instead of FileInputStream instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool.

    Following code creates an empty keystore with empty password

      KeyStore ks2 = KeyStore.getInstance("jks");
      ks2.load(null,"".toCharArray());
      FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore");
      ks2.store(out, "".toCharArray());
    

    Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.

    How to automate browsing using python?

    The best solution that i have found (and currently implementing) is : - scripts in python using selenium webdriver - PhantomJS headless browser (if firefox is used you will have a GUI and will be slower)

    How to upload & Save Files with Desired name

    You can grab the demo source code from here: http://abhinavsingh.com/blog/2008/05/gmail-type-attachment-how-to-make-one/

    It is ready to use, or you can modify to suit your application needs. Hope it helps :)

    C++ - how to find the length of an integer

    int intLength(int i) {
        int l=0;
        for(;i;i/=10) l++;
        return l==0 ? 1 : l;
    }
    

    Here's a tiny efficient one

    How to use pull to refresh in Swift?

    I suggest to make an Extension of pull To Refresh to use in every class.

    1) Make an empty swift file : File - New - File - Swift File.

    2) Add the Following

        //  AppExtensions.swift
    
        import Foundation
        import UIKit    
    
        var tableRefreshControl:UIRefreshControl = UIRefreshControl()    
    
        //MARK:- VIEWCONTROLLER EXTENSION METHODS
        public extension UIViewController
        {
            func makePullToRefreshToTableView(tableName: UITableView,triggerToMethodName: String){
    
                tableRefreshControl.attributedTitle = NSAttributedString(string: "TEST: Pull to refresh")
                tableRefreshControl.backgroundColor = UIColor.whiteColor()
                tableRefreshControl.addTarget(self, action: Selector(triggerToMethodName), forControlEvents: UIControlEvents.ValueChanged)
                tableName.addSubview(tableRefreshControl)
            }
            func makePullToRefreshEndRefreshing (tableName: String)
            {
                tableRefreshControl.endRefreshing()
    //additional codes
    
            }
        }    
    

    3) In Your View Controller call these methods as :

      override func viewWillAppear(animated: Bool) {
    
    self.makePullToRefreshToTableView(bidderListTable, triggerToMethodName: "pullToRefreshBidderTable")
    }
    

    4) At some point you wanted to end refreshing:

      func pullToRefreshBidderTable() {
    self.makePullToRefreshEndRefreshing("bidderListTable")    
    //Code What to do here.
    }
    OR    
    self.makePullToRefreshEndRefreshing("bidderListTable")
    

    No Title Bar Android Theme

    In your styles.xml, modify style "AppTheme" like

        <!-- Application theme. -->
        <style name="AppTheme" parent="AppBaseTheme">
            <item name="android:windowActionBar">false</item>
            <item name="android:windowNoTitle">true</item> 
        </style>
    

    How to display two digits after decimal point in SQL Server

    You can also do something much shorter:

    SELECT FORMAT(2.3332232,'N2')