Programs & Examples On #Google analytics

Google Analytics is a free web analytics solution provided by Google, featuring several client-side APIs, as well as REST APIs for data export and for management.

Tracking Google Analytics Page Views with AngularJS

Just a quick addition. If you're using the new analytics.js, then:

var track = function() {     
 ga('send', 'pageview', {'page': $location.path()});                
};

Additionally one tip is that google analytics will not fire on localhost. So if you are testing on localhost, use the following instead of the default create (full documentation)

ga('create', 'UA-XXXX-Y', {'cookieDomain': 'none'});

How to remove a web site from google analytics

Feb 2016 version: Admin tab, then select Property in the middle column, click Property Settings, then the Move To Trash Can button at the top right. No need to delete individual views.

Which browsers support <script async="async" />?

From your referenced page:

http://googlecode.blogspot.com/2009/12/google-analytics-launches-asynchronous.html

Firefox 3.6 is the first browser to officially offer support for this new feature. If you're curious, here are more details on the official HTML5 async specification.

Best place to insert the Google Analytics code

As google says:

Paste it into your web page, just before the closing </head> tag.

One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the <head> section, and we recommend placing the snippet at the bottom of the <head> section for best performance

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Close Xcode, rename the folder. Then make a new folder with the previous name. Run the project, stop the project. Delete the new folder, rename old folder and re-run.

My iPad Pro simulator is affected with this issue. Its something that makes me upset, so much hard work... hopefully Google works through bugs for the next SDK.

Can you test google analytics on a localhost address?

For those using google tag manager to integrate with google analytics events you can do what the guys mentioned about to set the cookies flag to none from GTM it self

enter image description here

open GTM > variables > google analytics variables > and set the cookies tag to none

Number of visitors on a specific page

As Blexy already answered, go to "Behavior > Site Content > All Pages".

Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:

                                                     sidebar

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

varvy.com (100/100 Google page speed insight) loads google analitycs code only if user make a scroll of the page:

var fired = false;

window.addEventListener("scroll", function(){
    if ((document.documentElement.scrollTop != 0 && fired === false) || (document.body.scrollTop != 0 && fired === false)) {

        (function(i,s,o,g,r,a,m{i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-XXXXXXXX-X', 'auto');
        ga('send', 'pageview');

        fired = true;
    }
}, true);

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

I solved the same problem here is simple solution: when you create firebase connection follow these guidelines:

  • Add your application name in firebase

  • Add your application pakage name (write same pakage name ,you are using in app)

  • when firebase make google-services.json file just download it and paste it in your app folder

  • Sync your project Problem is solved :)

    Thank you

Format the date using Ruby on Rails

@CMW's answer is bang on the money. I've added this answer as an example of how to configure an initializer so that both Date and Time objects get the formatting

config/initializers/time_formats.rb

date_formats = {
  concise: '%d-%b-%Y' # 13-Jan-2014
}

Time::DATE_FORMATS.merge! date_formats
Date::DATE_FORMATS.merge! date_formats

Also the following two commands will iterate through all the DATE_FORMATS in your current environment, and display today's date and time in each format:

Date::DATE_FORMATS.keys.each{|k| puts [k,Date.today.to_s(k)].join(':- ')}
Time::DATE_FORMATS.keys.each{|k| puts [k,Time.now.to_s(k)].join(':- ')}

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

How to create an integer-for-loop in Ruby?

Try Below Simple Ruby Magics :)

(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }

How do I find an element that contains specific text in Selenium WebDriver (Python)?

In the HTML which you have provided:

<div>My Button</div>

The text My Button is the innerHTML and have no whitespaces around it so you can easily use text() as follows:

my_element = driver.find_element_by_xpath("//div[text()='My Button']")

Note: text() selects all text node children of the context node


Text with leading/trailing spaces

In case the relevant text containing whitespaces either in the beginning:

<div>   My Button</div>

or at the end:

<div>My Button   </div>

or at both the ends:

<div> My Button </div>

In these cases you have two options:

  • You can use contains() function which determines whether the first argument string contains the second argument string and returns boolean true or false as follows:

      my_element = driver.find_element_by_xpath("//div[contains(., 'My Button')]")
    
  • You can use normalize-space() function which strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string as follows:

      driver.find_element_by_xpath("//div[normalize-space()='My Button']]")
    

XPath expression for variable text

In case the text is a variable, you can use:

foo= "foo_bar"
my_element = driver.find_element_by_xpath("//div[.='" + foo + "']")

How do I catch a PHP fatal (`E_ERROR`) error?

PHP doesn't provide conventional means for catching and recovering from fatal errors. This is because processing should not typically be recovered after a fatal error. String matching an output buffer (as suggested by the original post the technique described on PHP.net) is definitely ill-advised. It's simply unreliable.

Calling the mail() function from within an error handler method prove to be problematic, too. If you had a lot of errors, your mail server would be loaded with work, and you could find yourself with a gnarly inbox. To avoid this, you might consider running a cron to scan error logs periodically and send notifications accordingly. You might also like to look into system monitoring software, such as Nagios.


To speak to the bit about registering a shutdown function:

It's true that you can register a shutdown function, and that's a good answer.

The point here is that we typically shouldn't try to recover from fatal errors, especially not by using a regular expression against your output buffer. I was responding to the accepted answer, which linked to a suggestion on php.net which has since been changed or removed.

That suggestion was to use a regex against the output buffer during exception handling, and in the case of a fatal error (detected by the matching against whatever configured error text you might be expecting), try to do some sort of recovery or continued processing. That would not be a recommended practice (I believe that's why I can't find the original suggestion, too. I'm either overlooking it, or the php community shot it down).

It might be worth noting that the more recent versions of PHP (around 5.1) seem to call the shutdown function earlier, before the output buffering callback is envoked. In version 5 and earlier, that order was the reverse (the output buffering callback was followed by the shutdown function). Also, since about 5.0.5 (which is much earlier than the questioner's version 5.2.3), objects are unloaded well before a registered shutdown function is called, so you won't be able to rely on your in-memory objects to do much of anything.

So registering a shutdown function is fine, but the sort of tasks that ought to be performed by a shutdown function are probably limited to a handful of gentle shutdown procedures.

The key take-away here is just some words of wisdom for anyone who stumbles upon this question and sees the advice in the originally accepted answer. Don't regex your output buffer.

How do I get the web page contents from a WebView?

If you are working on kitkat and above, you can use the chrome remote debugging tools to find all the requests and responses going in and out of your webview and also the the html source code of the page viewed.

https://developer.chrome.com/devtools/docs/remote-debugging

Checkbox value true/false

Use Checked = true

$("#checkbox1").prop('checked', true);

Note: I am not clear whether you want to onclick/onchange event on checkbox. is(":checked", function(){}) is a wrong in the question.

if else condition in blade file (laravel 5.3)

No curly braces required you can directly write

@if($user->status =='waiting')         
      <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>         
@else
      <td>{{ $user->status }}</td>        
@endif

How can I decrease the size of Ratingbar?

If you want to show the rating bar in small size, then just copy and paste this code in your project.

  <RatingBar
    android:id="@+id/MyRating"
    style="?android:attr/ratingBarStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/getRating"
    android:isIndicator="true"
    android:numStars="5"
    android:stepSize="0.1" />

Set content of HTML <span> with Javascript

This is standards compliant and cross-browser safe.

Example: http://jsfiddle.net/kv9pw/

var span = document.getElementById('someID');

while( span.firstChild ) {
    span.removeChild( span.firstChild );
}
span.appendChild( document.createTextNode("some new content") );

Slack URL to open a channel from browser

The URI to open a specific channel in Slack app is:

slack://channel?id=<CHANNEL-ID>&team=<TEAM-ID>

You will probably need these resources of the Slack API to get IDs of your team and channel:

Here's the full documentation from Slack

Execute a SQL Stored Procedure and process the results

At the top of your .vb file:

Imports System.data.sqlclient

Within your code:

'Setup SQL Command
Dim CMD as new sqlCommand("StoredProcedureName")
CMD.parameters("@Parameter1", sqlDBType.Int).value = Param_1_value

Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure

Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300

'Fill the dataset
Dim DS as DataSet    
adapter.Fill(ds)
connection.Close()   

'Now, read through your data:
For Each DR as DataRow in DS.Tables(0).rows
    Msgbox("The value in Column ""ColumnName1"": " & cstr(DR("ColumnName1")))
next

Now that the basics are out of the way,

I highly recommend abstracting the actual SqlCommand Execution out into a function.

Here is a generic function that I use, in some form, on various projects:

''' <summary>Executes a SqlCommand on the Main DB Connection. Usage: Dim ds As DataSet = ExecuteCMD(CMD)</summary>'''
''' <param name="CMD">The command type will be determined based upon whether or not the commandText has a space in it. If it has a space, it is a Text command ("select ... from .."),''' 
''' otherwise if there is just one token, it's a stored procedure command</param>''''
Function ExecuteCMD(ByRef CMD As SqlCommand) As DataSet
    Dim connectionString As String = ConfigurationManager.ConnectionStrings("main").ConnectionString
    Dim ds As New DataSet()

    Try
        Dim connection As New SqlConnection(connectionString)
        CMD.Connection = connection

        'Assume that it's a stored procedure command type if there is no space in the command text. Example: "sp_Select_Customer" vs. "select * from Customers"
        If CMD.CommandText.Contains(" ") Then
            CMD.CommandType = CommandType.Text
        Else
            CMD.CommandType = CommandType.StoredProcedure
        End If

        Dim adapter As New SqlDataAdapter(CMD)
        adapter.SelectCommand.CommandTimeout = 300

        'fill the dataset
        adapter.Fill(ds)
        connection.Close()

    Catch ex As Exception
        ' The connection failed. Display an error message.
        Throw New Exception("Database Error: " & ex.Message)
    End Try

    Return ds
End Function

Once you have that, your SQL Execution + reading code is very simple:

'----------------------------------------------------------------------'
Dim CMD As New SqlCommand("GetProductName")
CMD.Parameters.Add("@productID", SqlDbType.Int).Value = ProductID
Dim DR As DataRow = ExecuteCMD(CMD).Tables(0).Rows(0)
MsgBox("Product Name: " & cstr(DR(0)))
'----------------------------------------------------------------------'

Editing an item in a list<T>

class1 item = lst[index];
item.foo = bar;

What do 3 dots next to a parameter type mean in Java?

Just think of it as the keyword params in C#, if you are coming from that background :)

CSS width of a <span> tag

I would use the padding attribute. This will allow you add a set number of pixels to either side of the element without the element loosing its span qualities:

  • It won't become a block
  • It will float as you expect

This method will only add to the padding however, so if you change the length of the content (from Categories to Tags, for example) the size of the content will change and the overall size of the element will change as well. But if you really want to set a rigid size, you should do as mentioned above and use a div.

See the box model for more details about the box model, content, padding, margin, etc.

Open Sublime Text from Terminal in macOS

You can just add an alias

alias subl='/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl'

Then you should be able to open a folder or whatever with

subl <path>

Wait one second in running program

use dataGridView1.Refresh(); :)

Maintain/Save/Restore scroll position when returning to a ListView

BEST SOLUTION IS:

// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());

// ...

// restore index and position
mList.post(new Runnable() {
    @Override
    public void run() {
      mList.setSelectionFromTop(index, top);
   }
});

YOU MUST CALL IN POST AND IN THREAD!

Automatic prune with Git fetch or pull

If you want to always prune when you fetch, I can suggest to use Aliases.

Just type git config -e to open your editor and change the configuration for a specific project and add a section like

[alias]
pfetch = fetch --prune   

the when you fetch with git pfetch the prune will be done automatically.

Python error message io.UnsupportedOperation: not readable

Use a+ to open a file for reading, writing as well as create it if it doesn't exist.

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. -Python file modes

with open('"File.txt', 'a+') as file:
    print(file.readlines())
    file.write("test")

Note: opening file in a with block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

What is the C# Using block and why should I use it?

Using calls Dispose() after the using-block is left, even if the code throws an exception.

So you usually use using for classes that require cleaning up after them, like IO.

So, this using block:

using (MyClass mine = new MyClass())
{
  mine.Action();
}

would do the same as:

MyClass mine = new MyClass();
try
{
  mine.Action();
}
finally
{
  if (mine != null)
    mine.Dispose();
}

Using using is way shorter and easier to read.

MVC 3: How to render a view without its layout page when loaded via ajax?

For a Ruby on Rails application, I was able to prevent a layout from loading by specifying render layout: false in the controller action that I wanted to respond with ajax html.

Python webbrowser.open() to open Chrome browser

Worked for me in windows

Put the path of your chrome application and do not forget to put th %s at the end. I am still trying to open the browser with html code without saving the file... I will add the code when I'll find how.

import webbrowser
chromedir= "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
webbrowser.get(chromedir).open("http://pythonprogramming.altervista.org")

>>> link to: [a page from my blog where I explain this]<<<

How to push object into an array using AngularJS

'Push' is for arrays.

You can do something like this:

app.js:

(function() {

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

 app.controller('myController', ['$scope', function($scope) {

    $scope.myText = "Let's go";

    $scope.arrayText = [
            'Hello',
            'world'
        ];

    $scope.addText = function() {
        $scope.arrayText.push(this.myText);
    }

 }]);

})();

index.html

<!doctype html>
<html ng-app="myApp">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
    <div>
      <form ng-controller="myController" ng-submit="addText()">
           <input type="text" ng-model="myText" value="Lets go">
           <input type="submit" id="submit"/>
           <pre>list={{arrayText}}</pre>
      </form>
    </div>
  </body>
</html>

best way to create object

Depends on your requirment, but the most effective way to create is:

 Product obj = new Product
            {
                ID = 21,
                Price = 200,
                Category = "XY",
                Name = "SKR",
            };

How to use JQuery with ReactJS

To install it, just run the command

npm install jquery

or

yarn add jquery

then you can import it in your file like

import $ from 'jquery';

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

As mentioned in other answers, you'll always get the QuotaExceededError in Safari Private Browser Mode on both iOS and OS X when localStorage.setItem (or sessionStorage.setItem) is called.

One solution is to do a try/catch or Modernizr check in each instance of using setItem.

However if you want a shim that simply globally stops this error being thrown, to prevent the rest of your JavaScript from breaking, you can use this:

https://gist.github.com/philfreo/68ea3cd980d72383c951

// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
// to avoid the entire page breaking, without having to do a check at each usage of Storage.
if (typeof localStorage === 'object') {
    try {
        localStorage.setItem('localStorage', 1);
        localStorage.removeItem('localStorage');
    } catch (e) {
        Storage.prototype._setItem = Storage.prototype.setItem;
        Storage.prototype.setItem = function() {};
        alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
    }
}

React JS Error: is not defined react/jsx-no-undef

This happens to me occasionally, usually it's just a simple oversight. Just pay attention to details, simple typos, etc. For example when copy/pasting import statements, like this: enter image description here

Angular 2 - NgFor using numbers instead collections

I couldn't bear the idea of allocating an array for plain repeat of components, so I've written a structural directive. In simplest form, that doesn't make the index available to the template, it looks like this:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({ selector: '[biRepeat]' })
export class RepeatDirective {

  constructor( private templateRef: TemplateRef<any>,
             private viewContainer: ViewContainerRef) { }

  @Input('biRepeat') set count(c:number) {
    this.viewContainer.clear();
    for(var i=0;i<c;i++) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }
}

http://plnkr.co/edit/bzoNuL7w5Ub0H5MdYyFR?p=preview

Insert Data Into Temp Table with Query

Fastest way to do this is using "SELECT INTO" command e.g.

SELECT * INTO #TempTableName
FROM....

This will create a new table, you don't have to create it in advance.

cURL POST command line on WINDOWS RESTful service

Another Alternative for the command line that is easier than fighting with quotation marks is to put the json into a file, and use the @ prefix of curl parameters, e.g. with the following in json.txt:

{ "syncheader" : {
    "servertimesync" : "20131126121749",
    "deviceid" : "testDevice"
  }
}

then in my case I issue:

curl localhost:9000/sync -H "Content-type:application/json" -X POST -d @json.txt

Keeps the json more readable too.

How can git be installed on CENTOS 5.5?

yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel

Get the required version of GIT from https://www.kernel.org/pub/software/scm/git/ 

wget https://www.kernel.org/pub/software/scm/git/{version.gz}

tar -xzvf git-version.gz

cd git-version

./configure

make

make install

for-in statement

TypeScript isn't giving you a gun to shoot yourself in the foot with.

The iterator variable is a string because it is a string, full stop. Observe:

var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';

for(var key in obj) {
    console.log('Type: ' + typeof key);
    console.log(key + ' => ' + obj[key]);
}

How many key/value pairs are in obj now? 6, more or less? No, 3, and all of the keys are strings:

Type: string
0 => zero point zero
Type: string
[object Object] => this obj; 
Type: string
undefined => the literal string "undefined" 

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

What's is the difference between include and extend in use case diagram?

I like to think of "includes" as a necessary prerequisite/accompaniment of the base use case. This means that the base use case cannot be considered complete without the use case it includes. I'll give the example of an e-commerce website that sells items to customers. There's no way you can pay for an item without first selecting that item and putting it in the cart. This implies that the use case "Pay for Item" includes "select item".

There are varying uses of extends but I like to think of it as an alternative that may or may not be used. For example - still on the e-commerce site. When paying for an item, you may choose to pay on delivery, pay using paypal or pay by card. These are all alternatives to the "pay for item" use case. I may choose any of these options depending on my preference.

For more clarity and the rules surrounding use cases, read my article here:

http://businessanalystlearnings.com/ba-techniques/2013/2/20/use-case-diagram-the-basics

How do I use MySQL through XAMPP?

Changing XAMPP Default Port: If you want to get XAMPP up and running, you should consider changing the port from the default 80 to say 7777.

  • In the XAMPP Control Panel, click on the Apache – Config button which is located next to the ‘Logs’ button.

  • Select ‘Apache (httpd.conf)’ from the drop down. (Notepad should open)

  • Do Ctrl+F to find ’80’ and change line Listen 80 to Listen 7777

  • Find again and change line ServerName localhost:80 to ServerName localhost:7777

  • Save and re-start Apache. It should be running by now.

The only demerit to this technique is, you have to explicitly include the port number in the localhost url. Rather than http://localhost it becomes http://localhost:7777.

HTML Canvas Full Screen

The javascript has

var canvasW     = 640;
var canvasH     = 480;

in it. Try changing those as well as the css for the canvas.

Or better yet, have the initialize function determine the size of the canvas from the css!

in response to your edits, change your init function:

function init()
{
    canvas = document.getElementById("mainCanvas");
    canvas.width = document.body.clientWidth; //document.width is obsolete
    canvas.height = document.body.clientHeight; //document.height is obsolete
    canvasW = canvas.width;
    canvasH = canvas.height;

    if( canvas.getContext )
    {
        setup();
        setInterval( run , 33 );
    }
}

Also remove all the css from the wrappers, that just junks stuff up. You have to edit the js to get rid of them completely though... I was able to get it full screen though.

html, body {
    overflow: hidden;
}

Edit: document.width and document.height are obsolete. Replace with document.body.clientWidth and document.body.clientHeight

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

how to fix java.lang.IndexOutOfBoundsException

This error happens because your list lstpp is empty (Nothing at index 0). So either there is a bug in your getResult() function, or the empty list is normal and you need to handle this case (By checking the size of the list before, or catching the exception).

Custom Date/Time formatting in SQL Server

Not answering your question specifically, but isn't that something that should be handled by the presentation layer of your application. Doing it the way you describe creates extra processing on the database end as well as adding extra network traffic (assuming the database exists on a different machine than the application), for something that could be easily computed on the application side, with more rich date processing libraries, as well as being more language agnostic, especially in the case of your first example which contains the abbreviated month name. Anyway the answers others give you should point you in the right direction if you still decide to go this route.

How to search JSON data in MySQL?

  1. Storing JSON in database violates the first normal form.

    The best thing you can do is to normalize and store features in another table. Then you will be able to use a much better looking and performing query with joins. Your JSON even resembles the table.

  2. Mysql 5.7 has builtin JSON functionality:
    http://mysqlserverteam.com/mysql-5-7-lab-release-json-functions-part-2-querying-json-data/

  3. Correct pattern is:

    WHERE  `attribs_json` REGEXP '"1":{"value":[^}]*"3"[^}]*}'
    

    [^}] will match any character except }

How do I determine the size of an object in Python?

The Pympler package's asizeof module can do this.

Use as follows:

from pympler import asizeof
asizeof.asizeof(my_object)

Unlike sys.getsizeof, it works for your self-created objects. It even works with numpy.

>>> asizeof.asizeof(tuple('bcd'))
200
>>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'})
400
>>> asizeof.asizeof({})
280
>>> asizeof.asizeof({'foo':'bar'})
360
>>> asizeof.asizeof('foo')
40
>>> asizeof.asizeof(Bar())
352
>>> asizeof.asizeof(Bar().__dict__)
280
>>> A = rand(10)
>>> B = rand(10000)
>>> asizeof.asizeof(A)
176
>>> asizeof.asizeof(B)
80096

As mentioned,

The (byte)code size of objects like classes, functions, methods, modules, etc. can be included by setting option code=True.

And if you need other view on live data, Pympler's

module muppy is used for on-line monitoring of a Python application and module Class Tracker provides off-line analysis of the lifetime of selected Python objects.

How to export a MySQL database to JSON?

I know this is old, but for the sake of somebody looking for an answer...

There's a JSON library for MYSQL that can be found here You need to have root access to your server and be comfortable installing plugins (it's simple).

1) upload the lib_mysqludf_json.so into the plugins directory of your mysql installation

2) run the lib_mysqludf_json.sql file (it pretty much does all of the work for you. If you run into trouble just delete anything that starts with 'DROP FUNCTION...')

3) encode your query in something like this:

SELECT json_array(
         group_concat(json_object( name, email))
FROM ....
WHERE ...

and it will return something like

[ 
   { 
     "name": "something",
     "email": "[email protected]"
    }, 
   { 
     "name": "someone",
     "email": "[email protected]"
    }

]

Spring @Value is not resolving to value from property file

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

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

CSS text-overflow in a table cell?

When it's in percentage table width, or you can't set fixed width on table cell. You can apply table-layout: fixed; to make it work.

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  border: 1px solid red;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</td>_x000D_
    <td>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I had the same problem with long-running scripts with the error messages "Premature end of script headers: index.php" and "Connection reset by peer: mod_fcgid: error reading data from FastCGI server" in error_log. After hours of testing this helps for me (CentOS 6, PHP-FPM 7, Plesk 12.5.30):

edit the config file:

/etc/httpd/conf.d/fcgid.conf

Set a higher running time. In my case 600 seconds

create the new entry:

FcgidBusyTimeout 600

adapt following entries:

FcgidIOTimeout 600

FcgidConnectTimeout 600

restart httpd:

service httpd restart

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

The global type Function serves this purpose.

Additionally, if you intend to invoke this callback with 0 arguments and will ignore its return value, the type () => void matches all functions taking no arguments.


Update with details and improvements.

The answer and question here has way too many updoots not to mention the only-slightly more complex yet best-practice method:

Solution to your question

interface Easy_Fix_Solution {
    title: string;
    callback: Function;
}

NOTE: Please do not use Function as you most likely do not want any callback function. It's okay to be a little specific.

Improvement to that solution

interface Safer_Easy_Fix {
    title: string;
    callback: () => void;
}
interface Alternate_Syntax_4_Safer_Easy_Fix {
    title: string;
    callback(): void;
}

NOTE: The original author is correct, accepting no arguments and returning void is better.. it's much safer, it tells the consumer of your interface that you will not be doing anything with their return value, and that you will not be passing them any parameters.

And better yet Use generics. This interface would also work for the same () => void function types mentioned before.

interface Better_still_safe_but_way_more_flexible_fix {
    title: string;
    callback: <T = unknown, R = unknown>(args?: T) => R;
}
interface Alternate_Syntax_4_Better_still_safe_but_way_more_flexible_fix {
    title: string;
    callback<T = unknown, R = unknown>(args?: T): R;
}

NOTE: If you aren't 100% sure about the callback signature right now, please choose the void option above, or this generic option if you think you may extend functionality going forward. Callbacks usually receive some arguments of some sort, and sometimes the callback orchestrator even does something with the return value.

And a slightly more advanced usecase you shouldn't use unless you need it

This allows any number of arguments, of any type in T.

More details here.

interface Alternate_Syntax_4_Advanced {
    title: string;
    callback<T extends unknown[], R = unknown>(...args?: T): R;
}

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

var formatedDate = DateTime.Now.ToString("yyyy-MM-dd",System.Globalization.CultureInfo.InvariantCulture);

To ensure the user's local settings don't affect it

How can I transform string to UTF-8 in C#?

 Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(mystring));

Delete all rows in a table based on another table

Found this link useful

Copied from there

Oftentimes, one wants to delete some records from a table based on criteria in another table. How do you delete from one of those tables without removing the records in both table?

DELETE DeletingFromTable
     FROM DeletingFromTable INNER JOIN CriteriaTable
     ON DeletingFromTable.field_id = CriteriaTable.id
     WHERE CriteriaTable.criteria = "value";

The key is that you specify the name of the table to be deleted from as the SELECT. So, the JOIN and WHERE do the selection and limiting, while the DELETE does the deleting. You're not limited to just one table, though. If you have a many-to-many relationship (for instance, Magazines and Subscribers, joined by a Subscription) and you're removing a Subscriber, you need to remove any potential records from the join model as well.

 DELETE subscribers, subscriptions
     FROM subscribers INNER JOIN subscriptions 
       ON subscribers.id = subscriptions.subscriber_id
     INNER JOIN magazines 
       ON subscriptions.magazine_id = magazines.id
     WHERE subscribers.name='Wes';

Deleting records with a join could also be done with a LEFT JOIN and a WHERE to see if the joined table was NULL, so that you could remove records in one table that didn't have a match (like in preparation for adding a relationship.) Example post to come.

Sort JavaScript object by key

Here is a clean lodash-based version that works with nested objects

/**
 * Sort of the keys of an object alphabetically
 */
const sortKeys = function(obj) {
  if(_.isArray(obj)) {
    return obj.map(sortKeys);
  }
  if(_.isObject(obj)) {
    return _.fromPairs(_.keys(obj).sort().map(key => [key, sortKeys(obj[key])]));
  }
  return obj;
};

It would be even cleaner if lodash had a toObject() method...

jQuery - prevent default, then continue default

With jQuery and a small variation of @Joepreludian's answer above:

Important points to keep in mind:

  • .one(...) instead on .on(...) or .submit(...)
  • named function instead of anonymous function since we will be referring it within the callback.

$('form#my-form').one('submit', function myFormSubmitCallback(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    var $this = $(this);
    if (allIsWell) {
        $this.submit(); // submit the form and it will not re-enter the callback because we have worked with .one(...)
    } else {
        $this.one('submit', myFormSubmitCallback); // lets get into the callback 'one' more time...
    }
});

You can change the value of allIsWell variable in the below snippet to true or false to test the functionality:

_x000D_
_x000D_
$('form#my-form').one('submit', function myFormSubmitCallback(evt){_x000D_
  evt.stopPropagation();_x000D_
  evt.preventDefault();_x000D_
  var $this = $(this);_x000D_
  var allIsWell = $('#allIsWell').get(0).checked;_x000D_
  if(allIsWell) {_x000D_
    $this.submit();_x000D_
  } else {_x000D_
    $this.one('submit', myFormSubmitCallback);_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="/" id="my-form">_x000D_
  <input name="./fname" value="John" />_x000D_
  <input name="./lname" value="Smith" />_x000D_
  <input type="submit" value="Lets Do This!" />_x000D_
  <br>_x000D_
  <label>_x000D_
    <input type="checkbox" value="true" id="allIsWell" />_x000D_
    All Is Well_x000D_
  </label>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Good Luck...

Copy or rsync command

Rsync is better since it will only copy only the updated parts of the updated file, instead of the whole file. It also uses compression and encryption if you want. Check out this tutorial.

Number of processors/cores in command line

If you need an os independent method, works across Windows and Linux. Use python

$ python -c 'import multiprocessing as m; print m.cpu_count()'
16

How can I get table names from an MS Access Database?

SELECT 
Name 
FROM 
MSysObjects 
WHERE 
(Left([Name],1)<>"~") 
AND (Left([Name],4) <> "MSys") 
AND ([Type] In (1, 4, 6)) 
ORDER BY 
Name

Correct way to synchronize ArrayList in java

Looking at your example, I think ArrayBlockingQueue (or its siblings) may be of use. They look after the synchronisation for you, so threads can write to the queue or peek/take without additional synchronisation work on your part.

HTML5 Video autoplay on iPhone

iOs 10+ allow video autoplay inline. but you have to turn off "Low power mode" on your iPhone.

How to debug a GLSL shader?

I am sharing a fragment shader example, how i actually debug.

#version 410 core

uniform sampler2D samp;
in VS_OUT
{
    vec4 color;
    vec2 texcoord;
} fs_in;

out vec4 color;

void main(void)
{
    vec4 sampColor;
    if( texture2D(samp, fs_in.texcoord).x > 0.8f)  //Check if Color contains red
        sampColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);  //If yes, set it to white
    else
        sampColor = texture2D(samp, fs_in.texcoord); //else sample from original
    color = sampColor;

}

enter image description here

Delete keychain items when an app is uninstalled

Just add an app setting bundle and implement a toggle to reset the keychain on app restart or something based on the value selected through settings (available through userDefaults)

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

The functionality, you described, can be easily achieved using the Bootstrap tooltip.

<button id="example1" data-toggle="tooltip">Tooltip on left</button>

Then call tooltip() function for the element.

$('#example1').tooltip();

http://getbootstrap.com/javascript/#tooltips

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

How to send SMS in Java

There are two ways : First : Use a SMS API Gateway which you need to pay for it , maybe you find some trial even free ones but it's scarce . Second : To use AT command with a modem GSM connected to your laptop . that's all

Gradle does not find tools.jar

Linux

Open /etc/environment in any text editor like nano or gedit and add the following line:

JAVA_HOME="/usr/lib/jvm/open-jdk"

Windows

  1. Start the System Control Panel applet (Start - Settings - Control Panel - System).
  2. Select the Advanced tab.
  3. Click the Environment Variables button.
  4. Under System Variables, click add button, then past the following lines:

    in Variable Name : JAVA_HOME

    in Variable Value : C:\Program Files\Java\jdk1.x.x_xxx

    where x.x_xxx jdk version you can get your jdk version from here C:\Program Files\Java

  5. Under System Variables, select Path, then click Edit,then click new button then past the following line:

    %JAVA_HOME%/bin;

Difference between null and empty ("") Java String

In Java a reference type assigned null has no value at all. A string assigned "" has a value: an empty string, which is to say a string with no characters in it. When a variable is assigned null it means there is no underlying object of any kind, string or otherwise.

IDEA: javac: source release 1.7 requires target release 1.7

If all the previous solutions haven't worked for you (which was my case), you can delete intellij config files:

  • project_directory/.idea/compiler.xml
  • project_directory/.idea/encodings.xml
  • project_directory/.idea/misc.xml
  • project_directory/.idea/modules.xml
  • project_directory/.idea/vcs.xml
  • project_directory/.idea/workspace.xml
  • etc.

Intellij will regenerate new ones later. However, BE CAREFUL, this will also delete all intellij configuration made on the projet (i.e: configuration of debug mode, ...)

How do I get currency exchange rates via an API such as Google Finance?

If you're looking for a ruby based solution for this problem, I recommend using the Google Calculator method a solution similar to the following: http://j.mp/QIC564

require 'faraday'
require 'faraday_middleware'
require 'json'

# Debug: 
# require "pry"


country_code_src = "USD"
country_code_dst = "INR"
connection = Faraday.get("http://www.google.com/ig/calculator?hl=en&q=1#{country_code_src}=?#{country_code_dst}")

currency_comparison_hash = eval connection.body #Google's output is not JSON, it's a hash

dst_currency_value, *dst_currency_text = *currency_comparison_hash[:rhs].split(' ')
dst_currency_value = dst_currency_value.to_f
dst_currency_text = dst_currency_text.join(' ')

puts "#{country_code_dst} -> #{dst_currency_value} (#{dst_currency_text} to 1 #{country_code_src})"

Setting Inheritance and Propagation flags with set-acl and powershell

Here's a table to help find the required flags for different permission combinations.

    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
    ¦             ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦    files    ¦
    ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦
    ¦ Propagation ¦ none        ¦ none                          ¦ none                   ¦ none             ¦ InheritOnly           ¦ InheritOnly ¦ InheritOnly ¦
    ¦ Inheritance ¦ none        ¦ Container|Object              ¦ Container              ¦ Object           ¦ Container|Object      ¦ Container   ¦ Object      ¦
    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+

So, as David said, you'll want

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
PropagationFlags.None

Counting unique / distinct values by group in a data frame

This should do the trick:

ddply(myvec,~name,summarise,number_of_distinct_orders=length(unique(order_no)))

This requires package plyr.

Error when trying vagrant up

Check Homestead.yaml file carefully.Check if there is any extra space character after line ends. Then, open gitbash -> go Homestead directory -> command "vagrant up --provision".

Get DataKey values in GridView RowCommand

you can just do this:

string id = GridName.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();

How to convert comma-delimited string to list in Python?

You can split that string on , and directly get a list:

mStr = 'A,B,C,D,E'
list1 = mStr.split(',')
print(list1)

Output:

['A', 'B', 'C', 'D', 'E']

You can also convert it to an n-tuple:

print(tuple(list1))

Output:

('A', 'B', 'C', 'D', 'E')

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

Change the following line

$(document).ready(function() {

To

jQuery.noConflict();
jQuery(document).ready(function($) {

Remove quotes from String in Python

if string.startswith('"'):
    string = string[1:]

if string.endswith('"'):
    string = string[:-1]

How can I convert a date into an integer?

You can run it through Number()

var myInt = Number(new Date(dates_as_int[0]));

If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.

Use of Number()

Hibernate: get entity by id

In getUserById you shouldn't create a new object (user1) which isn't used. Just assign it to the already (but null) initialized user. Otherwise Hibernate.initialize(user); is actually Hibernate.initialize(null);

Here's the new getUserById (I haven't tested this ;)):

public User getUserById(Long user_id) {
    Session session = null;
    Object user = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        user = (User)session.load(User.class, user_id);
        Hibernate.initialize(user);
    } catch (Exception e) {
       e.printStackTrace();
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return user;
}

Excluding directory when creating a .tar.gz file

This worked for me:

tar -zcvf target.tar.gz target/ --exclude="target/backups" --exclude="target/cache"

Eclipse error: "Editor does not contain a main type"

Did you import the packages for the file reading stuff.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

also here

cfiltering(numberOfUsers, numberOfMovies);

Are you trying to create an object or calling a method?

also another thing:

user_movie_matrix[userNo][movieNo]=rating;

you are assigning a value to a member of an instance as if it was a static variable also remove the Th in

private int user_movie_matrix[][];Th

Hope this helps.

Apache Proxy: No protocol handler was valid

I tried to get an uwsgi:// working, but somehow the manual thought it was clear to me that I actually needed mod_proxy_uwsgi. It was not. Here is how you do it: How to compile mod_proxy_uwsgi or mod_uwsgi?

Add text to textarea - Jquery

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

How to check if a process is in hang state (Linux)

Unfortunately there is no hung state for a process. Now hung can be deadlock. This is block state. The threads in the process are blocked. The other things could be live lock where the process is running but doing the same thing again and again. This process is in running state. So as you can see there is no definite hung state. As suggested you can use the top command to see if the process is using 100% CPU or lot of memory.

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

System.exit(0) by convention, a zero status code indicates successful termination.

System.exit(1) -It means termination unsuccessful due to some error

Adding items to an object through the .push() method

Another way of doing it would be:

stuff = Object.assign(stuff, {$(this).attr('value'):$(this).attr('checked')});

Read more here: Object.assign()

File content into unix variable with newlines

The envdir utility provides an easy way to do this. envdir uses files to represent environment variables, with file names mapping to env var names, and file contents mapping to env var values. If the file contents contain newlines, so will the env var.

See https://pypi.python.org/pypi/envdir

C++ style cast from unsigned char * to const char *

Hope it help. :)

const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;

Showing an image from an array of images - Javascript

Here's your problem:

if(imgArray[i] == img)

You're comparing an array element to a DOM object.

Changing SqlConnection timeout

You need to use command.CommandTimeout

How do you add CSS with Javascript?

if you know at least one <style> tag exist in page , use this function :

CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};

usage :

CSS("div{background:#00F}");

C++ convert from 1 char to string?

This solution will work regardless of the number of char variables you have:

char c1 = 'z';
char c2 = 'w';
std::string s1{c1};
std::string s12{c1, c2};

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

12 is a compile-time constant which can not be changed unlike the data referenced by int&. What you can do is

const int& z = 12;

C++ equivalent of java's instanceof

#include <iostream.h>
#include<typeinfo.h>

template<class T>
void fun(T a)
{
  if(typeid(T) == typeid(int))
  {
     //Do something
     cout<<"int";
  }
  else if(typeid(T) == typeid(float))
  {
     //Do Something else
     cout<<"float";
  }
}

void main()
 {
      fun(23);
      fun(90.67f);
 }

Generating Unique Random Numbers in Java

I have made this like that.

    Random random = new Random();
    ArrayList<Integer> arrayList = new ArrayList<Integer>();

    while (arrayList.size() < 6) { // how many numbers u need - it will 6
        int a = random.nextInt(49)+1; // this will give numbers between 1 and 50.

        if (!arrayList.contains(a)) {
            arrayList.add(a);
        }
    }

How to compare two colors for similarity/difference

The only "right" way to compare colors is to do it with deltaE in CIELab or CIELuv.

But for a lot of applications I think this is a good enough approximation:

distance = 3 * |dR| + 4 * |dG| + 3 * |dB|

I think a weighted manhattan distance makes a lot more sense when comparing colors. Remember that color primaries are only in our head. They don't have any physical significance. CIELab and CIELuv is modelled statistically from our perception of color.

What is <scope> under <dependency> in pom.xml for?

The <scope> element can take 6 values: compile, provided, runtime, test, system and import.

This scope is used to limit the transitivity of a dependency, and also to affect the classpath used for various build tasks.

compile

This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

provided

This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

runtime

This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.

test

This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

system

This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.

import (only available in Maven 2.0.9 or later)

This scope is only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM's section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

To answer the second part of your question:

How can we use it for running test?

Note that the test scope allows to use dependencies only for the test phase.

Read the documentation for full details.

CodeIgniter - Correct way to link to another page in a view

I assume you are meaning "internally" within your application.

you can create your own <a> tag and insert a url in the href like this

<a href="<?php echo site_url('controller/function/uri') ?>">Link</a>

OR you can use the URL helper this way to generate an <a> tag

anchor(uri segments, text, attributes)

So... to use it...

<?php echo anchor('controller/function/uri', 'Link', 'class="link-class"') ?>

and that will generate

<a href="http://domain.com/index.php/controller/function/uri" class="link-class">Link</a>

For the additional commented question

I would use my first example

so...

<a href="<?php echo site_url('controller/function') ?>"><img src="<?php echo base_url() ?>img/path/file.jpg" /></a>

for images (and other assets) I wouldn't put the file path within the php, I would just echo the base_url() and then add the path normally.

Which selector do I need to select an option by its text?

This works for me:

var result = $('#SubjectID option')
            .filter(function () 
             { return $(this).html() == "English"; }).val();

The result variable will return the index of the matched text value. Now I will just set it using it's index:

$('#SubjectID').val(result);

Is the 'as' keyword required in Oracle to define an alias?

Both are correct. Oracle allows the use of both.

How to modify memory contents using GDB?

As Nikolai has said you can use the gdb 'set' command to change the value of a variable.

You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20

This should work for any valid pointer, and can be cast to any appropriate data type.

How to use a different version of python during NPM install?

Ok, so you've found a solution already. Just wanted to share what has been useful to me so many times;

I have created setpy2 alias which helps me switch python.

alias setpy2="mkdir -p /tmp/bin; ln -s `which python2.7` /tmp/bin/python; export PATH=/tmp/bin:$PATH"

Execute setpy2 before you run npm install. The switch stays in effect until you quit the terminal, afterwards python is set back to system default.

You can make use of this technique for any other command/tool as well.

List of zeros in python

Here is the xrange way:

list(0 for i in xrange(0,5)) 

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

RESTful Authentication

I think restful authentication involves the passing of an authentication token as a parameter in the request. Examples are the use of apikeys by api's. I don't believe the use of cookies or http auth qualifies.

OrderBy pipe issue

orderby Pipe in Angular JS will support but Angular (higher versions) will not support . Please find he details discussed to increase performance speed its obsolete.

https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

How to check if an email address exists without sending an email?

<?php

   $email = "someone@exa mple.com";

   if(!filter_var($email, FILTER_VALIDATE_EMAIL))
      echo "E-mail is not valid";
   else
      echo "E-mail is valid";

?>

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

In our case, the wrong version of the Sysdeo Tomcat plugin for Eclipse 3.5 was being used. The fix:

  • Use tomcatPluginV33 instead of tomcatPluginV321 (extract to C:\eclipse\dropins)
  • Ensure that DevloaderTomcat7.jar was placed in the tomcat lib folder
  • In Window > Preferences > Tomcat, set the Tomcat version to 7.x

This problem may have been unique to our environment; but, I'll record it here anyway, for posterity's sake.

How to multiply a BigDecimal by an integer in Java

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

AND/OR in Python?

Are you looking for...

a if b else c

Or perhaps you misunderstand Python's or? True or True is True.

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

How to convert string to float?

Unfortunately, there is no way to do this easily. Every solution has its drawbacks.

  1. Use atof() or strtof() directly: this is what most people will tell you to do and it will work most of the time. However, if the program sets a locale or it uses a library that sets the locale (for instance, a graphics library that displays localised menus) and the user has their locale set to a language where the decimal separator is not . (such as fr_FR where the separator is ,) these functions will stop parsing at the . and you will stil get 4.0.

  2. Use atof() or strtof() but change the locale; it's a matter of calling setlocale(LC_ALL|~LC_NUMERIC, ""); before any call to atof() or the likes. The problem with setlocale is that it will be global to the process and you might interfer with the rest of the program. Note that you might query the current locale with setlocale() and restore it after you're done.

  3. Write your own float parsing routine. This might be quite quick if you do not need advanced features such as exponent parsing or hexadecimal floats.

Also, note that the value 4.08 cannot be represented exactly as a float; the actual value you will get is 4.0799999237060546875.

List all sequences in a Postgres db 8.1 with SQL

Improvement of the previous answer:

select string_agg('select sequence_name, last_value from ' || relname, chr(13) || 'union' || chr(13) order by relname) 
from pg_class where relkind ='S'

How do files get into the External Dependencies in Visual Studio C++?

The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).

You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.

With android studio no jvm found, JAVA_HOME has been set

Just delete the folder highlighted below. Depending on your Android Studio version, mine is 3.5 and reopen Android studio.

enter image description here

android studio 0.4.2: Gradle project sync failed error

I always remove the .gradle folder from %USERS% folder and start the studio again. When starting the IDE it downloads gradle again with all the dependencies again. Its work PERFECT.

How can I get the error message for the mail() function?

In my case, I couldn't get the error message in my PHP script no matter what I do (error_get_last(), or ini_set('display_errors',1);) don't show the error message

according to this post

The return value from $mail refers only to whether or not your server's mailing system accepted the message for delivery, and does not and can not in any way know whether or not you are providing valid arguments. For example, the return value would be false if sendmail failed to load (e.g. if it wasn't installed properly), but would return true if sendmail loaded properly but the recipient address doesn't exist.

I confirm this because after some failed attempts to use mail() in my PHP scripts, it turns that sendmail was not installed on my machine, however the php.ini variable sendmail_path was /usr/sbin/sendmail -t -i

1- I installed sendmail from my package manager shell> dnf install sendmail

2- I started it shell> service sendmail start

3- Now if any PHP mail() function fails I find the errors of the sendmail program logged under /var/mail/ directory. 1 file per user

For example this snippet is taken from my /var/mail/root file

The original message was received at Sun, 29 Jul 2018 22:37:51 +0200
from localhost [127.0.0.1]
   ----- The following addresses had permanent fatal errors -----
<[email protected]>
    (reason: 550 Host unknown)

My system is linux Fedora 28 with apache2.4 and PHP 7.2

C/C++ check if one bit is set in, i.e. int variable

I make this:

LATGbits.LATG0=((m&0x8)>0); //to check if bit-2 of m is 1

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

$query=file_get_contents('http://###.##.##.##/mp/get?' . http_build_query(array('mpsrc' => 'http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert format=flv')));

Facebook user url by id

As of now (NOV-2019), graph.api V5.0

graph API says, refer graph api

A link to the person's Timeline. The link will only resolve if the person clicking the link is logged into Facebook and is a friend of the person whose profile is being viewed.

doc

How can I create a progress bar in Excel VBA?

Just adding my part to the above collection.

If you are after less code and maybe cool UI. Check out my GitHub for Progressbar for VBA enter image description here

a customisable one:

enter image description here

The Dll is thought for MS-Access but should work in all VBA platform with minor changes. There is also an Excel file with samples. You are free to expand the vba wrappers to suit your needs.

This project is currently under development and not all errors are covered. So expect some!

You should be worried about 3rd party dlls and if you are, please feel free to use any trusted online antivirus before implementing the dll.

Display string as html in asp.net mvc view

I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.

I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.

So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.

I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.

Paste text on Android Emulator

If you are using Android Studio on a Mac, you may need to provide the full path to the adb executable. To find this path, open:

Android Studio > Tools > Android > SDK Manager

Copy the path to the SDK location. The adb executable will be within a platform-tools directory. For me, this was the path:

~/Library/Android/sdk/platform-tools/adb

Now you can run this command:

~/Library/Android/sdk/platform-tools/adb shell input text 'thetextyouwanttopaste'

Java Array Sort descending?

I know that this is a quite old thread, but here is an updated version for Integers and Java 8:

Arrays.sort(array, (o1, o2) -> o2 - o1);

Note that it is "o1 - o2" for the normal ascending order (or Comparator.comparingInt()).

This also works for any other kinds of Objects. Say:

Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());

How do I temporarily disable triggers in PostgreSQL?

For disable trigger

ALTER TABLE table_name DISABLE TRIGGER trigger_name

For enable trigger

ALTER TABLE table_name ENABLE TRIGGER trigger_name

How do I plot in real-time in a while loop using matplotlib?

Here is a version that I got to work on my system.

import matplotlib.pyplot as plt
from drawnow import drawnow
import numpy as np

def makeFig():
    plt.scatter(xList,yList) # I think you meant this

plt.ion() # enable interactivity
fig=plt.figure() # make a figure

xList=list()
yList=list()

for i in np.arange(50):
    y=np.random.random()
    xList.append(i)
    yList.append(y)
    drawnow(makeFig)
    #makeFig()      The drawnow(makeFig) command can be replaced
    #plt.draw()     with makeFig(); plt.draw()
    plt.pause(0.001)

The drawnow(makeFig) line can be replaced with a makeFig(); plt.draw() sequence and it still works OK.

What to do with commit made in a detached head

In case of detached HEAD, commits work like normal, except no named branch gets updated. To get master branch updated with your committed changes, make a temporary branch where you are (this way the temporary branch will have all the committed changes you have made in the detached HEAD) , then switch to the master branch and merge the temporary branch with the master.

git branch  temp
git checkout master
git merge temp

Generate a Hash from string in Javascript

If you want to avoid collisions you may want to use a secure hash like SHA-256. There are several JavaScript SHA-256 implementations.

I wrote tests to compare several hash implementations, see https://github.com/brillout/test-javascript-hash-implementations.

Or go to http://brillout.github.io/test-javascript-hash-implementations/, to run the tests.

CSS: Creating textured backgrounds

You should try slicing the image if possible into a smaller piece which could be repeated. I have sliced that image to a 101x101px image.

BG Tile

CSS:

body{
  background-image: url(SO_texture_bg.jpg);
  background-repeat:repeat;
}

But in some cases, we wouldn't be able to slice the image to a smaller one. In that case, I would use the whole image. But you could also use the CSS3 methods like what Mustafa Kamal had mentioned.

Wish you good luck.

delete all record from table in mysql

truncate tableName

That is what you are looking for.

Truncate will delete all records in the table, emptying it.

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

Variable interpolation in the shell

Use curly braces around the variable name:

`tail -1 ${filepath}_newstap.sh`

How do I disable form resizing for users?

Change the FormBorderStyle to one of the fixed values: FixedSingle, Fixed3D, FixedDialog or FixedToolWindow.

The FormBorderStyle property is under the Appearance category.

Or check this:

// Define the border style of the form to a dialog box.
form1.FormBorderStyle = FormBorderStyle.FixedDialog;

// Set the MaximizeBox to false to remove the maximize box.
form1.MaximizeBox = false;

// Set the MinimizeBox to false to remove the minimize box.
form1.MinimizeBox = false;

// Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen;

// Display the form as a modal dialog box.
form1.ShowDialog();

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

Detect when a window is resized using JavaScript ?

If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:

Super Super compact

var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }

All 3 possible combinations together (ES6)

var t
window.onresize = () => {
    resizing(this, this.innerWidth, this.innerHeight) //1
    if (typeof t == 'undefined') resStarted() //2
    clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}

function resizing(target, w, h) {
    console.log(`Youre resizing: width ${w} height ${h}`)
}    
function resStarted() { 
    console.log('Resize Started') 
}
function resEnded() { 
    console.log('Resize Ended') 
}

Generate a random point within a circle (uniformly)

Solution in Java and the distribution example (2000 points)

public void getRandomPointInCircle() {
    double t = 2 * Math.PI * Math.random();
    double r = Math.sqrt(Math.random());
    double x = r * Math.cos(t);
    double y = r * Math.sin(t);
    System.out.println(x);
    System.out.println(y);
}

Distribution 2000 points

based on previus solution https://stackoverflow.com/a/5838055/5224246 from @sigfpe

How do I get the App version and build number using Swift?

I also know this has already been answered but I wrapped up the previous answers:

(*)Updated for extensions

extension Bundle {
    var releaseVersionNumber: String? {
        return infoDictionary?["CFBundleShortVersionString"] as? String
    }
    var buildVersionNumber: String? {
        return infoDictionary?["CFBundleVersion"] as? String
    }
    var releaseVersionNumberPretty: String {
        return "v\(releaseVersionNumber ?? "1.0.0")"
    }
}

Usage:

someLabel.text = Bundle.main.releaseVersionNumberPretty

@Deprecated: Old answers

Swift 3.1:

class func getVersion() -> String {
    guard let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else {
        return "no version info"
    }
    return version
}

For older versions:

class func getVersion() -> String {
    if let version = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String {
        return version
    }
    return "no version info"
}

So if you want to set label text or want to use somewhere else;

self.labelVersion.text = getVersion()

Creating a copy of a database in PostgreSQL

In production environment, where the original database is under traffic, I'm simply using:

pg_dump production-db | psql test-db

How to center cards in bootstrap 4?

i basically suggest equal gap on right and left, and setting width to auto. Here like:

.bmi {         /*my additional class name -for card*/
    margin-left: 18%;      
    margin-right: 18%;
    width: auto;
}

How do I get length of list of lists in Java?

Just use

int listCount = data.size();

That tells you how many lists there are (assuming none are null). If you want to find out how many strings there are, you'll need to iterate:

int total = 0;
for (List<String> sublist : data) {
    // TODO: Null checking
    total += sublist.size();
}
// total is now the total number of strings

Volley JsonObjectRequest Post request not working

Easy one for me ! I got it few weeks ago :

This goes in getBody() method, not in getParams() for a post request.

Here is mine :

    @Override
/**
 * Returns the raw POST or PUT body to be sent.
 *
 * @throws AuthFailureError in the event of auth failure
 */
public byte[] getBody() throws AuthFailureError {
    //        Map<String, String> params = getParams();
    Map<String, String> params = new HashMap<String, String>();
    params.put("id","1");
    params.put("name", "myname");
    if (params != null && params.size() > 0) {
        return encodeParameters(params, getParamsEncoding());
    }
    return null;

}

(I assumed you want to POST the params you wrote in your getParams)

I gave the params to the request inside the constructor, but since you are creating the request on the fly, you can hard coded them inside your override of the getBody() method.

This is what my code looks like :

    Bundle param = new Bundle();
    param.putString(HttpUtils.HTTP_CALL_TAG_KEY, tag);
    param.putString(HttpUtils.HTTP_CALL_PATH_KEY, url);
    param.putString(HttpUtils.HTTP_CALL_PARAM_KEY, params);

    switch (type) {
    case RequestType.POST:
        param.putInt(HttpUtils.HTTP_CALL_TYPE_KEY, RequestType.POST);
        SCMainActivity.mRequestQueue.add(new SCRequestPOST(Method.POST, url, this, tag, receiver, params));

and if you want even more this last string params comes from :

param = JsonUtils.XWWWUrlEncoder.encode(new JSONObject(paramasJObj)).toString();

and the paramasJObj is something like this : {"id"="1","name"="myname"} the usual JSON string.

Zooming MKMapView to fit annotation pins?

Put this in to your code accordingly:

  - (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
    {
    id<MKAnnotation> mp = [annotationView annotation];
        MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,250,250);

       [mv setRegion:region animated:YES];

}

"’" showing on page instead of " ' "

The same thing happened to me with the '–' character (long minus sign).
I used this simple replace so resolve it:

htmlText = htmlText.Replace('–', '-');

How to import an Oracle database from dmp file and log file?

If you are using impdp command example from @sathyajith-bhat response:

impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;

you will need to use mandatory parameter directory and create and grant it as:

CREATE OR REPLACE DIRECTORY DMP_DIR AS 'c:\Users\USER\Downloads';
GRANT READ, WRITE ON DIRECTORY DMP_DIR TO {USER};

or use one of defined:

select * from DBA_DIRECTORIES;

My ORACLE Express 11g R2 has default named DATA_PUMP_DIR (located at {inst_dir}\app\oracle/admin/xe/dpdump/) you sill need to grant it for your user.

Twitter Bootstrap button click to toggle expand/collapse text section above button

html:

<h4 data-toggle-selector="#me">toggle</h4>
<div id="me">content here</div>

js:

$(function () {
    $('[data-toggle-selector]').on('click',function () {
        $($(this).data('toggle-selector')).toggle(300);
    })
})

css selector to match an element without attribute x

For a more cross-browser solution you could style all inputs the way you want the non-typed, text, and password then another style the overrides that style for radios, checkboxes, etc.

input { border:solid 1px red; }

input[type=radio], 
input[type=checkbox], 
input[type=submit], 
input[type=reset], 
input[type=file] 
      { border:none; }

- Or -

could whatever part of your code that is generating the non-typed inputs give them a class like .no-type or simply not output at all? Additionally this type of selection could be done with jQuery.

How can I download a file from a URL and save it in Rails?

If you're using PaperClip, downloading from a URL is now handled automatically.

Assuming you've got something like:

class MyModel < ActiveRecord::Base
  has_attached_file :image, ...
end

On your model, just specify the image as a URL, something like this (written in deliberate longhand):

@my_model = MyModel.new
image_url = params[:image_url]
@my_model.image = URI.parse(image_url)

You'll probably want to put this in a method in your model. This will also work just fine on Heroku's temporary filesystem.

Paperclip will take it from there.

source: paperclip documentation

JQuery - File attributes

Just try

var file = $("#uploadedfile").prop("files")[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");

It worked for me

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

Git update submodules recursively

git submodule update --recursive

You will also probably want to use the --init option which will make it initialize any uninitialized submodules:

git submodule update --init --recursive

Note: in some older versions of Git, if you use the --init option, already-initialized submodules may not be updated. In that case, you should also run the command without --init option.

Is it possible to set UIView border properties from interface builder?

while this might set the properties, it doesnt actually reflect in IB. So if you're essentially writing code in IB, you might as well then do it in your source code

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

For me an update solved the problem:

On Ubuntu:

sudo apt-get update
sudo apt-get upgrade

On CentOS:

sudo yum update

Install pdo for postgres Ubuntu

PDO driver for PostgreSQL is now included in the debian package php5-dev. The above steps using Pecl no longer works.

Android EditText for password with android:hint

android:hint="Enter your question" or something like this must work. I am using Relative layout with EditText as If you want to use password,say android:inputType="textPassword" for hiding characters and "textVisiblePassword" for showing what you enter as password.

Fatal error: Call to undefined function sqlsrv_connect()

When you install third-party extensions you need to make sure that all the compilation parameters match:

  • PHP version
  • Architecture (32/64 bits)
  • Compiler (VC9, VC10, VC11...)
  • Thread safety

Common glitches includes:

  • Editing the wrong php.ini file (that's typical with bundles); the right path is shown in phpinfo().
  • Forgetting to restart Apache.
  • Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:

    php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
    

If everything's right you should see sqlsrv in the command output and/or phpinfo() (depending on what SAPI you're configuring):

[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]

phpinfo()

Highlighting Text Color using Html.fromHtml() in Android?

 String name = modelOrderList.get(position).getName();   //get name from List
    String text = "<font color='#000000'>" + name + "</font>"; //set Black color of name
    /* check API version, according to version call method of Html class  */
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
        Log.d(TAG, "onBindViewHolder: if");
        holder.textViewName.setText(context.getString(R.string._5687982) + " ");
        holder.textViewName.append(Html.fromHtml(text));
    } else {
        Log.d(TAG, "onBindViewHolder: else");
        holder.textViewName.setText("123456" + " ");   //set text 
        holder.textViewName.append(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY));   //append text into textView
    }

Is key-value pair available in Typescript?

Another simple way is to use a tuple:

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);

Output:

First: hello Second: 10

How can I disable HREF if onclick is executed?

    yes_js_login = function() {
         // Your code here
         return false;
    }

If you return false it should prevent the default action (going to the href).

Edit: Sorry that doesn't seem to work, you can do the following instead:

<a href="http://example.com/no-js-login" onclick="yes_js_login(); return false;">Link</a>

Javascript receipt printing using POS Printer

Maybe you could have a look at this if your printer is an epson. There is a javascript driver

http://spsrprofessionals.com/ClientSite/readers/ePOS-Print_SDK_141020E/JavaScript/ePOS-Print_SDK_JS_en_revB.pdf

EDIT:

Previous link seems to be broken

All details about how to use epos of epson are on epson website:

https://reference.epson-biz.com/modules/ref_epos_device_js_en/index.php?content_id=139

How do I send a file as an email attachment using Linux command line?

I once wrote this function for ksh on Solaris (uses Perl for base64 encoding):

# usage: email_attachment to cc subject body attachment_filename
email_attachment() {
    to="$1"
    cc="$2"
    subject="$3"
    body="$4"
    filename="${5:-''}"
    boundary="_====_blah_====_$(date +%Y%m%d%H%M%S)_====_"
    {
        print -- "To: $to"
        print -- "Cc: $cc"
        print -- "Subject: $subject"
        print -- "Content-Type: multipart/mixed; boundary=\"$boundary\""
        print -- "Mime-Version: 1.0"
        print -- ""
        print -- "This is a multi-part message in MIME format."
        print -- ""
        print -- "--$boundary"
        print -- "Content-Type: text/plain; charset=ISO-8859-1"
        print -- ""
        print -- "$body"
        print -- ""
        if [[ -n "$filename" && -f "$filename" && -r "$filename" ]]; then
            print -- "--$boundary"
            print -- "Content-Transfer-Encoding: base64"
            print -- "Content-Type: application/octet-stream; name=$filename"
            print -- "Content-Disposition: attachment; filename=$filename"
            print -- ""
            print -- "$(perl -MMIME::Base64 -e 'open F, shift; @lines=<F>; close F; print MIME::Base64::encode(join(q{}, @lines))' $filename)"
            print -- ""
        fi
        print -- "--${boundary}--"
    } | /usr/lib/sendmail -oi -t
}

Force youtube embed to start in 720p

In case you're still wondering how to do it, then add: &feature=youtu.be&hd=1 Actually now I checked, this works only when you're sending the URL to someone else, not on embed.

Illegal pattern character 'T' when parsing a date string to java.util.Date

There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:

import java.time.Instant;
public static void main(String[] args) {
    String date="2010-10-02T12:23:23Z";
    try {
        Instant myDate = Instant.parse(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant directly, can be done via Calendar in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:

myDate.toString().substring(0,4);

Twitter - share button, but with image

You're right in thinking that, in order to share an image in this way without going down the Twitter Cards route, you need to to have tweeted the image already. As you say, it's also important that you grab the image link that's of the form pic.twitter.com/NuDSx1ZKwy

This step-by-step guide is worth checking out for anyone looking to implement a 'tweet this' link or button: http://onlinejournalismblog.com/2015/02/11/how-to-make-a-tweetable-image-in-your-blog-post/.

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

You can use general compound drawable implementation, but if you need to define a size of drawable use this library:

https://github.com/a-tolstykh/textview-rich-drawable

Here is a small example of usage:

<com.tolstykh.textviewrichdrawable.TextViewRichDrawable
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some text"
        app:compoundDrawableHeight="24dp"
        app:compoundDrawableWidth="24dp" />

Implement division with bit-wise operator

The standard way to do division is by implementing binary long-division. This involves subtraction, so as long as you don't discount this as not a bit-wise operation, then this is what you should do. (Note that you can of course implement subtraction, very tediously, using bitwise logical operations.)

In essence, if you're doing Q = N/D:

  1. Align the most-significant ones of N and D.
  2. Compute t = (N - D);.
  3. If (t >= 0), then set the least significant bit of Q to 1, and set N = t.
  4. Left-shift N by 1.
  5. Left-shift Q by 1.
  6. Go to step 2.

Loop for as many output bits (including fractional) as you require, then apply a final shift to undo what you did in Step 1.

Get most recent row for given ID

SELECT *
FROM   tbl
WHERE  id = 1
ORDER  BY signin DESC
LIMIT  1;

The obvious index would be on (id), or a multicolumn index on (id, signin DESC).

Conveniently for the case, MySQL sorts NULL values last in descending order. That's what you typically want if there can be NULL values: the row with the latest not-null signin.

To get NULL values first:

ORDER BY signin IS NOT NULL, signin DESC

You may want to append more expressions to ORDER BY to get a deterministic pick from (potentially) multiple rows with NULL.
The same applies without NULL if signin is not defined UNIQUE.

Related:

The SQL standard does not explicitly define a default sort order for NULL values. The behavior varies quite a bit across different RDBMS. See:

But there are the NULLS FIRST / NULLS LAST clauses defined in the SQL standard and supported by most major RDBMS, but not by MySQL. See:

What are the main differences between JWT and OAuth authentication?

JWT is an open standard that defines a compact and self-contained way for securely transmitting information between parties. It is an authentication protocol where we allow encoded claims (tokens) to be transferred between two parties (client and server) and the token is issued upon the identification of a client. With each subsequent request we send the token.

Whereas OAuth2 is an authorization framework, where it has a general procedures and setups defined by the framework. JWT can be used as a mechanism inside OAuth2.

You can read more on this here

OAuth or JWT? Which one to use and why?

How can I String.Format a TimeSpan object with a custom format in .NET?

You can also go with:

Dim ts As New TimeSpan(35, 21, 59, 59)  '(11, 22, 30, 30)    '
Dim TimeStr1 As String = String.Format("{0:c}", ts)
Dim TimeStr2 As String = New Date(ts.Ticks).ToString("dd.HH:mm:ss")

EDIT:

You can also look at Strings.Format.

    Dim ts As New TimeSpan(23, 30, 59)
    Dim str As String = Strings.Format(New DateTime(ts.Ticks), "H:mm:ss")

How to delete/truncate tables from Hadoop-Hive?

To Truncate:

hive -e "TRUNCATE TABLE IF EXISTS $tablename"

To Drop:

hive -e "Drop TABLE IF EXISTS $tablename"

Dynamically allocating an array of objects

Why not have a setSize method.

A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
    arrayOfAs[i].SetSize(3);
}

I like the "copy" but in this case the default constructor isn't really doing anything. The SetSize could copy the data out of the original m_array (if it exists).. You'd have to store the size of the array within the class to do that.
OR
The SetSize could delete the original m_array.

void SetSize(unsigned int p_newSize)
{
    //I don't care if it's null because delete is smart enough to deal with that.
    delete myArray;
    myArray = new int[p_newSize];
    ASSERT(myArray);
}

Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server

Supported by SQL Server 2005 and later versions

SELECT CONVERT(VARCHAR(10), GETDATE(), 101) 
       + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)

* See Microsoft's documentation to understand what the 101 and 108 style codes above mean.

Supported by SQL Server 2012 and later versions

SELECT FORMAT(GETDATE() , 'MM/dd/yyyy HH:mm:ss')

Result

Both of the above methods will return:

10/16/2013 17:00:20

Angular 4 img src is not found

Well, the problem was that, somehow, the path was not recognized when was inserted in src by a variable. I had to create a variable like this:

path:any = require("../../img/myImage.png");

and then I can use it in src. Thanks everyone!

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

You can catch that exception and return whatever you want from there.

open(target, 'a').close()
scores = {};
try:
    with open(target, "rb") as file:
        unpickler = pickle.Unpickler(file);
        scores = unpickler.load();
        if not isinstance(scores, dict):
            scores = {};
except EOFError:
    return {}

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

In addition to bvamos's answer, according to the documentation the use of sem is deprecated :

NAME ipcrm - remove a message queue, semaphore set or shared memory id SYNOPSIS ipcrm [ -M key | -m id | -Q key | -q id | -S key | -s id ] ... deprecated usage

ipcrm [ shm | msg | sem ] id ...

remove shared memory

us ipcrm -m to remove a shared memory segment by the id

#!/bin/bash

set IPCS_M = ipcs -m | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f2 -d" "

for id in $IPCS_M; do
  ipcrm -m $id;
done

or ipcrm -M to remove a shared memory segment by the key

#!/bin/bash

set IPCS_M = ipcs -m | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f1 -d" "

for id in $IPCS_M; do
  ipcrm -M $id;
done

remove message queues

us ipcrm -q to remove a shared memory segment by the id

#!/bin/bash

set IPCS_Q = ipcs -q | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f2 -d" "

for id in $IPCS_Q; do
  ipcrm -q $id;
done

or ipcrm -Q to remove a shared memory segment by the key

#!/bin/bash

set IPCS_Q = ipcs -q | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f1 -d" "

for id in $IPCS_Q; do
  ipcrm -Q $id;
done

remove semaphores

us ipcrm -s to remove a semaphore segment by the id

#!/bin/bash

set IPCS_S = ipcs -s | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f2 -d" "

for id in $IPCS_S; do
  ipcrm -s $id;
done

or ipcrm -S to remove a semaphore segment by the key

#!/bin/bash

set IPCS_S = ipcs -s | egrep "0x[0-9a-f]+ [0-9]+" | grep $USERNAME | cut -f1 -d" "

for id in $IPCS_S; do
  ipcrm -S $id;
done

how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);

.keyCode vs. .which

A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.

http://jaywcjlove.github.io/hotkeys/

hotkeys('ctrl+a,ctrl+b,r,f', function(event,handler){
    switch(handler.key){
        case "ctrl+a":alert('you pressed ctrl+a!');break;
        case "ctrl+b":alert('you pressed ctrl+b!');break;
        case "r":alert('you pressed r!');break;
        case "f":alert('you pressed f!');break;
    }
});

hotkeys understands the following modifiers: ?, shift, option, ?, alt, ctrl, control, command, and ?.

The following special keys can be used for shortcuts: backspace, tab, clear, enter, return, esc, escape, space, up, down, left, right, home, end, pageup, pagedown, del, delete and f1 through f19.

ES6 exporting/importing in index file

Nav.js comp inside components folder

export {Nav}

index.js in component folder

export {Nav} from './Nav';
export {Another} from './Another';

import anywhere

import {Nav, Another} from './components'

How does a hash table work?

It's even simpler than that.

A hashtable is nothing more than an array (usually sparse one) of vectors which contain key/value pairs. The maximum size of this array is typically smaller than the number of items in the set of possible values for the type of data being stored in the hashtable.

The hash algorithm is used to generate an index into that array based on the values of the item that will be stored in the array.

This is where storing vectors of key/value pairs in the array come in. Because the set of values that can be indexes in the array is typically smaller than the number of all possible values that the type can have, it is possible that your hash algorithm is going to generate the same value for two separate keys. A good hash algorithm will prevent this as much as possible (which is why it is relegated to the type usually because it has specific information which a general hash algorithm can't possibly know), but it's impossible to prevent.

Because of this, you can have multiple keys that will generate the same hash code. When that happens, the items in the vector are iterated through, and a direct comparison is done between the key in the vector and the key that is being looked up. If it is found, great and the value associated with the key is returned, otherwise, nothing is returned.

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

The properties center, bounds and frame are interlocked: changing one will update the others, so use them however you want. For example, instead of modifying the x/y params of frame to recenter a view, just update the center property.

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Its already answered above. I will summarise the steps to check above.

run git remote -v in project dir. If the output shows remote url starting with https://abc then you may need username password everytime.

So to change the remote url run git remote set-url origin {ssh remote url address starts with mostly [email protected]:}.

Now run git remote -v to verify the changed remote url.

Refer : https://help.github.com/articles/changing-a-remote-s-url/

How to increment a datetime by one day?

This was a straightforward solution for me:

from datetime import timedelta, datetime

today = datetime.today().strftime("%Y-%m-%d")
tomorrow = datetime.today() + timedelta(1)

Create an ISO date object in javascript

This worked for me:

_x000D_
_x000D_
var start = new Date("2020-10-15T00:00:00.000+0000");
 //or
start = new date("2020-10-15T00:00:00.000Z");

collection.find({
    start_date:{
        $gte: start
    }
})...etc
_x000D_
_x000D_
_x000D_ new Date(2020,9,15,0,0,0,0) may lead to wrong date: i mean non ISO format (remember javascript count months from 0 to 11 so it's 9 for october)

What does <> mean?

I instinctively read it as "different from". "!=" hits me milliseconds after.

Unnamed/anonymous namespaces vs. static functions

A compiler specific difference between anonymous namespaces and static functions can be seen compiling the following code.

#include <iostream>

namespace
{
    void unreferenced()
    {
        std::cout << "Unreferenced";
    }

    void referenced()
    {
        std::cout << "Referenced";
    }
}

static void static_unreferenced()
{
    std::cout << "Unreferenced";
}

static void static_referenced()
{
    std::cout << "Referenced";
}

int main()
{
    referenced();
    static_referenced();
    return 0;
}

Compiling this code with VS 2017 (specifying the level 4 warning flag /W4 to enable warning C4505: unreferenced local function has been removed) and gcc 4.9 with the -Wunused-function or -Wall flag shows that VS 2017 will only produce a warning for the unused static function. gcc 4.9 and higher, as well as clang 3.3 and higher, will produce warnings for the unreferenced function in the namespace and also a warning for the unused static function.

Live demo of gcc 4.9 and MSVC 2017

Simple state machine example in C#?

You can code an iterator block that lets you execute a code block in an orchestrated fashion. How the code block is broken up really doesn't have to correspond to anything, it's just how you want to code it. For example:

IEnumerable<int> CountToTen()
{
    System.Console.WriteLine("1");
    yield return 0;
    System.Console.WriteLine("2");
    System.Console.WriteLine("3");
    System.Console.WriteLine("4");
    yield return 0;
    System.Console.WriteLine("5");
    System.Console.WriteLine("6");
    System.Console.WriteLine("7");
    yield return 0;
    System.Console.WriteLine("8");
    yield return 0;
    System.Console.WriteLine("9");
    System.Console.WriteLine("10");
}

In this case, when you call CountToTen, nothing actually executes, yet. What you get is effectively a state machine generator, for which you can create a new instance of the state machine. You do this by calling GetEnumerator(). The resulting IEnumerator is effectively a state machine that you can drive by calling MoveNext(...).

Thus, in this example, the first time you call MoveNext(...) you will see "1" written to the console, and the next time you call MoveNext(...) you will see 2, 3, 4, and then 5, 6, 7 and then 8, and then 9, 10. As you can see, it's a useful mechanism for orchestrating how things should occur.

Drop multiple columns in pandas

Try this

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

Which browsers support <script async="async" />?

The async support as specified by google is achieved using two parts:

  • using script on your page (the script is supplied by google) to write out a <script> tag to the DOM.

  • that script has async="true" attribute to signal to compatible browsers that it can continue rendering the page.

The first part works on browsers without support for <script async.. tags, allowing them to load async with a "hack" (although a pretty solid one), and also allows rendering the page without waiting for ga.js to be retrieved.

The second part only affects compatible browsers that understand the async html attribute

  • FF 3.6+
  • FF for Android All Versions
  • IE 10+ (starting with preview 2)
  • Chrome 8+
  • Chrome For Android All versions
  • Safari 5.0+
  • iOS Safari 5.0+
  • Android Browser 3.0+ (honeycomb on up)
  • Opera 15.0+
  • Opera Mobile 16.0+
  • Opera Mini None (as of 8.0)

The "html5 proper" way to specify async is with a <script async src="...", not <script async="true". However, initially browsers did not support this syntax, nor did they support setting the script property on referenced elements. If you want this, the list changes:

  • FF 4+
  • IE 10+ (preview 2 and up)
  • Chrome 12+
  • Chrome For Android 32+
  • Safari 5.1+
  • No android versions

http post - how to send Authorization header?

I believe you need to map the result before you subscribe to it. You configure it like this:

  updateProfileInformation(user: User) {
    var headers = new Headers();
    headers.append('Content-Type', this.constants.jsonContentType);

    var t = localStorage.getItem("accessToken");
    headers.append("Authorization", "Bearer " + t;
    var body = JSON.stringify(user);

    return this.http.post(this.constants.userUrl + "UpdateUser", body, { headers: headers })
      .map((response: Response) => {
        var result = response.json();
        return result;
      })
      .catch(this.handleError)
      .subscribe(
      status => this.statusMessage = status,
      error => this.errorMessage = error,
      () => this.completeUpdateUser()
      );
  }

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

"If I want two columns for anything over 768px, should I apply both classes?"

This should be as simple as:

<div class="row">
      <div class="col-sm-6"></div>
      <div class="col-sm-6"></div>    
</div>

No need to add the col-lg-6 too.

Demo: http://www.bootply.com/73119

How to apply font anti-alias effects in CSS?

here you go Sir :-)

1

.myElement{
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-rendering: optimizeLegibility;
}

2

.myElement{
    text-shadow: rgba(0,0,0,.01) 0 0 1px;
}

Adding to an ArrayList Java

thanks for the help, I've solved my problem :) Here is the code if anyone else needs it :D

import java.util.*;

public class HelloWorld {


public static void main(String[] Args) {

Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(9);
list.add(11);
map.put(1,list);        

    int First = list.get(1);
    int Second = list.get(2);

    if (First < Second) {

        System.out.println("One or more of your items have been restocked. The current stock is: " + First);

        Random rn = new Random();
int answer = rn.nextInt(99) + 1;

System.out.println("You are buying " + answer + " New stock");

First = First + answer;
list.set(1, First);
System.out.println("There are now " + First + " in stock");
}     
}  
}

How to read a text-file resource into Java unit test?

Here's what i used to get the text files with text. I used commons' IOUtils and guava's Resources.

public static String getString(String path) throws IOException {
    try (InputStream stream = Resources.getResource(path).openStream()) {
        return IOUtils.toString(stream);
    }
}

Incrementing in C++ - When to use x++ or ++x?

Postfix form of ++,-- operator follows the rule use-then-change ,

Prefix form (++x,--x) follows the rule change-then-use.

Example 1:

When multiple values are cascaded with << using cout then calculations(if any) take place from right-to-left but printing takes place from left-to-right e.g., (if val if initially 10)

 cout<< ++val<<" "<< val++<<" "<< val;

will result into

12    10    10 

Example 2:

In Turbo C++, if multiple occurrences of ++ or (in any form) are found in an expression, then firstly all prefix forms are computed then expression is evaluated and finally postfix forms are computed e.g.,

int a=10,b;
b=a++ + ++a + ++a + a;
cout<<b<<a<<endl;

It's output in Turbo C++ will be

48 13

Whereas it's output in modern day compiler will be (because they follow the rules strictly)

45 13
  • Note: Multiple use of increment/decrement operators on same variable in one expression is not recommended. The handling/results of such
    expressions vary from compiler to compiler.

how to save DOMPDF generated content to file?

I have just used dompdf and the code was a little different but it worked.

Here it is:

require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);

$html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $output = $dompdf->output();
    file_put_contents('Brochure.pdf', $output);

Only difference here is that all of the files in the include directory are included.

Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.

Changing CSS Values with Javascript

I've never seen any practical use of this, but you should probably consider DOM stylesheets. However, I honestly think that's overkill.

If you simply want to get the width and height of an element, irrespective of where the dimensions are being applied from, just use element.offsetWidth and element.offsetHeight.

How do I implement a progress bar in C#?

If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.

expected constructor, destructor, or type conversion before ‘(’ token

The first constructor in the header should not end with a semicolon. #include <string> is missing in the header. string is not qualified with std:: in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream is broken. I suggest learning C++ before trying to use it.

Let's fix this up:

//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

#include <iostream>
#include <string>    

class Polygone {
public:
  // declarations have to end with a semicolon, definitions do not
  Polygone(){} // why would we needs this?
  Polygone(const std::string& fichier);
};

# endif

and

//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>


Polygone::Polygone(const std::string& nom)
{
  std::ifstream fichier (nom, ios::in);


  if (fichier.is_open())
  {
    // keep the scope as tiny as possible
    std::string line;
    // getline returns the stream and streams convert to booleans
    while ( std::getline(fichier, line) )
    {
      std::cout << line << std::endl;
    }
  }
  else
  {
    std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
  }
}

jQuery get mouse position within an element

Here is one that also gives you percent position of the point in case you need it. https://jsfiddle.net/Themezly/2etbhw01/

_x000D_
_x000D_
function ThzhotspotPosition(evt, el, hotspotsize, percent) {_x000D_
  var left = el.offset().left;_x000D_
  var top = el.offset().top;_x000D_
  var hotspot = hotspotsize ? hotspotsize : 0;_x000D_
  if (percent) {_x000D_
    x = (evt.pageX - left - (hotspot / 2)) / el.outerWidth() * 100 + '%';_x000D_
    y = (evt.pageY - top - (hotspot / 2)) / el.outerHeight() * 100 + '%';_x000D_
  } else {_x000D_
    x = (evt.pageX - left - (hotspot / 2));_x000D_
    y = (evt.pageY - top - (hotspot / 2));_x000D_
  }_x000D_
_x000D_
  return {_x000D_
    x: x,_x000D_
    y: y_x000D_
  };_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $('.box').click(function(e) {_x000D_
_x000D_
    var hp = ThzhotspotPosition(e, $(this), 20, true); // true = percent | false or no attr = px_x000D_
_x000D_
    var hotspot = $('<div class="hotspot">').css({_x000D_
      left: hp.x,_x000D_
      top: hp.y,_x000D_
    });_x000D_
    $(this).append(hotspot);_x000D_
    $("span").text("X: " + hp.x + ", Y: " + hp.y);_x000D_
  });_x000D_
_x000D_
_x000D_
});
_x000D_
.box {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  background: #efefef;_x000D_
  margin: 20px;_x000D_
  padding: 20px;_x000D_
  position: relative;_x000D_
  top: 20px;_x000D_
  left: 20px;_x000D_
}_x000D_
_x000D_
.hotspot {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  height: 20px;_x000D_
  width: 20px;_x000D_
  background: green;_x000D_
  border-radius: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="box">_x000D_
  <p>Hotspot position is at: <span></span></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Making heatmap from pandas DataFrame

If you don't need a plot per say, and you're simply interested in adding color to represent the values in a table format, you can use the style.background_gradient() method of the pandas data frame. This method colorizes the HTML table that is displayed when viewing pandas data frames in e.g. the JupyterLab Notebook and the result is similar to using "conditional formatting" in spreadsheet software:

import numpy as np 
import pandas as pd


index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
cols = ['A', 'B', 'C', 'D']
df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)
df.style.background_gradient(cmap='Blues')

enter image description here

For detailed usage, please see the more elaborate answer I provided on the same topic previously and the styling section of the pandas documentation.

inner join in linq to entities

public IList<Splitting> get(Guid companyId, long customrId) {    
    var res=from c in Customers_data_source
            where c.CustomerId = customrId && c.CompanyID == companyId
            from s in Splittings_data_srouce
            where s.CustomerID = c.CustomerID
            select s;

    return res.ToList();
}

The application was unable to start correctly (0xc000007b)

I just ran into this issue. I searched for "C++" under my "Apps & Features" in Windows 10 control panel and noticed that some kind of update had just run a few days prior and installed VC++ Redistributable 2012-2017. The app that was running into the error message only required VC++ 2010. I uninstalled all of them and then reinstalled just 2010 x86/x64, and the error went away and the application functioned as expected.