Programs & Examples On #Web site project

Web Site "projects" are created by using the File->New Web Site command in Visual Studio. They are very strange and should not be used unless you really need to. In most cases, you should use File->New Project.

Node.js Hostname/IP doesn't match certificate's altnames

I had the same issue using the request module to proxy POST request from somewhere else and it was because I left the host property in the header (I was copying the header from the original request).

How to show the last queries executed on MySQL?

For those blessed with MySQL >= 5.1.12, you can control this option globally at runtime:

  1. Execute SET GLOBAL log_output = 'TABLE';
  2. Execute SET GLOBAL general_log = 'ON';
  3. Take a look at the table mysql.general_log

If you prefer to output to a file instead of a table:

  1. SET GLOBAL log_output = "FILE"; the default.
  2. SET GLOBAL general_log_file = "/path/to/your/logfile.log";
  3. SET GLOBAL general_log = 'ON';

I prefer this method to editing .cnf files because:

  1. you're not editing the my.cnf file and potentially permanently turning on logging
  2. you're not fishing around the filesystem looking for the query log - or even worse, distracted by the need for the perfect destination. /var/log /var/data/log /opt /home/mysql_savior/var
  3. You don't have to restart the server and interrupt any current connections to it.
  4. restarting the server leaves you where you started (log is by default still off)

For more information, see MySQL 5.1 Reference Manual - Server System Variables - general_log

Sorting std::map using value

You can't sort a std::map this way, because a the entries in the map are sorted by the key. If you want to sort by value, you need to create a new std::map with swapped key and value.

map<long, double> testMap;
map<double, long> testMap2;

// Insert values from testMap to testMap2
// The values in testMap2 are sorted by the double value

Remember that the double keys need to be unique in testMap2 or use std::multimap.

Moving from one activity to another Activity in Android

1) place setContentView(R.layout.avtivity_next); to the next-activity's onCreate() method just like this (main) activity's onCreate()

2) if you have not defined the next-activity in your-apps manifest file then do this also, like:

<application
        android:allowBackup="true"
        android:icon="@drawable/app_icon"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="Main Activity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".NextActivity"
            android:label="Next Activity" >
        </activity>
    </application>

You must have to perform the 2nd step every time you create a new activity, otherwise your app will crash

What's the best way to share data between activities?

All of the aforementioned answers are great... I'm just adding one no one had mentioned yet about persisting data through activities and that is to use the built in android SQLite database to persist relevant data... In fact you can place your databaseHelper in the application state and call it as needed throughout the activates.. Or just make a helper class and make the DB calls when needed... Just adding another layer for you to consider... But all of the other answers would suffice as well.. Really just preference

HTTPS connections over proxy servers

TLS/SSL (The S in HTTPS) guarantees that there are no eavesdroppers between you and the server you are contacting, i.e. no proxies. Normally, you use CONNECT to open up a TCP connection through the proxy. In this case, the proxy will not be able to cache, read, or modify any requests/responses, and therefore be rather useless.

If you want the proxy to be able to read information, you can take the following approach:

  1. Client starts HTTPS session
  2. Proxy transparently intercepts the connection and returns an ad-hoc generated(possibly weak) certificate Ka, signed by a certificate authority that is unconditionally trusted by the client.
  3. Proxy starts HTTPS session to target
  4. Proxy verifies integrity of SSL certificate; displays error if the cert is not valid.
  5. Proxy streams content, decrypts it and re-encrypts it with Ka
  6. Client displays stuff

An example is Squid's SSL bump. Similarly, burp can be configured to do this. This has also been used in a less-benign context by an Egyptian ISP.

Note that modern websites and browsers can employ HPKP or built-in certificate pins which defeat this approach.

./configure : /bin/sh^M : bad interpreter

If you are using TextMate or a similar programme, do save as, and then in encodings choose LF instead of CRLF.

What is the best IDE for PHP?

All are good, but only Delphi for PHP (RadPHP 3.0) has a designer, drag and drop controls, GUI editeor, huge set of components including Zend Framework, Facebook, database, etc. components. It is the best in town.

RadPHP is the best of all; It has all the features the others have. Its designer is the best of all. You can design your page just like Dreamweaver (more than Dreamweaver).

If you use RadPHP you will feel like using ASP.NET with Visual Studio (but the language is PHP).

It's too bad only a few know about this.

Memcached vs. Redis?

Here is the really great article/differences provided by Amazon

Redis is a clear winner comparing with memcached.

Only one plus point for Memcached It is multithreaded and fast. Redis has lots of great features and is very fast, but limited to one core.

Great points about Redis, which are not supported in Memcached

  • Snapshots - User can take a snapshot of Redis cache and persist on secondary storage any point of time.
  • Inbuilt support for many data structures like Set, Map, SortedSet, List, BitMaps etc.
  • Support for Lua scripting in redis

Updating GUI (WPF) using a different thread

You may use a delegate to solve this issue. Here is an example that is showing how to update a textBox using diffrent thread

public delegate void UpdateTextCallback(string message);

private void TestThread()
{
    for (int i = 0; i <= 1000000000; i++)
    {
        Thread.Sleep(1000);                
        richTextBox1.Dispatcher.Invoke(
            new UpdateTextCallback(this.UpdateText),
            new object[] { i.ToString() }
        );
    }
}
private void UpdateText(string message)
{
    richTextBox1.AppendText(message + "\n");
}

private void button1_Click(object sender, RoutedEventArgs e)
{
   Thread test = new Thread(new ThreadStart(TestThread));
   test.Start();
}

TestThread method is used by thread named test to update textBox

Property 'json' does not exist on type 'Object'

The other way to tackle it is to use this code snippet:

JSON.parse(JSON.stringify(response)).data

This feels so wrong but it works

Returning value that was passed into a method

You can use a lambda with an input parameter, like so:

.Returns((string myval) => { return myval; });

Or slightly more readable:

.Returns<string>(x => x);

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

Maven skip tests

To skip the test case during maven clean install i used -DskipTests paramater in following command

mvn clean install -DskipTests

into terminal window

How can I embed a YouTube video on GitHub wiki pages?

It's not possible to embed videos directly, but you can put an image which links to a YouTube video:

[![IMAGE ALT TEXT HERE](https://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg)](https://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE)

How to inherit constructors?

The problem is not that Bar and Bah have to copy 387 constructors, the problem is that Foo has 387 constructors. Foo clearly does too many things - refactor quick! Also, unless you have a really good reason to have values set in the constructor (which, if you provide a parameterless constructor, you probably don't), I'd recommend using property getting/setting.

How do I mock a static method that returns void with PowerMock?

In simpler terms, Imagine if you want mock below line:

StaticClass.method();

then you write below lines of code to mock:

PowerMockito.mockStatic(StaticClass.class);
PowerMockito.doNothing().when(StaticClass.class);
StaticClass.method();

Explanation of <script type = "text/template"> ... </script>

<script type = “text/template”> … </script> is obsolete. Use <template> tag instead.

How to throw std::exceptions with variable messages?

There are different exceptions such as runtime_error, range_error, overflow_error, logic_error, etc.. You need to pass the string into its constructor, and you can concatenate whatever you want to your message. That's just a string operation.

std::string errorMessage = std::string("Error: on file ")+fileName;
throw std::runtime_error(errorMessage);

You can also use boost::format like this:

throw std::runtime_error(boost::format("Error processing file %1") % fileName);

Convert multiple rows into one with comma as separator

You can use this query to do the above task:

DECLARE @test NVARCHAR(max)  
SELECT @test = COALESCE(@test + ',', '') + field2 FROM #test
SELECT field2 = @test 

For detail and step by step explanation visit the following link http://oops-solution.blogspot.com/2011/11/sql-server-convert-table-column-data.html

Using jQuery's ajax method to retrieve images as a blob

A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
//          set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
   var postEnc, method;
   if (post == null)
   {
      postEnc = '';
      method = 'GET';
   }
   else
   {
      method = 'POST';
      postEnc = new FormData();
      for(var i in post)
         postEnc.append(i, post[i]);
   }
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200)
      {
         var res = this.response;
         var reader = new window.FileReader();
         reader.readAsDataURL(res); 
         reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
      }
   }
   xhr.open(method, url);
   xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   xhr.send('fname=Henry&lname=Ford');
   xhr.responseType = 'blob';
   xhr.send(postEnc);
}

How to give a pattern for new line in grep?

just found

grep $'\r'

It's using $'\r' for c-style escape in Bash.

in this article

MongoDB query multiple collections at once

Perform multiple queries or use embedded documents or look at "database references".

How to get a value from the last inserted row?

Use sequences in postgres for id columns:

INSERT mytable(myid) VALUES (nextval('MySequence'));

SELECT currval('MySequence');

currval will return the current value of the sequence in the same session.

(In MS SQL, you would use @@identity or SCOPE_IDENTITY())

How to reduce the image size without losing quality in PHP

If you are looking to reduce the size using coding itself, you can follow this code in php.

<?php 
function compress($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);

    return $destination;
}

$source_img = 'source.jpg';
$destination_img = 'destination .jpg';

$d = compress($source_img, $destination_img, 90);
?>

$d = compress($source_img, $destination_img, 90);

This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).

$info = getimagesize($source);

The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.

Add Bootstrap Glyphicon to Input Box

It can be done using classes from the official bootstrap 3.x version, without any custom css.

Use input-group-addon before the input tag, inside of input-group then use any of the glyphicons, here is the code

<form>
  <div class="form-group">
    <div class="col-xs-5">
      <div class="input-group">
          <span class="input-group-addon transparent"><span class="glyphicon glyphicon-user"></span></span>
          <input class="form-control left-border-none" placeholder="User Name" type="text" name="username">
      </div>
    </div>
  </div>
</form>

Here is the output

enter image description here

To customise it further add a couple of lines of custom css to your own custom.css file (adjust padding if needed)

.transparent {
    background-color: transparent !important;
    box-shadow: inset 0px 1px 0 rgba(0,0,0,.075);
 }
 .left-border-none {
    border-left:none !important;
    box-shadow: inset 0px 1px 0 rgba(0,0,0,.075);
 }

By making the background of the input-group-addon transparent and making the left gradient of the input tag to zero the input will have a seamless appearance. Here is the customised output

enter image description here

Here is a jsbin example

This will solve the custom css problems of overlapping with labels, alignment while using input-lg and focus on tab issue.

Found shared references to a collection org.hibernate.HibernateException

In a one to many and many to one relationship this error will occur. If you attempt to devote same instance from many to one entity to more than one instance from one to many entity.

For example, each person can have many books but each of these books can be owned by only one person if you consider more than one owner for a book this issue is raised.

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

if you want to upgrade only a single column of a table row then you can use as following:

$this->db->set('column_header', $value); //value that used to update column  
$this->db->where('column_id', $column_id_value); //which row want to upgrade  
$this->db->update('table_name');  //table name

Makefile ifeq logical or

I don't think there's a concise, sensible way to do that, but there are verbose, sensible ways (such as Foo Bah's) and concise, pathological ways, such as

ifneq (,$(findstring $(GCC_MINOR),4-5))
    CFLAGS += -fno-strict-overflow
endif

(which will execute the command provided that the string $(GCC_MINOR) appears inside the string 4-5).

Getting Checkbox Value in ASP.NET MVC 4

Since you are using Model.Name to set the value. I assume you are passing an empty view model to the View.

So the value for Remember is false, and sets the value on the checkbox element to false. This means that when you then select the checkbox, you are posting the value "false" with the form. When you don't select it, it doesn't get posted, so the model defaults to false. Which is why you are seeing a false value in both cases.

The value is only passed when you check the select box. To do a checkbox in Mvc use

@Html.CheckBoxFor(x => x.Remember)

or if you don't want to bind the model to the view.

@Html.CheckBox("Remember")

Mvc does some magic with a hidden field to persist values when they are not selected.

Edit, if you really have an aversion to doing that and want to generate the element yourself, you could do.

<input id="Remember" name="Remember" type="checkbox" value="true" @(Model.Remember ? "checked=\"checked\"" : "") />

Example: Communication between Activity and Service using Messaging

Note: You don't need to check if your service is running, CheckIfServiceIsRunning(), because bindService() will start it if it isn't running.

Also: if you rotate the phone you don't want it to bindService() again, because onCreate() will be called again. Be sure to define onConfigurationChanged() to prevent this.

Checking if a worksheet-based checkbox is checked

Is this what you are trying?

Sub Sample()
    Dim cb As Shape

    Set cb = ActiveSheet.Shapes("Check Box 1")

    If cb.OLEFormat.Object.Value = 1 Then
        MsgBox "Checkbox is Checked"
    Else
        MsgBox "Checkbox is not Checked"
    End If
End Sub

Replace Activesheet with the relevant sheetname. Also replace Check Box 1 with the relevant checkbox name.

"date(): It is not safe to rely on the system's timezone settings..."

This answer above from CtrlX is the correct answer, but it may not work completely. I added this line to my php.ini file:

date.timezone = "America/Los_Angeles"

but it did not remove the PHP error for all my files because some of my PHP scripts are in subfolders. So I had to edit .htaccess file to setup php.ini to be used recursively (in subfolders):

suphp_configpath /home/account_name/public_html

where account_name is your cpanel account name and public_html is the folder your php.ini file is in.

DateTime.MinValue and SqlDateTime overflow

use extensions

public static class DateTimeExtensions
{
    public static DateTime MinValue(this DateTime sqlDateTime)
    {
        return new DateTime(1900, 01, 01, 00, 00, 00);
    }
}


DateTime date = DateTime.Now;
Console.WriteLine("Minvalue is {0} ", date.MinValue().ToShortDateString());

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

How to negate the whole regex?

\b(?=\w)(?!(ma|(t){1}))\b(\w*)

this is for the given regex.
the \b is to find word boundary.
the positive look ahead (?=\w) is here to avoid spaces.
the negative look ahead over the original regex is to prevent matches of it.
and finally the (\w*) is to catch all the words that are left.
the group that will hold the words is group 3.
the simple (?!pattern) will not work as any sub-string will match
the simple ^(?!(?:m{2}|t)$).*$ will not work as it's granularity is full lines

Calling jQuery method from onClick attribute in HTML

this works....

<script language="javascript">
    (function($) {
     $.fn.MessageBox = function(msg) {
       return this.each(function(){
         alert(msg);
       })
     };
    })(jQuery);? 
</script>

.

   <body>
      <div class="Title">Welcome!</div>
     <input type="button" value="ahaha"  onclick="$(this).MessageBox('msg');" />
    </body>

edit

you are using a failsafe jQuery code using the $ alias... it should be written like:

(function($) {
  // plugin code here, use $ as much as you like
})(jQuery); 

or

jQuery(function($) {
   // your code using $ alias here
 });

note that it has a 'jQuery' word in each of it....

Compilation error - missing zlib.h

I also had the same problem. Then I installed the zlib, still the problem remained the same. Then I added the following lines in my .bashrc and it worked. You should replace the path with your zlib installation path. (I didn't have root privileges).

export PATH =$PATH:$HOME/Softwares/library/Zlib/zlib-1.2.11/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/Softwares/library/Zlib/zlib-1.2.11/lib/
export LIBRARY_PATH=$LIBRARY_PATH:$HOME/Softwares/library/Zlib/zlib-1.2.11/lib/
export C_INCLUDE_PATH=$HOME/Softwares/library/Zlib/zlib-1.2.11/include/
export CPLUS_INCLUDE_PATH=$HOME/Softwares/library/Zlib/zlib-1.2.11/include/
export PKG_CONFIG_PATH=$HOME/Softwares/library/Zlib/zlib-1.2.11/lib/pkgconfig

How can I display a tooltip on an HTML "option" tag?

If increasing the number of visible options is available, the following might work for you:

<html>
    <head>
        <title>Select Option Tooltip Test</title>
        <script>
            function showIETooltip(e){
                if(!e){var e = window.event;}
                var obj = e.srcElement;
                var objHeight = obj.offsetHeight;
                var optionCount = obj.options.length;
                var eX = e.offsetX;
                var eY = e.offsetY;

                //vertical position within select will roughly give the moused over option...
                var hoverOptionIndex = Math.floor(eY / (objHeight / optionCount));

                var tooltip = document.getElementById('dvDiv');
                tooltip.innerHTML = obj.options[hoverOptionIndex].title;

                mouseX=e.pageX?e.pageX:e.clientX;
                mouseY=e.pageY?e.pageY:e.clientY;

                tooltip.style.left=mouseX+10;
                tooltip.style.top=mouseY;

                tooltip.style.display = 'block';

                var frm = document.getElementById("frm");
                frm.style.left = tooltip.style.left;
                frm.style.top = tooltip.style.top;
                frm.style.height = tooltip.offsetHeight;
                frm.style.width = tooltip.offsetWidth;
                frm.style.display = "block";
            }
            function hideIETooltip(e){
                var tooltip = document.getElementById('dvDiv');
                var iFrm = document.getElementById('frm');
                tooltip.innerHTML = '';
                tooltip.style.display = 'none';
                iFrm.style.display = 'none';
            }
        </script>
    </head>
    <body>
        <select onmousemove="showIETooltip();" onmouseout="hideIETooltip();" size="10">
            <option title="Option #1" value="1">Option #1</option>
            <option title="Option #2" value="2">Option #2</option>
            <option title="Option #3" value="3">Option #3</option>
            <option title="Option #4" value="4">Option #4</option>
            <option title="Option #5" value="5">Option #5</option>
            <option title="Option #6" value="6">Option #6</option>
            <option title="Option #7" value="7">Option #7</option>
            <option title="Option #8" value="8">Option #8</option>
            <option title="Option #9" value="9">Option #9</option>
            <option title="Option #10" value="10">Option #10</option>
        </select>
        <div id="dvDiv" style="display:none;position:absolute;padding:1px;border:1px solid #333333;;background-color:#fffedf;font-size:smaller;z-index:999;"></div>
        <iframe id="frm" style="display:none;position:absolute;z-index:998"></iframe>
    </body>
</html>

Should Gemfile.lock be included in .gitignore?

Assuming you're not writing a rubygem, Gemfile.lock should be in your repository. It's used as a snapshot of all your required gems and their dependencies. This way bundler doesn't have to recalculate all the gem dependencies each time you deploy, etc.

From cowboycoded's comment below:

If you are working on a gem, then DO NOT check in your Gemfile.lock. If you are working on a Rails app, then DO check in your Gemfile.lock.

Here's a nice article explaining what the lock file is.

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

Instead of simply setting the font size to 16px, you can:

  1. Style the input field so that it is larger than its intended size, allowing the logical font size to be set to 16px.
  2. Use the scale() CSS transform and negative margins to shrink the input field down to the correct size.

For example, suppose your input field is originally styled with:

input[type="text"] {
    border-radius: 5px;
    font-size: 12px;
    line-height: 20px;
    padding: 5px;
    width: 100%;
}

If you enlarge the field by increasing all dimensions by 16 / 12 = 133.33%, then reduce using scale() by 12 / 16 = 75%, the input field will have the correct visual size (and font size), and there will be no zoom on focus.

As scale() only affects the visual size, you will also need to add negative margins to reduce the field's logical size.

With this CSS:

input[type="text"] {
    /* enlarge by 16/12 = 133.33% */
    border-radius: 6.666666667px;
    font-size: 16px;
    line-height: 26.666666667px;
    padding: 6.666666667px;
    width: 133.333333333%;

    /* scale down by 12/16 = 75% */
    transform: scale(0.75);
    transform-origin: left top;

    /* remove extra white space */
    margin-bottom: -10px;
    margin-right: -33.333333333%;
}

the input field will have a logical font size of 16px while appearing to have 12px text.

I have a blog post where I go into slightly more detail, and have this example as viewable HTML:
No input zoom in Safari on iPhone, the pixel perfect way

How do I create a datetime in Python from milliseconds?

What about this? I presume it can be counted on to handle dates before 1970 and after 2038.

target_date_time_ms = 200000 # or whatever
base_datetime = datetime.datetime( 1970, 1, 1 )
delta = datetime.timedelta( 0, 0, 0, target_date_time_ms )
target_date = base_datetime + delta

as mentioned in the Python standard lib:

fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It’s common for this to be restricted to years in 1970 through 2038.

Adding image inside table cell in HTML

Try using "/" instead of "\" for the path to your image. Some comments here seem to come from people that do not understand some of us are simply learning web development which in many cases is best done locally. So instead of using src=C:\Pics\H.gif use src="C:/Pics/H.gif" for an absolute path or just src="Pics/H.gif" for a relative path if your Pics are in a sub-directory of your html page's location). Note also, it is good practice to surround your path with quotes. otherwise you will have problems with paths that include spaces and other odd characters.

C++, copy set to vector

You haven't reserved enough space in your vector object to hold the contents of your set.

std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());

Deserialize JSON into C# dynamic object?

JsonFx can deserialize JSON content into dynamic objects.

Serialize to/from dynamic types (default for .NET 4.0):

var reader = new JsonReader(); var writer = new JsonWriter();

string input = @"{ ""foo"": true, ""array"": [ 42, false, ""Hello!"", null ] }";
dynamic output = reader.Read(input);
Console.WriteLine(output.array[0]); // 42
string json = writer.Write(output);
Console.WriteLine(json); // {"foo":true,"array":[42,false,"Hello!",null]}

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

Got a same error and this solved my error. Thanks! python 2 and python 3 differing in unicode handling is making pickled files quite incompatible to load. So Use python pickle's encoding argument. Link below helped me solve the similar problem when I was trying to open pickled data from my python 3.7, while my file was saved originally in python 2.x version. https://blog.modest-destiny.com/posts/python-2-and-3-compatible-pickle-save-and-load/ I copy the load_pickle function in my script and called the load_pickle(pickle_file) while loading my input_data like this:

input_data = load_pickle("my_dataset.pkl")

The load_pickle function is here:

def load_pickle(pickle_file):
    try:
        with open(pickle_file, 'rb') as f:
            pickle_data = pickle.load(f)
    except UnicodeDecodeError as e:
        with open(pickle_file, 'rb') as f:
            pickle_data = pickle.load(f, encoding='latin1')
    except Exception as e:
        print('Unable to load data ', pickle_file, ':', e)
        raise
    return pickle_data

Fixed header table with horizontal scrollbar and vertical scrollbar on

Here is a HTML / CSS only solution (with a little javascript).

Apology to answer the question after this long, but the solution given did not suit me and I found a better one. Here is the easiest way to do it with HTML (no jquery):

Before that, the solution fiddle to the question. https://jsfiddle.net/3vzrunkt/

<div>
    <div style="overflow:hidden;;margin-right:16px" id="headerdiv">
        <table id="headertable" style="min-width:900px" border=1>
            <thead>
                <tr>
                    <th style="width:120px;min-width:120px;">One</th>
                    <th style="width:420px;min-width:420px;">Two</th>
                    <th style="width:120px;min-width:120px;">Three</th>
                    <th style="width:120px;min-width:120px;">Four</th>
                    <th style="width:120px;min-width:120px;">Five</th>
                </tr>
            </thead>
        </table>
    </div>

    <div style="overflow-y:scroll;max-height:200px;" 
         onscroll="document.getElementById('headerdiv').scrollLeft = this.scrollLeft;">
        <table id="bodytable" border=1 style="min-width:900px; border:1px solid">
            <tbody>
                <tr>
                    <td style="width:120px;min-width:120px;">body row1</td>
                    <td style="width:420px;min-width:420px;">body row2</td>
                    <td style="width:120px;min-width:120px;">body row2</td>
                    <td style="width:120px;min-width:120px;">body row2</td>
                    <td style="width:120px;min-width:120px;">body row2 en nog meer</td>
                </tr>
                :
                :
                :
                :

            </tbody>
        </table>
    </div>
</div>

And to explain the solution:

  1. you need and enclosing div no overflow/scroll required

  2. a header div containing the header table with overflow:hidden to ensure that the scrollbar is not displayed. Add margin-right:16px to ensure that the scrollbar is left outside it while synching.

  3. another div for containing the table records and overflow-y:scroll. Note the padding is required to get the scrollbar move right of the header.

  4. And the most important thing the magical js to sync the header and table data:

     onscroll="document.getElementById('headerdiv').scrollLeft = this.scrollLeft;"
    

How to resize an image to a specific size in OpenCV?

Make a useful function like this:

IplImage* img_resize(IplImage* src_img, int new_width,int new_height)
{
    IplImage* des_img;
    des_img=cvCreateImage(cvSize(new_width,new_height),src_img->depth,src_img->nChannels);
    cvResize(src_img,des_img,CV_INTER_LINEAR);
    return des_img;
} 

Correct way to quit a Qt program?

If you're using Qt Jambi, this should work:

QApplication.closeAllWindows();

sh: 0: getcwd() failed: No such file or directory on cited drive

if some directory/folder does not exist but somehow you navigated to that directory in that case you can see this Error,

for example:

  • currently, you are in "mno" directory (path = abc/def/ghi/jkl/mno
  • run "sudo su" and delete mno
  • goto the "ghi" directory and delete "jkl" directory
  • now you are in "ghi" directory (path abc/def/ghi)
  • run "exit"
  • after running the "exit", you will get that Error
  • now you will be in "mno"(path = abc/def/ghi/jkl/mno) folder. that does not exist.

so, Generally this Error will show when Directory doesn't exist.

to fix this, simply run "cd;" or you can move to any other directory which exists.

Escape double quotes in a string

One solution, is to add support to the csharp language so that "" isn't the only scheme used for strings.

For another string terminator to the C# language - I'm a fan of backtick in ES6.

string test = `He said to me, "Hello World". How are you?`;

But also, the doubling idea in Markdown might be better:

string test = ""He said to me, "Hello World". How are you?"";

The code does not work at the date of this post. This post is a solution where the visitors to this Q&A jump onto this csharplank ticket for C# and upvote it - https://github.com/dotnet/csharplang/discussions/3917

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

DECLARE @t1 TABLE (
    TableID     int         IDENTITY,
    FieldValue  varchar(20)
)

--<< No empty string
IF EXISTS (
    SELECT *
    FROM @t1
    WHERE FieldValue = ''
) BEGIN
    SELECT TableID
    FROM @t1
    WHERE FieldValue=''
END
ELSE BEGIN
    INSERT INTO @t1 (FieldValue) VALUES ('')
    SELECT SCOPE_IDENTITY() AS TableID
END

--<< A record with an empty string already exists
IF EXISTS (
    SELECT *
    FROM @t1
    WHERE FieldValue = ''
) BEGIN
    SELECT TableID
    FROM @t1
    WHERE FieldValue=''
END
ELSE BEGIN
    INSERT INTO @t1 (FieldValue) VALUES ('')
    SELECT SCOPE_IDENTITY() AS TableID
END

How do I make a simple makefile for gcc on Linux?

Depending on the number of headers and your development habits, you may want to investigate gccmakedep. This program examines your current directory and adds to the end of the makefile the header dependencies for each .c/cpp file. This is overkill when you have 2 headers and one program file. However, if you have 5+ little test programs and you are editing one of 10 headers, you can then trust make to rebuild exactly those programs which were changed by your modifications.

What is stability in sorting algorithms and why is it important?

I know there are many answers for this, but to me, this answer, by Robert Harvey, summarized it much more clearly:

A stable sort is one which preserves the original order of the input set, where the [unstable] algorithm does not distinguish between two or more items.

Source

Generate random numbers using C++11 random library

Here is some resource you can read about pseudo-random number generator.

https://en.wikipedia.org/wiki/Pseudorandom_number_generator

Basically, random numbers in computer need a seed (this number can be the current system time).

Replace

std::default_random_engine generator;

By

std::default_random_engine generator(<some seed number>);

SQL Views - no variables?

How often do you need to refresh the view? I have a similar case where the new data comes once a month; then I have to load it, and during the loading processes I have to create new tables. At that moment I alter my view to consider the changes. I used as base the information in this other question:

Create View Dynamically & synonyms

In there, it is proposed to do it 2 ways:

  1. using synonyms.
  2. Using dynamic SQL to create view (this is what helped me achieve my result).

Best way to compare 2 XML documents in Java

Sounds like a job for XMLUnit

Example:

public class SomeTest extends XMLTestCase {
  @Test
  public void test() {
    String xml1 = ...
    String xml2 = ...

    XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences

    // can also compare xml Documents, InputSources, Readers, Diffs
    assertXMLEqual(xml1, xml2);  // assertXMLEquals comes from XMLTestCase
  }
}

How to style HTML5 range input to have different color before and after slider?

Building on top of @dargue3's answer, if you want the thumb to be larger than the track, you want to fully take advantage of the <input type="range" /> element and go cross browser, you need a little extra lines of JS & CSS.

On Chrome/Mozilla you can use the linear-gradient technique, but you need to adjust the ratio based on the min, max, value attributes as mentioned here by @Attila O.. You need to make sure you are not applying this on Edge, otherwise the thumb is not displayed. @Geoffrey Lalloué explains this in more detail here.

Another thing worth mentioning, is that you need to adjust the rangeEl.style.height = "20px"; on IE/Older. Simply put this is because in this case "the height is not applied to the track but rather the whole input including the thumb". fiddle

_x000D_
_x000D_
/**_x000D_
 * Sniffs for Older Edge or IE,_x000D_
 * more info here:_x000D_
 * https://stackoverflow.com/q/31721250/3528132_x000D_
 */_x000D_
function isOlderEdgeOrIE() {_x000D_
  return (_x000D_
    window.navigator.userAgent.indexOf("MSIE ") > -1 ||_x000D_
    !!navigator.userAgent.match(/Trident.*rv\:11\./) ||_x000D_
    window.navigator.userAgent.indexOf("Edge") > -1_x000D_
  );_x000D_
}_x000D_
_x000D_
function valueTotalRatio(value, min, max) {_x000D_
  return ((value - min) / (max - min)).toFixed(2);_x000D_
}_x000D_
_x000D_
function getLinearGradientCSS(ratio, leftColor, rightColor) {_x000D_
  return [_x000D_
    '-webkit-gradient(',_x000D_
    'linear, ',_x000D_
    'left top, ',_x000D_
    'right top, ',_x000D_
    'color-stop(' + ratio + ', ' + leftColor + '), ',_x000D_
    'color-stop(' + ratio + ', ' + rightColor + ')',_x000D_
    ')'_x000D_
  ].join('');_x000D_
}_x000D_
_x000D_
function updateRangeEl(rangeEl) {_x000D_
  var ratio = valueTotalRatio(rangeEl.value, rangeEl.min, rangeEl.max);_x000D_
_x000D_
  rangeEl.style.backgroundImage = getLinearGradientCSS(ratio, '#919e4b', '#c5c5c5');_x000D_
}_x000D_
_x000D_
function initRangeEl() {_x000D_
  var rangeEl = document.querySelector('input[type=range]');_x000D_
  var textEl = document.querySelector('input[type=text]');_x000D_
_x000D_
  /**_x000D_
   * IE/Older Edge FIX_x000D_
   * On IE/Older Edge the height of the <input type="range" />_x000D_
   * is the whole element as oposed to Chrome/Moz_x000D_
   * where the height is applied to the track._x000D_
   *_x000D_
   */_x000D_
  if (isOlderEdgeOrIE()) {_x000D_
    rangeEl.style.height = "20px";_x000D_
    // IE 11/10 fires change instead of input_x000D_
    // https://stackoverflow.com/a/50887531/3528132_x000D_
    rangeEl.addEventListener("change", function(e) {_x000D_
      textEl.value = e.target.value;_x000D_
    });_x000D_
    rangeEl.addEventListener("input", function(e) {_x000D_
      textEl.value = e.target.value;_x000D_
    });_x000D_
  } else {_x000D_
    updateRangeEl(rangeEl);_x000D_
    rangeEl.addEventListener("input", function(e) {_x000D_
      updateRangeEl(e.target);_x000D_
      textEl.value = e.target.value;_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
initRangeEl();
_x000D_
input[type="range"] {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  width: 300px;_x000D_
  height: 5px;_x000D_
  padding: 0;_x000D_
  border-radius: 2px;_x000D_
  outline: none;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
_x000D_
/*Chrome thumb*/_x000D_
_x000D_
input[type="range"]::-webkit-slider-thumb {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  -webkit-border-radius: 5px;_x000D_
  /*16x16px adjusted to be same as 14x14px on moz*/_x000D_
  height: 16px;_x000D_
  width: 16px;_x000D_
  border-radius: 5px;_x000D_
  background: #e7e7e7;_x000D_
  border: 1px solid #c5c5c5;_x000D_
}_x000D_
_x000D_
_x000D_
/*Mozilla thumb*/_x000D_
_x000D_
input[type="range"]::-moz-range-thumb {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  -moz-border-radius: 5px;_x000D_
  height: 14px;_x000D_
  width: 14px;_x000D_
  border-radius: 5px;_x000D_
  background: #e7e7e7;_x000D_
  border: 1px solid #c5c5c5;_x000D_
}_x000D_
_x000D_
_x000D_
/*IE & Edge input*/_x000D_
_x000D_
input[type=range]::-ms-track {_x000D_
  width: 300px;_x000D_
  height: 6px;_x000D_
  /*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */_x000D_
  background: transparent;_x000D_
  /*leave room for the larger thumb to overflow with a transparent border */_x000D_
  border-color: transparent;_x000D_
  border-width: 2px 0;_x000D_
  /*remove default tick marks*/_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
_x000D_
/*IE & Edge thumb*/_x000D_
_x000D_
input[type=range]::-ms-thumb {_x000D_
  height: 14px;_x000D_
  width: 14px;_x000D_
  border-radius: 5px;_x000D_
  background: #e7e7e7;_x000D_
  border: 1px solid #c5c5c5;_x000D_
}_x000D_
_x000D_
_x000D_
/*IE & Edge left side*/_x000D_
_x000D_
input[type=range]::-ms-fill-lower {_x000D_
  background: #919e4b;_x000D_
  border-radius: 2px;_x000D_
}_x000D_
_x000D_
_x000D_
/*IE & Edge right side*/_x000D_
_x000D_
input[type=range]::-ms-fill-upper {_x000D_
  background: #c5c5c5;_x000D_
  border-radius: 2px;_x000D_
}_x000D_
_x000D_
_x000D_
/*IE disable tooltip*/_x000D_
_x000D_
input[type=range]::-ms-tooltip {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
input[type="text"] {_x000D_
  border: none;_x000D_
}
_x000D_
<input type="range" value="80" min="10" max="100" step="1" />_x000D_
<input type="text" value="80" size="3" />
_x000D_
_x000D_
_x000D_

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST VERIFYPEER did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget to the same link as the cURL was doing also resulted in a certificate error.

-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.

For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover does not work try to reboot your machine.

Argument list too long error for rm, cp, mv commands

The reason this occurs is because bash actually expands the asterisk to every matching file, producing a very long command line.

Try this:

find . -name "*.pdf" -print0 | xargs -0 rm

Warning: this is a recursive search and will find (and delete) files in subdirectories as well. Tack on -f to the rm command only if you are sure you don't want confirmation.

You can do the following to make the command non-recursive:

find . -maxdepth 1 -name "*.pdf" -print0 | xargs -0 rm

Another option is to use find's -delete flag:

find . -name "*.pdf" -delete

What are the differences between type() and isinstance()?

For the real differences, we can find it in code, but I can't find the implement of the default behavior of the isinstance().

However we can get the similar one abc.__instancecheck__ according to __instancecheck__.

From above abc.__instancecheck__, after using test below:

# file tree
# /test/__init__.py
# /test/aaa/__init__.py
# /test/aaa/aa.py
class b():
pass

# /test/aaa/a.py
import sys
sys.path.append('/test')

from aaa.aa import b
from aa import b as c

d = b()

print(b, c, d.__class__)
for i in [b, c, object]:
    print(i, '__subclasses__',  i.__subclasses__())
    print(i, '__mro__', i.__mro__)
    print(i, '__subclasshook__', i.__subclasshook__(d.__class__))
    print(i, '__subclasshook__', i.__subclasshook__(type(d)))
print(isinstance(d, b))
print(isinstance(d, c))

<class 'aaa.aa.b'> <class 'aa.b'> <class 'aaa.aa.b'>
<class 'aaa.aa.b'> __subclasses__ []
<class 'aaa.aa.b'> __mro__ (<class 'aaa.aa.b'>, <class 'object'>)
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasses__ []
<class 'aa.b'> __mro__ (<class 'aa.b'>, <class 'object'>)
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'object'> __subclasses__ [..., <class 'aaa.aa.b'>, <class 'aa.b'>]
<class 'object'> __mro__ (<class 'object'>,)
<class 'object'> __subclasshook__ NotImplemented
<class 'object'> __subclasshook__ NotImplemented
True
False

I get this conclusion, For type:

# according to `abc.__instancecheck__`, they are maybe different! I have not found negative one 
type(INSTANCE) ~= INSTANCE.__class__
type(CLASS) ~= CLASS.__class__

For isinstance:

# guess from `abc.__instancecheck__`
return any(c in cls.__mro__ or c in cls.__subclasses__ or cls.__subclasshook__(c) for c in {INSTANCE.__class__, type(INSTANCE)})

BTW: better not to mix use relative and absolutely import, use absolutely import from project_dir( added by sys.path)

How to Set Focus on JTextField?

Try this one,

myFrame.setVisible(true);
EventQueue.invokeLater(new Runnable() {

   @Override
     public void run() {
         myComponent.grabFocus();
         myComponent.requestFocus();//or inWindow
     }
});

Change the current directory from a Bash script

If you are using bash you can try alias:

into the .bashrc file add this line:

alias p='cd /home/serdar/my_new_folder/path/'

when you write "p" on the command line, it will change the directory.

What is the maximum number of edges in a directed graph with n nodes?

In the graph with self loop

max edges= n*n

such as we have 4 nodes(vertex)

4 nodes = 16 edges= 4*4

Error while installing json gem 'mkmf.rb can't find header files for ruby'

BEFORE you follow the tip from Joki's answer (below) and IF :

  • you have MacOS 10.14.6

  • at /Library/Developer/CommandLineTools/SDKs/ you have folders MacOSX.sdk(symbolic), MacOSX10.14.sdk, MacOSX10.15.sdk

  • Move MacOSX10.15.sdk to anywhere (admin privileges needs)

  • Delete symbolic link (admin privileges needs)

  • At /Library/Developer/CommandLineTools/SDKs/ create another symbolic link now to MacOSX10.14.sdk folder using (admin privileges needs)

    sudo ln -s /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk MacOSX.sdk

  • Now you can follow Joki's answer

WARNING! If you move MacOSX10.15.sdk folder to /Library/Developer/CommandLineTools/SDKs/ again, the command

ruby -rrbconfig -e 'puts RbConfig::CONFIG["rubyhdrdir"]'

will show MacOSX10.15.sdk folder like default again, nowadays I dunno how to fix it! My suggestion, compress the folder and put the original folder until fix will be available.

Java Error: illegal start of expression

public static int [] locations={1,2,3};

public static test dot=new test();

Declare the above variables above the main method and the code compiles fine.

public static void main(String[] args){

Remove warning messages in PHP

Not exactly answering the question, but I think this is a better compromise in some situations:

I had a warning message as a result of a printf() statement in a third-party library. I knew exactly what the cause was - a temporary work-around while the third-party fixed their code. I agree that warnings should not be suppressed, but I could not demonstrate my work to a client with the warning message popping up on screen. My solution:

printf('<div style="display:none">');
    ...Third-party stuff here...
printf('</div>');

Warning was still in page source as a reminder to me, but invisible to the client.

How to spawn a process and capture its STDOUT in .NET?

Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output:

process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
process.Start();
process.BeginOutputReadLine();

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

Faced the same error. In my case , what i did wrong was that i injected the service(named DataService in my case) inside the constructor within the Component but I simply forgot to import it within the component.

 constructor(private dataService:DataService ) {
    console.log("constructor called");
  }

I missed the below import code.

import { DataService } from '../../services/data.service';

How to add days to the current date?

In SQL Server 2008 and above just do this:

SELECT DATEADD(day, 1, Getdate()) AS DateAdd;

List comprehension vs. lambda + filter

Since any speed difference is bound to be miniscule, whether to use filters or list comprehensions comes down to a matter of taste. In general I'm inclined to use comprehensions (which seems to agree with most other answers here), but there is one case where I prefer filter.

A very frequent use case is pulling out the values of some iterable X subject to a predicate P(x):

[x for x in X if P(x)]

but sometimes you want to apply some function to the values first:

[f(x) for x in X if P(f(x))]


As a specific example, consider

primes_cubed = [x*x*x for x in range(1000) if prime(x)]

I think this looks slightly better than using filter. But now consider

prime_cubes = [x*x*x for x in range(1000) if prime(x*x*x)]

In this case we want to filter against the post-computed value. Besides the issue of computing the cube twice (imagine a more expensive calculation), there is the issue of writing the expression twice, violating the DRY aesthetic. In this case I'd be apt to use

prime_cubes = filter(prime, [x*x*x for x in range(1000)])

How do I parse command line arguments in Java?

I've used JOpt and found it quite handy: http://jopt-simple.sourceforge.net/

The front page also provides a list of about 8 alternative libraries, check them out and pick the one that most suits your needs.

What exactly does the .join() method do?

To append a string, just concatenate it with the + sign.

E.g.

>>> a = "Hello, "
>>> b = "world"
>>> str = a + b
>>> print str
Hello, world

join connects strings together with a separator. The separator is what you place right before the join. E.g.

>>> "-".join([a,b])
'Hello, -world'

Join takes a list of strings as a parameter.

ggplot2 plot without axes, legends, etc

Late to the party, but might be of interest...

I find a combination of labs and guides specification useful in many cases:

You want nothing but a grid and a background:

ggplot(diamonds, mapping = aes(x = clarity)) + 
  geom_bar(aes(fill = cut)) + 
  labs(x = NULL, y = NULL) + 
  guides(x = "none", y = "none")

enter image description here

You want to only suppress the tick-mark label of one or both axes:

ggplot(diamonds, mapping = aes(x = clarity)) + 
  geom_bar(aes(fill = cut)) + 
  guides(x = "none", y = "none")

enter image description here

.ssh/config file for windows (git)

There is an option IdentityFile which you can use in your ~/.ssh/config file and specify key file for each host.

Host host_with_key1.net
  IdentityFile ~/.ssh/id_rsa

Host host_with_key2.net
  IdentityFile ~/.ssh/id_rsa_test

More info: http://linux.die.net/man/5/ssh_config

Also look at http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/

How to group an array of objects by key

Create a method which can be re-used

Array.prototype.groupBy = function(prop) {
      return this.reduce(function(groups, item) {
        const val = item[prop]
        groups[val] = groups[val] || []
        groups[val].push(item)
        return groups
      }, {})
    };

Then below you can group by any criteria

const groupByMake = cars.groupBy('make');
        console.log(groupByMake);

_x000D_
_x000D_
var cars = [_x000D_
    {_x000D_
        'make': 'audi',_x000D_
        'model': 'r8',_x000D_
        'year': '2012'_x000D_
    }, {_x000D_
        'make': 'audi',_x000D_
        'model': 'rs5',_x000D_
        'year': '2013'_x000D_
    }, {_x000D_
        'make': 'ford',_x000D_
        'model': 'mustang',_x000D_
        'year': '2012'_x000D_
    }, {_x000D_
        'make': 'ford',_x000D_
        'model': 'fusion',_x000D_
        'year': '2015'_x000D_
    }, {_x000D_
        'make': 'kia',_x000D_
        'model': 'optima',_x000D_
        'year': '2012'_x000D_
    },_x000D_
];_x000D_
  //re-usable method_x000D_
Array.prototype.groupBy = function(prop) {_x000D_
   return this.reduce(function(groups, item) {_x000D_
  const val = item[prop]_x000D_
  groups[val] = groups[val] || []_x000D_
  groups[val].push(item)_x000D_
  return groups_x000D_
   }, {})_x000D_
 };_x000D_
  _x000D_
 // initiate your groupBy. Notice the recordset Cars and the field Make...._x000D_
  const groupByMake = cars.groupBy('make');_x000D_
  console.log(groupByMake);_x000D_
    _x000D_
    //At this point we have objects. You can use Object.keys to return an array
_x000D_
_x000D_
_x000D_

How to empty a redis database?

open your Redis cli and There two possible option that you could use:

FLUSHDB - Delete all the keys of the currently selected DB. FLUSHALL - Delete all the keys of all the existing databases, not just the currently selected one.

Convert ascii value to char

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

Convert a date format in epoch

tl;dr

ZonedDateTime.parse( 
                        "Jun 13 2003 23:11:52.454 UTC" , 
                        DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" ) 
                    )
              .toInstant()
              .toEpochMilli()

1055545912454

java.time

This Answer expands on the Answer by Lockni.

DateTimeFormatter

First define a formatting pattern to match your input string by creating a DateTimeFormatter object.

String input = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );

ZonedDateTime

Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).

ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );

zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]

Table of types of date-time classes in modern java.time versus legacy.

Count-from-epoch

I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).

But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.

Instant instant = zdt.toInstant ();

instant.toString(): 2003-06-13T23:11:52.454Z

long millisSinceEpoch = instant.toEpochMilli() ; 

1055545912454


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How do I change the language of moment.js?

With momentjs 2.8+, do the following:

moment.locale("de").format('LLL');

http://momentjs.com/docs/#/i18n/

How to turn off INFO logging in Spark?

This below code snippet for scala users :

Option 1 :

Below snippet you can add at the file level

import org.apache.log4j.{Level, Logger}
Logger.getLogger("org").setLevel(Level.WARN)

Option 2 :

Note : which will be applicable for all the application which is using spark session.

import org.apache.spark.sql.SparkSession

  private[this] implicit val spark = SparkSession.builder().master("local[*]").getOrCreate()

spark.sparkContext.setLogLevel("WARN")

Option 3 :

Note : This configuration should be added to your log4j.properties.. (could be like /etc/spark/conf/log4j.properties (where the spark installation is there) or your project folder level log4j.properties) since you are changing at module level. This will be applicable for all the application.

log4j.rootCategory=ERROR, console

IMHO, Option 1 is wise way since it can be switched off at file level.

How to make Sonar ignore some classes for codeCoverage metric?

Accordingly to this document for SonarQube 7.1

sonar.exclusions - Comma-delimited list of file path patterns to be excluded from analysis sonar.coverage.exclusions - Comma-delimited list of file path patterns to be excluded from coverage calculations

This document gives some examples on how to create path patterns

# Exclude all classes ending by "Bean"
# Matches org/sonar.api/MyBean.java, org/sonar/util/MyOtherBean.java, org/sonar/util/MyDTO.java, etc.
sonar.exclusions=**/*Bean.java,**/*DTO.java

# Exclude all classes in the "src/main/java/org/sonar" directory
# Matches src/main/java/org/sonar/MyClass.java, src/main/java/org/sonar/MyOtherClass.java
# But does not match src/main/java/org/sonar/util/MyClassUtil.java
sonar.exclusions=src/main/java/org/sonar/*

# Exclude all COBOL programs in the "bank" directory and its sub-directories
# Matches bank/ZTR00021.cbl, bank/data/CBR00354.cbl, bank/data/REM012345.cob
sonar.exclusions=bank/**/*

# Exclude all COBOL programs in the "bank" directory and its sub-directories whose extension is .cbl
# Matches bank/ZTR00021.cbl, bank/data/CBR00354.cbl
sonar.exclusions=bank/**/*.cbl

If you are using Maven for your project, Maven command line parameters can be passed like this for example -Dsonar.coverage.exclusions=**/config/*,**/model/*

I was having problem with excluding single class explicitly. Below my observations:

**/*GlobalExceptionhandler.java - not working for some reason, I was expecting such syntax should work
com/some/package/name/GlobalExceptionhandler.java - not working
src/main/java/com/some/package/name/GlobalExceptionhandler.java - good, class excluded explicitly without using wildcards

Use HTML5 to resize an image before upload

Here is what I ended up doing and it worked great.

First I moved the file input outside of the form so that it is not submitted:

<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
    <input id="name" value="#{name}" />
    ... a few more inputs ... 
</form>

Then I changed the uploadPhotos function to handle only the resizing:

window.uploadPhotos = function(url){
    // Read in file
    var file = event.target.files[0];

    // Ensure it's an image
    if(file.type.match(/image.*/)) {
        console.log('An image has been loaded');

        // Load the image
        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            var image = new Image();
            image.onload = function (imageEvent) {

                // Resize the image
                var canvas = document.createElement('canvas'),
                    max_size = 544,// TODO : pull max size from a site config
                    width = image.width,
                    height = image.height;
                if (width > height) {
                    if (width > max_size) {
                        height *= max_size / width;
                        width = max_size;
                    }
                } else {
                    if (height > max_size) {
                        width *= max_size / height;
                        height = max_size;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                var dataUrl = canvas.toDataURL('image/jpeg');
                var resizedImage = dataURLToBlob(dataUrl);
                $.event.trigger({
                    type: "imageResized",
                    blob: resizedImage,
                    url: dataUrl
                });
            }
            image.src = readerEvent.target.result;
        }
        reader.readAsDataURL(file);
    }
};

As you can see I'm using canvas.toDataURL('image/jpeg'); to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl); to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:

/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = parts[1];

        return new Blob([raw], {type: contentType});
    }

    var parts = dataURL.split(BASE64_MARKER);
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;

    var uInt8Array = new Uint8Array(rawLength);

    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }

    return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB      */

Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.

/* Handle image resized events */
$(document).on("imageResized", function (event) {
    var data = new FormData($("form[id*='uploadImageForm']")[0]);
    if (event.blob && event.url) {
        data.append('image_data', event.blob);

        $.ajax({
            url: event.url,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(data){
               //handle errors...
            }
        });
    }
});

Project Links do not work on Wamp Server

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

But if you still face problem please use this method,

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

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

How to sleep for five seconds in a batch file/cmd

The following hack let's you sleep for 5 seconds

ping -n 6 127.0.0.1 > nul

Since ping waits a second between the pings, you have to specify one more than you need.

How to return a resolved promise from an AngularJS Service using $q?

Here's the correct code for your service:

myApp.service('userService', [
  '$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {

    var user = {
      access: false
    };

    var me = this;

    this.initialized = false;
    this.isAuthenticated = function() {

      var deferred = $q.defer();
      user = {
        first_name: 'First',
        last_name: 'Last',
        email: '[email protected]',
        access: 'institution'
      };
      deferred.resolve(user);
      me.initialized = true;

      return deferred.promise;
    };
  }
]);

Then you controller should align accordingly:

myApp.run([
  '$rootScope', 'userService', function($rootScope, userService) {
    return userService.isAuthenticated().then(function(user) {
      if (user) {
        // You have access to the object you passed in the service, not to the response.
        // You should either put response.data on the user or use a different property.
        return $rootScope.$broadcast('login', user.email);  
      } else {
        return userService.logout();
      }
    });
  }
]);

Few points to note about the service:

  • Expose in a service only what needs to be exposed. User should be kept internally and be accessed by getters only.

  • When in functions, use 'me' which is the service to avoid edge cases of this with javascript.

  • I guessed what initialized was meant to do, feel free to correct me if I guessed wrong.

Best way to handle multiple constructors in Java

Another consideration, if a field is required or has a limited range, perform the check in the constructor:

public Book(String title)
{
    if (title==null)
        throw new IllegalArgumentException("title can't be null");
    this.title = title;
}

Convert pyQt UI to python

You can use pyuic4 command on shell: pyuic4 input.ui -o output.py

NLTK and Stopwords Fail #lookuperror

I tried from ubuntu terminal and I don't know why the GUI didn't show up according to tttthomasssss answer. So I followed the comment from KLDavenport and it worked. Here is the summary:

Open your terminal/command-line and type python then

>>> import nltk .>>> nltk.download("stopwords")

This will store the stopwords corpus under the nltk_data. For my case it was /home/myusername/nltk_data/corpora/stopwords.

If you need another corpus then visit nltk data and find the corpus with their ID. Then use the ID to download like we did for stopwords.

How should I choose an authentication library for CodeIgniter?

I'm trying Ion_Auth and appreciate it, btw...

SimpleLoginSecure Makes authentication simple and secure.

How to create multidimensional array

var numeric = [
    ['input1','input2'],
    ['input3','input4']
];
numeric[0][0] == 'input1';
numeric[0][1] == 'input2';
numeric[1][0] == 'input3';
numeric[1][1] == 'input4';

var obj = {
    'row1' : {
        'key1' : 'input1',
        'key2' : 'input2'
    },
    'row2' : {
        'key3' : 'input3',
        'key4' : 'input4'
    }
};
obj.row1.key1 == 'input1';
obj.row1.key2 == 'input2';
obj.row2.key1 == 'input3';
obj.row2.key2 == 'input4';

var mixed = {
    'row1' : ['input1', 'inpu2'],
    'row2' : ['input3', 'input4']
};
mixed.row1[0] == 'input1';
mixed.row1[1] == 'input2';
mixed.row2[0] == 'input3';
mixed.row2[1] == 'input4';

http://jsfiddle.net/z4Un3/

And if you're wanting to store DOM elements:

var inputs = [
    [
        document.createElement('input'),
        document.createElement('input')
    ],
    [
        document.createElement('input'),
        document.createElement('input')
    ]
];
inputs[0][0].id = 'input1';
inputs[0][1].id = 'input2';
inputs[1][0].id = 'input3';
inputs[1][1].id = 'input4';

Not real sure how useful the above is until you attach the elements. The below may be more what you're looking for:

<input text="text" id="input5"/>
<input text="text" id="input6"/>
<input text="text" id="input7"/>
<input text="text" id="input8"/>    
var els = [
    [
        document.getElementById('input5'),
        document.getElementById('input6')
    ],
    [
        document.getElementById('input7'),
        document.getElementById('input8')
    ]
];    
els[0][0].id = 'input5';
els[0][1].id = 'input6';
els[1][0].id = 'input7';
els[1][1].id = 'input8';

http://jsfiddle.net/z4Un3/3/

Or, maybe this:

<input text="text" value="4" id="input5"/>
<input text="text" value="4" id="input6"/>
<br/>
<input text="text" value="2" id="input7"/>
<input text="text" value="4" id="input8"/>

var els = [
    [
        document.getElementById('input5'),
        document.getElementById('input6')
    ],
    [
        document.getElementById('input7'),
        document.getElementById('input8')
    ]
];

var result = [];

for (var i = 0; i < els.length; i++) {
    result[result.length] = els[0][i].value - els[1][i].value;
}

Which gives:

[2, 0]

In the console. If you want to output that to text, you can result.join(' ');, which would give you 2 0.

http://jsfiddle.net/z4Un3/6/

EDIT

And a working demonstration:

<input text="text" value="4" id="input5"/>
<input text="text" value="4" id="input6"/>
<br/>
<input text="text" value="2" id="input7"/>
<input text="text" value="4" id="input8"/>
<br/>
<input type="button" value="Add" onclick="add()"/>

// This would just go in a script block in the head
function add() {
    var els = [
        [
            document.getElementById('input5'),
            document.getElementById('input6')
        ],
        [
            document.getElementById('input7'),
            document.getElementById('input8')
        ]
    ];

    var result = [];

    for (var i = 0; i < els.length; i++) {
        result[result.length] = parseInt(els[0][i].value) - parseInt(els[1][i].value);
    }

    alert(result.join(' '));
}

http://jsfiddle.net/z4Un3/8/

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

This issue occurs because of the Gradle version changes, since your application uses old version of gradle, you need to update to new version.

This changes needs to be done in build.gradle file, have look at this link http://www.feelzdroid.com/2015/11/android-plugin-too-old-update-recent-version.html. to know how to update the gradle and detailed steps are provided. there.

Thans

Is it possible to delete an object's property in PHP?

This also works specially if you are looping over an object.

unset($object[$key])

Update

Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as array as mentioned by @CXJ . In that case you can use brackets instead

unset($object->{$key})

Eclipse: Enable autocomplete / content assist

  1. window->preferences->java->Editor->Contest Assist
  2. Enter in Auto activation triggers for java:
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._
  3. Apply and Close

other method:
type initial letter then ctrl+spacebar for auto-complete options.

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

Junit - run set up method once

Edit: I just found out while debugging that the class is instantiated before every test too. I guess the @BeforeClass annotation is the best here.

You can set up on the constructor too, the test class is a class after all. I'm not sure if it's a bad practice because almost all other methods are annotated, but it works. You could create a constructor like that:

public UT () {
    // initialize once here
}
@Test
// Some test here...

The ctor will be called before the tests because they are not static.

Format certain floating dataframe columns into percentage in pandas

replace the values using the round function, and format the string representation of the percentage numbers:

df['var2'] = pd.Series([round(val, 2) for val in df['var2']], index = df.index)
df['var3'] = pd.Series(["{0:.2f}%".format(val * 100) for val in df['var3']], index = df.index)

The round function rounds a floating point number to the number of decimal places provided as second argument to the function.

String formatting allows you to represent the numbers as you wish. You can change the number of decimal places shown by changing the number before the f.

p.s. I was not sure if your 'percentage' numbers had already been multiplied by 100. If they have then clearly you will want to change the number of decimals displayed, and remove the hundred multiplication.

jQuery detect if textarea is empty

This will check for empty textarea as well as will not allow only Spaces in textarea coz that looks empty too.

 var txt_msg = $("textarea").val();

 if (txt_msg.replace(/^\s+|\s+$/g, "").length == 0 || txt_msg=="") {
    return false;
  }

Hive: how to show all partitions of a table?

CLI has some limit when ouput is displayed. I suggest to export output into local file:

$hive -e 'show partitions table;' > partitions

Find what 2 numbers add to something and multiply to something

Here is how I would do that:

$sum = 5;
$product = 6;

$found = FALSE;
for ($a = 1; $a < $sum; $a++) {
  $b = $sum - $a;
  if ($a * $b == $product) {
    $found = TRUE;
    break;
  }
}

if ($found) {
  echo "The answer is a = $a, b = $b.";
} else {
  echo "There is no answer where a and b are both integers.";
}

Basically, start at $a = 1 and $b = $sum - $a, step through it one at a time since we know then that $a + $b == $sum is always true, and multiply $a and $b to see if they equal $product. If they do, that's the answer.

See it working

Whether that is the most efficient method is very much debatable.

Where to find Java JDK Source Code?

The JDK 1.6 I'm currently using on OSX Mountain Lion did not come with a src.zip either, and as far as i can tell there is no supported OSX JDK for 1.6 available anymore.

So I downloaded the OpenJDK source (using the links from the accepted answer (+1)) then ran:

cd ~/Downloads
mkdir jdk6src
cd jdk6src
tar xf ../openjdk-6-src-b27-26_oct_2012.tar.gz
cd jdk/src/share/classes
jar cf /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/src.jar *

(your file names and paths may vary...)

Associate that src.jar with the appropriate Java platform in your IDE and you should be good to go.

There are some discrepancies between the OpenJDK source and the JDK I'm currently running (line numbers don't match up in the debugger, for one), but if all you want is a zip/jar to point your IDE to for the relatively few cases you need to peek at some code to understand how something works, then this should do the trick.

How to use LINQ to select object with minimum or maximum property value

People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) <
    curMin.DateOfBirth ? x : curMin))

Show/Hide the console window of a C# console application

See my post here:

Show Console in Windows Application

You can make a Windows application (with or without the window) and show the console as desired. Using this method the console window never appears unless you explicitly show it. I use it for dual-mode applications that I want to run in either console or gui mode depending on how they are opened.

npm ERR cb() never called

There may be two possibilities=>

  1. Try to update your node js and npm.

  2. Permission issue => a. Move your solution on c drive in your respective user account b. Need to run bash or cmd as administrator.

Hope this will resolve your issue

Java: Converting String to and from ByteBuffer and associated problems

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

Change font-weight of FontAwesome icons?

The author appears to have taken a freemium approach to the font library and provides Black Tie to give different weights to the Font-Awesome library.

check android application is in foreground or not?

There is no global callback for this, but for each activity it is onStop(). You don't need to mess with an atomic int. Just have a global int with the number of started activities, in every activity increment it in onStart() and decrement it in onStop().

public class BaseActivity extends ActionBarActivity {
public static int count = 0;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}


@Override
protected void onStart() {
    super.onStart();
    count = count + 1;
    Log.d(TAG, "onStart" + count);
    if (count == 1) {

       Toast.makeText(getApplicationContext(), "online", Toast.LENGTH_SHORT).show();

    }

}



protected void onStop() {
    super.onStop();
    count = count - 1;
    if (count == 0) {

        Toast.makeText(getApplicationContext(), "offline", Toast.LENGTH_SHORT).show();

    }
}


}

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I'm familiar with this problem. The simplest workaround is to conditionally repeat the operation. I've never seen it fail twice in a row - unless there actually is an open file or a permissions issue, obviously!

rd /s /q c:\deleteme
if exist c:\deleteme rd /s /q c:\deleteme

How to use sys.exit() in Python

you didn't import sys in your code, nor did you close the () when calling the function... try:

import sys
sys.exit()

Return single column from a multi-dimensional array

Quite simple:

$input = array(
  array(
    'tag_name' => 'google'
  ),
  array(
    'tag_name' => 'technology'
  )
);

echo implode(', ', array_map(function ($entry) {
  return $entry['tag_name'];
}, $input));

http://3v4l.org/ltBZ0


and new in php v5.5.0, array_column:

echo implode(', ', array_column($input, 'tag_name'));

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

I had this problem with chrome when I was working on a WordPress site. I added this code

$_SERVER['HTTPS'] = false;

into the theme's functions.php file - it asks you to log in again when you save the file but once it's logged in it works straight away.

When to catch java.lang.Error?

And there are a couple of other cases where if you catch an Error, you have to rethrow it. For example ThreadDeath should never be caught, it can cause big problem is you catch it in a contained environment (eg. an application server) :

An application should catch instances of this class only if it must clean up after being terminated asynchronously. If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.

Sorting rows in a data table

I'm afraid you can't easily do an in-place sort of a DataTable like it sounds like you want to do.

What you can do is create a new DataTable from a DataView that you create from your original DataTable. Apply whatever sorts and/or filters you want on the DataView and then create a new DataTable from the DataView using the DataView.ToTable method:

   DataView dv = ft.DefaultView;
   dv.Sort = "occr desc";
   DataTable sortedDT = dv.ToTable();

Map implementation with duplicate keys

what about such a MultiMap impl?

public class MultiMap<K, V> extends HashMap<K, Set<V>> {
  private static final long serialVersionUID = 1L;
  private Map<K, Set<V>> innerMap = new HashMap<>();

  public Set<V> put(K key, V value) {
    Set<V> valuesOld = this.innerMap.get(key);
    HashSet<V> valuesNewTotal = new HashSet<>();
    if (valuesOld != null) {
      valuesNewTotal.addAll(valuesOld);
    }
    valuesNewTotal.add(value);
    this.innerMap.put(key, valuesNewTotal);
    return valuesOld;
  }

  public void putAll(K key, Set<V> values) {
    for (V value : values) {
      put(key, value);
    }
  }

  @Override
  public Set<V> put(K key, Set<V> value) {
    Set<V> valuesOld = this.innerMap.get(key);
    putAll(key, value);
    return valuesOld;
  }

  @Override
  public void putAll(Map<? extends K, ? extends Set<V>> mapOfValues) {
    for (Map.Entry<? extends K, ? extends Set<V>> valueEntry : mapOfValues.entrySet()) {
      K key = valueEntry.getKey();
      Set<V> value = valueEntry.getValue();
      putAll(key, value);
    }
  }

  @Override
  public Set<V> putIfAbsent(K key, Set<V> value) {
    Set<V> valueOld = this.innerMap.get(key);
    if (valueOld == null) {
      putAll(key, value);
    }
    return valueOld;
  }

  @Override
  public Set<V> get(Object key) {
    return this.innerMap.get(key);
  }

  @Override
  etc. etc. override all public methods size(), clear() .....

}

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

Tomcat also creates a ROOT directory at the same level as work/. ROOT/ also caches the old stuff. delete ROOT along with Catalina directory in work.

How can I use an array of function pointers?

You have a good example here (Array of Function pointers), with the syntax detailed.

int sum(int a, int b);
int subtract(int a, int b);
int mul(int a, int b);
int div(int a, int b);

int (*p[4]) (int x, int y);

int main(void)
{
  int result;
  int i, j, op;

  p[0] = sum; /* address of sum() */
  p[1] = subtract; /* address of subtract() */
  p[2] = mul; /* address of mul() */
  p[3] = div; /* address of div() */
[...]

To call one of those function pointers:

result = (*p[op]) (i, j); // op being the index of one of the four functions

Linker Error C++ "undefined reference "

Your header file Hash.h declares "what class hash should look like", but not its implementation, which is (presumably) in some other source file we'll call Hash.cpp. By including the header in your main file, the compiler is informed of the description of class Hash when compiling the file, but not how class Hash actually works. When the linker tries to create the entire program, it then complains that the implementation (toHash::insert(int, char)) cannot be found.

The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:

g++ -o main Hash.cpp main.cpp

will create the main program called "main".

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

FirebaseInstanceIdService is deprecated

And here the solution for C#/Xamarin.Android:

var token = await FirebaseInstallations.Instance.GetToken(forceRefresh: false).AsAsync<InstallationTokenResult>();

ViewDidAppear is not called when opening app from background

Swift 3.0 ++ version

In your viewDidLoad, register at notification center to listen to this opened from background action

NotificationCenter.default.addObserver(self, selector:#selector(doSomething), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
        

Then add this function and perform needed action

func doSomething(){
    //...
}

Finally add this function to clean up the notification observer when your view controller is destroyed.

deinit {
    NotificationCenter.default.removeObserver(self)
}

Bootstrap fullscreen layout with 100% height

_x000D_
_x000D_
<section class="min-vh-100 d-flex align-items-center justify-content-center py-3">
  <div class="container">
    <div class="row justify-content-between align-items-center">
    x
    x
    x
    </div>
  </div>
</section>
_x000D_
_x000D_
_x000D_

How do I commit case-sensitive only filename changes in Git?

If nothing worked use git rm filename to delete file from disk and add it back.

Fastest way to download a GitHub project

Another faster way of downloading a GitHub project would be to use the clone functionality with the --depth argument as:

git clone --depth=1 [email protected]:organization/your-repo.git

to perform a shallow clone.

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

How to stretch a table over multiple pages

You should \usepackage{longtable}.

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

Since the question on how to convert from ISO-8859-1 to UTF-8 is closed because of this one I'm going to post my solution here.

The problem is when you try to GET anything by using XMLHttpRequest, if the XMLHttpRequest.responseType is "text" or empty, the XMLHttpRequest.response is transformed to a DOMString and that's were things break up. After, it's almost impossible to reliably work with that string.

Now, if the content from the server is ISO-8859-1 you'll have to force the response to be of type "Blob" and later convert this to DOMSTring. For example:

var ajax = new XMLHttpRequest();
ajax.open('GET', url, true);
ajax.responseType = 'blob';
ajax.onreadystatechange = function(){
    ...
    if(ajax.responseType === 'blob'){
        // Convert the blob to a string
        var reader = new window.FileReader();
        reader.addEventListener('loadend', function() {
           // For ISO-8859-1 there's no further conversion required
           Promise.resolve(reader.result);
        });
        reader.readAsBinaryString(ajax.response);
    }
}

Seems like the magic is happening on readAsBinaryString so maybe someone can shed some light on why this works.

MVC [HttpPost/HttpGet] for Action

You cant combine this to attributes.

But you can put both on one action method but you can encapsulate your logic into a other method and call this method from both actions.

The ActionName Attribute allows to have 2 ActionMethods with the same name.

[HttpGet]
public ActionResult MyMethod()
{
    return MyMethodHandler();
}

[HttpPost]
[ActionName("MyMethod")]
public ActionResult MyMethodPost()
{
    return MyMethodHandler();
}

private ActionResult MyMethodHandler()
{
    // handle the get or post request
    return View("MyMethod");
}

Prevent wrapping of span or div

Looks like divs will not go outside of their body's width. Even within another div.

I threw this up to test (without a doctype though) and it does not work as thought.

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
}_x000D_
.slide {_x000D_
    float: left;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <div class="slide" style="background: #f00">Some content Some content Some content Some content Some content Some content</div>_x000D_
    <div class="slide" style="background: #ff0">More content More content More content More content More content More content</div>_x000D_
    <div class="slide" style="background: #f0f">Even More content! Even More content! Even More content!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What i am thinking is that the inner div's could be loaded through an iFrame, since that is another page and its content could be very wide.

Subtract two dates in Java

Edit 2018-05-28 I have changed the example to use Java 8's Time API:

LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();

Centering floating divs within another div

The following solution does not use inline blocks. However, it requires two helper divs:

  1. The content is floated
  2. The inner helper is floated (it stretches as much as the content)
  3. The inner helper is pushed right 50% (its left aligns with center of outer helper)
  4. The content is pulled left 50% (its center aligns with left of inner helper)
  5. The outer helper is set to hide the overflow

_x000D_
_x000D_
.ca-outer {_x000D_
  overflow: hidden;_x000D_
  background: #FFC;_x000D_
}_x000D_
.ca-inner {_x000D_
  float: left;_x000D_
  position: relative;_x000D_
  left: 50%;_x000D_
  background: #FDD;_x000D_
}_x000D_
.content {_x000D_
  float: left;_x000D_
  position: relative;_x000D_
  left: -50%;_x000D_
  background: #080;_x000D_
}_x000D_
/* examples */_x000D_
div.content > div {_x000D_
  float: left;_x000D_
  margin: 10px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #FFF;_x000D_
}_x000D_
ul.content {_x000D_
  padding: 0;_x000D_
  list-style-type: none;_x000D_
}_x000D_
ul.content > li {_x000D_
  margin: 10px;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="ca-outer">_x000D_
  <div class="ca-inner">_x000D_
    <div class="content">_x000D_
      <div>Box 1</div>_x000D_
      <div>Box 2</div>_x000D_
      <div>Box 3</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<hr>_x000D_
<div class="ca-outer">_x000D_
  <div class="ca-inner">_x000D_
    <ul class="content">_x000D_
      <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>_x000D_
      <li>Nullam efficitur nulla in libero consectetur dictum ac a sem.</li>_x000D_
      <li>Suspendisse iaculis risus ut dapibus cursus.</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

Facebook how to check if user has liked page and show content?

UPDATE 21/11/2012 @ALL : I have updated the example so that it works better and takes into accounts remarks from Chris Jacob and FB Best practices, have a look of working example here


Hi So as promised here is my answer using only javascript :

The content of the BODY of the page :

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
  FB.init({
    appId  : 'YOUR APP ID',
    status : true, 
    cookie : true, 
    xfbml  : true  
  });
</script>

<div id="container_notlike">
YOU DONT LIKE
</div>

<div id="container_like">
YOU LIKE
</div>

The CSS :

body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}

#container_notlike, #container_like {
    display:none
}

And finally the javascript :

$(document).ready(function(){

    FB.login(function(response) {
      if (response.session) {

          var user_id = response.session.uid;
          var page_id = "40796308305"; //coca cola
          var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
          var the_query = FB.Data.query(fql_query);

          the_query.wait(function(rows) {

              if (rows.length == 1 && rows[0].uid == user_id) {
                  $("#container_like").show();

                  //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.

              } else {
                  $("#container_notlike").show();
                  //and here you could get the content for a non liker in ajax...
              }
          });


      } else {
        // user is not logged in
      }
    });

});

So what what does it do ?

First it logins to FB (if you already have the USER ID, and you are sure your user is already logged in facebook, you can bypass the login stuff and replace response.session.uid with YOUR_USER_ID (from your rails app for example)

After that it makes a FQL query on the page_fan table, and the meaning is that if the user is a fan of the page, it returns the user id and otherwise it returns an empty array, after that and depending on the results its show a div or the other.

Also there is a working demo here : http://jsfiddle.net/dwarfy/X4bn6/

It's using the coca-cola page as an example, try it go and like/unlike the coca cola page and run it again ...

Finally some related docs :

FQL page_fan table

FBJS FB.Data.query

Don't hesitate if you have any question ..

Cheers

UPDATE 2

As stated by somebody, jQuery is required for the javascript version to work BUT you could easily remove it (it's only used for the document.ready and show/hide).

For the document.ready, you could wrap your code in a function and use body onload="your_function" or something more complicated like here : Javascript - How to detect if document has loaded (IE 7/Firefox 3) so that we replace document ready.

And for the show and hide stuff you could use something like : document.getElementById("container_like").style.display = "none" or "block" and for more reliable cross browser techniques see here : http://www.webmasterworld.com/forum91/441.htm

But jQuery is so easy :)

UPDATE

Relatively to the comment I posted here below here is some ruby code to decode the "signed_request" that facebook POST to your CANVAS URL when it fetches it for display inside facebook.

In your action controller :

decoded_request = Canvas.parse_signed_request(params[:signed_request])

And then its a matter of checking the decoded request and display one page or another .. (Not sure about this one, I'm not comfortable with ruby)

decoded_request['page']['liked']

And here is the related Canvas Class (from fbgraph ruby library) :

 class Canvas

    class << self
      def parse_signed_request(secret_id,request)
        encoded_sig, payload = request.split('.', 2)
        sig = ""
        urldecode64(encoded_sig).each_byte { |b|
          sig << "%02x" % b
        }
        data = JSON.parse(urldecode64(payload))
          if data['algorithm'].to_s.upcase != 'HMAC-SHA256'
          raise "Bad signature algorithm: %s" % data['algorithm']
        end
        expected_sig = OpenSSL::HMAC.hexdigest('sha256', secret_id, payload)
        if expected_sig != sig
          raise "Bad signature"
        end
        data
      end

      private

      def urldecode64(str)
        encoded_str = str.gsub('-','+').gsub('_','/')
        encoded_str += '=' while !(encoded_str.size % 4).zero?
        Base64.decode64(encoded_str)
      end
    end  

 end

Remove large .pack file created by git

One option:

run git gc manually to condense a number of pack files into one or a few pack files. This operation is persistent (i.e. the large pack file will retain its compression behavior) so it may be beneficial to compress a repository periodically with git gc --aggressive

Another option is to save the code and .git somewhere and then delete the .git and start again using this existing code, creating a new git repository (git init).

Best way to split string into lines

If you want to keep empty lines just remove the StringSplitOptions.

var result = input.Split(System.Environment.NewLine.ToCharArray());

DateDiff to output hours and minutes

Divide the Datediff in MS by the number of ms in a day, cast to Datetime, and then to time:

Declare @D1 datetime = '2015-10-21 14:06:22.780', @D2 datetime = '2015-10-21 14:16:16.893'

Select  Convert(time,Convert(Datetime, Datediff(ms,@d1, @d2) / 86400000.0))

How do I get bootstrap-datepicker to work with Bootstrap 3?

I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.

You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.

Here is my solution:

<div class="form-group row">
  <div class="col-xs-8">
    <label class="control-label">My Label</label>
    <div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
      <input class="form-control" type="text" readonly="" value="12-02-2012">
      <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
  </div>
</div>

CSS changes in datepicker.css on lines 176-177:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 34:

this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;

UPDATE

Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:

CSS changes in datepicker.css on lines 446-447:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 46:

 this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;

Finally, the JavaScript to enable the datepicker (with some options):

 $(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });

Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.

Are PostgreSQL column names case-sensitive?

if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:

select
    psat.schemaname,
    psat.relname,
    pa.attname,
    psat.relid
from
    pg_catalog.pg_stat_all_tables psat,
    pg_catalog.pg_attribute pa
where
    psat.relid = pa.attrelid

change schema name:

ALTER SCHEMA "XXXXX" RENAME TO xxxxx;

change table names:

ALTER TABLE xxxxx."AAAAA" RENAME TO aaaaa;

change column names:

ALTER TABLE xxxxx.aaaaa RENAME COLUMN "CCCCC" TO ccccc;

Any way to generate ant build.xml file automatically from Eclipse?

  • Select File > Export from main menu (or right click on the project name and select Export > Export…).
  • In the Export dialog, select General > Ant Buildfiles as follows: enter image description here

  • Click Next. In the Generate Ant Buildfilesscreen:

    • Check the project in list.
    • Uncheck the option "Create target to compile project using Eclipse compiler" - because we want to create a build file which is independent of Eclipse.
    • Leave the Name for Ant buildfile as default: build.xml

enter image description here

  • Click Finish, Eclipse will generate the build.xml file under project’s directory as follows:
    enter image description here
  • Double click on the build.xml file to open its content in Ant editor: enter image description here

source

How to align an image dead center with bootstrap

You should use

<div class="row fluid-img">
  <img class="col-lg-12 col-xs-12" src="src.png">
</div>

.fluid-img {
    margin: 60px auto;
}

@media( min-width: 768px ){
        .fluid-img {
            max-width: 768px;
        }
}
@media screen and (min-width: 768px) {
        .fluid-img {
            padding-left: 0;
            padding-right: 0;
        }
}

Insert HTML from CSS

No. The only you can do is to add content (and not an element) using :before or :after pseudo-element.

More information: http://www.w3.org/TR/CSS2/generate.html#before-after-content

How to use format() on a moment.js duration?

const duration = moment.duration(62, 'hours');
const n = 24 * 60 * 60 * 1000;
const days = Math.floor(duration / n);
const str = moment.utc(duration % n).format('H [h] mm [min] ss [s]');
console.log(`${days > 0 ? `${days} ${days == 1 ? 'day' : 'days'} ` : ''}${str}`);

Prints:

2 days 14 h 00 min 00 s

@AspectJ pointcut for all methods of a class with specific annotation

From Spring's AnnotationTransactionAspect:

/**
 * Matches the execution of any public method in a type with the Transactional
 * annotation, or any subtype of a type with the Transactional annotation.
 */
private pointcut executionOfAnyPublicMethodInAtTransactionalType() :
    execution(public * ((@Transactional *)+).*(..)) && within(@Transactional *);

What's the best way to cancel event propagation between nested ng-click calls?

This works for me:

<a href="" ng-click="doSomething($event)">Action</a>

this.doSomething = function($event) {
  $event.stopPropagation();
  $event.preventDefault();
};

Use table row coloring for cells in Bootstrap

Updated html for the newer bootstrap

    .table-hover > tbody > tr.danger:hover > td {
     background-color: red !important;
}
.table-hover > tbody > tr.warning:hover > td {
     background-color: yellow !important;
}
.table-hover > tbody > tr.success:hover > td {
     background-color: blue !important;
}

Xampp-mysql - "Table doesn't exist in engine" #1932

If you have copied & Pasted files from an old backup folder to new then its simple. Just copy the old ibdata1 into your new one. You can find it from \xampp\mysql\data

Plotting multiple lines, in different colors, with pandas dataframe

Another simple way is to use the pivot function to format the data as you need first.

df.plot() does the rest

df = pd.DataFrame([
    ['red', 0, 0],
    ['red', 1, 1],
    ['red', 2, 2],
    ['red', 3, 3],
    ['red', 4, 4],
    ['red', 5, 5],
    ['red', 6, 6],
    ['red', 7, 7],
    ['red', 8, 8],
    ['red', 9, 9],
    ['blue', 0, 0],
    ['blue', 1, 1],
    ['blue', 2, 4],
    ['blue', 3, 9],
    ['blue', 4, 16],
    ['blue', 5, 25],
    ['blue', 6, 36],
    ['blue', 7, 49],
    ['blue', 8, 64],
    ['blue', 9, 81],
], columns=['color', 'x', 'y'])

df = df.pivot(index='x', columns='color', values='y')

df.plot()

result

pivot effectively turns the data into:

enter image description here

Confusing "duplicate identifier" Typescript error message

remove this @types/express-validator from package.json file, then run npm install

Read More

Author message: This package has been deprecated This is a stub types definition for express-validator (https://github.com/ctavan/express-validator). express-validator provides its own type definitions, so you don't need @types/express-validator installed!

Switch statement for string matching in JavaScript

It may be easier. Try to think like this:

  • first catch a string between regular characters
  • after that find "case"

:

// 'www.dev.yyy.com'
// 'xxx.foo.pl'

var url = "xxx.foo.pl";

switch (url.match(/\..*.\./)[0]){
   case ".dev.yyy." :
          console.log("xxx.dev.yyy.com");break;

   case ".some.":
          console.log("xxx.foo.pl");break;
} //end switch

How do I remove/delete a folder that is not empty?

import os
import stat
import shutil

def errorRemoveReadonly(func, path, exc):
    excvalue = exc[1]
    if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
        # change the file to be readable,writable,executable: 0777
        os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  
        # retry
        func(path)
    else:
        # raiseenter code here

shutil.rmtree(path, ignore_errors=False, onerror=errorRemoveReadonly) 

If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised.enter code here

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

Your code is

urlpatterns = [
    url(r'^$', 'myapp.views.home'),
    url(r'^contact/$', 'myapp.views.contact'),
    url(r'^login/$', 'django.contrib.auth.views.login'),
]

change it to following as you're importing include() function :

urlpatterns = [
    url(r'^$', views.home),
    url(r'^contact/$', views.contact),
    url(r'^login/$', views.login),
]

How to change the data type of a column without dropping the column with query?

With SQL server 2008 and more, using this query:

ALTER TABLE [RecipeInventorys] ALTER COLUMN [RecipeName] varchar(550)

Shorter syntax for casting from a List<X> to a List<Y>?

To add to Sweko's point:

The reason why the cast

var listOfX = new List<X>();
ListOf<Y> ys = (List<Y>)listOfX; // Compile error: Cannot implicitly cast X to Y

is not possible is because the List<T> is invariant in the Type T and thus it doesn't matter whether X derives from Y) - this is because List<T> is defined as:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T> ... // Other interfaces

(Note that in this declaration, type T here has no additional variance modifiers)

However, if mutable collections are not required in your design, an upcast on many of the immutable collections, is possible, e.g. provided that Giraffe derives from Animal:

IEnumerable<Animal> animals = giraffes;

This is because IEnumerable<T> supports covariance in T - this makes sense given that IEnumerable implies that the collection cannot be changed, since it has no support for methods to Add or Remove elements from the collection. Note the out keyword in the declaration of IEnumerable<T>:

public interface IEnumerable<out T> : IEnumerable

(Here's further explanation for the reason why mutable collections like List cannot support covariance, whereas immutable iterators and collections can.)

Casting with .Cast<T>()

As others have mentioned, .Cast<T>() can be applied to a collection to project a new collection of elements casted to T, however doing so will throw an InvalidCastException if the cast on one or more elements is not possible (which would be the same behaviour as doing the explicit cast in the OP's foreach loop).

Filtering and Casting with OfType<T>()

If the input list contains elements of different, incompatable types, the potential InvalidCastException can be avoided by using .OfType<T>() instead of .Cast<T>(). (.OfType<>() checks to see whether an element can be converted to the target type, before attempting the conversion, and filters out incompatable types.)

foreach

Also note that if the OP had written this instead: (note the explicit Y y in the foreach)

List<Y> ListOfY = new List<Y>();

foreach(Y y in ListOfX)
{
    ListOfY.Add(y);
}

that the casting will also be attempted. However, if no cast is possible, an InvalidCastException will result.

Examples

For example, given the simple (C#6) class hierarchy:

public abstract class Animal
{
    public string Name { get;  }
    protected Animal(string name) { Name = name; }
}

public class Elephant :  Animal
{
    public Elephant(string name) : base(name){}
}

public class Zebra : Animal
{
    public Zebra(string name)  : base(name) { }
}

When working with a collection of mixed types:

var mixedAnimals = new Animal[]
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

foreach(Animal animal in mixedAnimals)
{
     // Fails for Zed - `InvalidCastException - cannot cast from Zebra to Elephant`
     castedAnimals.Add((Elephant)animal);
}

var castedAnimals = mixedAnimals.Cast<Elephant>()
    // Also fails for Zed with `InvalidCastException
    .ToList();

Whereas:

var castedAnimals = mixedAnimals.OfType<Elephant>()
    .ToList();
// Ellie

filters out only the Elephants - i.e. Zebras are eliminated.

Re: Implicit cast operators

Without dynamic, user defined conversion operators are only used at compile-time*, so even if a conversion operator between say Zebra and Elephant was made available, the above run time behaviour of the approaches to conversion wouldn't change.

If we add a conversion operator to convert a Zebra to an Elephant:

public class Zebra : Animal
{
    public Zebra(string name) : base(name) { }
    public static implicit operator Elephant(Zebra z)
    {
        return new Elephant(z.Name);
    }
}

Instead, given the above conversion operator, the compiler will be able to change the type of the below array from Animal[] to Elephant[], given that the Zebras can be now converted to a homogeneous collection of Elephants:

var compilerInferredAnimals = new []
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

Using Implicit Conversion Operators at run time

*As mentioned by Eric, the conversion operator can however be accessed at run time by resorting to dynamic:

var mixedAnimals = new Animal[] // i.e. Polymorphic collection
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

foreach (dynamic animal in mixedAnimals)
{
    castedAnimals.Add(animal);
}
// Returns Zed, Ellie

How to load all modules in a folder?

Python, include all files under a directory:

For newbies who just can't get it to work who need their hands held.

  1. Make a folder /home/el/foo and make a file main.py under /home/el/foo Put this code in there:

    from hellokitty import *
    spam.spamfunc()
    ham.hamfunc()
    
  2. Make a directory /home/el/foo/hellokitty

  3. Make a file __init__.py under /home/el/foo/hellokitty and put this code in there:

    __all__ = ["spam", "ham"]
    
  4. Make two python files: spam.py and ham.py under /home/el/foo/hellokitty

  5. Define a function inside spam.py:

    def spamfunc():
      print("Spammity spam")
    
  6. Define a function inside ham.py:

    def hamfunc():
      print("Upgrade from baloney")
    
  7. Run it:

    el@apollo:/home/el/foo$ python main.py 
    spammity spam
    Upgrade from baloney
    

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

There are a couple things missing, both from the solutions above and also from the Microsoft documentation. If you follow the link to the GitHub repository linked from the documentation above, you'll find the real solution.

I think the confusion lies with the fact that the default templates that many people are using do not contain the default constructor for Startup, so people don't necessarily know where the injected Configuration is coming from.

So, in Startup.cs, add:

 public IConfiguration Configuration { get; }
 public Startup(IConfiguration configuration) 
 {
     Configuration = configuration;
 }

and then in ConfigureServices method add what other people have said...

services.AddDbContext<ChromeContext>(options =>                    
    options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection")));

you also have to ensure that you've got your appsettings.json file created and have a connection strings section similar to this

{
  "ConnectionStrings": {
    "DatabaseConnection": "Server=MyServer;Database=MyDatabase;Persist Security Info=True;User ID=SA;Password=PASSWORD;MultipleActiveResultSets=True;"
  }
}

Of course, you will have to edit that to reflect your configuration.

Things to keep in mind. This was tested using Entity Framework Core 3 in a .Net Standard 2.1 project. I needed to add the nuget packages for: Microsoft.EntityFrameworkCore 3.0.0 Microsoft.EntityFrameworkCore.SqlServer 3.0.0 because that's what I'm using, and that's what is required to get access to the UseSqlServer.

How to convert an xml string to a dictionary?

I have modified one of the answers to my taste and to work with multiple values with the same tag for example consider the following xml code saved in XML.xml file

     <A>
        <B>
            <BB>inAB</BB>
            <C>
                <D>
                    <E>
                        inABCDE
                    </E>
                    <E>value2</E>
                    <E>value3</E>
                </D>
                <inCout-ofD>123</inCout-ofD>
            </C>
        </B>
        <B>abc</B>
        <F>F</F>
    </A>

and in python

import xml.etree.ElementTree as ET




class XMLToDictionary(dict):
    def __init__(self, parentElement):
        self.parentElement = parentElement
        for child in list(parentElement):
            child.text = child.text if (child.text != None) else  ' '
            if len(child) == 0:
                self.update(self._addToDict(key= child.tag, value = child.text.strip(), dict = self))
            else:
                innerChild = XMLToDictionary(parentElement=child)
                self.update(self._addToDict(key=innerChild.parentElement.tag, value=innerChild, dict=self))

    def getDict(self):
        return {self.parentElement.tag: self}

    class _addToDict(dict):
        def __init__(self, key, value, dict):
            if not key in dict:
                self.update({key: value})
            else:
                identical = dict[key] if type(dict[key]) == list else [dict[key]]
                self.update({key: identical + [value]})


tree = ET.parse('./XML.xml')
root = tree.getroot()
parseredDict = XMLToDictionary(root).getDict()
print(parseredDict)

the output is

{'A': {'B': [{'BB': 'inAB', 'C': {'D': {'E': ['inABCDE', 'value2', 'value3']}, 'inCout-ofD': '123'}}, 'abc'], 'F': 'F'}}

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

If you face this issue directly after a complete new installation on Windows:

It seems like the setup program already starts the http.exe process and blocks the initial port 80 but does not reflect this state in the control panel.

To verify, just test for a running server in your browser. Type into your browser address bar:

localhost

If this displays the XAMPP dashboard, you're fine. Alternatively, check the Task Manager for a running 'Apache HTTP Server' (httpd.exe) process.

You could stop the apache process with the xampp_stop.exe in your xampp base folder. Then, the XAMPP control panel should work as expected.

T-SQL split string

I had to write something like this recently. Here's the solution I came up with. It's generalized for any delimiter string and I think it would perform slightly better:

CREATE FUNCTION [dbo].[SplitString] 
    ( @string nvarchar(4000)
    , @delim nvarchar(100) )
RETURNS
    @result TABLE 
        ( [Value] nvarchar(4000) NOT NULL
        , [Index] int NOT NULL )
AS
BEGIN
    DECLARE @str nvarchar(4000)
          , @pos int 
          , @prv int = 1

    SELECT @pos = CHARINDEX(@delim, @string)
    WHILE @pos > 0
    BEGIN
        SELECT @str = SUBSTRING(@string, @prv, @pos - @prv)
        INSERT INTO @result SELECT @str, @prv

        SELECT @prv = @pos + LEN(@delim)
             , @pos = CHARINDEX(@delim, @string, @pos + 1)
    END

    INSERT INTO @result SELECT SUBSTRING(@string, @prv, 4000), @prv
    RETURN
END

Getting the first character of a string with $str[0]

My only doubt would be how applicable this technique would be on multi-byte strings, but if that's not a consideration, then I suspect you're covered. (If in doubt, mb_substr() seems an obviously safe choice.)

However, from a big picture perspective, I have to wonder how often you need to access the 'n'th character in a string for this to be a key consideration.

java - path to trustStore - set property doesn't work?

You have a typo - it is trustStore.

Apart from setting the variables with System.setProperty(..), you can also use

-Djavax.net.ssl.keyStore=path/to/keystore.jks

How to Access Hive via Python?

None of the answers demonstrate how to fetch and print the table headers. Modified the standard example from PyHive which is widely used and actively maintained.

from pyhive import hive
cursor = hive.connect(host="localhost", 
                      port=10000, 
                      username="shadan", 
                      auth="KERBEROS", 
                      kerberos_service_name="hive"
                      ).cursor()
cursor.execute("SELECT * FROM my_dummy_table LIMIT 10")
columnList = [desc[0] for desc in cursor.description]
headerStr = ",".join(columnList)
headerTuple = tuple(headerStr.split (",")
print(headerTuple)
print(cursor.fetchone())
print(cursor.fetchall())

How to install pip for Python 3 on Mac OS X?

Plus: when you install requests with python3, the command is:

pip3 install requests

not

pip install requests

Display Records From MySQL Database using JTable in Java

If you need to work a lot with database in your code and you know the structure of your table, I suggest you do it as follow:

First of all you can define a class which will help you to make objects capable of keeping your table rows data. For example in my project I created a class named Document.java to keep data of a single document from my database and I made an array list of these objects to keep data of my table which is gain by a query.

package financialdocuments;

import java.lang.*;
import java.util.HashMap;

/**
 *
 * @author Administrator
 */
public class Document {

 private int document_number; 
 private boolean document_type;
 private boolean document_status; 
 private StringBuilder document_date;
 private StringBuilder document_statement;
 private int document_code_number;
 private int document_employee_number;
 private int document_client_number;
 private String document_employee_name;
 private String document_client_name;
 private long document_amount;
 private long document_payment_amount;

 HashMap<Integer,Activity> document_activity_hashmap;


public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna){

    document_date = new StringBuilder(dd);
    document_date.setLength(10);
    document_date.setCharAt(4, '.');
    document_date.setCharAt(7, '.');
    document_statement = new StringBuilder(dst);
    document_statement.setLength(50);
    document_number = dn; 
    document_type = dt;
    document_status = ds;
    document_code_number = dcon;
    document_employee_number = den;
    document_client_number = dcln;
    document_amount = da;
    document_employee_name = dena;
    document_client_name = dcna;

    document_payment_amount = 0;

    document_activity_hashmap = new HashMap<>();

}

public Document(int dn,boolean dt,boolean ds, long dpa){

    document_number = dn; 
    document_type = dt;
    document_status = ds;

    document_payment_amount = dpa;

    document_activity_hashmap = new HashMap<>();

}

// Print document information 
public void printDocumentInformation (){
    System.out.println("Document Number:" + document_number); 
    System.out.println("Document Date:" + document_date); 
    System.out.println("Document Type:" + document_type); 
    System.out.println("Document Status:" + document_status); 
    System.out.println("Document Statement:" + document_statement); 
    System.out.println("Document Code Number:" + document_code_number); 
    System.out.println("Document Client Number:" + document_client_number); 
    System.out.println("Document Employee Number:" + document_employee_number); 
    System.out.println("Document Amount:" + document_amount); 
    System.out.println("Document Payment Amount:" + document_payment_amount); 
    System.out.println("Document Employee Name:" + document_employee_name); 
    System.out.println("Document Client Name:" + document_client_name); 

} 
} 

Second of all, you can define a class to handle your database needs. For example I defined a class named DataBase.java which handles my connections to the database and my needed queries. And I instantiated an objected of it in my main class.

package financialdocuments;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class DataBase {

/** 
 * 
 * Defining parameters and strings that are going to be used
 * 
 */
//Connection connect;

// Tables which their datas are extracted at the beginning 
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;

// Resultset Returned by queries 
private ResultSet result;

// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root"; 
String password = "";

public DataBase(){

    code_table = new HashMap<>();
    activity_table = new HashMap<>();
    client_table = new HashMap<>();
    employee_table = new HashMap<>();
    Initialize();

}

/**
 * Set variables and objects for this class.
 */
private void Initialize(){

    System.out.println("Loading driver..."); 
    try {
        Class.forName(driver);
        System.out.println("Driver loaded!"); 
    } catch (ClassNotFoundException e) { 
        throw new IllegalStateException("Cannot find the driver in the classpath!", e); 
    }

    System.out.println("Connecting database...");

try (Connection connect = DriverManager.getConnection(url,userName,password)) {
            System.out.println("Database connected!");
            //Get tables' information 
            selectCodeTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printCodeTableQueryArray();

            selectActivityTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printActivityTableQueryArray(); 

            selectClientTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printClientTableQueryArray();

            selectEmployeeTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printEmployeeTableQueryArray();

            connect.close();
    }catch (SQLException e) { 
        throw new IllegalStateException("Cannot connect the database!", e);
    }

} 

/**
 * Write Queries 
 * @param s
 * @return 
 */
public boolean insertQuery(String s){

    boolean ret = false;
    System.out.println("Loading driver..."); 
    try {
        Class.forName(driver);
        System.out.println("Driver loaded!"); 
    } catch (ClassNotFoundException e) { 
        throw new IllegalStateException("Cannot find the driver in the classpath!", e); 
    }

    System.out.println("Connecting database...");

try (Connection connect = DriverManager.getConnection(url,userName,password)) {
            System.out.println("Database connected!");
            //Set tables' information 
            try {
                Statement st = connect.createStatement();
                int val = st.executeUpdate(s);
                if(val==1){ 
                    System.out.print("Successfully inserted value");
                    ret = true;
                }
                else{ 
                    System.out.print("Unsuccessful insertion");
                    ret = false;
                }
                st.close();
            } catch (SQLException ex) {
                Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
            }
            connect.close();
    }catch (SQLException e) { 
        throw new IllegalStateException("Cannot connect the database!", e);
    } 
    return ret;
}

/**
 * Query needed to get code table's data
 * @param c
 * @return 
 */
private void selectCodeTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  code;");
        while (res.next()) {
                int id = res.getInt("code_number");
                String msg = res.getString("code_statement");
                code_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printCodeTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : code_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get activity table's data
 * @param c
 * @return 
 */
private void selectActivityTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  activity;");
        while (res.next()) {
                int id = res.getInt("activity_number");
                String msg = res.getString("activity_statement");
                activity_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printActivityTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get client table's data
 * @param c
 * @return 
 */
private void selectClientTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  client;");
        while (res.next()) {
                int id = res.getInt("client_number");
                String msg = res.getString("client_full_name");
                client_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printClientTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : client_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get activity table's data
 * @param c
 * @return 
 */
private void selectEmployeeTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  employee;");
        while (res.next()) {
                int id = res.getInt("employee_number");
                String msg = res.getString("employee_full_name");
                employee_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printEmployeeTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
} 
}

I hope this could be a little help.

What is default session timeout in ASP.NET?

It depends on either the configuration or programmatic change.
Therefore the most reliable way to check the current value is at runtime via code.

See the HttpSessionState.Timeout property; default value is 20 minutes.

You can access this propery in ASP.NET via HttpContext:

this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere

Disabling of EditText in Android

Set below properties in class:

editText.setFocusable(false);
editText.setEnabled(false);

It will work smoothly as you required.

How can I apply a function to every row/column of a matrix in MATLAB?

The accepted answer seems to be to convert to cells first and then use cellfun to operate over all of the cells. I do not know the specific application, but in general I would think using bsxfun to operate over the matrix would be more efficient. Basically bsxfun applies an operation element-by-element across two arrays. So if you wanted to multiply each item in an n x 1 vector by each item in an m x 1 vector to get an n x m array, you could use:

vec1 = [ stuff ];    % n x 1 vector
vec2 = [ stuff ];    % m x 1 vector
result = bsxfun('times', vec1.', vec2);

This will give you matrix called result wherein the (i, j) entry will be the ith element of vec1 multiplied by the jth element of vec2.

You can use bsxfun for all sorts of built-in functions, and you can declare your own. The documentation has a list of many built-in functions, but basically you can name any function that accepts two arrays (vector or matrix) as arguments and get it to work.

SQL Server equivalent of MySQL's NOW()?

getdate() 

is the direct equivalent, but you should always use UTC datetimes

getutcdate()

whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions

How can I set an SQL Server connection string?

They are a number of things to worry about when connecting to SQL Server on another machine.

  • Host/IP address of the machine
  • Initial catalog (database name)
  • Valid username/password

Very often SQL Server may be running as a default instance which means you can simply specify the hostname/IP address, but you may encounter a scenario where it is running as a named instance (SQL Server Express Edition for instance). In this scenario you'll have to specify the hostname/instance name.

convert string to number node.js

You do not have to install something.

parseInt(req.params.year, 10);

should work properly.

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

Running Facebook application on localhost

In your app's basic settings (https://developers.facebook.com/apps) under Settings->Basic->Select how your app integrates with Facebook...

Use "Site URL:" and "Mobile Site URL:" to hold your production and development URLs. Both sites will be allowed to authenticate. I'm just using Facebook for authentication so I don't need any of the mobile site redirection features. I usually change the "Mobile Site URL:" to my "localhost:12345" site while I'm testing the authentication, and then set it back to normal when I'm done.

Bitbucket fails to authenticate on git pull

I was facing same error, But I didn't need to change my password.

Just go to bitbucket->preferences->accounts select your account and check if your password is correct.

In my case, my password was messed up. Just corrected my password and it worked.

How do I parse JSON into an int?

I use a combination of json.get() and instanceof to read in values that might be either integers or integer strings.

These three test cases illustrate:

int val;
Object obj;
JSONObject json = new JSONObject();
json.put("number", 1);
json.put("string", "10");
json.put("other", "tree");

obj = json.get("number");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);

obj = json.get("string");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);

try {
    obj = json.get("other");
    val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
} catch (Exception e) {
    // throws exception
}

int *array = new int[n]; what is this function actually doing?

The new operator is allocating space for a block of n integers and assigning the memory address of that block to the int* variable array.

The general form of new as it applies to one-dimensional arrays appears as follows:

array_var = new Type[desired_size];

Warning message: In `...` : invalid factor level, NA generated

I have got similar issue which data retrieved from .xlsx file. Unfortunately, I could not find the proper answer here. I handled it on my own with dplyr as below which might help others:

#install.packages("xlsx")
library(xlsx)
extracted_df <- read.xlsx("test.xlsx", sheetName='Sheet1', stringsAsFactors=FALSE)
# Replace all NAs in a data frame with "G" character
extracted_df[is.na(extracted_df)] <- "G"

However, I could not handle it with the readxl package which does not have similar parameter to the stringsAsFactors. For the reason, I have moved to the xlsx package.

Best way to get user GPS location in background in Android

--Kotlin Version

package com.ps.salestrackingapp.Services

import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import android.util.Log

 class LocationService : Service() {
    private var mLocationManager: LocationManager? = null

    var mLocationListeners = arrayOf(LocationListener(LocationManager.GPS_PROVIDER), LocationListener(LocationManager.NETWORK_PROVIDER))

     class LocationListener(provider: String) : android.location.LocationListener {
        internal var mLastLocation: Location

        init {
            Log.e(TAG, "LocationListener $provider")
            mLastLocation = Location(provider)
        }

        override fun onLocationChanged(location: Location) {
            Log.e(TAG, "onLocationChanged: $location")
            mLastLocation.set(location)
            Log.v("LastLocation", mLastLocation.latitude.toString() +"  " + mLastLocation.longitude.toString())
        }

        override fun onProviderDisabled(provider: String) {
            Log.e(TAG, "onProviderDisabled: $provider")
        }

        override fun onProviderEnabled(provider: String) {
            Log.e(TAG, "onProviderEnabled: $provider")
        }

        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
            Log.e(TAG, "onStatusChanged: $provider")
        }
    }

    override fun onBind(arg0: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e(TAG, "onStartCommand")
        super.onStartCommand(intent, flags, startId)
        return Service.START_STICKY
    }

    override fun onCreate() {
        Log.e(TAG, "onCreate")
        initializeLocationManager()
        try {
            mLocationManager!!.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
                    mLocationListeners[1])
        } catch (ex: java.lang.SecurityException) {
            Log.i(TAG, "fail to request location update, ignore", ex)
        } catch (ex: IllegalArgumentException) {
            Log.d(TAG, "network provider does not exist, " + ex.message)
        }

        try {
            mLocationManager!!.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
                    mLocationListeners[0])
        } catch (ex: java.lang.SecurityException) {
            Log.i(TAG, "fail to request location update, ignore", ex)
        } catch (ex: IllegalArgumentException) {
            Log.d(TAG, "gps provider does not exist " + ex.message)
        }

    }

    override fun onDestroy() {
        Log.e(TAG, "onDestroy")
        super.onDestroy()
        if (mLocationManager != null) {
            for (i in mLocationListeners.indices) {
                try {
                    mLocationManager!!.removeUpdates(mLocationListeners[i])
                } catch (ex: Exception) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex)
                }

            }
        }
    }

    private fun initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager")
        if (mLocationManager == null) {
            mLocationManager = applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        }
    }

    companion object {
        private val TAG = "BOOMBOOMTESTGPS"
        private val LOCATION_INTERVAL = 1000
        private val LOCATION_DISTANCE = 0f
    }
}

ASP.net page without a code behind

I thought you could deploy just your .aspx page without the .aspx.cs so long as the DLL was in your bin. Part of the issue here is how visual studio .net works with .aspx pages.

Check it out here: Working with Single-File Web Forms Pages in Visual Studio .NET

I know for sure that VS2008 with asp.net MVC RC you don't have code-behind files for your views.

How to Batch Rename Files in a macOS Terminal?

To rename files, you can use the rename utility:

brew install rename

For example, to change a search string in all filenames in current directory:

rename -nvs searchword replaceword *

Remove the 'n' parameter to apply the changes.

More info: man rename

CSS table-cell equal width

Replace

  <div style="display:table;">
    <div style="display:table-cell;"></div>
    <div style="display:table-cell;"></div>
  </div>

with

  <table>
    <tr><td>content cell1</td></tr>
    <tr><td>content cell1</td></tr>
  </table>

Look at all the issues surrounding trying to make divs perform like tables. They had to add table-xxx to mimic table layouts

Tables are supported and work very well in all browsers. Why ditch them? the fact that they had to mimic them is proof they did their job and well.

In my opinion use the best tool for the job and if you want tabulated data or something that resembles tabulated data tables just work.

Very Late reply I know but worth voicing.

Setting query string using Fetch GET request

I know this is stating the absolute obvious, but I feel it's worth adding this as an answer as it's the simplest of all:

const orderId = 1;
fetch('http://myapi.com/orders?order_id=' + orderId);

Viewing localhost website from mobile device

Another option is http://localtunnel.me/ if you're running NodeJS

npm install -g localtunnel

Start a webserver on any local port such as 8080, and create a tunnel to that port:

lt -p 8080

which will return a public URL for your localhost at randomname.localtunnel.me. You can request your own subdomain if it's available:

lt -p 8080 -s myname

which will return myname.localtunnel.me

Use of def, val, and var in scala

There are three ways of defining things in Scala:

  • def defines a method
  • val defines a fixed value (which cannot be modified)
  • var defines a variable (which can be modified)

Looking at your code:

def person = new Person("Kumar",12)

This defines a new method called person. You can call this method only without () because it is defined as parameterless method. For empty-paren method, you can call it with or without '()'. If you simply write:

person

then you are calling this method (and if you don't assign the return value, it will just be discarded). In this line of code:

person.age = 20

what happens is that you first call the person method, and on the return value (an instance of class Person) you are changing the age member variable.

And the last line:

println(person.age)

Here you are again calling the person method, which returns a new instance of class Person (with age set to 12). It's the same as this:

println(person().age)

Can I add jars to maven 2 build classpath without installing them?

This is how we add or install a local jar

    <dependency>
        <groupId>org.example</groupId>
        <artifactId>iamajar</artifactId>
        <version>1.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/lib/iamajar.jar</systemPath>
    </dependency>

i gave some default groupId and artifactId because they are mandatory :)

Number input type that takes only integers?

The best you can achieve with HTML only (documentation):

_x000D_
_x000D_
<input type="number" min="0" step="1"/>
_x000D_
_x000D_
_x000D_

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

I use this script - it's antiquated, but effective in targeting a separate Internet Explorer 10 style sheet or JavaScript file that is included only if the browser is Internet Explorer 10, the same way you would with conditional comments. No jQuery or other plugin is required.

<script>
    /*@cc_on
      @if (@_jscript_version == 10)
          document.write(' <link type= "text/css" rel="stylesheet" href="your-ie10-styles.css" />');
      @end
    @*/
</script >

Making an API call in Python with an API that requires a bearer token

Here is full example of implementation in cURL and in Python - for authorization and for making API calls

cURL

1. Authorization

You have received access data like this:

Username: johndoe

Password: zznAQOoWyj8uuAgq

Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa

Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga

Which you can call in cURL like this:

curl -k -d "grant_type=password&username=Username&password=Password" \

                    -H "Authorization: Basic Base64(consumer-key:consumer-secret)" \

                       https://somedomain.test.com/token

or for this case it would be:

curl -k -d "grant_type=password&username=johndoe&password=zznAQOoWyj8uuAgq" \

                    -H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \

                      https://somedomain.test.com/token

Answer would be something like:

{
    "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
    "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
    "scope": "default",
    "token_type": "Bearer",
    "expires_in": 3600
}

2. Calling API

Here is how you call some API that uses authentication from above. Limit and offset are just examples of 2 parameters that API could implement. You need access_token from above inserted after "Bearer ".So here is how you call some API with authentication data from above:

curl -k -X GET "https://somedomain.test.com/api/Users/Year/2020/Workers?offset=1&limit=100" -H "accept: application/json" -H "Authorization: Bearer zz8d62zz-56zz-34zz-9zzf-azze1b8057f8"

Python

Same thing from above implemented in Python. I've put text in comments so code could be copy-pasted.

# Authorization data

import base64
import requests

username = 'johndoe'
password= 'zznAQOoWyj8uuAgq'
consumer_key = 'ggczWttBWlTjXCEtk3Yie_WJGEIa'
consumer_secret = 'uuzPjjJykiuuLfHkfgSdXLV98Ciga'
consumer_key_secret = consumer_key+":"+consumer_secret
consumer_key_secret_enc = base64.b64encode(consumer_key_secret.encode()).decode()

# Your decoded key will be something like:
#zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh


headersAuth = {
    'Authorization': 'Basic '+ str(consumer_key_secret_enc),
}

data = {
  'grant_type': 'password',
  'username': username,
  'password': password
}

## Authentication request

response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
j = response.json()

# When you print that response you will get dictionary like this:

    {
        "access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
        "refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
        "scope": "default",
        "token_type": "Bearer",
        "expires_in": 3600
    }

# You have to use `access_token` in API calls explained bellow.
# You can get `access_token` with j['access_token'].


# Using authentication to make API calls   

## Define header for making API calls that will hold authentication data

headersAPI = {
    'accept': 'application/json',
    'Authorization': 'Bearer '+j['access_token'],
}

### Usage of parameters defined in your API
params = (
    ('offset', '0'),
    ('limit', '20'),
)

# Making sample API call with authentication and API parameters data

response = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, params=params, verify=True)
api_response = response.json()

codeigniter model error: Undefined property

function user() { 

       parent::Model(); 

} 

=> class name is User, construct name is User.

function User() { 

       parent::Model(); 

} 

How to force a html5 form validation without submitting it via jQuery

var $myForm = $('#myForm ');
if (!$myForm[0].checkValidity()) {
  $('<input type="submit">').hide().appendTo($myForm).click().remove();
}

What is the scope of variables in JavaScript?

Modern Js, ES6+, 'const' and 'let'

You should be using block scoping for every variable you create, just like most other major languages. var is obsolete. This makes your code safer and more maintainable.

const should be used for 95% of cases. It makes it so the variable reference can't change. Array, object, and DOM node properties can change and should likely be const.

let should be be used for any variable expecting to be reassigned. This includes within a for loop. If you ever change value beyond initialization, use let.

Block scope means that the variable will only be available within the brackets in which it is declared. This extends to internal scopes, including anonymous functions created within your scope.

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

I solved by following these steps:

  • Right click in the project > Configure > Convert to Maven project
  • After the conversion, right click in the project > Maven > Update project

This fixes the "Deployment Assembly" settings of the project.

Get element type with jQuery

As Distdev alluded to, you still need to differentiate the input type. That is to say,

$(this).prev().prop('tagName');

will tell you input, but that doesn't differentiate between checkbox/text/radio. If it's an input, you can then use

$('#elementId').attr('type');

to tell you checkbox/text/radio, so you know what kind of control it is.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

Similar problem - same error message. I got the same message when trying to clone something from bitbucket with ssh. The problem was in my ssh configuration configured in the mercurial.ini: I used the wrong bitbucket username. After I corrected the user name things worked.

List of Java class file format major version numbers?

If you have a class file at build/com/foo/Hello.class, you can check what java version it is compiled at using the command:

javap -v build/com/foo/Hello.class | grep "major"

Example usage:

$ javap -v build/classes/java/main/org/aguibert/liberty/Book.class | grep major
  major version: 57

According to the table in the OP, major version 57 means the class file was compiled to JDK 13 bytecode level

Python's "in" set operator

Yes it can mean so, or it can be a simple iterator. For example: Example as iterator:

a=set(['1','2','3'])
for x in a:
 print ('This set contains the value ' + x)

Similarly as a check:

a=set('ILovePython')
if 'I' in a:
 print ('There is an "I" in here')

edited: edited to include sets rather than lists and strings

Django Template Variables and Javascript

Note, that if you want to pass a variable to an external .js script then you need to precede your script tag with another script tag that declares a global variable.

<script type="text/javascript">
    var myVar = "{{ myVar }}"
</script>

<script type="text/javascript" src="{% static "scripts/my_script.js" %}"></script>

data is defined in the view as usual in the get_context_data

def get_context_data(self, *args, **kwargs):
    context['myVar'] = True
    return context

How to delete an element from a Slice in Golang

This is a little strange to see but most answers here are dangerous and gloss over what they are actually doing. Looking at the original question that was asked about removing an item from the slice a copy of the slice is being made and then it's being filled. This ensures that as the slices are passed around your program you don't introduce subtle bugs.

Here is some code comparing users answers in this thread and the original post. Here is a go playground to mess around with this code in.

Append based removal

package main

import (
    "fmt"
)

func RemoveIndex(s []int, index int) []int {
    return append(s[:index], s[index+1:]...)
}

func main() {
    all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println("all: ", all) //[0 1 2 3 4 5 6 7 8 9]
    removeIndex := RemoveIndex(all, 5)

    fmt.Println("all: ", all) //[0 1 2 3 4 6 7 8 9 9]
    fmt.Println("removeIndex: ", removeIndex) //[0 1 2 3 4 6 7 8 9]

    removeIndex[0] = 999
    fmt.Println("all: ", all) //[999 1 2 3 4 6 7 9 9]
    fmt.Println("removeIndex: ", removeIndex) //[999 1 2 3 4 6 7 8 9]
}

In the above example you can see me create a slice and fill it manually with numbers 0 to 9. We then remove index 5 from all and assign it to remove index. However when we go to print out all now we see that it has been modified as well. This is because slices are pointers to an underlying array. Writing it out to removeIndex causes all to be modified as well with the difference being all is longer by one element that is no longer reachable from removeIndex. Next we change a value in removeIndex and we can see all gets modified as well. Effective go goes into some more detail on this.

The following example I won't go into but it does the same thing for our purposes. And just illustrates that using copy is no different.

package main

import (
    "fmt"
)

func RemoveCopy(slice []int, i int) []int {
    copy(slice[i:], slice[i+1:])
    return slice[:len(slice)-1]
}

func main() {
    all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println("all: ", all) //[0 1 2 3 4 5 6 7 8 9]
    removeCopy := RemoveCopy(all, 5)

    fmt.Println("all: ", all) //[0 1 2 3 4 6 7 8 9 9]
    fmt.Println("removeCopy: ", removeCopy) //[0 1 2 3 4 6 7 8 9]

    removeCopy[0] = 999
    fmt.Println("all: ", all) //[99 1 2 3 4 6 7 9 9]
    fmt.Println("removeCopy: ", removeCopy) //[999 1 2 3 4 6 7 8 9]
}

The questions original answer

Looking at the original question it does not modify the slice that it's removing an item from. Making the original answer in this thread the best so far for most people coming to this page.

package main

import (
    "fmt"
)

func OriginalRemoveIndex(arr []int, pos int) []int {
    new_arr := make([]int, (len(arr) - 1))
    k := 0
    for i := 0; i < (len(arr) - 1); {
        if i != pos {
            new_arr[i] = arr[k]
            k++
        } else {
            k++
        }
        i++
    }

    return new_arr
}

func main() {
    all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println("all: ", all) //[0 1 2 3 4 5 6 7 8 9]
    originalRemove := OriginalRemoveIndex(all, 5)

    fmt.Println("all: ", all) //[0 1 2 3 4 5 6 7 8 9]
    fmt.Println("originalRemove: ", originalRemove) //[0 1 2 3 4 6 7 8 9]

    originalRemove[0] = 999
    fmt.Println("all: ", all) //[0 1 2 3 4 5 6 7 8 9]
    fmt.Println("originalRemove: ", originalRemove) //[999 1 2 3 4 6 7 8 9]
}

As you can see this output acts as most people would expect and likely what most people want. Modification of originalRemove doesn't cause changes in all and the operation of removing the index and assigning it doesn't cause changes as well! Fantastic!

This code is a little lengthy though so the above can be changed to this.

A correct answer

package main

import (
    "fmt"
)

func RemoveIndex(s []int, index int) []int {
    ret := make([]int, 0)
    ret = append(ret, s[:index]...)
    return append(ret, s[index+1:]...)
}

func main() {
    all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println("all: ", all) //[0 1 2 3 4 5 6 7 8 9]
    removeIndex := RemoveIndex(all, 5)

    fmt.Println("all: ", all) //[0 1 2 3 4 5 6 7 8 9]
    fmt.Println("removeIndex: ", removeIndex) //[0 1 2 3 4 6 7 8 9]

    removeIndex[0] = 999
    fmt.Println("all: ", all) //[0 1 2 3 4 5 6 7 9 9]
    fmt.Println("removeIndex: ", removeIndex) //[999 1 2 3 4 6 7 8 9]
}

Almost identical to the original remove index solution however we make a new slice to append to before returning.

Only variables should be passed by reference

Php 7 compatible proper usage:

$fileName      = 'long.file.name.jpg';
$tmp           = explode('.', $fileName);
$fileExtension = end($tmp);

echo $fileExtension;
// jpg

Trigger to fire only if a condition is met in SQL Server

For triggers in general, you need to use a cursor to handle inserts or updates of multiple rows. For example:

DECLARE @Attribute;
DECLARE @ParameterValue;
DECLARE mycursor CURSOR FOR SELECT Attribute, ParameterValue FROM inserted;
OPEN mycursor;
FETCH NEXT FROM mycursor into @Attribute, @ParameterValue;
WHILE @@FETCH_STATUS = 0
BEGIN

If @Attribute LIKE 'NoHist_%'
      Begin
          Return
      End

etc.

FETCH NEXT FROM mycursor into @Attribute, @ParameterValue;
END

Triggers, at least in SQL Server, are a big pain and I avoid using them at all.

(HTML) Download a PDF file instead of opening them in browser when clicked

I needed to do this for files created with dynamic names in a particular folder and served by IIS.

This worked for me:

  • In IIS, go that folder and double click HTTP Response Headers.
  • Add a new header with the following info:

    Name: content-disposition Value: attachment

(from: http://forums.iis.net/t/1175103.aspx?add+CustomHeaders+only+for+certain+file+types+)

Setting session variable using javascript

You can use

sessionStorage.SessionName = "SessionData" ,

sessionStorage.getItem("SessionName") and

sessionStorage.setItem("SessionName","SessionData");

See the supported browsers on http://caniuse.com/namevalue-storage

Form onSubmit determine which submit button was pressed

Not in the submit event handler itself, no.

But what you can do is add click handlers to each submit which will inform the submit handler as to which was clicked.

Here's a full example (using jQuery for brevity)

<html>
<head>
  <title>Test Page</title>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript">

  jQuery(function($) {
      var submitActor = null;
      var $form = $('#test');
      var $submitActors = $form.find('input[type=submit]');

      $form.submit(function(event) {
          if (null === submitActor) {
              // If no actor is explicitly clicked, the browser will
              // automatically choose the first in source-order
              // so we do the same here
              submitActor = $submitActors[0];
          }

          console.log(submitActor.name);
          // alert(submitActor.name);

          return false;
      });

      $submitActors.click(function(event) {
          submitActor = this;
      });
  });

  </script>
</head>

<body>

  <form id="test">

    <input type="text" />

    <input type="submit" name="save" value="Save" />
    <input type="submit" name="saveAndAdd" value="Save and add another" />

  </form>

</body>
</html>