Programs & Examples On #Import hooks

How to get dictionary values as a generic list

Dictionary<string, MyType> myDico = GetDictionary();

var items = myDico.Select(d=> d.Value).ToList();

C Macro definition to determine big endian or little endian machine?

If you are looking for a compile time test and you are using gcc, you can do:

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__

See gcc documentation for more information.

How do I find an element position in std::vector?

You probably should not use your own function here. Use find() from STL.

Example:

list L;
L.push_back(3);
L.push_back(1);
L.push_back(7);

list::iterator result = find(L.begin(), L.end(), 7); assert(result == L.end() || *result == 7);

How to export query result to csv in Oracle SQL Developer?

Version I am using

alt text

Update 5th May 2012

Jeff Smith has blogged showing, what I believe is the superior method to get CSV output from SQL Developer. Jeff's method is shown as Method 1 below:

Method 1

Add the comment /*csv*/ to your SQL query and run the query as a script (using F5 or the 2nd execution button on the worksheet toolbar)

enter image description here

That's it.

Method 2

Run a query

alt text

Right click and select unload.

Update. In Sql Developer Version 3.0.04 unload has been changed to export Thanks to Janis Peisenieks for pointing this out

alt text

Revised screen shot for SQL Developer Version 3.0.04

enter image description here

From the format drop down select CSV

alt text

And follow the rest of the on screen instructions.

What is the IntelliJ shortcut key to create a javadoc comment?

Typing /** + then pressing Enter above a method signature will create Javadoc stubs for you.

Undefined index error PHP

Apparently the index 'productid' is missing from your html form. Inspect your html inputs first. eg <input type="text" name="productid" value=""> But this will handle the current error PHP is raising.

  $rowID = isset($_POST['rowID']) ? $_POST['rowID'] : '';
  $productid = isset($_POST['productid']) ? $_POST['productid'] : '';
  $name = isset($_POST['name']) ? $_POST['name'] : '';
  $price = isset($_POST['price']) ? $_POST['price'] : '';
  $description = isset($_POST['description']) ? $_POST['description'] : '';

Generate war file from tomcat webapp folder

You can create .war file back from your existing folder.

Using this command

cd /to/your/folder/location
jar -cvf my_web_app.war *

How to perform a real time search and filter on a HTML table

Here is the best solution for searching inside HTML table while covering all of the table, (all td, tr in the table), pure javascript and as short as possible:

<input id='myInput' onkeyup='searchTable()' type='text'>

<table id='myTable'>
   <tr>
      <td>Apple</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Grapes</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Orange</td>
      <td>Orange</td>
   </tr>
</table>

<script>
function searchTable() {
    var input, filter, found, table, tr, td, i, j;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td");
        for (j = 0; j < td.length; j++) {
            if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                found = true;
            }
        }
        if (found) {
            tr[i].style.display = "";
            found = false;
        } else {
            tr[i].style.display = "none";
        }
    }
}
</script>

How to check if an object implements an interface?

Use

if (gor instanceof Monster) {
    //...
}

How to update an object in a List<> in C#

This was a new discovery today - after having learned the class/struct reference lesson!

You can use Linq and "Single" if you know the item will be found, because Single returns a variable...

myList.Single(x => x.MyProperty == myValue).OtherProperty = newValue;

Disable form auto submit on button click

another one:

if(this.checkValidity() == false) {

                $(this).addClass('was-validated');
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();

                return false;
}

powershell - list local users and their groups

For Googlers, another way to get a list of users is to use:

Get-WmiObject -Class Win32_UserAccount

From http://buckeyejeeps.com/blog/?p=764

How to add buttons at top of map fragment API v2 layout

Maybe a simpler solution is to set an overlay in front of your map using FrameLayout or RelativeLayout and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapActivity" >

    <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scrollbars="vertical"  
        class="com.google.android.gms.maps.SupportMapFragment"/>

    <RadioGroup 
        android:id="@+id/radio_group_list_selector"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:orientation="horizontal" 
        android:background="#80000000"
        android:padding="4dp" >

        <RadioButton
            android:id="@+id/radioPopular"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="@string/Popular"
            android:gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioAZ"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/AZ"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />

        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioCategory"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/Category"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioNearBy"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/NearBy"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton3"
            android:textColor="@color/textcolor_radiobutton" />
    </RadioGroup>
</FrameLayout>

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

For some programs setting the super secret __COMPAT_LAYER environment variable to RunAsInvoker will work.Check this :

set "__COMPAT_LAYER=RunAsInvoker"
start regedit.exe

Though like this there will be no UAC prompting the user will continue without admin permissions.

SSL cert "err_cert_authority_invalid" on mobile chrome only

I guess you should install CA certificate form one if authority canter:

ssl_trusted_certificate ssl/SSL_CA_Bundle.pem;

How to run TypeScript files from command line?

Like Zeeshan Ahmad's answer, I also think ts-node is the way to go. I would also add a shebang and make it executable, so you can just run it directly.

  1. Install typescript and ts-node globally:

    npm install -g ts-node typescript
    

    or

    yarn global add ts-node typescript
    
  2. Create a file hello with this content:

    #!/usr/bin/env ts-node-script
    
    import * as os from 'os'
    
    function hello(name: string) {
        return 'Hello, ' + name
    }
    const user = os.userInfo().username
    console.log(`Result: ${hello(user)}`)
    

    As you can see, line one has the shebang for ts-node

  3. Run directly by just executing the file

    $ ./hello
    Result: Hello, root
    

Some notes:


Update 2020-04-06: Some changes after great input in the comments: Update shebang to use ts-node-script instead of ts-node, link to issues in ts-node.

Turning error reporting off php

Read up on the configuration settings (e.g., display_errors, display_startup_errors, log_errors) and update your php.ini or .htaccess or .user.ini file, whichever is appropriate.

It works.

How can I set selected option selected in vue.js 2?

The simplest answer is to set the selected option to true or false.

<option :selected="selectedDay === 1" value="1">1</option>

Where the data object is:

data() {
    return {
        selectedDay: '1',
        // [1, 2, 3, ..., 31]
        days: Array.from({ length: 31 }, (v, i) => i).slice(1)
    }
}

This is an example to set the selected month day:

<select v-model="selectedDay" style="width:10%;">
    <option v-for="day in days" :selected="selectedDay === day">{{ day }}</option>
</select>

On your data set:

{
    data() {
        selectedDay: 1,
        // [1, 2, 3, ..., 31]
        days: Array.from({ length: 31 }, (v, i) => i).slice(1)
    },
    mounted () {
        let selectedDay = new Date();
        this.selectedDay = selectedDay.getDate(); // Sets selectedDay to the today's number of the month
    }
}

Using momentjs to convert date to epoch then back to date

http://momentjs.com/docs/#/displaying/unix-timestamp/

You get the number of unix seconds, not milliseconds!

You you need to multiply it with 1000 or using valueOf() and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.

moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()

Select Specific Columns from Spark DataFrame

Just by using select select you can select particular columns, give them readable names and cast them. For example like this:

spark.read.csv(path).select(
          '_c0.alias("stn").cast(StringType),
          '_c1.alias("wban").cast(StringType),
          '_c2.alias("lat").cast(DoubleType),
          '_c3.alias("lon").cast(DoubleType)
        )
          .where('_c2.isNotNull && '_c3.isNotNull && '_c2 =!= 0.0 && '_c3 =!= 0.0)

How to print struct variables in console?

I like litter.

From their readme:

type Person struct {
  Name   string
  Age    int
  Parent *Person
}

litter.Dump(Person{
  Name:   "Bob",
  Age:    20,
  Parent: &Person{
    Name: "Jane",
    Age:  50,
  },
})

Sdump is pretty handy in tests:

func TestSearch(t *testing.T) {
  result := DoSearch()

  actual := litterOpts.Sdump(result)
  expected, err := ioutil.ReadFile("testdata.txt")
  if err != nil {
    // First run, write test data since it doesn't exist
        if !os.IsNotExist(err) {
      t.Error(err)
    }
    ioutil.Write("testdata.txt", actual, 0644)
    actual = expected
  }
  if expected != actual {
    t.Errorf("Expected %s, got %s", expected, actual)
  }
}

Javascript checkbox onChange

HTML:

<input type="checkbox" onchange="handleChange(event)">

JS:

function handleChange(e) {
     const {checked} = e.target;
}

How do I clear only a few specific objects from the workspace?

You'll find the answer by typing ?rm

rm(data_1, data_2, data_3)

Image is not showing in browser?

do not place *jsp or *html in root folder of webapp and images you want to display in same root folder browser cannot acess the image in WEB-INF folder

NuGet Package Restore Not Working

Sometimes something strange happens and using Visual Studio to automatically restore doesn't work. In that case you can use the NuGet Package Manager Console. That is opened within Visual Studio from Tools -> NuGet Package Manager -> Package Manager Console. The commands within the console are simple. And to get context help while typing a command just press the button and it will give you all options that start with the letters you're typing. So if a package isn't installed, for example log4net, type the following command:

Install-Package log4net

You can do a whole lot more, like specify the version to install, update a package, uninstall a package, etc.

I had to use the console to help me when Visual Studio was acting like a weirdo.

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

just try this:

_x000D_
_x000D_
//don't call getActivity()
getActivity().startActivityForResult(intent, REQ_CODE);

//just call 
startActivityForResult(intent, REQ_CODE);
//directly from fragment
_x000D_
_x000D_
_x000D_

How do I convert a list of ascii values to a string in python?

You can use bytes(list).decode() to do this - and list(string.encode()) to get the values back.

Creating InetAddress object in Java

This is a project for getting IP address of any website , it's usefull and so easy to make.

import java.net.InetAddress;
import java.net.UnkownHostExceptiin;

public class Main{
    public static void main(String[]args){
        try{
            InetAddress addr = InetAddresd.getByName("www.yahoo.com");
            System.out.println(addr.getHostAddress());

          }catch(UnknownHostException e){
             e.printStrackTrace();
        }
    }
}

How can I write a heredoc to a file in Bash script?

If you want to keep the heredoc indented for readability:

$ perl -pe 's/^\s*//' << EOF
     line 1
     line 2
EOF

The built-in method for supporting indented heredoc in Bash only supports leading tabs, not spaces.

Perl can be replaced with awk to save a few characters, but the Perl one is probably easier to remember if you know basic regular expressions.

How to get the data-id attribute?

Accessing data attribute with its own id is bit easy for me.

$("#Id").data("attribute");

_x000D_
_x000D_
function myFunction(){_x000D_
  alert($("#button1").data("sample-id"));_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>
_x000D_
_x000D_
_x000D_

VBA: Counting rows in a table (list object)

You need to go one level deeper in what you are retrieving.

Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("MyTable")
MsgBox tbl.Range.Rows.Count
MsgBox tbl.HeaderRowRange.Rows.Count
MsgBox tbl.DataBodyRange.Rows.Count
Set tbl = Nothing

More information at:

ListObject Interface
ListObject.Range Property
ListObject.DataBodyRange Property
ListObject.HeaderRowRange Property

Difference between the Apache HTTP Server and Apache Tomcat?

Apache is an HTTP web server which serve as HTTP.

Apache Tomcat is a java servlet container. It features same as web server but is customized to execute java servlet and JSP pages.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I faced this issue due to Mysql 8.0.11 version reverting back to 5.7 solved for me

Disable submit button when form invalid with AngularJS

_x000D_
_x000D_
<form name="myForm">_x000D_
        <input name="myText" type="text" ng-model="mytext" required/>_x000D_
        <button ng-disabled="myForm.$pristine|| myForm.$invalid">Save</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

If you want to be a bit more strict

Python-Requests close http connection

I came to this question looking to solve the "too many open files" error, but I am using requests.session() in my code. A few searches later and I came up with an answer on the Python Requests Documentation which suggests to use the with block so that the session is closed even if there are unhandled exceptions:

with requests.Session() as s:
    s.get('http://google.com')

If you're not using Session you can actually do the same thing: https://2.python-requests.org/en/master/user/advanced/#session-objects

with requests.get('http://httpbin.org/get', stream=True) as r:
    # Do something

Assign command output to variable in batch file

A method has already been devised, however this way you don't need a temp file.

for /f "delims=" %%i in ('command') do set output=%%i

However, I'm sure this has its own exceptions and limitations.

Cannot deserialize the current JSON array (e.g. [1,2,3])


To read more than one json tip (array, attribute) I did the following.


var jVariable = JsonConvert.DeserializeObject<YourCommentaryClass>(jsonVariableContent);

change to

var jVariable = JsonConvert.DeserializeObject <List<YourCommentaryClass>>(jsonVariableContent);

Because you cannot see all the bits in the method used in the foreach loop. Example foreach loop

foreach (jsonDonanimSimple Variable in jVariable)
                {    
                    debugOutput(jVariable.Id.ToString());
                    debugOutput(jVariable.Header.ToString());
                    debugOutput(jVariable.Content.ToString());
                }

I also received an error in this loop and changed it as follows.

foreach (jsonDonanimSimple Variable in jVariable)
                    {    
                        debugOutput(Variable.Id.ToString());
                        debugOutput(Variable.Header.ToString());
                        debugOutput(Variable.Content.ToString());
                    }

Custom alert and confirm box in jquery

Try using SweetAlert its just simply the best . You will get a lot of customization and flexibility.

Confirm Example

sweetAlert(
  {
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",   
    showCancelButton: true,   
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!"
  }, 
  deleteIt()
);

Sample Alert

How do I format a date with Dart?

This will work too:

DateTime today = new DateTime.now();
String dateSlug ="${today.year.toString()}-${today.month.toString().padLeft(2,'0')}-${today.day.toString().padLeft(2,'0')}";
print(dateSlug);

Using Bootstrap Modal window as PartialView

Yes we have done this.

In your Index.cshtml you'll have something like..

<div id='gameModal' class='modal hide fade in' data-url='@Url.Action("GetGameListing")'>
   <div id='gameContainer'>
   </div>
</div>

<button id='showGame'>Show Game Listing</button>

Then in JS for the same page (inlined or in a separate file you'll have something like this..

$(document).ready(function() {
   $('#showGame').click(function() {
        var url = $('#gameModal').data('url');

        $.get(url, function(data) {
            $('#gameContainer').html(data);

            $('#gameModal').modal('show');
        });
   });
});

With a method on your controller that looks like this..

[HttpGet]
public ActionResult GetGameListing()
{
   var model = // do whatever you need to get your model
   return PartialView(model);
}

You will of course need a view called GetGameListing.cshtml inside of your Views folder..

Why is my CSS bundling not working with a bin deployed MVC4 app?

Another thing to consider is the references cannot have the same name. For example, if you have jQuery UI in the libraries directory, and bundle its JavaScript file like so:

bundles.Add(new ScriptBundle("~/libraries").Include("~/libraries/jquery-ui/jqyery-ui.js"));

and then try to bundle its CSS files like so:

bundles.Add(new StyleBundle("~/libraries").Include("~/libraries/jquery-ui/jqyery-ui.css"));
...

it will fail. They have to have unique names. So do something like ScriptBundle("~/libraries/js")... and ScriptBundle("~/libraries/css")... or whatever.

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

A duplicate in the database should be a 409 CONFLICT.

I recommend using 422 UNPROCESSABLE ENTITY for validation errors.

I give a longer explanation of 4xx codes here: http://parker0phil.com/2014/10/16/REST_http_4xx_status_codes_syntax_and_sematics/

MySQL connection not working: 2002 No such file or directory

Digital Ocean MySql 2002-no-such-file-or-directory

Add this end of file /etc/mysql/my.cnf

[mysqld]
innodb_force_recovery = 1

Restart MySql

service mysql restart

How to open a txt file and read numbers in Java

Read file, parse each line into an integer and store into a list:

List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;

    while ((text = reader.readLine()) != null) {
        list.add(Integer.parseInt(text));
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
    }
}

//print out the list
System.out.println(list);

How to count the number of set bits in a 32-bit integer?

The Hacker's Delight bit-twiddling becomes so much clearer when you write out the bit patterns.

unsigned int bitCount(unsigned int x)
{
  x = ((x >> 1) & 0b01010101010101010101010101010101)
     + (x       & 0b01010101010101010101010101010101);
  x = ((x >> 2) & 0b00110011001100110011001100110011)
     + (x       & 0b00110011001100110011001100110011); 
  x = ((x >> 4) & 0b00001111000011110000111100001111)
     + (x       & 0b00001111000011110000111100001111); 
  x = ((x >> 8) & 0b00000000111111110000000011111111)
     + (x       & 0b00000000111111110000000011111111); 
  x = ((x >> 16)& 0b00000000000000001111111111111111)
     + (x       & 0b00000000000000001111111111111111); 
  return x;
}

The first step adds the even bits to the odd bits, producing a sum of bits in each two. The other steps add high-order chunks to low-order chunks, doubling the chunk size all the way up, until we have the final count taking up the entire int.

How to find the socket connection state in C?

You could call getsockopt just like the following:

int error = 0;
socklen_t len = sizeof (error);
int retval = getsockopt (socket_fd, SOL_SOCKET, SO_ERROR, &error, &len);

To test if the socket is up:

if (retval != 0) {
    /* there was a problem getting the error code */
    fprintf(stderr, "error getting socket error code: %s\n", strerror(retval));
    return;
}

if (error != 0) {
    /* socket has a non zero error status */
    fprintf(stderr, "socket error: %s\n", strerror(error));
}

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

Try this

Check this How do i get the gmt time in php

date_default_timezone_set("UTC");
echo date("Y-m-d H:i:s", time()); 

How to temporarily disable a click handler in jQuery?

You can unbind your handler with .off, but there's a caveat; if you're doing this just prevent the handler from being triggered again while it's already running, you need to defer rebinding the handler.

For example, consider this code, which uses a 5-second hot sleep to simulate something synchronous and computationally expensive being done from within the handler (like heavy DOM manipulation, say):

<button id="foo">Click Me!</div>
<script>
    function waitForFiveSeconds() {
        var startTime = new Date();
        while (new Date() - startTime < 5000) {}
    }
    $('#foo').click(function handler() {
        // BAD CODE, DON'T COPY AND PASTE ME!
        $('#foo').off('click');
        console.log('Hello, World!');
        waitForFiveSeconds();
        $('#foo').click(handler);
    });
</script>

This won't work. As you can see if you try it out in this JSFiddle, if you click the button while the handler is already executing, the handler will execute a second time once the first execution finishes. What's more, at least in Chrome and Firefox, this would be true even if you didn't use jQuery and used addEventListener and removeEventListener to add and remove the handler instead. The browser executes the handler after the first click, unbinding and rebinding the handler, and then handles the second click and checks whether there's a click handler to execute.

To get around this, you need to defer rebinding of the handler using setTimeout, so that clicks that happen while the first handler is executing will be processed before you reattach the handler.

<button id="foo">Click Me!</div>
<script>
    function waitForFiveSeconds() {
        var startTime = new Date();
        while (new Date() - startTime < 5000) {}
    }
    $('#foo').click(function handler() {
        $('#foo').off('click');
        console.log('Hello, World!');
        waitForFiveSeconds();

        // Defer rebinding the handler, so that any clicks that happened while
        // it was unbound get processed first.
        setTimeout(function () {
            $('#foo').click(handler);
        }, 0);
    });
</script>

You can see this in action at this modified JSFiddle.

Naturally, this is unnecessary if what you're doing in your handler is already asynchronous, since then you're already yielding control to the browser and letting it flush all the click events before you rebind your handler. For instance, code like this will work fine without a setTimeout call:

<button id="foo">Save Stuff</div>
<script>
    $('#foo').click(function handler() {
        $('#foo').off('click');
        $.post( "/some_api/save_stuff", function() {
            $('#foo').click(handler);
        });
    });
</script>

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

How to save the output of a console.log(object) to a file?

right click on console.. click save as.. its this simple.. you'll get an output text file

Merging Cells in Excel using C#

Excel.Application xl = new Excel.ApplicationClass();

Excel.Workbook wb = xl.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorkshe et);

Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;

ws.Cells[1,1] = "Testing";

Excel.Range range = ws.get_Range(ws.Cells[1,1],ws.Cells[1,2]);

range.Merge(true);

range.Interior.ColorIndex =36;

xl.Visible =true;

How to change date format using jQuery?

var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

curr_year = curr_year.toString().substr(2,2);

document.write(curr_date+"-"+curr_month+"-"+curr_year);

You can change this as your need..

Insert php variable in a href

You could try:

<a href="<?php echo $directory ?>">The link to the file</a>

Or for PHP 5.4+ (<?= is the PHP short echo tag):

<a href="<?= $directory ?>">The link to the file</a>

But your path is relative to the server, don't forget that.

Table cell widths - fixing width, wrapping/truncating long words

As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
        td { width: 30px; overflow: hidden; }
        table { width : 90px; table-layout: fixed; }
    </style>
</head>
<body>

    <table border="2">
        <tr>
            <td>word</td>
            <td>two words</td>
            <td>onereallylongword</td>

        </tr>
    </table>
</body>
</html>

I've tested this in IE6 and 7 and it seems to work fine.

Which loop is faster, while or for?

If that were a C program, I would say neither. The compiler will output exactly the same code. Since it's not, I say measure it. Really though, it's not about which loop construct is faster, since that's a miniscule amount of time savings. It's about which loop construct is easier to maintain. In the case you showed, a for loop is more appropriate because it's what other programmers (including future you, hopefully) will expect to see there.

How does HTTP_USER_AGENT work?

The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.

Eclipse Build Path Nesting Errors

Here is a simple solution:

  1. Right click the project >> properties >> build path;
  2. In Source tab, Select all the source folders;
  3. Remove them;
  4. Right click on project, Maven >> Update the project.

How can I adjust DIV width to contents

EDIT2- Yea auto fills the DOM SOZ!

#img_box{        
    width:90%;
    height:90%;
    min-width: 400px;
    min-height: 400px;
}

check out this fiddle

http://jsfiddle.net/ppumkin/4qjXv/2/

http://jsfiddle.net/ppumkin/4qjXv/3/

and this page

http://www.webmasterworld.com/css/3828593.htm

Removed original answer because it was wrong.

The width is ok- but the height resets to 0

so

 min-height: 400px;

Format a message using MessageFormat.format() in Java

Here is a method that does not require editing the code and works regardless of the number of characters.

String text = 
  java.text.MessageFormat.format(
    "You're about to delete {0} rows.".replaceAll("'", "''"), 5);

Selecting a row in DataGridView programmatically

You can use the Select method if you have a datasource: http://msdn.microsoft.com/en-us/library/b51xae2y%28v=vs.71%29.aspx

Or use linq if you have objects in you datasource

How do I print output in new line in PL/SQL?

Most likely you need to use this trick:

dbms_output.put_line('Hi' || chr(10) || 
                     'good' || chr(10) || 
                     'morning' || chr(10) || 
                     'friends' || chr(10));

How can I create an MSI setup?

If you don't understand Windows Installer then I highly recommend The Definitive Guide to Windows Installer. You can't really use WiX without understanding MSI. Also worth downloading is the Windows Installer 4.5 SDK.

If you don't want to learn the Windows Installer fundamentals, then you'll need some wizard type package to hide all the nitty gritty details and hold your hand. There are plenty of options, some more expensive than others.

  • InstallShield
  • Advanced Installer
  • MSI Factory
  • etc..

However still I'd suggest picking up the above book and taking some time to understand what's going on "under the hood", it'll really help you figure out what's going wrong when customers start complaining that something is broken with the setup :)

How to convert all tables from MyISAM into InnoDB?

To generate ALTER statements for all tables in all the non-system schemas, ordered by those schemas/tables run the following:

SELECT  CONCAT('ALTER TABLE ',TABLE_SCHEMA,'.', table_name, ' ENGINE=InnoDB;') AS sql_statements
FROM    information_schema.tables
WHERE   TABLE_SCHEMA NOT IN ('mysql', 'information_schema', 'performance_schema', 'innodb', 'sys', 'tmp')
AND     `ENGINE` = 'MyISAM'
AND     `TABLE_TYPE` = 'BASE TABLE'
ORDER BY TABLE_SCHEMA, table_name DESC;

After that, run those queries via a client to perform the alteration.

  • Answer is based on above answers, but improves schema handling.

extract the date part from DateTime in C#

DateTime is a DataType which is used to store both Date and Time. But it provides Properties to get the Date Part.

You can get the Date part from Date Property.

http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx

DateTime date1 = new DateTime(2008, 6, 1, 7, 47, 0);
Console.WriteLine(date1.ToString());

// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("d"));
// Display date using 24-hour clock.
Console.WriteLine(dateOnly.ToString("g"));
Console.WriteLine(dateOnly.ToString("MM/dd/yyyy HH:mm"));   
// The example displays the following output to the console:
//       6/1/2008 7:47:00 AM
//       6/1/2008
//       6/1/2008 12:00 AM
//       06/01/2008 00:00

Server cannot set status after HTTP headers have been sent IIS7.5

How about checking this before doing the redirect:

if (!Response.IsRequestBeingRedirected)
{
   //do the redirect
}

How to make a TextBox accept only alphabetic characters?

The simplest way is to handle the TextChangedEvent and check what's been typed:

string oldText = string.Empty;
    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        if (textBox2.Text.All(chr => char.IsLetter(chr)))
        {
            oldText = textBox2.Text;
            textBox2.Text = oldText;

            textBox2.BackColor = System.Drawing.Color.White;
            textBox2.ForeColor = System.Drawing.Color.Black;
        }
        else
        {
            textBox2.Text = oldText;
            textBox2.BackColor = System.Drawing.Color.Red;
            textBox2.ForeColor = System.Drawing.Color.White;
        }
        textBox2.SelectionStart = textBox2.Text.Length;
    }

This is a regex-free version if you prefer. It will make the text box blink on bad input. Please note that it also seems to support paste operations as well.

LaTeX: Prevent line break in a span of text

Define myurl command:


\def\myurl{\hfil\penalty 100 \hfilneg \hbox}

I don't want to cause line overflows, 
I'd just rather LaTeX insert linebreaks before 
\myurl{\tt http://stackoverflow.com/questions/1012799/} 
regions rather than inside them.

Arithmetic operation resulted in an overflow. (Adding integers)

This error occurred for me when a value was returned as -1.#IND due to a division by zero. More info on IEEE floating-point exceptions in C++ here on SO and by John Cook

For the one who has downvoted this answer (and did not specify why), the reason why this answer can be significant to some is that a division by zero will lead to an infinitely large number and thus a value that doesn't fit in an Int32 (or even Int64). So the error you receive will be the same (Arithmetic operation resulted in an overflow) but the reason is slightly different.

Java Command line arguments

Command-line arguments are passed in the first String[] parameter to main(), e.g.

public static void main( String[] args ) {
}

In the example above, args contains all the command-line arguments.

The short, sweet answer to the question posed is:

public static void main( String[] args ) {
    if( args.length > 0 && args[0].equals( "a" ) ) {
        // first argument is "a"
    } else {
        // oh noes!?
    }
}

How can one change the timestamp of an old commit in Git?

Each commit is associated with two dates, the committer date and the author date. You can view these dates with:

git log --format=fuller

If you want to change the author date and the committer date of the last 6 commits, you can simply use an interactive rebase :

git rebase -i HEAD~6

.

pick c95a4b7 Modification 1
pick 1bc0b44 Modification 2
pick de19ad3 Modification 3
pick c110e7e Modification 4
pick 342256c Modification 5
pick 5108205 Modification 6

# Rebase eadedca..5108205 onto eadedca (6 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit

For all commits where you want to change the date, replace pick by edit (or just e), then save and quit your editor.

You can now amend each commit by specifying the author date and the committer date in ISO-8601 format:

GIT_COMMITTER_DATE="2017-10-08T09:51:07" git commit --amend --date="2017-10-08T09:51:07"

The first date is the commit date, the second one is the author date.

Then go to the next commit with :

git rebase --continue

Repeat the process until you amend all your commits. Check your progression with git status.

How can I get client information such as OS and browser

There are two not bad libs for parsing user agent strings:

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

Liam's link looks great, but also check out pandas.Timedelta - looks like it plays nicely with NumPy's and Python's time deltas.

https://pandas.pydata.org/pandas-docs/stable/timedeltas.html

pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)

How to Deserialize JSON data?

You can write your own JSON parser and make it more generic based on your requirement. Here is one which served my purpose nicely, hope will help you too.

class JsonParsor
{
    public static DataTable JsonParse(String rawJson)
    {
        DataTable dataTable = new DataTable();
        Dictionary<string, string> outdict = new Dictionary<string, string>();
        StringBuilder keybufferbuilder = new StringBuilder();
        StringBuilder valuebufferbuilder = new StringBuilder();
        StringReader bufferreader = new StringReader(rawJson);
        int s = 0;
        bool reading = false;
        bool inside_string = false;
        bool reading_value = false;
        bool reading_number = false;
        while (s >= 0)
        {
            s = bufferreader.Read();
            //open JSON
            if (!reading)
            {
                if ((char)s == '{' && !inside_string && !reading)
                {
                    reading = true;
                    continue;
                }
                if ((char)s == '}' && !inside_string && !reading)
                    break;
                if ((char)s == ']' && !inside_string && !reading)
                    continue;
                if ((char)s == ',')
                    continue;
            }
            else
            {
                if (reading_value)
                {
                    if (!inside_string && (char)s >= '0' && (char)s <= '9')
                    {
                        reading_number = true;
                        valuebufferbuilder.Append((char)s);
                        continue;
                    }
                }
                //if we find a quote and we are not yet inside a string, advance and get inside
                if (!inside_string)
                {
                    if ((char)s == '\"' && !inside_string)
                        inside_string = true;
                    if ((char)s == '[' && !inside_string)
                    {
                        keybufferbuilder.Length = 0;
                        valuebufferbuilder.Length = 0;
                                reading = false;
                                inside_string = false;
                                reading_value = false;
                    }
                    if ((char)s == ',' && !inside_string && reading_number)
                    {
                        if (!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                            dataTable.Columns.Add(keybufferbuilder.ToString(), typeof(string));
                        if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                            outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                        keybufferbuilder.Length = 0;
                        valuebufferbuilder.Length = 0;
                        reading_value = false;
                        reading_number = false;
                    }
                    continue;
                }

                //if we reach end of the string
                if (inside_string)
                {
                    if ((char)s == '\"')
                    {
                        inside_string = false;
                        s = bufferreader.Read();
                        if ((char)s == ':')
                        {
                            reading_value = true;
                            continue;
                        }
                        if (reading_value && (char)s == ',')
                        {
                            //put the key-value pair into dictionary
                            if(!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                                dataTable.Columns.Add(keybufferbuilder.ToString(),typeof(string));
                            if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                            outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            keybufferbuilder.Length = 0;
                            valuebufferbuilder.Length = 0;
                            reading_value = false;
                        }
                        if (reading_value && (char)s == '}')
                        {
                            if (!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                                dataTable.Columns.Add(keybufferbuilder.ToString(), typeof(string));
                            if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                                outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            ICollection key = outdict.Keys;
                            DataRow newrow = dataTable.NewRow();
                            foreach (string k_loopVariable in key)
                            {
                                CommonModule.LogTheMessage(outdict[k_loopVariable],"","","");
                                newrow[k_loopVariable] = outdict[k_loopVariable];
                            }
                            dataTable.Rows.Add(newrow);
                            CommonModule.LogTheMessage(dataTable.Rows.Count.ToString(), "", "row_count", "");
                            outdict.Clear();
                            keybufferbuilder.Length=0;
                            valuebufferbuilder.Length=0;
                            reading_value = false;
                            reading = false;
                            continue;
                        }
                    }
                    else
                    {
                        if (reading_value)
                        {
                            valuebufferbuilder.Append((char)s);
                            continue;
                        }
                        else
                        {
                            keybufferbuilder.Append((char)s);
                            continue;
                        }
                    }
                }
                else
                {
                    switch ((char)s)
                    {
                        case ':':
                            reading_value = true;
                            break;
                        default:
                            if (reading_value)
                            {
                                valuebufferbuilder.Append((char)s);
                            }
                            else
                            {
                                keybufferbuilder.Append((char)s);
                            }
                            break;
                    }
                }
            }
        }

        return dataTable;
    }
}

System.Data.SqlClient.SqlException: Login failed for user

kinda dumb, but I had a weird character (é) in my password. After omitting it, I no longer got the error.

Can media queries resize based on a div element instead of the screen?

The question is very vague. As BoltClock says, media queries only know the dimensions of the device. However, you can use media queries in combination with descender selectors to perform adjustments.

.wide_container { width: 50em }

.narrow_container { width: 20em }

.my_element { border: 1px solid }

@media (max-width: 30em) {
    .wide_container .my_element {
        color: blue;
    }

    .narrow_container .my_element {
        color: red;
    }
}

@media (max-width: 50em) {
    .wide_container .my_element {
        color: orange;
    }

    .narrow_container .my_element {
        color: green;
    }
}

The only other solution requires JS.

Two Divs on the same row and center align both of them

Please take a look on flex it will help you make things right,

on the main div set css display :flex

the div's that inside set css: flex:1 1 auto;

attached jsfiddle link as example enjoy :)

https://jsfiddle.net/hodca/v1uLsxbg/

How to move certain commits to be based on another branch in git?

You can use git cherry-pick to just pick the commit that you want to copy over.

Probably the best way is to create the branch out of master, then in that branch use git cherry-pick on the 2 commits from quickfix2 that you want.

How can I lookup a Java enum from its String value?

In case it helps others, the option I prefer, which is not listed here, uses Guava's Maps functionality:

public enum Vebosity {
    BRIEF("BRIEF"),
    NORMAL("NORMAL"),
    FULL("FULL");

    private String value;
    private Verbosity(final String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }

    private static ImmutableMap<String, Verbosity> reverseLookup = 
            Maps.uniqueIndex(Arrays.asList(Verbosity.values()), Verbosity::getValue);

    public static Verbosity fromString(final String id) {
        return reverseLookup.getOrDefault(id, NORMAL);
    }
}

With the default you can use null, you can throw IllegalArgumentException or your fromString could return an Optional, whatever behavior you prefer.

How to query values from xml nodes?

SELECT  b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    Batches b
CROSS APPLY b.RawXml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol);

Demo: SQLFiddle

executing shell command in background from script

For example you have a start program named run.sh to start it working at background do the following command line. ./run.sh &>/dev/null &

What is the difference between LATERAL and a subquery in PostgreSQL?

First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.

Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:

Consider following query.

Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A 

You can use lateral in this condition.

Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
  Select B.Column1,B.Column2,B.Fk1 from B  Limit 1
) x ON X.Fk1 = A.PK

In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.

There are more usages for lateral or cross apply but this is most common one I found.

What is the --save option for npm install?

–npm install --save or -S: When the following command is used with npm install this will save all your installed core packages into the dependency section in the package.json file. Core dependencies are those packages without which your application will not give the desired results. But as mentioned earlier, it is an unnecessary feature in the npm 5.0.0 version onwards.

npm install --save

Gradle failed to resolve library in Android Studio

Some time you may just need to add maven { url "https://jitpack.io" } in your allprojects block in project level build.gradle file.

Example:

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

Iterate over object in Angular

It appears they do not want to support the syntax from ng1.

According to Miško Hevery (reference):

Maps have no orders in keys and hence they iteration is unpredictable. This was supported in ng1, but we think it was a mistake and will not be supported in NG2

The plan is to have a mapToIterable pipe

<div *ngFor"var item of map | mapToIterable">

So in order to iterate over your object you will need to use a "pipe". Currently there is no pipe implemented that does that.

As a workaround, here is a small example that iterates over the keys:

Component:

import {Component} from 'angular2/core';

@Component({
  selector: 'component',
  templateUrl: `
       <ul>
       <li *ngFor="#key of keys();">{{key}}:{{myDict[key]}}</li>
       </ul>
  `
})
export class Home {
  myDict : Dictionary;
  constructor() {
    this.myDict = {'key1':'value1','key2':'value2'};
  }

  keys() : Array<string> {
    return Object.keys(this.myDict);
  }
}

interface Dictionary {
    [ index: string ]: string
}

How to Install Font Awesome in Laravel Mix

How to Install Font Awesome 5 in Laravel 5.3 - 5.6 (The Right Way)

Build your webpack.mix.js configuration.

mix.setResourceRoot("../");

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

Install the latest free version of Font Awesome via a package manager like npm.

npm install @fortawesome/fontawesome-free

This dependency entry should now be in your package.json.

// Font Awesome
"dependencies": {
    "@fortawesome/fontawesome-free": "^5.15.2",

In your main SCSS file /resources/assets/sass/app.scss, import one or more styles.

@import '~@fortawesome/fontawesome-free/scss/fontawesome';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/brands';

Compile your assets and produce a minified, production-ready build.

npm run production

Finally, reference your generated CSS file in your Blade template/layout.

<link type="text/css" rel="stylesheet" href="{{ mix('css/app.css') }}">

How to Install Font Awesome 5 with Laravel Mix 6 in Laravel 8 (The Right Way)

https://gist.github.com/karlhillx/89368bfa6a447307cbffc59f4e10b621

What do the different readystates in XMLHttpRequest mean, and how can I use them?

The full list of readyState values is:

State  Description
0      The request is not initialized
1      The request has been set up
2      The request has been sent
3      The request is in process
4      The request is complete

(from https://www.w3schools.com/js/js_ajax_http_response.asp)

In practice you almost never use any of them except for 4.

Some XMLHttpRequest implementations may let you see partially received responses in responseText when readyState==3, but this isn't universally supported and shouldn't be relied upon.

How to import Angular Material in project?

You should consider using a SharedModule for the essential material components of your app, and then import every single module you need to use into your feature modules. I wrote an article on medium explaining how to import Angular material, check it out:

https://medium.com/@benmohamehdi/how-to-import-angular-material-angular-best-practices-80d3023118de

How to find index of STRING array in Java from a given value?

An easy way would be to iterate over the items in the array in a loop.

for (var i = 0; i < arrayLength; i++) {
 // (string) Compare the given string with myArray[i]
 // if it matches store/save i and exit the loop.
}

There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.

The split() method in Java does not work on a dot (.)

java.lang.String.split splits on regular expressions, and . in a regular expression means "any character".

Try temp.split("\\.").

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

Please make sure that you are not consuming your inputstream anywhere before parsing. Sample code is following: the respose below is httpresponse(i.e. response) and main content is contain inside StringEntity (i.e. getEntity())in form of inputStream(i.e. getContent()).

InputStream rescontent = response.getEntity().getContent();
tsResponse=(TsResponse) transformer.convertFromXMLToObject(rescontent );

PHP - SSL certificate error: unable to get local issuer certificate

I have Very Simple Solution of this problem. You can do this without any certificate file..

Go on Laravel Root Folder -> Vender -> guzzlehttp -> guzzle -> src

open Client.php

find $defaults Array . that look like this way ..

$defaults = [
    'allow_redirects' => RedirectMiddleware::$defaultSettings,
    'http_errors'     => true,
    'decode_content'  => true,
    'verify'          => true,
    'cookies'         => false
];

Now main Job is to change value of verify key ..

'verify'          => false,

So After this it will not check SSL Certificate for CURL Request... This Solution is work for me. I find this solution after many research ...

Xcode "Device Locked" When iPhone is unlocked

This can also happen due to pending update on your device. This also means you need to update your phone, connect to the MacBook (trust it if needed). This how I found my problem and solution.

How to pass object from one component to another in Angular 2?

you could also store your data in an service with an setter and get it over a getter

import { Injectable } from '@angular/core';

@Injectable()
export class StorageService {

    public scope: Array<any> | boolean = false;

    constructor() {
    }

    public getScope(): Array<any> | boolean {
        return this.scope;
    }

    public setScope(scope: any): void {
        this.scope = scope;
    }
}

Angularjs - Pass argument to directive

You can try like below:

app.directive("directive_name", function(){
return {
    restrict:'E',
    transclude:true,
    template:'<div class="title"><h2>{{title}}</h3></div>',
    scope:{
      accept:"="
    },
    replace:true
  };
})

it sets up a two-way binding between the value of the 'accept' attribute and the parent scope.

And also you can set two way data binding with property: '='

For example, if you want both key and value bound to the local scope you would do:

  scope:{
    key:'=',
    value:'='
  },

For more info, https://docs.angularjs.org/guide/directive

So, if you want to pass an argument from controller to directive, then refer this below fiddle

http://jsfiddle.net/jaimem/y85Ft/7/

Hope it helps..

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

Your problem is that String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4"; is not JSON.
What you want to do is open an HTTP connection to "http://www.json-generator.com/j/cglqaRcMSW?indent=4" and parse the JSON response.

String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";
JSONObject jsonObject = new JSONObject(JSON); // <-- Problem here!

Will not open a connection to the site and retrieve the content.

Possible to make labels appear when hovering over a point in matplotlib?

It seems none of the other answers here actually answer the question. So here is a code that uses a scatter and shows an annotation upon hovering over the scatter points.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)

norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn

fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)

annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

def update_annot(ind):

    pos = sc.get_offsets()[ind["ind"][0]]
    annot.xy = pos
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), 
                           " ".join([names[n] for n in ind["ind"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
    annot.get_bbox_patch().set_alpha(0.4)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", hover)

plt.show()

enter image description here

Because people also want to use this solution for a line plot instead of a scatter, the following would be the same solution for plot (which works slightly differently).

_x000D_
_x000D_
import matplotlib.pyplot as plt_x000D_
import numpy as np; np.random.seed(1)_x000D_
_x000D_
x = np.sort(np.random.rand(15))_x000D_
y = np.sort(np.random.rand(15))_x000D_
names = np.array(list("ABCDEFGHIJKLMNO"))_x000D_
_x000D_
norm = plt.Normalize(1,4)_x000D_
cmap = plt.cm.RdYlGn_x000D_
_x000D_
fig,ax = plt.subplots()_x000D_
line, = plt.plot(x,y, marker="o")_x000D_
_x000D_
annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",_x000D_
                    bbox=dict(boxstyle="round", fc="w"),_x000D_
                    arrowprops=dict(arrowstyle="->"))_x000D_
annot.set_visible(False)_x000D_
_x000D_
def update_annot(ind):_x000D_
    x,y = line.get_data()_x000D_
    annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])_x000D_
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), _x000D_
                           " ".join([names[n] for n in ind["ind"]]))_x000D_
    annot.set_text(text)_x000D_
    annot.get_bbox_patch().set_alpha(0.4)_x000D_
_x000D_
_x000D_
def hover(event):_x000D_
    vis = annot.get_visible()_x000D_
    if event.inaxes == ax:_x000D_
        cont, ind = line.contains(event)_x000D_
        if cont:_x000D_
            update_annot(ind)_x000D_
            annot.set_visible(True)_x000D_
            fig.canvas.draw_idle()_x000D_
        else:_x000D_
            if vis:_x000D_
                annot.set_visible(False)_x000D_
                fig.canvas.draw_idle()_x000D_
_x000D_
fig.canvas.mpl_connect("motion_notify_event", hover)_x000D_
_x000D_
plt.show()
_x000D_
_x000D_
_x000D_

In case someone is looking for a solution for lines in twin axes, refer to How to make labels appear when hovering over a point in multiple axis?

In case someone is looking for a solution for bar plots, please refer to e.g. this answer.

instantiate a class from a variable in PHP?

How to pass dynamic constructor parameters too

If you want to pass dynamic constructor parameters to the class, you can use this code:

$reflectionClass = new ReflectionClass($className);

$module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters);

More information on dynamic classes and parameters

PHP >= 5.6

As of PHP 5.6 you can simplify this even more by using Argument Unpacking:

// The "..." is part of the language and indicates an argument array to unpack.
$module = new $className(...$arrayOfConstructorParameters);

Thanks to DisgruntledGoat for pointing that out.

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

Is it possible to change the radio button icon in an android radio button group

In case you want to do it programmatically,

checkBoxOrRadioButton.setButtonDrawable(null);
checkBoxOrRadioButton.setBackgroundResource(R.drawable.resource_name);

Getting a POST variable

Use this for GET values:

Request.QueryString["key"]

And this for POST values

Request.Form["key"]

Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:

Request["key"]

Another thing to note (if you need it) is you can check the type of request by using:

Request.RequestType

Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

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

you should add this line above your page

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

The jersey-container-servlet actually uses the jersey-container-servlet-core dependency. But if you use maven, that does not really matter. If you just define the jersey-container-servlet usage, it will automatically download the dependency as well.

But for those who add jar files to their project manually (i.e. without maven) It is important to know that you actually need both jar files. The org.glassfish.jersey.servlet.ServletContainer class is actually part of the core dependency.

Break a previous commit into multiple commits

git rebase -i will do it.

First, start with a clean working directory: git status should show no pending modifications, deletions, or additions.

Now, you have to decide which commit(s) you want to split.

A) Splitting the most recent commit

To split apart your most recent commit, first:

$ git reset HEAD~

Now commit the pieces individually in the usual way, producing as many commits as you need.

B) Splitting a commit farther back

This requires rebasing, that is, rewriting history. To find the correct commit, you have several choices:

  • If it was three commits back, then

    $ git rebase -i HEAD~3
    

    where 3 is how many commits back it is.

  • If it was farther back in the tree than you want to count, then

    $ git rebase -i 123abcd~
    

    where 123abcd is the SHA1 of the commit you want to split up.

  • If you are on a different branch (e.g., a feature branch) that you plan to merge into master:

    $ git rebase -i master
    

When you get the rebase edit screen, find the commit you want to break apart. At the beginning of that line, replace pick with edit (e for short). Save the buffer and exit. Rebase will now stop just after the commit you want to edit. Then:

$ git reset HEAD~

Commit the pieces individually in the usual way, producing as many commits as you need, then

$ git rebase --continue

How update the _id of one MongoDB Document?

You can also create a new document from MongoDB compass or using command and set the specific _id value that you want.

Remove multiple items from a Python list in just one statement

You can use filterfalse function from itertools module

Example

import random
from itertools import filterfalse

random.seed(42)

data = [random.randrange(5) for _ in range(10)]
clean = [*filterfalse(lambda i: i == 0, data)]
print(f"Remove 0s\n{data=}\n{clean=}\n")


clean = [*filterfalse(lambda i: i in (0, 1), data)]
print(f"Remove 0s and 1s\n{data=}\n{clean=}")

Output:

Remove 0s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 1, 1, 1, 4, 4]

Remove 0s and 1s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 4, 4]

PHP XML how to output nice format

This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.

When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).

Consider the following code:

$dom = new DOMDocument();                               //create a document
$dom->preserveWhiteSpace = false;                       //disable whitespace preservation
$dom->formatOutput = true;                              //pretty print output
$documentElement = $dom->createElement("Entry");        //create a node
$dom->appendChild ($documentElement);                   //append it 
$message = new DOMDocument();                           //create another document
$message->loadXML($messageXMLtext);                     //populate the new document from XML text
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document
$documentElement->appendChild($node);                   //append the new node to the document Element
$dom->saveXML($dom->documentElement);                   //print the original document

In this context, the $dom->saveXML(); statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.

In order to achieve pretty printing for the entire $dom document, the line:

$message->preserveWhiteSpace = false; 

must be included after the $message = new DOMDocument(); line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.

FPDF utf-8 encoding (HOW-TO)

I wanted to answer this for anyone who hasn't switched over to TFPDF for whatever reason (framework integration, etc.)

Go to: http://www.fpdf.org/makefont/index.php

Use a .ttf compatible font for the language you want to use. Make sure to choose the encoding number that is correct for your language. Download the files and paste them in your current FPDF font directory.

Use this to activate the new font: $pdf->AddFont($font_name,'','Your_Font_Here.php');

Then you can use $pdf->SetFont normally.

On the font itself, use iconv to convert to UTF-8. So if for example you're using Hebrew, you would do iconv('UTF-8', 'windows-1255', $first_name).

Substitute the windows encoding number for your language encoding.

For right to left, a quick fix is doing something like strrev(iconv('UTF-8', 'windows-1255', $first_name)).

How to filter input type="file" dialog by specific file type?

Add a custom attribute to <input type="file" file-accept="jpg gif jpeg png bmp"> and read the filenames within javascript that matches the extension provided by the attribute file-accept. This will be kind of bogus, as a text file with any of the above extension will erroneously deteted as image.

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

The problem mainly occurs after updating OS X to El Capitan (OS X 10.11) or macOS Sierra (macOS 10.12).

This is because of file permission issues with El Capitan’s or later macOS's new SIP process. Try changing the permissions for the /usr/local directory:

$ sudo chown -R $(whoami):admin /usr/local  

If it still doesn't work, use these steps inside a terminal session and everything will be fine:

cd /usr/local/Library/Homebrew  
git reset --hard  
git clean -df
brew update

This may be because homebrew is not updated.

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

I've updated the Microsoft.Net.Compilers to version 2.0 or higher

see this

Is it possible to decompile an Android .apk file?

First, an apk file is just a modified jar file. So the real question is can they decompile the dex files inside. The answer is sort of. There are already disassemblers, such as dedexer and smali. You can expect these to only get better, and theoretically it should eventually be possible to decompile to actual Java source (at least sometimes). See the previous question decompiling DEX into Java sourcecode.

What you should remember is obfuscation never works. Choose a good license and do your best to enforce it through the law. Don't waste time with unreliable technical measures.

Find duplicate entries in a column

Using:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

...will show you the ctn_no value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
   WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

If you want to see the other column values associated with the duplicate, you'll want to use a self join:

SELECT x.*
  FROM YOUR_TABLE x
  JOIN (SELECT t.ctn_no
          FROM YOUR_TABLE t
      GROUP BY t.ctn_no
        HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no

How to use the onClick event for Hyperlink using C# code?

this may help you.

In .cs page,

//Declare a string
   public string usertypeurl = "";
  //check who is the user
       //place your code to check who is the user
       //if it is admin
       usertypeurl = "help/AdminTutorial.html";
       //if it is other 
        usertypeurl = "help/UserTutorial.html";

In .aspx age pass this variabe

  <a href='<%=usertypeurl%>'>Tutorial</a>

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

You must ensure the URL contains embed rather watch as the /embed endpoint allows outside requests, whereas the /watch endpoint does not.

<iframe width="420" height="315" src="https://www.youtube.com/embed/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>

How to get current SIM card number in Android?

Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.

=================================================================================

Its been almost 6 months and I believe I should update this with an alternative solution you might want to consider.

As of today, you can rely on another big application Whatsapp, using AccountManager. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager, you may give this a shot.

Permission:

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

Code:

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();

ArrayList<String> googleAccounts = new ArrayList<String>();
for (Account ac : accounts) {
    String acname = ac.name;
    String actype = ac.type;
    // Take your time to look at all available accounts
    System.out.println("Accounts : " + acname + ", " + actype);
}

Check actype for whatsapp account

if(actype.equals("com.whatsapp")){
    String phoneNumber = ac.name;
}

Of course you may not get it if user did not install Whatsapp, but its worth to try anyway. And remember you should always ask user for confirmation.

What does the "@" symbol do in SQL?

@ followed by a number is the parameters in the order they're listed in a function.

Evaluating a mathematical expression in a string

Pyparsing can be used to parse mathematical expressions. In particular, fourFn.py shows how to parse basic arithmetic expressions. Below, I've rewrapped fourFn into a numeric parser class for easier reuse.

from __future__ import division
from pyparsing import (Literal, CaselessLiteral, Word, Combine, Group, Optional,
                       ZeroOrMore, Forward, nums, alphas, oneOf)
import math
import operator

__author__ = 'Paul McGuire'
__version__ = '$Revision: 0.0 $'
__date__ = '$Date: 2009-03-20 $'
__source__ = '''http://pyparsing.wikispaces.com/file/view/fourFn.py
http://pyparsing.wikispaces.com/message/view/home/15549426
'''
__note__ = '''
All I've done is rewrap Paul McGuire's fourFn.py as a class, so I can use it
more easily in other places.
'''


class NumericStringParser(object):
    '''
    Most of this code comes from the fourFn.py pyparsing example

    '''

    def pushFirst(self, strg, loc, toks):
        self.exprStack.append(toks[0])

    def pushUMinus(self, strg, loc, toks):
        if toks and toks[0] == '-':
            self.exprStack.append('unary -')

    def __init__(self):
        """
        expop   :: '^'
        multop  :: '*' | '/'
        addop   :: '+' | '-'
        integer :: ['+' | '-'] '0'..'9'+
        atom    :: PI | E | real | fn '(' expr ')' | '(' expr ')'
        factor  :: atom [ expop factor ]*
        term    :: factor [ multop factor ]*
        expr    :: term [ addop term ]*
        """
        point = Literal(".")
        e = CaselessLiteral("E")
        fnumber = Combine(Word("+-" + nums, nums) +
                          Optional(point + Optional(Word(nums))) +
                          Optional(e + Word("+-" + nums, nums)))
        ident = Word(alphas, alphas + nums + "_$")
        plus = Literal("+")
        minus = Literal("-")
        mult = Literal("*")
        div = Literal("/")
        lpar = Literal("(").suppress()
        rpar = Literal(")").suppress()
        addop = plus | minus
        multop = mult | div
        expop = Literal("^")
        pi = CaselessLiteral("PI")
        expr = Forward()
        atom = ((Optional(oneOf("- +")) +
                 (ident + lpar + expr + rpar | pi | e | fnumber).setParseAction(self.pushFirst))
                | Optional(oneOf("- +")) + Group(lpar + expr + rpar)
                ).setParseAction(self.pushUMinus)
        # by defining exponentiation as "atom [ ^ factor ]..." instead of
        # "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right
        # that is, 2^3^2 = 2^(3^2), not (2^3)^2.
        factor = Forward()
        factor << atom + \
            ZeroOrMore((expop + factor).setParseAction(self.pushFirst))
        term = factor + \
            ZeroOrMore((multop + factor).setParseAction(self.pushFirst))
        expr << term + \
            ZeroOrMore((addop + term).setParseAction(self.pushFirst))
        # addop_term = ( addop + term ).setParseAction( self.pushFirst )
        # general_term = term + ZeroOrMore( addop_term ) | OneOrMore( addop_term)
        # expr <<  general_term
        self.bnf = expr
        # map operator symbols to corresponding arithmetic operations
        epsilon = 1e-12
        self.opn = {"+": operator.add,
                    "-": operator.sub,
                    "*": operator.mul,
                    "/": operator.truediv,
                    "^": operator.pow}
        self.fn = {"sin": math.sin,
                   "cos": math.cos,
                   "tan": math.tan,
                   "exp": math.exp,
                   "abs": abs,
                   "trunc": lambda a: int(a),
                   "round": round,
                   "sgn": lambda a: abs(a) > epsilon and cmp(a, 0) or 0}

    def evaluateStack(self, s):
        op = s.pop()
        if op == 'unary -':
            return -self.evaluateStack(s)
        if op in "+-*/^":
            op2 = self.evaluateStack(s)
            op1 = self.evaluateStack(s)
            return self.opn[op](op1, op2)
        elif op == "PI":
            return math.pi  # 3.1415926535
        elif op == "E":
            return math.e  # 2.718281828
        elif op in self.fn:
            return self.fn[op](self.evaluateStack(s))
        elif op[0].isalpha():
            return 0
        else:
            return float(op)

    def eval(self, num_string, parseAll=True):
        self.exprStack = []
        results = self.bnf.parseString(num_string, parseAll)
        val = self.evaluateStack(self.exprStack[:])
        return val

You can use it like this

nsp = NumericStringParser()
result = nsp.eval('2^4')
print(result)
# 16.0

result = nsp.eval('exp(2^4)')
print(result)
# 8886110.520507872

Gradient text color

The way this effect works is very simple. The element is given a background which is the gradient. It goes from one color to another depending on the colors and color-stop percentages given for it.

For example, in rainbow text sample (note that I've converted the gradient into the standard syntax):

  • The gradient starts at color #f22 at 0% (that is the left edge of the element). First color is always assumed to start at 0% even though the percentage is not mentioned explicitly.
  • Between 0% to 14.25%, the color changes from #f22 to #f2f gradually. The percenatge is set at 14.25 because there are seven color changes and we are looking for equal splits.
  • At 14.25% (of the container's size), the color will exactly be #f2f as per the gradient specified.
  • Similarly the colors change from one to another depending on the bands specified by color stop percentages. Each band should be a step of 14.25%.

So, we end up getting a gradient like in the below snippet. Now this alone would mean the background applies to the entire element and not just the text.

_x000D_
_x000D_
.rainbow {_x000D_
  background-image: linear-gradient(to right, #f22, #f2f 14.25%, #22f 28.5%, #2ff 42.75%, #2f2 57%, #2f2 71.25%, #ff2 85.5%, #f22);_x000D_
  color: transparent;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>
_x000D_
_x000D_
_x000D_

Since, the gradient needs to be applied only to the text and not to the element on the whole, we need to instruct the browser to clip the background from the areas outside the text. This is done by setting background-clip: text.

(Note that the background-clip: text is an experimental property and is not supported widely.)


Now if you want the text to have a simple 3 color gradient (that is, say from red - orange - brown), we just need to change the linear-gradient specification as follows:

  • First parameter is the direction of the gradient. If the color should be red at left side and brown at the right side then use the direction as to right. If it should be red at right and brown at left then give the direction as to left.
  • Next step is to define the colors of the gradient. Since our gradient should start as red on the left side, just specify red as the first color (percentage is assumed to be 0%).
  • Now, since we have two color changes (red - orange and orange - brown), the percentages must be set as 100 / 2 for equal splits. If equal splits are not required, we can assign the percentages as we wish.
  • So at 50% the color should be orange and then the final color would be brown. The position of the final color is always assumed to be at 100%.

Thus the gradient's specification should read as follows:

background-image: linear-gradient(to right, red, orange 50%, brown).

If we form the gradients using the above mentioned method and apply them to the element, we can get the required effect.

_x000D_
_x000D_
.red-orange-brown {_x000D_
  background-image: linear-gradient(to right, red, orange 50%, brown);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}_x000D_
.green-yellowgreen-yellow-gold {_x000D_
  background-image: linear-gradient(to right, green, yellowgreen 33%, yellow 66%, gold);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<span class="red-orange-brown">Red to Orange to Brown</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<span class="green-yellowgreen-yellow-gold">Green to Yellow-green to Yellow to Gold</span>
_x000D_
_x000D_
_x000D_

How to hide a div after some time period?

setTimeout('$("#someDivId").hide()',1500);

Nginx 403 forbidden for all files

I solved this problem by adding user settings.

in nginx.conf

worker_processes 4;
user username;

change the 'username' with linux user name.

Datanode process not running in Hadoop

Follow these steps and your datanode will start again.

1)Stop dfs. 2)Open hdfs-site.xml 3)Remove the data.dir and name.dir properties from hdfs-site.xml and -format namenode again.

4)Then start dfs again.

What is 'Context' on Android?

A Context is what most of us would call Application. It's made by the Android system and is able to do only what an application is able to. In Tomcat, a Context is also what I would call an application.

There is one Context that holds many Activities, each Activity may have many Views.

Obviously, some will say that it doesn't fit because of this or that and they are probably right, but saying that a Context is your current application will help you to understand what you are putting in method parameters.

LINQ to SQL - How to select specific columns and return strongly typed list

Basically you are doing it the right way. However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query):

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new Person { Name = a.Name, Age = a.Age }).ToList();

Apparently, the Person class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

class PersonInformation {
   public string Name {get;set;}
   public int Age {get;set;}
}

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();

You can freely swap var with List<PersonInformation> here without affecting anything (as this is what the compiler does).

Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new { a.Name, a.Age }).ToList();

Note that in all of these cases, the result is statically typed (it's type is known at compile time). The latter type is a List of a compiler generated anonymous class similar to the PersonInformation class I wrote above. As of C# 3.0, there's no dynamic typing in the language.

UPDATE:

If you really want to return a List<Person> (which might or might not be the best thing to do), you can do this:

var result = from a in new DataContext().Persons
             where a.Age > 18
             select new { a.Name, a.Age };

List<Person> list = result.AsEnumerable()
                          .Select(o => new Person {
                                           Name = o.Name, 
                                           Age = o.Age
                          }).ToList();

You can merge the above statements too, but I separated them for clarity.

Backporting Python 3 open(encoding="utf-8") to Python 2

Here's one way:

with open("filename.txt", "rb") as f:
    contents = f.read().decode("UTF-8")

How to capture UIView to UIImage without loss of quality on retina display

The currently accepted answer is now out of date, at least if you are supporting iOS 7.

Here is what you should be using if you are only supporting iOS7+:

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0f);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

Swift 4:

func imageWithView(view: UIView) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
    defer { UIGraphicsEndImageContext() }
    view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
    return UIGraphicsGetImageFromCurrentImageContext()
}

As per this article, you can see that the new iOS7 method drawViewHierarchyInRect:afterScreenUpdates: is many times faster than renderInContext:. benchmark

Create a CSS rule / class with jQuery at runtime

In (unusual) cases where you want to be able to dynamically change styles often -- e.g. a theme builder app -- adding <style> tags or calling CSSStyleSheet.insertRule() will result in a growing stylesheet, which can have performance and design debugging implications.

My approach only allows a single rule per selector/property combo, clearing any existing on setting any rule. The API is simple and flexible:

function addStyle(selector, rulename, value) {
    var stylesheet = getAppStylesheet();
    var cssRules = stylesheet.cssRules || stylesheet.rules;
    var rule = stylesheet.insertRule(selector + ' { ' + rulename + ':' + value + ';}', cssRules.length);
}

function clearStyle(selector, rulename) {
    var stylesheet = getAppStylesheet();
    var cssRules = stylesheet.cssRules || stylesheet.rules;
    for (var i=0; i<cssRules.length; i++) {
        var rule = cssRules[i];
        if (rule.selectorText == selector && rule.style[0] == rulename) {
            stylesheet.deleteRule(i);
            break;
        }
    }       
}

function addStyles(selector, rules) {
    var stylesheet = getAppStylesheet();
    var cssRules = stylesheet.cssRules || stylesheet.rules;
    for (var prop in rules) {
        addStyle(selector, prop, rules[prop]);
    }
}

function getAppStylesheet() {
    var stylesheet = document.getElementById('my-styles');
    if (!stylesheet) {
        stylesheet = $('<style id="my-styles">').appendTo('head')[0];
    }
    stylesheet = stylesheet.sheet;
    return stylesheet;
}

Usage:

addStyles('body', {
    'background-color': 'black',
    color: 'green',
    margin: 'auto'
});

clearStyle('body', 'background-color');
addStyle('body', 'color', '#333')

Print a file's last modified date in Bash

I wanted to get a file's modification date in YYYYMMDDHHMMSS format. Here is how I did it:

date -d @$( stat -c %Y myfile.css ) +%Y%m%d%H%M%S

Explanation. It's the combination of these commands:

stat -c %Y myfile.css # Get the modification date as a timestamp
date -d @1503989421 +%Y%m%d%H%M%S # Convert the date (from timestamp)

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

  1. If you have released to Apple TestFlight for testing

    You have to click the link each time and select No, only after that, your tester can see the build. This is quite annoying if you want to get your build delivered as soon as possible.

    enter image description here

  2. Do this for the next build, (If do this before the build then this error will not occur)

The solution is add the following setting to your iOS Info.plist:

    <key>ITSAppUsesNonExemptEncryption</key>
    <false/>

enter image description here

Can not add "Missing Compliance", see this Missing Compliance

Can I store images in MySQL

You'll need to save as a blob, LONGBLOB datatype in mysql will work.

Ex:

CREATE TABLE 'test'.'pic' (
    'idpic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
    'caption' VARCHAR(45) NOT NULL,
    'img' LONGBLOB NOT NULL,
  PRIMARY KEY ('idpic')
)

As others have said, its a bad practice but it can be done. Not sure if this code would scale well, though.

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

How to allow Cross domain request in apache2

You can also put below code to the httaccess file as well to allow CORS using htaccess file

    ######################## Handling Options for the CORS
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [L,R=204]

   ##################### Add custom headers
   Header set X-Content-Type-Options "nosniff"
   Header set X-XSS-Protection "1; mode=block"
   # Always set these headers for CORS. 
   Header always set Access-Control-Max-Age 1728000
   Header always set Access-Control-Allow-Origin: "*"
   Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
   Header always set Access-Control-Allow-Headers: "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,C$
   Header always set Access-Control-Allow-Credentials true

For information purpose, You can also have a look at this article http://www.ipragmatech.com/enable-cors-using-htaccess/ which allow CORS header.

What's the best way to get the last element of an array without deleting it?

In almost every language with arrays you can't really go wrong with A[A.size-1]. I can't think of an example of a language with 1 based arrays (as opposed to zero based).

Load a bitmap image into Windows Forms using open file dialog

It's simple. Just add:

PictureBox1.BackgroundImageLayout = ImageLayout.Zoom;

How to sort List<Integer>?

You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.

Sorting a list in ascending order can be performed as default operation on this way:

Collections.sort(list);

Sorting a list in descending order can be performed on this way:

Collections.reverse(list);

According to these facts, your solution has to be written like this:

public class tes 
{
    public static void main(String args[])
    {
        List<Integer> lList = new ArrayList<Integer>();
        lList.add(4);
        lList.add(1);
        lList.add(7);
        lList.add(2);
        lList.add(9);
        lList.add(1);
        lList.add(5);

        Collections.sort(lList);
        for(int i=0; i<lList.size();i++ )
        {
            System.out.println(lList.get(i));
        }
     }
}

More about Collections you can read here.

How to retrieve the LoaderException property?

Using Quick Watch in Visual Studio you can access the LoaderExceptions from ViewDetails of the thrown exception like this:

($exception).LoaderExceptions

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line

denimjeansButton.addItemListener(this);

There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

If anyone wants to get installed application package code, just execute below command with your application name in the command prompt. You will be getting product code along with package code.

wmic product where "Name like '%YOUR_APPLICATION_NAME%'" get IdentifyingNumber, PackageCode

How to iterate over rows in a DataFrame in Pandas

The easiest way, use the apply function

def print_row(row):
   print row['c1'], row['c2']

df.apply(lambda row: print_row(row), axis=1)

Set focus on <input> element

html of component:

<input [cdkTrapFocusAutoCapture]="show" [cdkTrapFocus]="show">

controler of component:

showSearch() {
  this.show = !this.show;    
}

..and do not forget about import A11yModule from @angular/cdk/a11y

import { A11yModule } from '@angular/cdk/a11y'

How can I see the request headers made by curl when sending a request to the server?

Here is my http client in php to make post queries with cookies included:

function http_login_client($url, $params = "", $cookies_send = "" ){

    // Vars
    $cookies = array();
    $headers = getallheaders();

    // Perform a http post request to $ur1 using $params
    $ch = curl_init($url);
    $options = array(   CURLOPT_POST => 1,
                        CURLINFO_HEADER_OUT => true,
                        CURLOPT_POSTFIELDS => $params,
                        CURLOPT_RETURNTRANSFER => 1,
                        CURLOPT_HEADER => 1,
                        CURLOPT_COOKIE => $cookies_send,
                        CURLOPT_USERAGENT => $headers['User-Agent']
                    );

    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);

/// DEBUG info echo $response; var_dump (curl_getinfo($ch)); ///

    // Parse response and read cookies
    preg_match_all('/^Set-Cookie: (.*?)=(.*?);/m', $response, $matches);

    // Build an array with cookies
    foreach( $matches[1] as $index => $cookie )
        $cookies[$cookie] = $matches[2][$index];

    return $cookies;
} // end http_login_client

PDO mysql: How to know if insert was successful

You can test the rowcount

    $sqlStatement->execute( ...);
    if ($sqlStatement->rowCount() > 0)
    {
        return true;
    }

How to make <input type="file"/> accept only these types?

Use accept attribute with the MIME_type as values

<input type="file" accept="image/gif, image/jpeg" />

Does the join order matter in SQL?

Oracle optimizer chooses join order of tables for inner join. Optimizer chooses the join order of tables only in simple FROM clauses . U can check the oracle documentation in their website. And for the left, right outer join the most voted answer is right. The optimizer chooses the optimal join order as well as the optimal index for each table. The join order can affect which index is the best choice. The optimizer can choose an index as the access path for a table if it is the inner table, but not if it is the outer table (and there are no further qualifications).

The optimizer chooses the join order of tables only in simple FROM clauses. Most joins using the JOIN keyword are flattened into simple joins, so the optimizer chooses their join order.

The optimizer does not choose the join order for outer joins; it uses the order specified in the statement.

When selecting a join order, the optimizer takes into account: The size of each table The indexes available on each table Whether an index on a table is useful in a particular join order The number of rows and pages to be scanned for each table in each join order

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

Adding input elements dynamically to form

You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.

Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.

Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.

_x000D_
_x000D_
<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Number of inputs to create
            var number = document.getElementById("member").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>
_x000D_
_x000D_
_x000D_

See a working sample in this JSFiddle.

Capturing a form submit with jquery and .submit

Just replace the form.submit function with your own implementation:

var form = document.getElementById('form');
var formSubmit = form.submit; //save reference to original submit function

form.onsubmit = function(e)
{
    formHandler();
    return false;
};

var formHandler = form.submit = function()
{
    alert('hi there');
    formSubmit(); //optionally submit the form
};

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

How to show "Done" button on iPhone number pad

Below is an overhaul of Luda's answer with the following changes:

  • the accessory view is automatically sized to the width of the application frame

  • the deprecated constant UIBarButtonItemStyleBordered is avoided

  • the "Done" button is instantiated as a UIBarButtonSystemItemDone

Currently the "Done" button is centered in the accessory view. You can position it at left or right by deleting the space on the pertinent side.

I have omitted a "Cancel" button because the default keyboard doesn't have one either. If you do want a "Cancel" button, I suggest that you instantiate it as a UIBarButtonSystemItemCancel and that you make sure you're not discarding the original value in your text field. The "Cancel" behavior implemented in Luda's answer, which overwrites the value with a blank string, may not be what you want.

- (void)viewDidLoad {
  [super viewDidLoad];
  float appWidth = CGRectGetWidth([UIScreen mainScreen].applicationFrame);
  UIToolbar *accessoryView = [[UIToolbar alloc]
                              initWithFrame:CGRectMake(0, 0, appWidth, 0.1 * appWidth)];
  UIBarButtonItem *space = [[UIBarButtonItem alloc]
                            initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                            target:nil
                            action:nil];
  UIBarButtonItem *done = [[UIBarButtonItem alloc]
                           initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                           target:self
                           action:@selector(selectDoneButton)];
  accessoryView.items = @[space, done, space];
  self.valueField.inputAccessoryView = accessoryView;
}

- (void)selectDoneButton {
  [self.valueField resignFirstResponder];
}

For more information about building accessory views, see the Apple documentation on custom views for data input. You will probably want to consult the reference pages on UIToolbar and UIBarButtonItem as well.

Function for Factorial in Python

On Python 2.6 and up, try:

import math
math.factorial(n)

Performing user authentication in Java EE / JSF using j_security_check

It should be mentioned that it is an option to completely leave authentication issues to the front controller, e.g. an Apache Webserver and evaluate the HttpServletRequest.getRemoteUser() instead, which is the JAVA representation for the REMOTE_USER environment variable. This allows also sophisticated log in designs such as Shibboleth authentication. Filtering Requests to a servlet container through a web server is a good design for production environments, often mod_jk is used to do so.

Google Map API v3 — set bounds and center

The setCenter() method is still applicable for latest version of Maps API for Flash where fitBounds() does not exist.

How to insert a timestamp in Oracle?

I prefer ANSI timestamp literals:

insert into the_table 
  (the_timestamp_column)
values 
  (timestamp '2017-10-12 21:22:23');

More details in the manual: https://docs.oracle.com/database/121/SQLRF/sql_elements003.htm#SQLRF51062

Laravel - display a PDF file in storage without forcing download?

Retrieve File name first then in Blade file use anchor(a) tag like below shown. This would works for image view also.

<a href="{{ asset('storage/admission-document-uploads/' . $filename) }}" target="_black"> view Pdf </a>;

Changing java platform on which netbeans runs

In my Windows 7 box I found netbeans.conf in <Drive>:\<Program Files folder>\<NetBeans installation folder>\etc . Thanks all.

Android Overriding onBackPressed()

You may just call the onBackPressed()and if you want some activity to display after the back button you have mention the

Intent intent = new Intent(ResetPinActivity.this, MenuActivity.class);
    startActivity(intent);
    finish();

that worked for me.

How to send redirect to JSP page in Servlet

    String u = request.getParameter("username");
    String p = request.getParameter("password");

    try {
        st = con.createStatement();
        String sql;
        sql = "SELECT * FROM TableName where USERNAME = '" + u + "' and PASSWORD = '"
                + p + "'";
        ResultSet rs = st.executeQuery(sql);
        if (rs.next()) {
            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/home.jsp");
            requestDispatcher.forward(request, response);
        } else {

            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/invalidLogin.jsp");
            requestDispatcher.forward(request, response);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    finally{
        try {
            rs.close();
            ps.close();
            con.close();
            st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Matlab: Running an m-file from command-line

On Linux you can do the same and you can actually send back to the shell a custom error code, like the following:

#!/bin/bash
matlab -nodisplay -nojvm -nosplash -nodesktop -r \ 
      "try, run('/foo/bar/my_script.m'), catch, exit(1), end, exit(0);"
echo "matlab exit code: $?"

it prints matlab exit code: 1 if the script throws an exception, matlab exit code: 0 otherwise.

How to create a GUID/UUID in Python

This function is fully configurable and generates unique uid based on the format specified

eg:- [8, 4, 4, 4, 12] , this is the format mentioned and it will generate the following uuid

LxoYNyXe-7hbQ-caJt-DSdU-PDAht56cMEWi

 import random as r

 def generate_uuid():
        random_string = ''
        random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        uuid_format = [8, 4, 4, 4, 12]
        for n in uuid_format:
            for i in range(0,n):
                random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
            if n != 12:
                random_string += '-'
        return random_string

WPF Check box: Check changed handling

I know this is an old question, but how about just binding to Command if using MVVM?

ex:

<CheckBox Content="Case Sensitive" Command="{Binding bSearchCaseSensitive}"/>

For me it triggers on both Check and Uncheck.

How to close existing connections to a DB

Short Answer:

You get "close existing connections to destination database" option only in "Databases context >> Restore Wizard" and NOT ON context of any particular database.

Long Answer:

Right Click on the Databases under your Server-Name as shown below:

and select the option: "Restore Database..." from it.

db

In the "Restore Database" wizard,

  1. select one of your databases to restore
  2. in the left vertical menu, click on "Options"

db1

Here you can find the checkbox saying, "close existing connections to destination database"

db3

Just check it, and you can proceed for the restore operation.

It automatically will resume all connections after completion of the Restore.

Why is System.Web.Mvc not listed in Add References?

You can also add this from the Nuget Package Manager Console, something like:

Install-Package Microsoft.AspNet.Mvc -Version 4.0.20710.0 -ProjectName XXXXX

Microsoft.AspNet.Mvc has dependencies on:

  • 'Microsoft.AspNet.WebPages (= 2.0.20710.0 && < 2.1)'
  • 'Microsoft.Web.Infrastructure (= 1.0.0.0)'
  • 'Microsoft.AspNet.Razor (= 2.0.20710.0 && < 2.1)'

...which seems like no biggie to me. In our case, this is a class library that exists solely to provide support for our Mvc apps. So, we figure it's a benign dependency at worst.

I definitely prefer this to pointing to an assembly on the file system or in the GAC, since updating the package in the future will likely be a lot less painful than experiences I've had with the GAC and file system assembly references in the past.

c++ Read from .csv file

That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r

and, using c/c++ to parse text is not a good idea. try awk:

 $awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
 ID=0   Name=Filipe Age=19  Gender=M
 ID=1   Name=Maria  Age=20  Gender=F
 ID=2   Name=Walter Age=60  Gender=M

How do I read an attribute on a class at runtime?

System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);

for (int i = 0; i < attributes.Length; i++)
{
    if (attributes[i] is DomainNameAttribute)
    {
        System.Console.WriteLine(((DomainNameAttribute) attributes[i]).Name);
    }   
}

Shell script to set environment variables

Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.

Meanwhile you have to use double quotes not single quote to expand variables:

export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"

Semicolons at the end of a single command are also unnecessary.

So far:

#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

For su you can run it with:

su -c 'sh /path/to/script.sh'

Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using . or source from the interactive shell. It could have been a standalone scipt, or it could have been source'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.

How do I zip two arrays in JavaScript?

Use the map method:

_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
  return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_

DEMO

How can I use pointers in Java?

Java does have pointers. Any time you create an object in Java, you're actually creating a pointer to the object; this pointer could then be set to a different object or to null, and the original object will still exist (pending garbage collection).

What you can't do in Java is pointer arithmetic. You can't dereference a specific memory address or increment a pointer.

If you really want to get low-level, the only way to do it is with the Java Native Interface; and even then, the low-level part has to be done in C or C++.

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

After so many changes and tries and answers. For

SOs: Windows 7 / Windows 10

Xampp Version: Xampp or Xampp portable 7.1.18 / 7.3.7 (control panel v3.2.4)

Installers: win32-7.1.18-0-VC14-installer / xampp-windows-x64-7.3.7-0-VC15-installer

  1. Do not edit other files like httpd-xampp

  2. Stop Apache

  3. Open httpd-vhosts.conf located in **your_xampp_directory**\apache\conf\extra\ (your XAMPP directory might be by default: C:/xampp/htdocs)

  4. Remove hash before the following line (aprox. line 20): NameVirtualHost *:80 (this might be optional)

  5. Add the following virtual hosts at the end of the file, considering your directories paths:

    ##127.0.0.1
    <VirtualHost *:80>
        DocumentRoot "C:/xampp/htdocs"
        ServerName localhost
        ErrorLog "logs/localhost-error.log"
        CustomLog "logs/localhost-access.log" common
    </VirtualHost>
    
    ##127.0.0.2
    <VirtualHost *:80>
        DocumentRoot "F:/myapp/htdocs/"
        ServerName test1.localhost
        ServerAlias www.test1.localhost
        ErrorLog "logs/myapp-error.log"
        CustomLog "logs/myapp-access.log" common
        <Directory  "F:/myapp/htdocs/">
            #Options All # Deprecated
            #AllowOverride All # Deprecated
            Require all granted  
        </Directory>
    </VirtualHost>
    
  6. Edit (with admin access) your host file (located at Windows\System32\drivers\etc, but with the following tip, only one loopback ip for every domain:

    127.0.0.1 localhost
    127.0.0.2 test1.localhost
    127.0.0.2 www.test1.localhost
    

For every instance, repeat the second block, the first one is the main block only for "default" purposes.

Print raw string from variable? (not getting the answers)

Get rid of the escape characters before storing or manipulating the raw string:

You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:

>>> mypath = os.getcwd().replace('\\','/')  
>>> os.path.exists(mypath)  
True  
>>>   

CSS3 Transparency + Gradient

#grad
{
    background: -webkit-linear-gradient(left,rgba(255,0,0,0),rgba(255,0,0,1)); /*Safari 5.1-6*/
    background: -o-linear-gradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); /*Opera 11.1-12*/
    background: -moz-linear-gradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); /*Fx 3.6-15*/
    background: linear-gradient(to right, rgba(255,0,0,0), rgba(255,0,0,1)); /*Standard*/
}

I found this in w3schools and suited my needs while I was looking for gradient and transparency. I am providing the link to refer to w3schools. Hope this helps if any one is looking for gradient and transparency.

http://www.w3schools.com/css/css3_gradients.asp

Also I tried it in w3schools to change the opacity pasting the link for it check it

http://www.w3schools.com/css/tryit.asp?filename=trycss3_gradient-linear_trans

Hope it helps.

What to do with "Unexpected indent" in python?

Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.

While you can use tabs with Python mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with 4 spaces is the recommended approach for writing Python code.

Send a SMS via intent

I have developed this functionality from one Blog. There are 2 ways you can send SMS.

  1. Open native SMS composer
  2. write your message and send from your Android application

This is the code of 1st method.

Main.xml

<?xml version="1.0" encoding="utf-8"?>  
    <RelativeLayout  
        android:id="@+id/relativeLayout1"  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent"  
        xmlns:android="http://schemas.android.com/apk/res/android">  

            <Button  
                android:id="@+id/btnSendSMS"  
               android:layout_height="wrap_content"  
               android:layout_width="wrap_content"  
               android:text="Send SMS"  
               android:layout_centerInParent="true"  
               android:onClick="sendSMS">  
           </Button>  
   </RelativeLayout>

Activity

public class SendSMSActivity extends Activity {  
     /** Called when the activity is first created. */  
     @Override  
     public void onCreate(Bundle savedInstanceState) {  
         super.onCreate(savedInstanceState);  
         setContentView(R.layout.main);  
      }  

     public void sendSMS(View v)  
     {  
         String number = "12346556";  // The number on which you want to send SMS  
         startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));  
     }  
    /* or 
     public void sendSMS(View v) 
      { 
     Uri uri = Uri.parse("smsto:12346556"); 
         Intent it = new Intent(Intent.ACTION_SENDTO, uri); 
         it.putExtra("sms_body", "Here you can set the SMS text to be sent"); 
         startActivity(it); 
      } */  
 }

NOTE:- In this method, you don’t require SEND_SMS permission inside the AndroidManifest.xml file.

For 2nd method refer to this BLOG. You will find a good explanation from here.

Hope this will help you...

Batch Renaming of Files in a Directory

I had a similar problem, but I wanted to append text to the beginning of the file name of all files in a directory and used a similar method. See example below:

folder = r"R:\mystuff\GIS_Projects\Website\2017\PDF"

import os


for root, dirs, filenames in os.walk(folder):


for filename in filenames:  
    fullpath = os.path.join(root, filename)  
    filename_split = os.path.splitext(filename) # filename will be filename_split[0] and extension will be filename_split[1])
    print fullpath
    print filename_split[0]
    print filename_split[1]
    os.rename(os.path.join(root, filename), os.path.join(root, "NewText_2017_" + filename_split[0] + filename_split[1]))

Execute a shell script in current shell with sudo permission

Basically sudo expects, an executable (command) to follow & you are providing with a .

Hence the error.

Try this way $ sudo setup.sh


How do I create a message box with "Yes", "No" choices and a DialogResult?

dynamic MsgResult = this.ShowMessageBox("Do you want to cancel all pending changes ?", "Cancel Changes", MessageBoxOption.YesNo);

if (MsgResult == System.Windows.MessageBoxResult.Yes)
{
    enter code here
}
else 
{
    enter code here
}

Check more detail from here

Why should hash functions use a prime number modulus?

Just to provide an alternate viewpoint there's this site:

http://www.codexon.com/posts/hash-functions-the-modulo-prime-myth

Which contends that you should use the largest number of buckets possible as opposed to to rounding down to a prime number of buckets. It seems like a reasonable possibility. Intuitively, I can certainly see how a larger number of buckets would be better, but I'm unable to make a mathematical argument of this.

Center HTML Input Text Field Placeholder

By using the code snippet below, you are selecting the placeholder inside your input, and any code placed inside will affect only the placeholder.

input::-webkit-input-placeholder {
      text-align: center
}

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

Div height 100% and expands to fit content

Just add these two line in your css id #some_div

display: block;
overflow: auto;

After that you will get what your are looking for !

Add new line in text file with Windows batch file

DISCLAIMER: The below solution does not preserve trailing tabs.


If you know the exact number of lines in the text file, try the following method:

@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /P L=
  IF %%i==%insertbefore% ECHO(
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%

The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.

After finishing, the original file is deleted and the temporary one gets assigned the original name.


UPDATE

If the number of lines is unknown beforehand, you can use the following method to obtain it:

FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C

(This line simply replaces the SET totallines=200 line in the above script.)

The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.

Android Webview gives net::ERR_CACHE_MISS message

To Solve this Error in Webview Android, First Check the Permissions in Manifest.xml, if not define there,then define as like this. <uses-permission android:name="android.permission.INTERNET"/>

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

The solution provided by Emanuele worked for me. I could see the report when I accessed it directly from the server but when I used a ReportViewer control on my aspx page, I was unable to see the report. Upon inspecting the rendered HTML, I found a div by the id "ReportViewerGeneral_ctl09" (ReportViewerGeneral is the server id of the report viewer control) which had it's overflow property set to auto.

<div id="ReportViewerGeneral_ctl09" style="height: 100%; width: 100%; overflow: auto; position: relative; ">...</div>

I used the procedure explained by Emanuele to change this to visible as follows:

function pageLoad() {
    var element = document.getElementById("ReportViewerGeneral_ctl09");

    if (element) {
        element.style.overflow = "visible";
    }
}

Is there an onSelect event or equivalent for HTML <select>?

The wonderful thing about the select tag (in this scenario) is that it will grab its value from the option tags.

Try:

<select onChange="javascript:doSomething(this.value);">
<option value="A">A</option>
<option value="B">B</option>
<option value="Foo">C</option>
</select>

Worked decent for me.

Bootstrap 3 breakpoints and media queries

@media screen and (max-width: 767px) {

}

@media screen and (min-width: 768px) and (max-width: 991px){


}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape){


}

@media screen and (min-width: 992px) {



}

Is there a format code shortcut for Visual Studio?

Visual Studio with C# key bindings

To answer the specific question, in C# you are likely to be using the C# keyboard mapping scheme, which will use these hotkeys by default:

Ctrl+E, Ctrl+D to format the entire document.

Ctrl+E, Ctrl+F to format the selection.

You can change these in menu Tools ? Options ? Environment ? Keyboard (either by selecting a different "keyboard mapping scheme", or binding individual keys to the commands "Edit.FormatDocument" and "Edit.FormatSelection").

If you have not chosen to use the C# keyboard mapping scheme, then you may find the key shortcuts are different. For example, if you are not using the C# bindings, the keys are likely to be:

Ctrl + K + D (Entire document)

Ctrl + K + F (Selection only)

To find out which key bindings apply in your copy of Visual Studio, look in menu Edit ? Advanced menu - the keys are displayed to the right of the menu items, so it's easy to discover what they are on your system.


(Please do not edit this answer to change the key bindings above to what your system has!)

What is the proper way to re-attach detached objects in Hibernate?

So it seems that there is no way to reattach a stale detached entity in JPA.

merge() will push the stale state to the DB, and overwrite any intervening updates.

refresh() cannot be called on a detached entity.

lock() cannot be called on a detached entity, and even if it could, and it did reattach the entity, calling 'lock' with argument 'LockMode.NONE' implying that you are locking, but not locking, is the most counterintuitive piece of API design I've ever seen.

So you are stuck. There's an detach() method, but no attach() or reattach(). An obvious step in the object lifecycle is not available to you.

Judging by the number of similar questions about JPA, it seems that even if JPA does claim to have a coherent model, it most certainly does not match the mental model of most programmers, who have been cursed to waste many hours trying understand how to get JPA to do the simplest things, and end up with cache management code all over their applications.

It seems the only way to do it is discard your stale detached entity and do a find query with the same id, that will hit the L2 or the DB.

Mik

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

It is because * is used as a metacharacter to signify one or more occurences of previous character. So if i write M* then it will look for files MMMMMM..... ! Here you are using * as the only character so the compiler is looking for the character to find multiple occurences of,so it throws the exception.:)

How to get first character of a string in SQL?

It is simple to achieve by the following

DECLARE @SomeString NVARCHAR(20) = 'This is some string'
DECLARE @Result NVARCHAR(20)

Either

SET @Result = SUBSTRING(@SomeString, 2, 3)
SELECT @Result

@Result = his

or

SET @Result = LEFT(@SomeString, 6)
SELECT @Result

@Result = This i

Conditional step/stage in Jenkins pipeline

Just use if and env.BRANCH_NAME, example:

    if (env.BRANCH_NAME == "deployment") {                                          
        ... do some build ...
    } else {                                   
        ... do something else ...
    }                                                                       

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

Since you are asking in the context of a facebook app, you might want to consider detecting this at the server when the initial request is made. Facebook will pass along a bunch of querystring data including the fb_sig_user key if it is called from an iframe.

Since you probably need to check and use this data anyway in your app, use it to determine the the appropriate context to render.

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

Setting Authorization Header of HttpClient

It may be easier to use an existing library.

For example, the extension methods below are added with Identity Server 4 https://www.nuget.org/packages/IdentityModel/

 public static void SetBasicAuthentication(this HttpClient client, string userName, string password);
    //
    // Summary:
    //     Sets a basic authentication header.
    //
    // Parameters:
    //   request:
    //     The HTTP request message.
    //
    //   userName:
    //     Name of the user.
    //
    //   password:
    //     The password.
    public static void SetBasicAuthentication(this HttpRequestMessage request, string userName, string password);
    //
    // Summary:
    //     Sets a basic authentication header for RFC6749 client authentication.
    //
    // Parameters:
    //   client:
    //     The client.
    //
    //   userName:
    //     Name of the user.
    //
    //   password:
    //     The password.
    public static void SetBasicAuthenticationOAuth(this HttpClient client, string userName, string password);
    //
    // Summary:
    //     Sets a basic authentication header for RFC6749 client authentication.
    //
    // Parameters:
    //   request:
    //     The HTTP request message.
    //
    //   userName:
    //     Name of the user.
    //
    //   password:
    //     The password.
    public static void SetBasicAuthenticationOAuth(this HttpRequestMessage request, string userName, string password);
    //
    // Summary:
    //     Sets an authorization header with a bearer token.
    //
    // Parameters:
    //   client:
    //     The client.
    //
    //   token:
    //     The token.
    public static void SetBearerToken(this HttpClient client, string token);
    //
    // Summary:
    //     Sets an authorization header with a bearer token.
    //
    // Parameters:
    //   request:
    //     The HTTP request message.
    //
    //   token:
    //     The token.
    public static void SetBearerToken(this HttpRequestMessage request, string token);
    //
    // Summary:
    //     Sets an authorization header with a given scheme and value.
    //
    // Parameters:
    //   client:
    //     The client.
    //
    //   scheme:
    //     The scheme.
    //
    //   token:
    //     The token.
    public static void SetToken(this HttpClient client, string scheme, string token);
    //
    // Summary:
    //     Sets an authorization header with a given scheme and value.
    //
    // Parameters:
    //   request:
    //     The HTTP request message.
    //
    //   scheme:
    //     The scheme.
    //
    //   token:
    //     The token.
    public static void SetToken(this HttpRequestMessage request, string scheme, string token);

Redirect non-www to www in .htaccess

The following example works on both ssl and non-ssl and is much faster as you use just one rule to manage http and https

RewriteEngine on


RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s on(s)|offs()
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

[Tested]

This will redirect

http

to

https

to

jQuery - Fancybox: But I don't want scrollbars!

I had the same problem with fancybox and an iframe, googled for a solution and ended up here. The overflow: hidden did not work for me, however I found out that fancybox allows you to set the option for the iframe scrolling (equivalent to setting "scrolling=no" attribute on the iframe), which fixes the problem in IE7 in a more graceful manner:

$.fancybox({
    'type'        : 'iframe',
    'scrolling'   : 'no',
... and the rest of the parameters.

port 8080 is already in use and no process using 8080 has been listed

In windows " wmic process where processid="pid of the process running" get commandline " worked for me. The culprit was wrapper.exe process of webhuddle jboss soft.