Programs & Examples On #Chainable

Difference between jar and war in Java

A JAR file extension is .jar and is created with jar command from command prompt (like javac command is executed). Generally, a JAR file contains Java related resources like libraries, classes etc.JAR file is like winzip file except that Jar files are platform independent.

A WAR file is simply a JAR file but contains only Web related Java files like Servlets, JSP, HTML.

To execute a WAR file, a Web server or Web container is required, for example, Tomcat or Weblogic or Websphere. To execute a JAR file, simple JDK is enough.

How to change max_allowed_packet size

Change in the my.ini or ~/.my.cnf file by including the single line under [mysqld] or [client] section in your file:

max_allowed_packet=500M

then restart the MySQL service and you are done.

See the documentation for further information.

jQuery - add additional parameters on submit (NOT ajax)

This one did it for me:

var input = $("<input>")
               .attr("type", "hidden")
               .attr("name", "mydata").val("bla");
$('#form1').append(input);

is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)

used the Firefox firebug to check whether the element was inserted.

Hidden elements do get posted back in the form collection, only read-only fields are discarded.

Michel

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

If your underlying database data types are varchar then you should stick with the approach below. Otherwise the query would have a huge performance impact.

var firstName = new SqlParameter("@firstName", System.Data.SqlDbType.VarChar, 20)
                            {
                                Value = "whatever"
                            };

var id = new SqlParameter("@id", System.Data.SqlDbType.Int)
                            {
                                Value = 1
                            };
ctx.Database.ExecuteSqlCommand(@"Update [User] SET FirstName = @firstName WHERE Id = @id"
                               , firstName, id);

You can check Sql profiler to see the difference.

The network path was not found

As others pointed out this could be more to do with the connectionstring config Make sure,

  1. user id and password are correct
  2. Data Source is pointing to correct one , for example if you are using SQL express it will be .\SQLEXPRESS
  3. Database is pointing to correct name of database Hope that helps.

Node.js create folder or use existing

Just as a newer alternative to Teemu Ikonen's answer, which is very simple and easily readable, is to use the ensureDir method of the fs-extra package.

It can not only be used as a blatant replacement for the built in fs module, but also has a lot of other functionalities in addition to the functionalities of the fs package.

The ensureDir method, as the name suggests, ensures that the directory exists. If the directory structure does not exist, it is created. Like mkdir -p. Not just the end folder, instead the entire path is created if not existing already.

the one provided above is the async version of it. It also has a synchronous method to perform this in the form of the ensureDirSync method.

Editing in the Chrome debugger

You can use "Overrides" in Chrome to persist javascript changes between page loads, even where you aren't hosting the original source.

  1. Create a folder under Developer Tools > Sources > Overrides
  2. Chrome will ask for permission to the folder, click Allow
  3. Edit the file in Sources>Page then save (ctrl-s). A purple dot will indicate the file is saved locally.

The Overrides sub tab in Chrome Developer Tools

Difference between SRC and HREF

You should remember when to use everyone and that is it
the href is used with links

<a href="#"></a>
<link rel="stylesheet" href="style.css" />

the src is used with scripts and images

<img src="the_image_link" />
<script type="text/javascript" src="" />

the url is used generally in CSS to include something, for exemple to add a background image

selector { background-image: url('the_image_link'); } 

How can I remove duplicate rows?

Oh sure. Use a temp table. If you want a single, not-very-performant statement that "works" you can go with:

DELETE FROM MyTable WHERE NOT RowID IN
    (SELECT 
        (SELECT TOP 1 RowID FROM MyTable mt2 
        WHERE mt2.Col1 = mt.Col1 
        AND mt2.Col2 = mt.Col2 
        AND mt2.Col3 = mt.Col3) 
    FROM MyTable mt)

Basically, for each row in the table, the sub-select finds the top RowID of all rows that are exactly like the row under consideration. So you end up with a list of RowIDs that represent the "original" non-duplicated rows.

Get the IP Address of local computer

Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.

How to get unique values in an array

Another thought of this question. Here is what I did to achieve this with fewer code.

_x000D_
_x000D_
var distinctMap = {};_x000D_
var testArray = ['John', 'John', 'Jason', 'Jason'];_x000D_
for (var i = 0; i < testArray.length; i++) {_x000D_
  var value = testArray[i];_x000D_
  distinctMap[value] = '';_x000D_
};_x000D_
var unique_values = Object.keys(distinctMap);_x000D_
_x000D_
console.log(unique_values);
_x000D_
_x000D_
_x000D_

Fill username and password using selenium in python

I am new to selenium and I tried all solutions above but they don't work. Finally, I tried this manually by

driver = webdriver.Firefox()
import time

driver.get(url)

time.sleep(20)

print (driver.page_source.encode("utf-8"))

Then I could get contents from web.

Full examples of using pySerial package

http://web.archive.org/web/20131107050923/http://www.roman10.net/serial-port-communication-in-python/comment-page-1/

#!/usr/bin/python

import serial, time
#initialization and open the port

#possible timeout values:
#    1. None: wait forever, block call
#    2. 0: non-blocking mode, return immediately
#    3. x, x is bigger than 0, float allowed, timeout block call

ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "/dev/ttyUSB7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 1            #non-block read
#ser.timeout = 2              #timeout block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2     #timeout for write

try: 
    ser.open()
except Exception, e:
    print "error open serial port: " + str(e)
    exit()

if ser.isOpen():

    try:
        ser.flushInput() #flush input buffer, discarding all its contents
        ser.flushOutput()#flush output buffer, aborting current output 
                 #and discard all that is in buffer

        #write data
        ser.write("AT+CSQ")
        print("write data: AT+CSQ")

       time.sleep(0.5)  #give the serial port sometime to receive the data

       numOfLines = 0

       while True:
          response = ser.readline()
          print("read data: " + response)

        numOfLines = numOfLines + 1

        if (numOfLines >= 5):
            break

        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)

else:
    print "cannot open serial port "

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

Writing your own square root function

A simple (but not very fast) method to calculate the square root of X:

squareroot(x)
    if x<0 then Error
    a = 1
    b = x
    while (abs(a-b)>ErrorMargin) 
        a = (a+b)/2
        b = x/a
    endwhile
    return a;

Example: squareroot(70000)

    a       b
    1   70000
35001       2
17502       4
 8753       8
 4381      16
 2199      32
 1116      63
  590     119
  355     197
  276     254
  265     264

As you can see it defines an upper and a lower boundary for the square root and narrows the boundary until its size is acceptable.

There are more efficient methods but this one illustrates the process and is easy to understand.

Just beware to set the Errormargin to 1 if using integers else you have an endless loop.

How do I pass command line arguments to a Node.js program?

Without libraries

If you want to do this in vanilla JS/ES6 you can use the following solution

worked only in NodeJS > 6

const args = process.argv
  .slice(2)
  .map((val, i)=>{
    let object = {};
    let [regexForProp, regexForVal] = (() => [new RegExp('^(.+?)='), new RegExp('\=(.*)')] )();
    let [prop, value] = (() => [regexForProp.exec(val), regexForVal.exec(val)] )();
    if(!prop){
      object[val] = true;
      return object;
    } else {
      object[prop[1]] = value[1] ;
      return object
    }
  })
  .reduce((obj, item) => {
    let prop = Object.keys(item)[0];
    obj[prop] = item[prop];
    return obj;
  }, {});

And this command

node index.js host=http://google.com port=8080 production

will produce the following result

console.log(args);//{ host:'http://google.com',port:'8080',production:true }
console.log(args.host);//http://google.com
console.log(args.port);//8080
console.log(args.production);//true

p.s. Please correct the code in map and reduce function if you find more elegant solution, thanks ;)

cor shows only NA or 1 for correlations - Why?

Tell the correlation to ignore the NAs with use argument, e.g.:

cor(data$price, data$exprice, use = "complete.obs")

What is the most efficient way to create HTML elements using jQuery?

You don't need raw performance from an operation you will perform extremely infrequently from the point of view of the CPU.

How to configure WAMP (localhost) to send email using Gmail?

As an alternative to PHPMailer, Pear's Mail and others you could use the Zend's library

  $config = array('auth' => 'login',
                   'ssl' => 'ssl',
                   'port'=> 465,
                   'username' => '[email protected]',
                   'password' => 'XXXXXXX');

 $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
 $mail = new Zend_Mail();
 $mail->setBodyText('This is the text of the mail.');
 $mail->setFrom('[email protected]', 'Some Sender');
 $mail->addTo('[email protected]', 'Some Recipient');
 $mail->setSubject('TestSubj');
 $mail->send($transport); 

That is my set up in localhost server and I can able to see incoming mail to my mail box.

How to set upload_max_filesize in .htaccess?

Both commands are correct

php_value post_max_size 30M 
php_value upload_max_filesize 30M 

BUT to use the .htaccess you have to enable rewrite_module in Apache config file. In httpd.conf find this line:

# LoadModule rewrite_module modules/mod_rewrite.so

and remove the #.

ASP.NET postback with JavaScript

Here is a complete solution

Entire form tag of the asp.net page

<form id="form1" runat="server">
    <asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>

    <input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
    <input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />

    <asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
    <asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>

Entire Contents of the Page's Code-Behind Class

Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
    Response.Write("You ran the ButtonA click event")
End Sub

Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
    Response.Write("You ran the ButtonB click event")
End Sub
  • The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed

What's going on?

Two input controls are rendered to the client:

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
  • __EVENTTARGET receives argument 1 of __doPostBack
  • __EVENTARGUMENT receives argument 2 of __doPostBack

The __doPostBack function is rendered out like this:

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
  • As you can see, it assigns the values to the hidden inputs.

When the form submits / postback occurs:

  • If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (javascript:__doPostBack('ButtonB',''), then the button click handler for that button will be run.

What if I don't want to run a click handler, but want to do something else instead?

You can pass whatever you want as arguments to __doPostBack

You can then analyze the hidden input values and run specific code accordingly:

If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
    Response.Write("Do Something else") 
End If

Other Notes

  • What if I don't know the ID of the control whose click handler I want to run?
    • If it is not acceptable to set ClientIDMode="Static", then you can do something like this: __doPostBack('<%= myclientid.UniqueID %>', '').
    • Or: __doPostBack('<%= MYBUTTON.UniqueID %>','')
    • This will inject the unique id of the control into the javascript, should you wish it

How can I search for a multiline pattern in a file?

perl -ne 'print if (/begin pattern/../end pattern/)' filename

Using CookieContainer with WebClient class

This one is just extension of article you found.


public class WebClientEx : WebClient
{
    public WebClientEx(CookieContainer container)
    {
        this.container = container;
    }

    public CookieContainer CookieContainer
        {
            get { return container; }
            set { container= value; }
        }

    private CookieContainer container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest r = base.GetWebRequest(address);
        var request = r as HttpWebRequest;
        if (request != null)
        {
            request.CookieContainer = container;
        }
        return r;
    }

    protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
    {
        WebResponse response = base.GetWebResponse(request, result);
        ReadCookies(response);
        return response;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
        ReadCookies(response);
        return response;
    }

    private void ReadCookies(WebResponse r)
    {
        var response = r as HttpWebResponse;
        if (response != null)
        {
            CookieCollection cookies = response.Cookies;
            container.Add(cookies);
        }
    }
}

In Git, what is the difference between origin/master vs origin master?

I suggest merging develop and master with that command

git checkout master

git merge --commit --no-ff --no-edit develop

For more information, check https://git-scm.com/docs/git-merge

Check if event exists on element

You may use:

$("#foo").unbind('click');

to make sure all click events are unbinded, then attach your event

Executing JavaScript without a browser?

I found this related question on the topic, but if you want direct links, here they are:

  • You can install Rhino as others have pointed out. This post shows an easy way to get it up and running and how to alias a command to invoke it easily
  • If you're on a Mac, you can use JavaScriptCore, which invokes WebKit's JavaScript engine. Here's a post on it
  • You can use Chome/Google's V8 interpreter as well. Here are instructions
  • The JavaScript as OSA is interesting because it lets you (AFAIK) interact with scriptable OS X apps as though you were in AppleScript (without the terrible syntax)

I'm surprised node.js doesn't come with a shell, but I guess it's really more like an epoll/selector-based callback/event-oriented webserver, so perhaps it doesn't need the full JS feature set, but I'm not too familiar with its inner workings.

Since you seem interested in node.js and since it's based on V8, it might be best to follow those instructions on getting a V8 environment set up so you can have a consistent basis for your JavaScript programming (I should hope JSC and V8 are mostly the same, but I'm not sure).

Best way to show a loading/progress indicator?

ProgressDialog has become deprecated since API Level 26 https://developer.android.com/reference/android/app/ProgressDialog.html

I include a ProgressBar in my layout

   <ProgressBar
        android:layout_weight="1"
        android:id="@+id/progressBar_cyclic"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="40dp"
        android:minWidth="40dp" />

and change its visibility to .GONE | .VISIBLE depending on the use case.

    progressBar_cyclic.visibility = View.VISIBLE

How to make a vertical line in HTML

For an inline style I used this code:

<div style="border-left:1px black solid; position:absolute; left:50%; height:300px;" />

and that positioned it directly in the center.

turn typescript object into json string

Just use JSON.stringify(object). It's built into Javascript and can therefore also be used within Typescript.

How to include duplicate keys in HashMap?

Map does not supports duplicate keys. you can use collection as value against same key.

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.

Documentation

you can use any kind of List or Set implementation according to your requirement.

If your values might be also duplicate you can go with ArrayList or LinkedList, in case values are unique you can use HashSet or TreeSet etc.


Also In google guava collection library Multimap is available, it is a collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values:

a ? 1, 2
b ? 3  

Example -

ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("a", "1");
multimap.put("a", "2");
multimap.put("c", "3");

splitting a number into the integer and decimal parts

This variant allows getting desired precision:

>>> a = 1234.5678
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e0)
(1234, 0.0)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e1)
(1234, 0.5)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e15)
(1234, 0.5678)

How do I install Python OpenCV through Conda?

I have just tried on two Win32 Python 3.5 computers. At first, I was able to conda install opencv, but it didn't work nor did the version from menpp, but this did:

conda install -c https://conda.binstar.org/conda-forge opencv

How can I detect if this dictionary key exists in C#?

What is the type of c.PhysicalAddresses? If it's Dictionary<TKey,TValue>, then you can use the ContainsKey method.

Add and remove attribute with jquery

Once you remove the ID "page_navigation" that element no longer has an ID and so cannot be found when you attempt to access it a second time.

The solution is to cache a reference to the element:

$(document).ready(function(){
    // This reference remains available to the following functions
    // even when the ID is removed.
    var page_navigation = $("#page_navigation1");

    $("#add").click(function(){
        page_navigation.attr("id","page_navigation1");
    });     

    $("#remove").click(function(){
        page_navigation.removeAttr("id");
    });     
});

Add two numbers and display result in textbox with Javascript

Here a working fiddle: http://jsfiddle.net/sjh36otu/

        function add_number() {

            var first_number = parseInt(document.getElementById("Text1").value);
            var second_number = parseInt(document.getElementById("Text2").value);
            var result = first_number + second_number;

            document.getElementById("txtresult").value = result;
        }

Resize an Array while keeping current elements in Java?

Sorry, but at this time is not possible resize arrays, and may be never will be.

So my recommendation, is to think more to find a solution that allow you get from the beginning of the process, the size of the arrays that you will requiere. This often will implicate that your code need a little more time (lines) to run, but you will save a lot of memory resources.

How to make a Qt Widget grow with the window size?

In Designer, activate the centralWidget and assign a layout, e.g. horizontal or vertical layout. Then your QFormLayout will automatically resize.

Image of Designer

Always make sure, that all widgets have a layout! Otherwise, automatic resizing will break with that widget!

See also

Controls insist on being too large, and won't resize, in QtDesigner

Add to python path mac os x

Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.

  1. In terminal, cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
  2. then sudo nano idlemain.py, enter password if required.
  3. after os.chdir(os.path.expanduser('~/Documents')) this line, I added sys.path.append("/Users/admin/Downloads....") NOTE: replace contents of the quotes with the directory where python module to be added
  4. to save the change, ctrl+x and enter Now open idle and try to import the python module, no error for me!!!

Check for database connection, otherwise display message

very basic:

<?php 
$username = 'user';
$password = 'password';
$server = 'localhost'; 
// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
//if you want to suppress the error message, substitute the connection line for:
//$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');
?>

result:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please

as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php

How to get Database Name from Connection String using SqlConnectionStringBuilder

string connectString = "Data Source=(local);" + "Integrated Security=true";

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);

Console.WriteLine("builder.InitialCatalog = " + builder.InitialCatalog);

Making text bold using attributed string in swift

If you're working with localised strings, you might not be able to rely on the bold string always being at the end of the sentence. If this is the case then the following works well:

e.g. Query "blah" does not match any items

/* Create the search query part of the text, e.g. "blah". 
   The variable 'text' is just the value entered by  the user. */
let searchQuery = "\"\(text)\""

/* Put the search text into the message */
let message = "Query \(searchQuery). does not match any items"

/* Find the position of the search string. Cast to NSString as we want
   range to be of type NSRange, not Swift's Range<Index> */
let range = (message as NSString).rangeOfString(searchQuery)

/* Make the text at the given range bold. Rather than hard-coding a text size,
   Use the text size configured in Interface Builder. */
let attributedString = NSMutableAttributedString(string: message)
attributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(label.font.pointSize), range: range)

/* Put the text in a label */
label.attributedText = attributedString

How do you convert a byte array to a hexadecimal string, and vice versa?

I suspect the speed of this will knock the socks off most of the other tests...

Public Function BufToHex(ByVal buf() As Byte) As String
    Dim sB As New System.Text.StringBuilder
    For i As Integer = 0 To buf.Length - 1
        sB.Append(buf(i).ToString("x2"))
    Next i
    Return sB.ToString
End Function

Converting EditText to int? (Android)

Try this,

EditText x = (EditText) findViewById(R.id.editText1);
int n = Integer.parseInt(x.getText().toString());

How to insert a column in a specific position in oracle without dropping and recreating the table?

You (still) can not choose the position of the column using ALTER TABLE: it can only be added to the end of the table. You can obviously select the columns in any order you want, so unless you are using SELECT * FROM column order shouldn't be a big deal.

If you really must have them in a particular order and you can't drop and recreate the table, then you might be able to drop and recreate columns instead:-

First copy the table

CREATE TABLE my_tab_temp AS SELECT * FROM my_tab;

Then drop columns that you want to be after the column you will insert

ALTER TABLE my_tab DROP COLUMN three;

Now add the new column (two in this example) and the ones you removed.

ALTER TABLE my_tab ADD (two NUMBER(2), three NUMBER(10));

Lastly add back the data for the re-created columns

UPDATE my_tab SET my_tab.three = (SELECT my_tab_temp.three FROM my_tab_temp WHERE my_tab.one = my_tab_temp.one);

Obviously your update will most likely be more complex and you'll have to handle indexes and constraints and won't be able to use this in some cases (LOB columns etc). Plus this is a pretty hideous way to do this - but the table will always exist and you'll end up with the columns in a order you want. But does column order really matter that much?

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

Why does make think the target is up to date?

EDIT: This only applies to some versions of make - you should check your man page.

You can also pass the -B flag to make. As per the man page, this does:

-B, --always-make Unconditionally make all targets.

So make -B test would solve your problem if you were in a situation where you don't want to edit the Makefile or change the name of your test folder.

Matplotlib-Animation "No MovieWriters Available"

I'm running Ubuntu 20 and I had a similar problem

Installed ffmpeg

pip install ffmpeg

then

sudo apt install ffmpeg

How to set value to variable using 'execute' in t-sql?

You can use output parameters with sp_executesql.

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId int 
DECLARE @SQL nvarchar(max) = N'SELECT TOP 1 @siteId = Id FROM ' + quotename(@dbName) + N'..myTbl'
exec sp_executesql @SQL, N'@siteId int out', @siteId out
select @siteId

How to export the Html Tables data into PDF using Jspdf

Unfortunately it is not possible to do it.

jsPDF does not support exporting images and tables in fromHTML method. in jsPDF v0.9.0 rc2

iPhone: Setting Navigation Bar Title

I guess you need a dynamic title that is why you don't set it in IB.

And I presume your viewController object is the one specified in the NIB?

Perhaps trying setting it to a dummy value in IB and then debug the methods to see which controller has the dummy value - assuming it appears as the title...

Make a div fill up the remaining width

I was looking for a solution to the opposite problem where I needed a fixed width div in the centre and a fluid width div on either side, so I came up with the following and thought I'd post it here in case anyone needs it.

_x000D_
_x000D_
#wrapper {_x000D_
  clear: both;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#wrapper div {_x000D_
  display: inline-block;_x000D_
  height: 500px;_x000D_
}_x000D_
_x000D_
#center {_x000D_
  background-color: green;_x000D_
  margin: 0 auto;_x000D_
  overflow: auto;_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
#left {_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
#right {_x000D_
  float: right;_x000D_
}_x000D_
_x000D_
.fluid {_x000D_
  background-color: yellow;_x000D_
  width: calc(50% - 250px);_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="center">_x000D_
    This is fixed width in the centre_x000D_
  </div>_x000D_
  <div id="left" class="fluid">_x000D_
    This is fluid width on the left_x000D_
  </div>_x000D_
  <div id="right" class="fluid">_x000D_
    This is fluid width on the right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you change the width of the #center element then you need to update the width property of .fluid to:

width: calc(50% - [half of center width]px);

What's the "Content-Length" field in HTTP header?

Consider if you have headers such as:

content-encoding: gzip
content-length: 52098
content-type: text/javascript; charset=UTF-8

The content-length is the size of the compressed message body, in "octets" (i.e. in units of 8 bits, which happen to be "bytes" for all modern computers).

The size of the actual message body can be something else, perhaps 150280 bytes.

The number of characters can be different again, perhaps 150231 characters, because some unicode characters use multiple bytes (note UTF-8 is a standard encoding).

So, different numbers depending on whether you care how much data is transmitted, or how much data is held, or how many symbols are seen. Of course, there is no guarantee that these headers will be provided..

syntaxerror: "unexpected character after line continuation character in python" math

The division operator is / rather than \.

Also, the backslash has a special meaning inside a Python string. Either escape it with another backslash:

"\\ 1.5 = "`

or use a raw string

r" \ 1.5 = "

Using Django time/date widgets in custom form

The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that.

That said, here's what you have to do if you're determined to make this work:

  1. Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model):

    from django import forms
    from my_app.models import Product
    from django.contrib.admin import widgets                                       
    
    class ProductForm(forms.ModelForm):
        class Meta:
            model = Product
        def __init__(self, *args, **kwargs):
            super(ProductForm, self).__init__(*args, **kwargs)
            self.fields['mydate'].widget = widgets.AdminDateWidget()
            self.fields['mytime'].widget = widgets.AdminTimeWidget()
            self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()
    
  2. Change your URLconf to pass 'form_class': ProductForm instead of 'model': Product to the generic create_object view (that'll mean "from my_app.forms import ProductForm" instead of "from my_app.models import Product", of course).

  3. In the head of your template, include {{ form.media }} to output the links to the Javascript files.

  4. And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above {{ form.media }} you'll need:

    <script type="text/javascript" src="/my_admin/jsi18n/"></script>
    <script type="text/javascript" src="/media/admin/js/core.js"></script>
    

    You may also wish to use the following admin CSS (thanks Alex for mentioning this):

    <link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/>
    <link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/>
    <link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/>
    <link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/>
    

This implies that Django's admin media (ADMIN_MEDIA_PREFIX) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question.

This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks Jeremy for pointing this out). Sample code for your URLconf:

(r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'),

Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media:

{% load adminmedia %} /* At the top of the template. */

/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>

Thanks lupefiasco for this addition.

How to split a single column values to multiple column values?

I used it recently:

select 
substring(name,1,charindex(' ',name)-1) as Col1,
substring(name,charindex(' ',name)+1,len(name)) as Col2 
from TableName

Most useful NLog configurations

Some of these fall into the category of general NLog (or logging) tips rather than strictly configuration suggestions.

Here are some general logging links from here at SO (you might have seen some or all of these already):

log4net vs. Nlog

Logging best practices

What's the point of a logging facade?

Why do loggers recommend using a logger per class?

Use the common pattern of naming your logger based on the class Logger logger = LogManager.GetCurrentClassLogger(). This gives you a high degree of granularity in your loggers and gives you great flexibility in the configuration of the loggers (control globally, by namespace, by specific logger name, etc).

Use non-classname-based loggers where appropriate. Maybe you have one function for which you really want to control the logging separately. Maybe you have some cross-cutting logging concerns (performance logging).

If you don't use classname-based logging, consider naming your loggers in some kind of hierarchical structure (maybe by functional area) so that you can maintain greater flexibility in your configuration. For example, you might have a "database" functional area, an "analysis" FA, and a "ui" FA. Each of these might have sub-areas. So, you might request loggers like this:

Logger logger = LogManager.GetLogger("Database.Connect");
Logger logger = LogManager.GetLogger("Database.Query");
Logger logger = LogManager.GetLogger("Database.SQL");
Logger logger = LogManager.GetLogger("Analysis.Financial");
Logger logger = LogManager.GetLogger("Analysis.Personnel");
Logger logger = LogManager.GetLogger("Analysis.Inventory");

And so on. With hierarchical loggers, you can configure logging globally (the "*" or root logger), by FA (Database, Analysis, UI), or by subarea (Database.Connect, etc).

Loggers have many configuration options:

<logger name="Name.Space.Class1" minlevel="Debug" writeTo="f1" /> 
<logger name="Name.Space.Class1" levels="Debug,Error" writeTo="f1" /> 
<logger name="Name.Space.*" writeTo="f3,f4" />
<logger name="Name.Space.*" minlevel="Debug" maxlevel="Error" final="true" /> 

See the NLog help for more info on exactly what each of the options means. Probably the most notable items here are the ability to wildcard logger rules, the concept that multiple logger rules can "execute" for a single logging statement, and that a logger rule can be marked as "final" so subsequent rules will not execute for a given logging statement.

Use the GlobalDiagnosticContext, MappedDiagnosticContext, and NestedDiagnosticContext to add additional context to your output.

Use "variable" in your config file to simplify. For example, you might define variables for your layouts and then reference the variable in the target configuration rather than specify the layout directly.

  <variable name="brief" value="${longdate} | ${level} | ${logger} | ${message}"/>
  <variable name="verbose" value="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | ${message}"/>
  <targets>
    <target name="file" xsi:type="File" layout="${verbose}" fileName="${basedir}/${shortdate}.log" />
    <target name="console" xsi:type="ColoredConsole" layout="${brief}" />
  </targets>

Or, you could create a "custom" set of properties to add to a layout.

  <variable name="mycontext" value="${gdc:item=appname} , ${mdc:item=threadprop}"/>
  <variable name="fmt1withcontext" value="${longdate} | ${level} | ${logger} | [${mycontext}] |${message}"/>
  <variable name="fmt2withcontext" value="${shortdate} | ${level} | ${logger} | [${mycontext}] |${message}"/>

Or, you can do stuff like create "day" or "month" layout renderers strictly via configuration:

  <variable name="day" value="${date:format=dddd}"/>
  <variable name="month" value="${date:format=MMMM}"/>
  <variable name="fmt" value="${longdate} | ${level} | ${logger} | ${day} | ${month} | ${message}"/>
  <targets>
    <target name="console" xsi:type="ColoredConsole" layout="${fmt}" />
  </targets>

You can also use layout renders to define your filename:

  <variable name="day" value="${date:format=dddd}"/>
  <targets>
    <target name="file" xsi:type="File" layout="${verbose}" fileName="${basedir}/${day}.log" />
  </targets>

If you roll your file daily, each file could be named "Monday.log", "Tuesday.log", etc.

Don't be afraid to write your own layout renderer. It is easy and allows you to add your own context information to the log file via configuration. For example, here is a layout renderer (based on NLog 1.x, not 2.0) that can add the Trace.CorrelationManager.ActivityId to the log:

  [LayoutRenderer("ActivityId")]
  class ActivityIdLayoutRenderer : LayoutRenderer
  {
    int estimatedSize = Guid.Empty.ToString().Length;

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
      builder.Append(Trace.CorrelationManager.ActivityId);
    }

    protected override int GetEstimatedBufferSize(LogEventInfo logEvent)
    {
      return estimatedSize;
    }
  }

Tell NLog where your NLog extensions (what assembly) like this:

  <extensions>
    <add assembly="MyNLogExtensions"/>
  </extensions>

Use the custom layout renderer like this:

  <variable name="fmt" value="${longdate} | ${ActivityId} | ${message}"/>

Use async targets:

<nlog>
  <targets async="true">
    <!-- all targets in this section will automatically be asynchronous -->
  </targets>
</nlog>

And default target wrappers:

<nlog>  
  <targets>  
    <default-wrapper xsi:type="BufferingWrapper" bufferSize="100"/>  
    <target name="f1" xsi:type="File" fileName="f1.txt"/>  
    <target name="f2" xsi:type="File" fileName="f2.txt"/>  
  </targets>  
  <targets>  
    <default-wrapper xsi:type="AsyncWrapper">  
      <wrapper xsi:type="RetryingWrapper"/>  
    </default-wrapper>  
    <target name="n1" xsi:type="Network" address="tcp://localhost:4001"/>  
    <target name="n2" xsi:type="Network" address="tcp://localhost:4002"/>  
    <target name="n3" xsi:type="Network" address="tcp://localhost:4003"/>  
  </targets>  
</nlog>

where appropriate. See the NLog docs for more info on those.

Tell NLog to watch and automatically reload the configuration if it changes:

<nlog autoReload="true" /> 

There are several configuration options to help with troubleshooting NLog

<nlog throwExceptions="true" />
<nlog internalLogFile="file.txt" />
<nlog internalLogLevel="Trace|Debug|Info|Warn|Error|Fatal" />
<nlog internalLogToConsole="false|true" />
<nlog internalLogToConsoleError="false|true" />

See NLog Help for more info.

NLog 2.0 adds LayoutRenderer wrappers that allow additional processing to be performed on the output of a layout renderer (such as trimming whitespace, uppercasing, lowercasing, etc).

Don't be afraid to wrap the logger if you want insulate your code from a hard dependency on NLog, but wrap correctly. There are examples of how to wrap in the NLog's github repository. Another reason to wrap might be that you want to automatically add specific context information to each logged message (by putting it into LogEventInfo.Context).

There are pros and cons to wrapping (or abstracting) NLog (or any other logging framework for that matter). With a little effort, you can find plenty of info here on SO presenting both sides.

If you are considering wrapping, consider using Common.Logging. It works pretty well and allows you to easily switch to another logging framework if you desire to do so. Also if you are considering wrapping, think about how you will handle the context objects (GDC, MDC, NDC). Common.Logging does not currently support an abstraction for them, but it is supposedly in the queue of capabilities to add.

JavaScript code to stop form submission

I would recommend not using onsubmit and instead attaching an event in the script.

var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
  submit.addEventListener("click", returnToPreviousPage);
} else {
  submit.attachEvent("onclick", returnToPreviousPage);
}

Then use preventDefault() (or returnValue = false for older browsers).

function returnToPreviousPage (e) {
  e = e || window.event;
  // validation code

  // if invalid
  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }
}

Can I have onScrollListener for a ScrollView?

You can use NestedScrollView instead of ScrollView. However, when using a Kotlin Lambda, it won't know you want NestedScrollView's setOnScrollChangeListener instead of the one at View (which is API level 23). You can fix this by specifying the first parameter as a NestedScrollView.

nestedScrollView.setOnScrollChangeListener { _: NestedScrollView, scrollX: Int, scrollY: Int, _: Int, _: Int ->
    Log.d("ScrollView", "Scrolled to $scrollX, $scrollY")
}

Postgresql: error "must be owner of relation" when changing a owner object

From the fine manual.

You must own the table to use ALTER TABLE.

Or be a database superuser.

ERROR: must be owner of relation contact

PostgreSQL error messages are usually spot on. This one is spot on.

CSS Printing: Avoiding cut-in-half DIVs between pages?

page-break-inside: avoid; gave me trouble using wkhtmltopdf.

To avoid breaks in the text add display: table; to the CSS of the text-containing div.

I hope this works for you too. Thanks JohnS.

Change string color with NSAttributedString?

Use something like this (Not compiler checked)

NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSRange range=[self.myLabel.text rangeOfString:texts[sliderValue]]; //myLabel is the outlet from where you will get the text, it can be same or different

NSArray *colors=@[[UIColor redColor],
                  [UIColor redColor],
                  [UIColor yellowColor],
                  [UIColor greenColor]
                 ];

[string addAttribute:NSForegroundColorAttributeName 
               value:colors[sliderValue] 
               range:range];           

[self.scanLabel setAttributedText:texts[sliderValue]];

Why does intellisense and code suggestion stop working when Visual Studio is open?

In my case, I had added an .ascx.cs into the project via right-click => "Include in Project", but the project had it set as "Content" instead of "Compile". Once I set this to "Compile", intellisense began working again.

How to read until end of file (EOF) using BufferedReader in Java?

With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.

for each inside a for each - Java

most simple solution would be to set a boolean var. if to true where you do the insert statement and then in the outter loop check this and insert the tweet there if the boolean is true...

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

I was able to get rid of this issue by installing nvm, then setting node to latest version.

  1. Install nvm using curl (for latest version go to nvm.sh)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
  1. List available node versions
nvm ls

v10.12.0
default -> v10.12 (-> v10.12.0)
node -> stable (-> v10.12.0) (default)
stable -> 10.12 (-> v10.12.0)

  1. Choose which version of node to use
nvm use v10.12

nvm is not compatible with the npm config "prefix" option: currently set to ""

  1. Run this to unset the option:
nvm use --delete-prefix v10.12.0

After following the commands above, you will be able to install react/angular in Ubuntu.

How to use java.String.format in Scala?

The official reference is the class Formatter.

How to stop the task scheduled in java.util.Timer class

Terminate the Timer once after awake at a specific time in milliseconds.

Timer t = new Timer();
t.schedule(new TimerTask() {
            @Override
             public void run() {
             System.out.println(" Run spcific task at given time.");
             t.cancel();
             }
 }, 10000);

Fastest way to check if a file exist using standard C++/C++11/C?

In C++17 :

#include <experimental/filesystem>

bool is_file_exist(std::string& str) {   
    namespace fs = std::experimental::filesystem;
    fs::path p(str);
    return fs::exists(p);
}

List of all unique characters in a string?

char_seen = []
for char in string:
    if char not in char_seen:
        char_seen.append(char)
print(''.join(char_seen))

This will preserve the order in which alphabets are coming,

output will be

abcd

c - warning: implicit declaration of function ‘printf’

You need to include a declaration of the printf() function.

#include <stdio.h>

Show Image View from file path?

       public static Bitmap decodeFile(String path) {
    Bitmap b = null;
    File f = new File(path);
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);
        BitmapFactory.decodeStream(fis, null, o);
        fis.close();

        int IMAGE_MAX_SIZE = 1024; // maximum dimension limit
        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;

        fis = new FileInputStream(f);
        b = BitmapFactory.decodeStream(fis, null, o2);
        fis.close();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return b;
}

public static Bitmap showBitmapFromFile(String file_path)
{
    try {
        File imgFile = new  File(file_path);
        if(imgFile.exists()){

            Bitmap pic_Bitmap = decodeFile(file_path);
            return pic_Bitmap;

        }
    } catch (Exception e) {
        MyLog.e("Exception showBitmapFromFile");
        return null;
    }
    return null;
}   

if you are using image loading in List view then use Aquery concept .

https://github.com/AshishPsaini/AqueryExample

     AQuery  aq= new AQuery((Activity) activity, convertView);
            //load image from file, down sample to target width of 250 pixels .gi 
    File file=new File("//pic/path/here/aaaa.jpg");
    if(aq!=null)
    aq.id(holder.pic_imageview).image(file, 250);

Calculating time difference in Milliseconds

In such a small cases where difference is less than 0 milliseconds you can get difference in nano seconds as well.

System.nanoTime()

How do I get the HTTP status code with jQuery?

I think you should also implement the error function of the $.ajax method.

error(XMLHttpRequest, textStatus, errorThrown)Function

A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
        alert(xhr.status); 
    },
    error: function(xhr, statusText, err){
        alert("Error:" + xhr.status); 
    }
});

Current date and time as string

you can use asctime() function of time.h to get a string simply .

time_t _tm =time(NULL );

struct tm * curtime = localtime ( &_tm );
cout<<"The current date/time is:"<<asctime(curtime);

Sample output:

The current date/time is:Fri Oct 16 13:37:30 2015

Frequency table for a single variable

You can use list comprehension on a dataframe to count frequencies of the columns as such

[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]

Breakdown:

my_series.select_dtypes(include=['O']) 

Selects just the categorical data

list(my_series.select_dtypes(include=['O']).columns) 

Turns the columns from above into a list

[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)] 

Iterates through the list above and applies value_counts() to each of the columns

RVM is not a function, selecting rubies with 'rvm use ...' will not work

You need to add source ~/.rvm/scripts/rvm to ~/.your_shellrc file. From now when you load a shell, rvm will be loaded.

For example:

if you are using zsh shell, need to add in ~/.zshrc file

if you are using bash shell, need to add in ~/.bashrc file

And then open a new tab to see the effect.

How do I declare and assign a variable on a single line in SQL

on sql 2008 this is valid

DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable

on sql server 2005, you need to do this

DECLARE @myVariable nvarchar(Max) 
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable

jQuery: Can I call delay() between addClass() and such?

jQuery's CSS manipulation isn't queued, but you can make it executed inside the 'fx' queue by doing:

$('#div').delay(1000).queue('fx', function() { $(this).removeClass('error'); });

Quite same thing as calling setTimeout but uses jQuery's queue mecanism instead.

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Difference between webdriver.get() and webdriver.navigate()

driver.get(url) and navigate.to(url) both are used to go to particular web page. The key difference is that driver.get(url): It does not maintain the browser history and cookies and wait till page fully loaded. driver.navigate.to(url):It is also used to go to particular web page.it maintain browser history and cookies and does not wait till page fully loaded and have navigation between the pages back, forward and refresh.

how can I enable scrollbars on the WPF Datagrid?

Put the DataGrid in a Grid, DockPanel, ContentControl or directly in the Window. A vertically-oriented StackPanel will give its children whatever vertical space they ask for - even if that means it is rendered out of view.

How can I return the difference between two lists?

With Stream API you can do something like this:

List<String> aWithoutB = a.stream()
    .filter(element -> !b.contains(element))
    .collect(Collectors.toList());

List<String> bWithoutA = b.stream()
    .filter(element -> !a.contains(element))
    .collect(Collectors.toList());

Change label text using JavaScript

Try this:

<label id="lbltipAddedComment"></label>
<script type="text/javascript"> 
      document.getElementById('<%= lbltipAddedComment.ClientID %>').innerHTML = 'your tip has been submitted!';
</script>

CSS: Fix row height

HTML Table row heights will typically change proportionally to the table height, if the table height is larger than the height of your rows. Since the table is forcing the height of your rows, you can remove the table height to resolve the issue. If this is not acceptable, you can also give the rows explicit height, and add a third row that will auto size to the remaining table height.

Another option in CSS2 is the Max-Height Property, although it may lead to strange behavior in a table.http://www.w3schools.com/cssref/pr_dim_max-height.asp

.

Storing data into list with class

You're not adding a new instance of the class to the list. Try this:

lstemail.Add(new EmailData { FirstName="John", LastName="Smith", Location="Los Angeles" });`

List is a generic class. When you specify a List<EmailData>, the Add method is expecting an object that's of type EmailData. The example above, expressed in more verbose syntax, would be:

EmailData data = new EmailData();
data.FirstName="John";
data.LastName="Smith;
data.Location = "Los Angeles";
lstemail.Add(data);

C# - Fill a combo box with a DataTable

For example, i created a table :

DataTable dt = new DataTable ();
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Value", typeof(int));

Add recorde to table :

DataRow row = dt.NewRow();
row["Title"] = "Price"
row["Value"] = 2000;
dt.Rows.Add(row);

or :

dt.Rows.Add("Price",2000);

finally :

combo.DataSource = dt;
combo.DisplayMember = "Title";
combo.ValueMember = "Value";

Environment variable substitution in sed

Dealing with VARIABLES within sed

[root@gislab00207 ldom]# echo domainname: None > /tmp/1.txt

[root@gislab00207 ldom]# cat /tmp/1.txt

domainname: None

[root@gislab00207 ldom]# echo ${DOMAIN_NAME}

dcsw-79-98vm.us.oracle.com

[root@gislab00207 ldom]# cat /tmp/1.txt | sed -e 's/domainname: None/domainname: ${DOMAIN_NAME}/g'

 --- Below is the result -- very funny.

domainname: ${DOMAIN_NAME}

 --- You need to single quote your variable like this ... 

[root@gislab00207 ldom]# cat /tmp/1.txt | sed -e 's/domainname: None/domainname: '${DOMAIN_NAME}'/g'


--- The right result is below 

domainname: dcsw-79-98vm.us.oracle.com

How can I find all the subsets of a set, with exactly n elements?

itertools.combinations is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function.

import itertools
def findsubsets(S,m):
    return set(itertools.combinations(S, m))

S: The set for which you want to find subsets
m: The number of elements in the subset

How to convert any Object to String?

To convert any object to string there are several methods in Java

String convertedToString = String.valueOf(Object);  //method 1

String convertedToString = "" + Object;   //method 2

String convertedToString = Object.toString();  //method 3

I would prefer the first and third

EDIT
If working in kotlin, the official android language

val number: Int = 12345
String convertAndAppendToString = "number = $number"   //method 1

String convertObjectMemberToString = "number = ${Object.number}" //method 2

String convertedToString = Object.toString()  //method 3

String comparison technique used by Python

From the docs:

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

Also:

Lexicographical ordering for strings uses the Unicode code point number to order individual characters.

or on Python 2:

Lexicographical ordering for strings uses the ASCII ordering for individual characters.

As an example:

>>> 'abc' > 'bac'
False
>>> ord('a'), ord('b')
(97, 98)

The result False is returned as soon as a is found to be less than b. The further items are not compared (as you can see for the second items: b > a is True).

Be aware of lower and uppercase:

>>> [(x, ord(x)) for x in abc]
[('a', 97), ('b', 98), ('c', 99), ('d', 100), ('e', 101), ('f', 102), ('g', 103), ('h', 104), ('i', 105), ('j', 106), ('k', 107), ('l', 108), ('m', 109), ('n', 110), ('o', 111), ('p', 112), ('q', 113), ('r', 114), ('s', 115), ('t', 116), ('u', 117), ('v', 118), ('w', 119), ('x', 120), ('y', 121), ('z', 122)]
>>> [(x, ord(x)) for x in abc.upper()]
[('A', 65), ('B', 66), ('C', 67), ('D', 68), ('E', 69), ('F', 70), ('G', 71), ('H', 72), ('I', 73), ('J', 74), ('K', 75), ('L', 76), ('M', 77), ('N', 78), ('O', 79), ('P', 80), ('Q', 81), ('R', 82), ('S', 83), ('T', 84), ('U', 85), ('V', 86), ('W', 87), ('X', 88), ('Y', 89), ('Z', 90)]

Html table tr inside td

Put another table inside the td element like this.

<table>
    <tr>
        ...
    </tr>
    <tr>
        <td>ABC</td>
        <td>ABC</td>
        <td>
            <table>
                <tr>
                    <td>name1</td>
                    <td>price1</td>
                </tr>
...
            </table>
        </td>
        <td>ABC</td>
    </tr>
...
</table>

Concatenating null strings in Java

The second line is transformed to the following code:

s = (new StringBuilder()).append((String)null).append("hello").toString();

The append methods can handle null arguments.

adb shell su works but adb root does not

I ran into this issue when trying to root the emulator, I found out it was because I was running the Nexus 5x emulator which had Google Play on it. Created a different emulator that didn't have google play and adb root will root the device for you. Hope this helps someone.

Python Progress Bar

If your work can't be broken down into measurable chunks, you could call your function in a new thread and time how long it takes:

import thread
import time
import sys

def work():
    time.sleep( 5 )

def locked_call( func, lock ):
    lock.acquire()
    func()
    lock.release()

lock = thread.allocate_lock()
thread.start_new_thread( locked_call, ( work, lock, ) )

# This part is icky...
while( not lock.locked() ):
    time.sleep( 0.1 )

while( lock.locked() ):
    sys.stdout.write( "*" )
    sys.stdout.flush()
    time.sleep( 1 )
print "\nWork Done"

You can obviously increase the timing precision as required.

Custom Date/Time formatting in SQL Server

I'm adding this answer (for myself) as relevant to custom formatting.

For underscore yyyy_MM_dd

REPLACE(SUBSTRING(CONVERT(VARCHAR, @dt, 120), 1, 10),'-','_')

Java: How to convert String[] to List or Set

java.util.Arrays.asList(new String[]{"a", "b"})

Run function from the command line

We can write something like this. I have used with python-3.7.x

import sys

def print_fn():
    print("Hi")

def sum_fn(a, b):
    print(a + b)

if __name__ == "__main__":
    args = sys.argv
    # args[0] = current file
    # args[1] = function name
    # args[2:] = function args : (*unpacked)
    globals()[args[1]](*args[2:])

python demo.py print_fn
python demo.py sum_fn 5 8

C++ convert from 1 char to string?

I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:

#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;

Running multiple async tasks and waiting for them all to complete

You can use WhenAll which will return an awaitable Task or WaitAll which has no return type and will block further code execution simular to Thread.Sleep until all tasks are completed, canceled or faulted.

enter image description here

Example

var tasks = new Task[] {
    TaskOperationOne(),
    TaskOperationTwo()
};

Task.WaitAll(tasks);
// or
await Task.WhenAll(tasks);

If you want to run the tasks in a praticular order you can get inspiration form this anwser.

ExecutorService that interrupts tasks after a timeout

You can use a ScheduledExecutorService for this. First you would submit it only once to begin immediately and retain the future that is created. After that you can submit a new task that would cancel the retained future after some period of time.

 ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); 
 final Future handler = executor.submit(new Callable(){ ... });
 executor.schedule(new Runnable(){
     public void run(){
         handler.cancel();
     }      
 }, 10000, TimeUnit.MILLISECONDS);

This will execute your handler (main functionality to be interrupted) for 10 seconds, then will cancel (i.e. interrupt) that specific task.

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

https://mail.google.com/mail/u/0/x/?&v=b&eot=1&pv=tl&cs=b

This link works for composing directly in m.gmail.com as mobile in a desktop browser. Why? It is really faster.

app-release-unsigned.apk is not signed

In tool window bar select Build Variants Change Build Variant from Release to Debug

Write to UTF-8 file in Python

@S-Lott gives the right procedure, but expanding on the Unicode issues, the Python interpreter can provide more insights.

Jon Skeet is right (unusual) about the codecs module - it contains byte strings:

>>> import codecs
>>> codecs.BOM
'\xff\xfe'
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
>>> 

Picking another nit, the BOM has a standard Unicode name, and it can be entered as:

>>> bom= u"\N{ZERO WIDTH NO-BREAK SPACE}"
>>> bom
u'\ufeff'

It is also accessible via unicodedata:

>>> import unicodedata
>>> unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE')
u'\ufeff'
>>> 

Short IF - ELSE statement

As others have indicated, something of the form

x ? y : z

is an expression, not a (complete) statement. It is an rvalue which needs to get used someplace - like on the right side of an assignment, or a parameter to a function etc.

Perhaps you could look at this: http://download.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html

Where is the IIS Express configuration / metabase file found?

For VS 2015 & VS 2017: Right-click the IIS Express system tray icon (when running the application), and select "Show all applications":

Context menu for IIS Express system tray icon showing the alternative "Show all applications" highlighted

Then, select the relevant application and click the applicationhost.config file path:

Dialog showing arbritrary website with accompanying applicationhost.config file path

How to sort a Ruby Hash by number value?

Since value is the last entry, you can do:

metrics.sort_by(&:last)

How to run Gulp tasks sequentially one after the other

I generated a node/gulp app using the generator-gulp-webapp Yeoman generator. It handled the "clean conundrum" this way (translating to the original tasks mentioned in the question):

gulp.task('develop', ['clean'], function () {
  gulp.start('coffee');
});

Google Map API v3 ~ Simply Close an infowindow?

Or you can share/reuse the same infoWindow object. See this google demo for reference.

Same code from demo

var Demo = { map: null,  infoWindow: null
};

/**
 * Called when clicking anywhere on the map and closes the info window.
 */
Demo.closeInfoWindow = function() {
  Demo.infoWindow.close();
};

/**
 * Opens the shared info window, anchors it to the specified marker, and
 * displays the marker's position as its content.
 */
Demo.openInfoWindow = function(marker) {
  var markerLatLng = marker.getPosition();
  Demo.infoWindow.setContent([
    '<b>Marker position is:</b><br/>',
    markerLatLng.lat(),
    ', ',
    markerLatLng.lng()
  ].join(''));
  Demo.infoWindow.open(Demo.map, marker);
},

/**
 * Called only once on initial page load to initialize the map.
 */
Demo.init = function() {
  // Create single instance of a Google Map.
  var centerLatLng = new google.maps.LatLng(37.789879, -122.390442);
  Demo.map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 13,
    center: centerLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // Create a single instance of the InfoWindow object which will be shared
  // by all Map objects to display information to the user.
  Demo.infoWindow = new google.maps.InfoWindow();

  // Make the info window close when clicking anywhere on the map.
  google.maps.event.addListener(Demo.map, 'click', Demo.closeInfoWindow);

  // Add multiple markers in a few random locations around San Francisco.
  // First random marker
  var marker1 = new google.maps.Marker({
    map: Demo.map,
    position: centerLatLng
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker1, 'click', function() {
    Demo.openInfoWindow(marker1);
  });

  // Second random marker
  var marker2 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.787814,-122.40764),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker2, 'click', function() {
    Demo.openInfoWindow(marker2);
  });

  // Third random marker
  var marker3 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.767568,-122.391665),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker3, 'click', function() {
    Demo.openInfoWindow(marker3);
  });
}

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

@dimas's answer is not logically consistent with your question; ifAllGranted cannot be directly replaced with hasAnyRole.

From the Spring Security 3—>4 migration guide:

Old:

<sec:authorize ifAllGranted="ROLE_ADMIN,ROLE_USER">
    <p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>

New (SPeL):

<sec:authorize access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')">
    <p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>

Replacing ifAllGranted directly with hasAnyRole will cause spring to evaluate the statement using an OR instead of an AND. That is, hasAnyRole will return true if the authenticated principal contains at least one of the specified roles, whereas Spring's (now deprecated as of Spring Security 4) ifAllGranted method only returned true if the authenticated principal contained all of the specified roles.

TL;DR: To replicate the behavior of ifAllGranted using Spring Security Taglib's new authentication Expression Language, the hasRole('ROLE_1') and hasRole('ROLE_2') pattern needs to be used.

How to check if a directory containing a file exist?

To check if a folder exists or not, you can simply use the exists() method:

// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )

// If it doesn't exist
if( !folder.exists() ) {
  // Create all folders up-to and including B
  folder.mkdirs()
}

// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
  w << "Some text\n"
}

Best dynamic JavaScript/JQuery Grid

Have a look at agiletoolkit.org as this has a simple to use CRUD which supports 2,4,6,7,9,10 and 12 out of the box (uses Ajax to defender the grid when adding,deleting data and it integrates with jquery.

I would post some examples but on an iPad at the moment.

How to remove decimal values from a value of type 'double' in Java

the simple way to remove

new java.text.DecimalFormat("#").format(value)

How to launch PowerShell (not a script) from the command line

If you go to C:\Windows\system32\Windowspowershell\v1.0 (and C:\Windows\syswow64\Windowspowershell\v1.0 on x64 machines) in Windows Explorer and double-click powershell.exe you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe can be set independently from the default properties.

To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.

Running start powershell from cmd.exe should start a new console with your default settings.

Android Studio - mergeDebugResources exception

In my case, when I changed package name this issue appeared, I just followed below steps to fix my problem:

  1. Removed previously installed apk (uninstall)

  2. Applied project clean

  3. Run the app

Parse an HTML string with JS

The following function parseHTML will return either :


The code :

function parseHTML(markup) {
    if (markup.toLowerCase().trim().indexOf('<!doctype') === 0) {
        var doc = document.implementation.createHTMLDocument("");
        doc.documentElement.innerHTML = markup;
        return doc;
    } else if ('content' in document.createElement('template')) {
       // Template tag exists!
       var el = document.createElement('template');
       el.innerHTML = markup;
       return el.content;
    } else {
       // Template tag doesn't exist!
       var docfrag = document.createDocumentFragment();
       var el = document.createElement('body');
       el.innerHTML = markup;
       for (i = 0; 0 < el.childNodes.length;) {
           docfrag.appendChild(el.childNodes[i]);
       }
       return docfrag;
    }
}

How to use :

var links = parseHTML('<!doctype html><html><head></head><body><a>Link 1</a><a>Link 2</a></body></html>').getElementsByTagName('a');

How to change default text file encoding in Eclipse?

What worked for me in Eclipse Mars was to go to Window > Preferences > Web > HTML Files, and in the right panel in Encoding select ISO 10646/Unicode(UTF-8), Apply and OK, then and only then my .html files were created with .

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.

Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx

How to filter object array based on attributes?

var filterHome = homes.filter(home =>
  return (home.price <= 999 &&
         home.num_of_baths >= 2.5 &&
         home.num_of_beds >=2 &&
         home.sqft >= 998));
console.log(filterHome);

You can use this lambda function. More detail can be found here since we are filtering the data based on you have condition which return true or false and it will collect the data in different array so your actual array will be not modified.

@JGreig Please look into it.

getting only name of the class Class.getName()

Get simple name instead of path.

String onlyClassName =  this.getLocalClassName(); 

call above method in onCreate

MySQL: How to copy rows, but change a few fields?

This is a solution where you have many fields in your table and don't want to get a finger cramp from typing all the fields, just type the ones needed :)

How to copy some rows into the same table, with some fields having different values:

  1. Create a temporary table with all the rows you want to copy
  2. Update all the rows in the temporary table with the values you want
  3. If you have an auto increment field, you should set it to NULL in the temporary table
  4. Copy all the rows of the temporary table into your original table
  5. Delete the temporary table

Your code:

CREATE table temporary_table AS SELECT * FROM original_table WHERE Event_ID="155";

UPDATE temporary_table SET Event_ID="120";

UPDATE temporary_table SET ID=NULL

INSERT INTO original_table SELECT * FROM temporary_table;

DROP TABLE temporary_table

General scenario code:

CREATE table temporary_table AS SELECT * FROM original_table WHERE <conditions>;

UPDATE temporary_table SET <fieldx>=<valuex>, <fieldy>=<valuey>, ...;

UPDATE temporary_table SET <auto_inc_field>=NULL;

INSERT INTO original_table SELECT * FROM temporary_table;

DROP TABLE temporary_table

Simplified/condensed code:

CREATE TEMPORARY TABLE temporary_table AS SELECT * FROM original_table WHERE <conditions>;

UPDATE temporary_table SET <auto_inc_field>=NULL, <fieldx>=<valuex>, <fieldy>=<valuey>, ...;

INSERT INTO original_table SELECT * FROM temporary_table;

As creation of the temporary table uses the TEMPORARY keyword it will be dropped automatically when the session finishes (as @ar34z suggested).

How to see the proxy settings on windows?

You can use a tool called: NETSH

To view your system proxy information via command line:

netsh.exe winhttp show proxy

Another way to view it is to open IE, then click on the "gear" icon, then Internet options -> Connections tab -> click on LAN settings

Checkout subdirectories in Git?

One thing I don't like about sparse checkouts, is that if you want to checkout a subdirectory that is a few directories deep, your directory structure must contain all directories leading to it.

How I work around this is to clone the repo in a place that is not my workspace and then create a symbolic link in my workspace directory to the subdirectory in the repository. Git works like this quite nicely because things like git status will display the change files relative to your current working directory.

Why do I get access denied to data folder when using adb?

I had a lot of trouble with this also. I still don't fully understand the permission and root run, but this worked for me (one of the previous answers partly) to copy database file from /data/data/[package name]/databases/my_db.db . Running shell root, or su in shell for some reason didn't work, nor did copying the db file (I could navigate to the directory though), nor did sqlite3.

So, this worked! In DOS command prompt:

C:\Program Files\Android\android-sdk\platform-tools>adb shell
1|shell@android:/ $ run-as de.vogella.android.locationapi.maps
run-as de.vogella.android.locationapi.maps
1|shell@android:/data/data/de.vogella.android.locationapi.maps $ cd /data
cd /data
shell@android:/data $ cd data
cd data
shell@android:/data/data $ cd de.vogella.android.locationapi.maps
cd de.vogella.android.locationapi.maps
shell@android:/data/data/de.vogella.android.locationapi.maps $ cd databases
cd databases
shell@android:/data/data/de.vogella.android.locationapi.maps/databases $ ls
ls
bus_timetable_lines.db
bus_timetable_lines.db-journal
shell@android:/data/data/de.vogella.android.locationapi.maps/databases $ cat bus
_timetable_lines.db > /sdcard/db_copy.db
 bus_timetable_lines.db > /sdcard/db_copy.db                                   <
shell@android:/data/data/de.vogella.android.locationapi.maps/databases $exit   ^
exit
shell@android:/ $ exit
exit

C:\Program Files\Android\android-sdk\platform-tools>

Now go to SDCARD directory and get your file db_copy.db . Even that was hidden, but I managed to email it. Back in Windows, I was able to open db file with SQLite Database Browser. :)

Fully change package name including company domain

I found another solution for renaming a package in the entire project:

Open a file in the package. IntelliJ displays the breadcrumbs of the file, above the opened file. On the package you want renamed: Right click > Refactor > Rename. This renames the package/directory throughout the entire project.

How do I validate a date in rails?

Here's a non-chronic answer..

class Pimping < ActiveRecord::Base

validate :valid_date?

def valid_date?
  if scheduled_on.present?
    unless scheduled_on.is_a?(Time)
      errors.add(:scheduled_on, "Is an invalid date.")
    end
  end
end

How do you print in Sublime Text 2

This isn't supported yet. You can use plugins to export the text into HTML or RTF first, and then you can print it out, if you want.

Here is for example the SublimeHighlight plugin which you can use for exporting.

How to set iPhone UIView z index?

You can use the zPosition property of the view's layer (it's a CALayer object) to change the z-index of the view.

theView.layer.zPosition = 1;

As Viktor Nordling added, "big values are on top. You can use any values you want, including negative values." The default value is 0.

You need to import the QuartzCore framework to access the layer. Just add this line of code at the top of your implementation file.

#import "QuartzCore/QuartzCore.h"

OAuth: how to test with local URLs?

Taking Google OAuth as reference

  • In your OAuth client Tab

    1. Add your App URI example(http://localhost:3000) to Authorized JavaScript origins URIs
  • In your OAuth consent screen

    1. Add mywebsite.com to Authorized domains
  • Edit the hosts file on windows or linux Windows C:\Windows\System32\Drivers\etc\hosts Linux : /etc/hosts to add 127.0.0.1 mywebsite.com (N.B. Comment out any if there is any other 127.0.0.1)

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

The final keyword is used to declare constants.

final int FILE_TYPE = 3;

The finally keyword is used in a try catch statement to specify a block of code to execute regardless of thrown exceptions.

try
{
  //stuff
}
catch(Exception e)
{
  //do stuff
}
finally
{
  //this is always run
}

And finally (haha), finalize im not entirely sure is a keyword, but there is a finalize() function in the Object class.

JavaScript: client-side vs. server-side validation

JavaScript can be modified at runtime.

I suggest a pattern of creating a validation structure on the server, and sharing this with the client.

You'll need separate validation logic on both ends, ex:

"required" attributes on inputs client-side

field.length > 0 server-side.

But using the same validation specification will eliminate some redundancy (and mistakes) of mirroring validation on both ends.

jQuery see if any or no checkboxes are selected

JQuery .is will test all specified elements and return true if at least one of them matches selector:

if ($(":checkbox[name='choices']", form).is(":checked"))
{
    // one or more checked
}
else
{
    // nothing checked
}

Converting java date to Sql timestamp

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

This gives me the following output:

 utilDate:Fri Apr 04 12:07:37 MSK 2014
 sqlDate:2014-04-04

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

Logging request/response messages when using HttpClient

Network tracing also available for next objects (see article on msdn)

  • System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
  • System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
  • System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
  • System.Net.Cache Some private and internal methods in System.Net.Cache.
  • System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
  • System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.

Put next lines of code to the configuration file

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Cache">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Http">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Sockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.WebSockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <add name="System.Net" value="Verbose"/>  
      <add name="System.Net.Cache" value="Verbose"/>  
      <add name="System.Net.Http" value="Verbose"/>  
      <add name="System.Net.Sockets" value="Verbose"/>  
      <add name="System.Net.WebSockets" value="Verbose"/>  
    </switches>  
    <sharedListeners>  
      <add name="System.Net"  
        type="System.Diagnostics.TextWriterTraceListener"  
        initializeData="network.log"  
      />  
    </sharedListeners>  
    <trace autoflush="true"/>  
  </system.diagnostics>  
</configuration>  

Find and replace string values in list

You can use, for example:

words = [word.replace('[br]','<br />') for word in words]

How to open .mov format video in HTML video Tag?

You can use below code:

<video width="400" controls autoplay>
    <source src="D:/mov1.mov" type="video/mp4">
</video>

this code will help you.

How to put a text beside the image?

make the image float: left; and the text float: right;

Take a look at this fiddle I used a picture online but you can just swap it out for your picture.

SQL MAX of multiple columns?

If you're using MySQL, you can use

SELECT GREATEST(col1, col2 ...) FROM table

How to print from Flask @app.route to python console

I tried running @Viraj Wadate's code, but couldn't get the output from app.logger.info on the console.

To get INFO, WARNING, and ERROR messages in the console, the dictConfig object can be used to create logging configuration for all logs (source):

from logging.config import dictConfig
from flask import Flask


dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'ext://flask.logging.wsgi_errors_stream',
        'formatter': 'default'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})


app = Flask(__name__)

@app.route('/')
def index():
    return "Hello from Flask's test environment"

@app.route('/print')
def printMsg():
    app.logger.warning('testing warning log')
    app.logger.error('testing error log')
    app.logger.info('testing info log')
    return "Check your console"

if __name__ == '__main__':
    app.run(debug=True)

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

import { HttpClientModule } from '@angular/common/http';

The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below

http.get('friends.json').subscribe(result => this.result =result);

Find all special characters in a column in SQL Server 2008

The following transact SQL script works for all languages (international). The solution is not to check for alphanumeric but to check for not containing special characters.

DECLARE @teststring nvarchar(max)
SET @teststring = 'Test''Me'
SELECT 'IS ALPHANUMERIC: ' + @teststring
WHERE @teststring NOT LIKE '%[-!#%&+,./:;<=>@`{|}~"()*\\\_\^\?\[\]\'']%' {ESCAPE '\'}

How to wait in a batch script?

Well, does sleep even exist on your Windows XP box? According to this post: http://malektips.com/xp_dos_0002.html sleep isn't available on Windows XP, and you have to download the Windows 2003 Resource Kit in order to get it.

Chakrit's answer gives you another way to pause, too.

Try running sleep 10 from a command prompt.

Function to return only alpha-numeric characters from string?

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.

What are examples of TCP and UDP in real life?

TCP :

Transmission Control Protocol is a connection-oriented protocol, which means that it requires handshaking to set up end-to-end communications. Once a connection is set up, user data may be sent bi-directionally over the connection.

Reliable – Strictly only at transport layer, TCP manages message acknowledgment, retransmission and timeout. Multiple attempts to deliver the message are made. If it gets lost along the way, the server will re-request the lost part. In TCP, there's either no missing data, or, in case of multiple timeouts, the connection is dropped. (This reliability however does not cover application layer, at which a separate acknowledgement flow control is still necessary)

Ordered – If two messages are sent over a connection in sequence, the first message will reach the receiving application first. When data segments arrive in the wrong order, TCP buffers delay the out-of-order data until all data can be properly re-ordered and delivered to the application.

Heavyweight – TCP requires three packets to set up a socket connection, before any user data can be sent. TCP handles reliability and congestion control. Streaming – Data is read as a byte stream, no distinguishing indications are transmitted to signal message (segment) boundaries.

Applications of TCP

World Wide Web, email, remote administration, and file transfer rely on TCP.

UDP :

User Datagram Protocol is a simpler message-based connectionless protocol. Connectionless protocols do not set up a dedicated end-to-end connection. Communication is achieved by transmitting information in one direction from source to destination without verifying the readiness or state of the receiver.

Unreliable – When a UDP message is sent, it cannot be known if it will reach its destination; it could get lost along the way. There is no concept of acknowledgment, retransmission, or timeout.

Not ordered – If two messages are sent to the same recipient, the order in which they arrive cannot be predicted.

Lightweight – There is no ordering of messages, no tracking connections, etc. It is a small transport layer designed on top of IP.

Datagrams – Packets are sent individually and are checked for integrity only if they arrive. Packets have definite boundaries which are honored upon receipt, meaning a read operation at the receiver socket will yield an entire message as it was originally sent. No congestion control – UDP itself does not avoid congestion. Congestion control measures must be implemented at the application level.

Broadcasts – being connectionless, UDP can broadcast - sent packets can be addressed to be receivable by all devices on the subnet.

Multicast – a multicast mode of operation is supported whereby a single datagram packet can be automatically routed without duplication to very large numbers of subscribers.

Applications of UDP

Numerous key Internet applications use UDP, including: the Domain Name System (DNS), where queries must be fast and only consist of a single request followed by a single reply packet, the Simple Network Management Protocol (SNMP), the Routing Information Protocol (RIP) and the Dynamic Host Configuration Protocol (DHCP).

Voice and video traffic is generally transmitted using UDP. Real-time video and audio streaming protocols are designed to handle occasional lost packets, so only slight degradation in quality occurs, rather than large delays if lost packets were retransmitted. Because both TCP and UDP run over the same network, many businesses are finding that a recent increase in UDP traffic from these real-time applications is hindering the performance of applications using TCP, such as point of sale, accounting, and database systems. When TCP detects packet loss, it will throttle back its data rate usage. Since both real-time and business applications are important to businesses, developing quality of service solutions is seen as crucial by some.

Some VPN systems such as OpenVPN may use UDP while implementing reliable connections and error checking at the application level.

How to Set a Custom Font in the ActionBar Title?

From Android Support Library v26 + Android Studio 3.0 onwards, this process has become easy as a flick!!

Follow these steps to change the font of Toolbar Title:

  1. Read Downloadable Fonts & select any font from the list (my recommendation) or load a custom font to res > font as per Fonts in XML
  2. In res > values > styles, paste the following (use your imagination here!)

    <style name="TitleBarTextAppearance" parent="android:TextAppearance">
        <item name="android:fontFamily">@font/your_desired_font</item>
        <item name="android:textSize">23sp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@android:color/white</item>
    </style>
    
  3. Insert a new line in your Toolbar properties app:titleTextAppearance="@style/TextAppearance.TabsFont" as shown below

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:titleTextAppearance="@style/TitleBarTextAppearance"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>
    
  4. Enjoy Custom Actionbar Title font styling!!

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.

AFAIK, these are your options:

  1. Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters

  2. There also executable wrappers - see How can I convert my Java program to an .exe file?

See also: Convert Java to EXE: Why, When, When Not and How

MySQL Workbench not opening on Windows

What works for me (workbench 64bit) is that I installed Visual Studio 2015, 2017 and 2019 here is url: https://support.microsoft.com/en-ph/help/2977003/the-latest-supported-visual-c-downloads

I installed both x86: vc_redist.x86.exe and x64: vc_redist.x64.exe

What is the definition of "interface" in object oriented programming

I don't think "blueprint" is a good word to use. A blueprint tells you how to build something. An interface specifically avoids telling you how to build something.

An interface defines how you can interact with a class, i.e. what methods it supports.

When is a language considered a scripting language?

just to breif

Scripting languages run inside another program. Scripting languages are not compiled. Scripting languages are easy to use and easy to write. but …

Very popular programming languages (Java, C#) run inside a ‘parent’ program – like scripting languages. Scripting languages today are used to build complex software. Computers are so fast these days, and scripting languages are so efficient, that for most business operations, there is no practical speed advantage (that there once was,) with a compiled programming language.

Allow 2 decimal places in <input type="number">

Try this for allowing only 2 decimal in input type

<input type="number" step="0.01" class="form-control"  />

Or Use jQuery as suggested by @SamohtVII

$( "#ELEMENTID" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You can just create the required CORS configuration as a bean. As per the code below this will allow all requests coming from any origin. This is good for development but insecure. Spring Docs

@Bean
WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
        }
    }
}

Print: Entry, ":CFBundleIdentifier", Does Not Exist

The error message similar to The domain/default pair of (../ios/Runner/Info, CFBundleIdentifier) does not exist

Means Xcode think you plist have invalid format content.

You need to past out the content of Info.plist file to find out what's wrong with that file.

One possible problem is that this <key>s and <values>s (<array>s, <string>s, or <bool>s ) are not paired correct. For example:

<key>UISupportedInterfaceOrientations</key>         //<------ here is the key
<key>NSPhotoLibraryUsageDescription</key>
<key>NSCameraUsageDescription</key>
<string>Tagueo necesita usar la camara</string>
<key>NSMicrophoneUsageDescription</key>
<string>Tagueo necesita usar el microfono</string>
<array>                                            //<------ here is the value
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>   //<------ please compare this key
<array>                                            //<------ please compare this value
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationPortraitUpsideDown</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>

You only need to move the key and value togather

<key>UISupportedInterfaceOrientations</key>        //<------ here is the key
<array>                                            //<------ follow with the value
   <string>UIInterfaceOrientationPortrait</string>
   <string>UIInterfaceOrientationLandscapeLeft</string>
   <string>UIInterfaceOrientationLandscapeRight</string>
</array>

SQL Server procedure declare a list

You can convert the list of passed values into a table valued parameter and then select against this list

DECLARE @list NVARCHAR(MAX)
SET @list = '1,2,5,7,10';

DECLARE @pos INT
DECLARE @nextpos INT
DECLARE @valuelen INT
DECLARE @tbl TABLE (number int NOT NULL)

SELECT @pos = 0, @nextpos = 1;

WHILE @nextpos > 0
BEGIN
    SELECT @nextpos = charindex(',', @list, @pos + 1)
    SELECT @valuelen = CASE WHEN @nextpos > 0
                            THEN @nextpos
                            ELSE len(@list) + 1
                        END - @pos - 1
    INSERT @tbl (number)
        VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
    SELECT @pos = @nextpos;
END

SELECT * FROM DBTable WHERE id IN (SELECT number FROM @tbl);

In this example the string passed in '1,2,5,7,10' is split by the commas and each value is added as a new row within the @tbl table variable. This can then be selected against using standard SQL.

If you intend to reuse this functionality you could go further and convert this into a function.

How to programmatically click a button in WPF?

The problem with the Automation API solution is, that it required a reference to the Framework assembly UIAutomationProvider as project/package dependency.

An alternative is to emulate the behaviour. In the following there is my extended solution which also condiders the MVVM-pattern with its bound commands - implemented as extension method:

public static class ButtonExtensions
{
    /// <summary>
    /// Performs a click on the button.<br/>
    /// This is the WPF-equivalent of the Windows Forms method "<see cref="M:System.Windows.Forms.Button.PerformClick" />".
    /// <para>This simulates the same behaviours as the button was clicked by the user by keyboard or mouse:<br />
    /// 1. The raising the ClickEvent.<br />
    /// 2.1. Checking that the bound command can be executed, calling <see cref="ICommand.CanExecute" />, if a command is bound.<br />
    /// 2.2. If command can be executed, then the <see cref="ICommand.Execute(object)" /> will be called and the optional bound parameter is p
    /// </para>
    /// </summary>
    /// <param name="sourceButton">The source button.</param>
    /// <exception cref="ArgumentNullException">sourceButton</exception>
    public static void PerformClick(this Button sourceButton)
    {
        // Check parameters
        if (sourceButton == null)
            throw new ArgumentNullException(nameof(sourceButton));

        // 1.) Raise the Click-event
        sourceButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));

        // 2.) Execute the command, if bound and can be executed
        ICommand boundCommand = sourceButton.Command;
        if (boundCommand != null)
        {
            object parameter = sourceButton.CommandParameter;
            if (boundCommand.CanExecute(parameter) == true)
                boundCommand.Execute(parameter);
        }
    }
}

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Here's another solution not using date(). not so smart:)

$var = '20/04/2012';
echo implode("-", array_reverse(explode("/", $var)));

log4j configuration via JVM argument(s)?

Do you have a log4j configuration file ? Just reference it using

-Dlog4j.configuration={path to file}

where {path to file} should be prefixed with file:

Edit: If you are working with log4j2, you need to use

-Dlog4j.configurationFile={path to file}

Taken from answer https://stackoverflow.com/a/34001970/552525

Add default value of datetime field in SQL Server to a timestamp

This works for me...

ALTER TABLE [accounts] 
 ADD [user_registered] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;

MySQL JOIN the most recent row only?

You can also do this

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
LEFT JOIN  (
              SELECT * FROM  customer_data ORDER BY id DESC
          ) customer_data ON (customer_data.customer_id = c.customer_id)
GROUP BY  c.customer_id          
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

How to build a JSON array from mysql database

Is something like this what you want to do?

$return_arr = array();

$fetch = mysql_query("SELECT * FROM table"); 

while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
    $row_array['id'] = $row['id'];
    $row_array['col1'] = $row['col1'];
    $row_array['col2'] = $row['col2'];

    array_push($return_arr,$row_array);
}

echo json_encode($return_arr);

It returns a json string in this format:

[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]

OR something like this:

$year = date('Y');
$month = date('m');

$json_array = array(

//Each array below must be pulled from database
    //1st record
    array(
    'id' => 111,
    'title' => "Event1",
    'start' => "$year-$month-10",
    'url' => "http://yahoo.com/"
),

     //2nd record
     array(
    'id' => 222,
    'title' => "Event2",
    'start' => "$year-$month-20",
    'end' => "$year-$month-22",
    'url' => "http://yahoo.com/"
)

);

echo json_encode($json_array);

Excluding Maven dependencies

Global exclusions look like they're being worked on, but until then...

From the Sonatype maven reference (bottom of the page):

Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.

As an example:

  <dependencies>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
    </dependencies>
  </dependencyManagement>

It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

remote VisualSVN server 2.5.8 is accessible from at least 3 computers. However on my local computer the url of the repository was not accessible and svn ls https://server-ip:443/svn/project/trunk return error

OPTIONS of 'https://…' could not connect to server (…)

My local computer used to have access to the server. The only thing that was changed was switching to http connection instead of https for Redmine reasons(certificate issue).

I tried different things listed above. What actually solved my problem was installing a new the VisualSVN server 2.5.9 using the same repository. And also Redmine recognized the new repository through https.

Javascript: how to validate dates in format MM-DD-YYYY?

try this:

function validateDate(dates){
    re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;     
    var days=new Array(31,28,31,30,31,30,31,31,30,31,30,31);

            if(regs = dates.match(re)) {
                    // day value between 1 and 31
                    if(regs[1] < 1 || regs[1] > 31) {                    
                      return false;
                    }
                    // month value between 1 and 12
                    if(regs[2] < 1 || regs[2] > 12) {                         
                      return false;
                    }

                    var maxday=days[regs[2]-1];

                    if(regs[2]==2){
                        if(regs[3]%4==0){
                            maxday=maxday+1;                                
                        }
                    }

                    if(regs[1]>maxday){
                        return false;
                    }

                    return true;
              }else{
                  return false;
              }                   
}

How to get a list of installed android applications and pick one to run

Get All the apps:

    PackageManager pm = getContext().getPackageManager();
    List<ApplicationInfo> apps = pm.getInstalledApplications(0);

Check if installed app then open:

if((app.flags & (ApplicationInfo.FLAG_UPDATED_SYSTEM_APP | ApplicationInfo.FLAG_SYSTEM)) > 0) {
                String app_package = app.packageName;
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(app_package);
context.startActivity(launchIntent);

How to get .app file of a xcode application

You can find the .app file here:

~/Library/Developer/Xcode/DerivedData/{app name}/Build/Products/Deployment/ 

credit for path goes to this answer

SIDENOTE: I had a lot of fun trying to get this into my iPad after that. It worked however. Using Snow Leopard + Xcode 4.2 + iPad with IOS 5.1.1 :) - I used the iPhone configuration utility to get the app into the ipad (you have to add the app, then click on the device, then click "install" behind the app you just added in the "application library" of iphone configuration utility) and had to create a Distribution Provisioning Profile and get the WWDR certificate and finally change the build settings in Xcode after all the certificates were in place. See here

But after much fun I am now looking at my first app on my iPad :) - btw, for getting apps into the app store you need to create a app store Distribution Provisioning Profile, while for ad hoc installs like these you create an ad hoc one. There is a bit more to it, but I think these are the most important and tricky steps. Enjoy.

PS. Just remembered that you also have to set the build type (top left of Xcode) to "iOS device", otherwise it will never sign your application. So the path name above only has limited value: yes, it will have the .app file in it, but no you can't upload it (at least not using the iPhone configuration utility) since it is not code signed - you will get an "Could not copy validate signature" error. So change it to "iOS device" and build (remember to select the right certificates in the build section of Xcode as per the url info above). In that same build section, you can also set the "Installation Build Products Location" to a different path, so that you can determine where the .app (the one that is properly code signed) ends up.

How to drop all user tables?

begin
  for i in (select 'drop table '||table_name||' cascade constraints' tbl from user_tables) 
  loop
     execute immediate i.tbl;
  end loop;
end;

MVC 4 Data Annotations "Display" Attribute

If two different views are sharing the same model (for instance, maybe one is for mobile output and one is regular), it could be nice to have the string reside in a single place: as metadata on the ViewModel.

Additionally, if you had an inherited version of the model that necessitated a different display, it could be useful. For instance:

public class BaseViewModel
{
    [Display(Name = "Basic Name")]
    public virtual string Name { get; set; }
}

public class OtherViewModel : BaseViewModel
{
    [Display(Name = "Customized Inherited Name")]
    public override string Name { get; set; }
}

I'll admit that that example is pretty contrived...

Those are the best arguments in favor of using the attribute that I can come up with. My personal opinion is that, for the most part, that sort of thing is best left to the markup.

List and kill at jobs on UNIX

First

ps -ef

to list all processes. Note the the process number of the one you want to kill. Then

kill 1234

were you replace 1234 with the process number that you want.

Alternatively, if you are absolutely certain that there is only one process with a particular name, or you want to kill multiple processes which share the same name

killall processname

How to convert an address to a latitude/longitude?

When you convert an address or object to a lat/long it is called Geocoding.

There are a lot geocoding solutions around. The solution right for your project will depend on the acceptability of the licensing terms of each geocoding solution. Both Microsoft Virtual Earth and Google Maps offer solutions which are free to use under a very restrictive licenses...

https://developers.google.com/maps/documentation/javascript/tutorial

Create PDF with Java

Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.

Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Don't detect mobile devices, go for stationary ones instead.

Nowadays (2016) there is a way to detect dots per inch/cm/px that seems to work in most modern browsers (see http://caniuse.com/#feat=css-media-resolution). I needed a method to distinguish between a relatively small screen, orientation didn't matter, and a stationary computer monitor.

Because many mobile browsers don't support this, one can write the general css code for all cases and use this exception for large screens:

@media (max-resolution: 1dppx) {
    /* ... */
}

Both Windows XP and 7 have the default setting of 1 dot per pixel (or 96dpi). I don't know about other operating systems, but this works really well for my needs.

Edit: dppx doesn't seem to work in Internet Explorer.. use (96)dpi instead.

Change URL parameters

I think you want the query plugin.

E.g.:

window.location.search = jQuery.query.set("rows", 10);

This will work regardless of the current state of rows.

How can I use "e" (Euler's number) and power operation in python 2.7

Just saying: numpy has this too. So no need to import math if you already did import numpy as np:

>>> np.exp(1)
2.718281828459045

WPF Image Dynamically changing Image source during runtime

Try Stretch="UniformToFill" on the Image

LOAD DATA INFILE Error Code : 13

I have experienced same problem and applied the solutions above.

First of all my test environment are as follows

  • Ubuntu 14.04.3 64bit
  • mysql Ver 14.14 Distrib 5.5.47, for debian-linux-gnu (x86_64) using readline 6.3 (installed by just 'sudo apt-get install ...' command)

My testing results are

i) AppArmor solution only work for /tmp cases.

ii) Following solution works without AppArmor solution. I would like to appreciate Avnish Mehta for his answer.

$ mysql -u root -p --in-file=1
...
mysql> LOAD DATA LOCAL INFILE '/home/hongsoog/study/mysql/member.dat'
    -> INTO TABLE member_table;

Important three points are

  • start mysql client with --in-file=1 option
  • use LOAD DATA LOCAL INFILE instead of LOAD DATA INFILE
  • check all path element have world read permission from the / to data file path. For example, following subpath should be world readable or mysql group readable if INFILE is targeting for '/home/hongsoog/study/mysql/memer.dat'

    • /home
    • /home/hongsoog
    • /home/hongsoog/study/mysql
    • /home/hongsoog/study/mysql/member.data

When you start mysql client WITHOUT "--in-file=1" option and use

LOAD DATA LOCAL INFILE ...
, you will get

ERROR 1148 (42000): The used command is not allowed with this MySQL version


In summary, "--in-file=1" option in mysql client command and "LOAD DATA LOCAL INFILE ..." should go hand in hand.

Hope to helpful to anyone.

Where to find the complete definition of off_t type?

If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.

$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
  __off_t __pos;
  __off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;

If you look at the complete output you can even see the exact header file location and line number where it was defined:

# 132 "/usr/include/bits/types.h" 2 3 4


typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;

...

# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;

Install dependencies globally and locally using package.json

You could use a separate file, like npm_globals.txt, instead of package.json. This file would contain each module on a new line like this,

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

Then in the command line run,

< npm_globals.txt xargs npm install -g

Check that they installed properly with,

npm list -g --depth=0

As for whether you should do this or not, I think it all depends on use case. For most projects, this isn't necessary; and having your project's package.json encapsulate these tools and dependencies together is much preferred.

But nowadays I find that I'm always installing create-react-app and other CLI's globally when I jump on a new machine. It's nice to have an easy way to install a global tool and its dependencies when versioning doesn't matter much.

And nowadays, I'm using npx, an npm package runner, instead of installing packages globally.

How to take column-slices of dataframe in pandas

You can slice along the columns of a DataFrame by referring to the names of each column in a list, like so:

data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
data_ab = data[list('ab')]
data_cde = data[list('cde')]

Get AVG ignoring Null or Zero values

worked for me:

AVG(CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)

What are type hints in Python 3.5?

Adding to Jim's elaborate answer:

Check the typing module -- this module supports type hints as specified by PEP 484.

For example, the function below takes and returns values of type str and is annotated as follows:

def greeting(name: str) -> str:
    return 'Hello ' + name

The typing module also supports:

  1. Type aliasing.
  2. Type hinting for callback functions.
  3. Generics - Abstract base classes have been extended to support subscription to denote expected types for container elements.
  4. User-defined generic types - A user-defined class can be defined as a generic class.
  5. Any type - Every type is a subtype of Any.

How to check the version of GitLab?

Instead of http://domain-name/help you can also check your Gitlab version name in browser by logging as Admin

  • Go to http://domain-name
  • Log in to Gitlab as Admin (Root)
  • Go to Admin Area
  • On the right corner, below Groups tab, you can find Components tab

There you can find not only Gitlab version but also different components like Gitlab Shell, Gitlab workhorse, Gitlab API etc, version numbers enter image description here You will also find the suggestions to update the versions there

Correct way to find max in an Array in Swift

var numbers = [1, 2, 7, 5];    
var val = sort(numbers){$0 > $1}[0];

Create a 3D matrix

Create a 3D matrix

A = zeros(20, 10, 3);   %# Creates a 20x10x3 matrix

Add a 3rd dimension to a matrix

B = zeros(4,4);  
C = zeros(size(B,1), size(B,2), 4);  %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B;                        %# Copy the content of B into C's first set of values

zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0 for a 3D matrix. To confirm the size of your matrices you can run: size(A) which gives 20 10 3.

There is no explicit bound on the number of dimensions a matrix may have.

How to create a circle icon button in Flutter?

Try out this Card

Card(
    elevation: 10,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(25.0), // half of height and width of Image
      ),
    child: Image.asset(
      "assets/images/home.png",
      width: 50,
      height: 50,
    ),
  )

To show error message without alert box in Java Script

web masters or web programmers, please insert

<!DOCTYPE html>

at the start of your page. Second you should enclose your attributes with quotes like

type="text" id="fname"

input element should not contain end element, just close it like:

 />

input element dont have innerHTML, it has value sor your javascript line should be:

document.getElementById("fname").value = "this is invalid name";

Please write in organized way and make sure it is convenient to standards.

How to get screen dimensions as pixels in Android

Above code has been deprecated in API level 30. Now you can get using following code

 val width = windowManager.currentWindowMetrics.bounds.width()
 val height = windowManager.currentWindowMetrics.bounds.height()

This method reports the window size including all system bar areas, while Display#getSize(Point) reports the area excluding navigation bars and display cutout areas. The value reported by Display#getSize(Point) can be obtained by using:

 val metrics = windowManager.currentWindowMetrics
 // Gets all excluding insets
 val windowInsets = metrics.windowInsets
 var insets: Insets = windowInsets.getInsets(WindowInsets.Type.navigationBars())
 val cutout = windowInsets.displayCutout
 if (cutout != null) {
    val cutoutSafeInsets = Insets.of(cutout.safeInsetLeft, cutout.safeInsetTop, cutout.safeInsetRight, cutout.safeInsetBottom)
    insets = Insets.max(insets, cutoutSafeInsets)
 }

 val insetsWidth = insets.right + insets.left
 val insetsHeight = insets.top + insets.bottom

 // Legacy size that Display#getSize reports
 val legacySize =  Size(metrics.bounds.width() - insetsWidth, metrics.bounds.height() - insetsHeight)

Source : WindowManager#getCurrentWindowMetrics()

How to check if a column is empty or null using SQL query select statement?

An answer above got me 99% of the way there (thanks Denis Ivin!). For my PHP / MySQL implementation, I needed to change the syntax a little:

SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LENGTH(IFNULL(PropertyValue,'')) = 0)

LEN becomes LENGTH and ISNULL becomes IFNULL.

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

Z=np.array([1.0,1.0,1.0,1.0])  

def func(TempLake,Z):
    A=TempLake
    B=Z
    return A*B
Nlayers=Z.size
N=3
TempLake=np.zeros((N+1,Nlayers))
kOUT=np.vectorize(func)(TempLake,Z)

This works too , instead of looping , just vectorize however read below notes from the scipy documentation : https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html

The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.

If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if cache is True to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive.

How to install bcmath module?

The following worked for me on Centos 7.4 with PHP 7.1 using remi repository.

First find out which PHP version I have:

[kiat@reporting ~]$ php --version
PHP 7.1.33 (cli) (built: Oct 23 2019 07:28:45) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.1.33, Copyright (c) 1999-2018, by Zend Technologies

Then search for bcmath extension in remi-php71 repository:

[kiat@reporting ~]$ yum search php71 | grep bcmath
php71-php-bcmath.x86_64 : A module for PHP applications for using the bcmath
php71u-bcmath.x86_64 : A module for PHP applications for using the bcmath

Now install the first matching extension:

[kiat@reporting ~]$ sudo yum --enablerepo=remi-php71 install php-bcmath
Loaded plugins: fastestmirror, langpacks
base                                                     | 3.6 kB     00:00
.
.
.

Finally, restart php and nginx:

[kiat@reporting ~]$ sudo systemctl restart php-fpm nginx

Fix footer to bottom of page

Like this add position:fixed; and bottom:0; below the selector #footer:

demo

CSS

#footer {
    background-color: #F3F3F3;
    padding-top: 10px;
    padding-bottom: 0px;
    position:fixed;
    bottom:0;
    width:100%;
}

How to get the mobile number of current sim card in real device?

I have to make an application which shows the Contact no of the SIM card that is being used in the cell. For that I need to use Telephony Manager class. Can i get details on its usage?

Yes, You have to use Telephony Manager;If at all you not found the contact no. of user; You can get Sim Serial Number of Sim Card and Imei No. of Android Device by using the same Telephony Manager Class...

Add permission:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Import:

import android.telephony.TelephonyManager;

Use the below code:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

         // get IMEI
         imei = tm.getDeviceId();

         // get SimSerialNumber
         simSerialNumber = tm.getSimSerialNumber();

isset() and empty() - what to use

You can just use empty() - as seen in the documentation, it will return false if the variable has no value.

An example on that same page:

<?php
$var = 0;

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?>

You can use isset if you just want to know if it is not NULL. Otherwise it seems empty() is just fine to use alone.

How to display count of notifications in app launcher icon

I have figured out how this is done for Sony devices.

I've blogged about it here. I've also posted a seperate SO question about this here.


Sony devices use a class named BadgeReciever.

  1. Declare the com.sonyericsson.home.permission.BROADCAST_BADGE permission in your manifest file:

  2. Broadcast an Intent to the BadgeReceiver:

    Intent intent = new Intent();
    
    intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", "com.yourdomain.yourapp.MainActivity");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", "99");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", "com.yourdomain.yourapp");
    
    sendBroadcast(intent);
    
  3. Done. Once this Intent is broadcast the launcher should show a badge on your application icon.

  4. To remove the badge again, simply send a new broadcast, this time with SHOW_MESSAGE set to false:

    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
    

I've excluded details on how I found this to keep the answer short, but it's all available in the blog. Might be an interesting read for someone.

Multiple aggregate functions in HAVING clause

Something like this?

HAVING COUNT(caseID) > 2
AND COUNT(caseID) < 4

generate random double numbers in c++

This solution requires C++11 (or TR1).

#include <random>

int main()
{
   double lower_bound = 0;
   double upper_bound = 10000;
   std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
   std::default_random_engine re;
   double a_random_double = unif(re);

   return 0;
}

For more details see John D. Cook's "Random number generation using C++ TR1".

See also Stroustrup's "Random number generation".