Programs & Examples On #Ora 02049

How to create Drawable from resource

I would just like to add that if you are getting "deprecated" message when using getDrawable(...) you should use the following method from the support library instead.

ContextCompat.getDrawable(getContext(),R.drawable.[name])

You do not have to use getResources() when using this method.

This is equivalent to doing something like

Drawable mDrawable;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    mDrawable = ContextCompat.getDrawable(getContext(),R.drawable.[name]);
} else {
    mDrawable = getResources().getDrawable(R.id.[name]);
}

This works on both pre and post Lollipop versions.

JavaScript/jQuery - How to check if a string contain specific words

In javascript the includes() method can be used to determines whether a string contains particular word (or characters at specified position). Its case sensitive.

var str = "Hello there."; 

var check1 = str.includes("there"); //true
var check2 = str.includes("There"); //false, the method is case sensitive
var check3 = str.includes("her");   //true
var check4 = str.includes("o",4);   //true, o is at position 4 (start at 0)
var check5 = str.includes("o",6);   //false o is not at position 6

How to use index in select statement?

The optimiser will judge if the use of your index will make your query run faster, and if it is, it will use the index.

Depending on your RDBMS you can force the use of an index, although it is not recommended unless you know what you are doing.

In general you should index columns that you use in table join's and where statements

How to autosize and right-align GridViewColumn data in WPF?

I liked user1333423's solution except that it always re-sized every column; i needed to allow some columns to be fixed width. So in this version columns with a width set to "Auto" will be auto-sized and those set to a fixed amount will not be auto-sized.

public class AutoSizedGridView : GridView
{
    HashSet<int> _autoWidthColumns;

    protected override void PrepareItem(ListViewItem item)
    {
        if (_autoWidthColumns == null)
        {
            _autoWidthColumns = new HashSet<int>();

            foreach (var column in Columns)
            {
                if(double.IsNaN(column.Width))
                    _autoWidthColumns.Add(column.GetHashCode());
            }                
        }

        foreach (GridViewColumn column in Columns)
        {
            if (_autoWidthColumns.Contains(column.GetHashCode()))
            {
                if (double.IsNaN(column.Width))
                    column.Width = column.ActualWidth;

                column.Width = double.NaN;                    
            }          
        }

        base.PrepareItem(item);
    }        
}

Problems using Maven and SSL behind proxy

I simply used new java version and it worked for me.

Convert digits into words with JavaScript

Update: Looks like this is more useful than I thought. I've just published this on npm. https://www.npmjs.com/package/num-words


Here's a shorter code. with one RegEx and no loops. converts as you wanted, in south asian numbering system

_x000D_
_x000D_
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];_x000D_
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];_x000D_
_x000D_
function inWords (num) {_x000D_
    if ((num = num.toString()).length > 9) return 'overflow';_x000D_
    n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);_x000D_
    if (!n) return; var str = '';_x000D_
    str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';_x000D_
    str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';_x000D_
    str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';_x000D_
    str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';_x000D_
    str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';_x000D_
    return str;_x000D_
}_x000D_
_x000D_
document.getElementById('number').onkeyup = function () {_x000D_
    document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);_x000D_
};
_x000D_
<span id="words"></span>_x000D_
<input id="number" type="text" />
_x000D_
_x000D_
_x000D_

The only limitation is, you can convert maximum of 9 digits, which I think is more than sufficient in most cases..

how to configure hibernate config file for sql server

Don't forget to enable tcp/ip connections in SQL SERVER Configuration tools

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

How to disable <br> tags inside <div> by css?

<p style="color:black">Shop our collection of beautiful women's <br> <span> wedding ring in classic &amp; modern design.</span></p>

Remove <br> effect using CSS.

<style> p br{ display:none; } </style>

Setting Inheritance and Propagation flags with set-acl and powershell

Here's some succinct Powershell code to apply new permissions to a folder by modifying it's existing ACL (Access Control List).

# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path 'C:\DemoFolder'

# Set the permissions that you want to apply to the folder
$permissions = $env:username, 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'

# Create a new FileSystemAccessRule object
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions

# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($rule)

# Apply the modified access rule to the folder
$existingAcl | Set-Acl -Path 'C:\DemoFolder'

Each of the values in the $permissions variable list pertain to the parameters of this constructor for the FileSystemAccessRule class.

Courtesy of this page.

how to change color of TextinputLayout's label and edittext underline android

Based on Fedor Kazakov and others answers, I created a default config.

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="Widget.Design.TextInputLayout" parent="AppTheme">
        <item name="hintTextAppearance">@style/AppTheme.TextFloatLabelAppearance</item>
        <item name="errorTextAppearance">@style/AppTheme.TextErrorAppearance</item>
        <item name="counterTextAppearance">@style/TextAppearance.Design.Counter</item>
        <item name="counterOverflowTextAppearance">@style/TextAppearance.Design.Counter.Overflow</item>
    </style>

    <style name="AppTheme.TextFloatLabelAppearance" parent="TextAppearance.Design.Hint">
        <!-- Floating label appearance here -->
        <item name="android:textColor">@color/colorAccent</item>
        <item name="android:textSize">20sp</item>
    </style>

    <style name="AppTheme.TextErrorAppearance" parent="TextAppearance.Design.Error">
        <!-- Error message appearance here -->
        <item name="android:textColor">#ff0000</item>
        <item name="android:textSize">20sp</item>
    </style>

</resources>

activity_layout.xml

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.AppCompatEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Text hint here"
        android:text="5,2" />

</android.support.design.widget.TextInputLayout>

Focused:

Focused

Without focus:

Without focus

Error message:

enter image description here

Is the LIKE operator case-sensitive with MSSQL Server?

If you want to achieve a case sensitive search without changing the collation of the column / database / server, you can always use the COLLATE clause, e.g.

USE tempdb;
GO
CREATE TABLE dbo.foo(bar VARCHAR(32) COLLATE Latin1_General_CS_AS);
GO
INSERT dbo.foo VALUES('John'),('john');
GO
SELECT bar FROM dbo.foo 
  WHERE bar LIKE 'j%';
-- 1 row

SELECT bar FROM dbo.foo 
  WHERE bar COLLATE Latin1_General_CI_AS LIKE 'j%';
-- 2 rows

GO    
DROP TABLE dbo.foo;

Works the other way, too, if your column / database / server is case sensitive and you don't want a case sensitive search, e.g.

USE tempdb;
GO
CREATE TABLE dbo.foo(bar VARCHAR(32) COLLATE Latin1_General_CI_AS);
GO
INSERT dbo.foo VALUES('John'),('john');
GO
SELECT bar FROM dbo.foo 
  WHERE bar LIKE 'j%';
-- 2 rows

SELECT bar FROM dbo.foo 
  WHERE bar COLLATE Latin1_General_CS_AS LIKE 'j%';
-- 1 row

GO
DROP TABLE dbo.foo;

Bootstrap change div order with pull-right, pull-left on 3 columns

Try this...

<div class="row">
    <div class="col-xs-3">
        Menu
    </div>
    <div class="col-xs-9">
        <div class="row">
          <div class="col-sm-4 col-sm-push-8">
          Right content
          </div>
          <div class="col-sm-8 col-sm-pull-4">
          Content
          </div>
       </div>
    </div>
</div>

Bootply

Excel: replace part of cell's string value

You have a character = STQ8QGpaM4CU6149665!7084880820, and you have a another column = 7084880820.

If you want to get only this in excel using the formula: STQ8QGpaM4CU6149665!, use this:

=REPLACE(H11,SEARCH(J11,H11),LEN(J11),"")

H11 is an old character and for starting number use search option then for no of character needs to replace use len option then replace to new character. I am replacing this to blank.

ERROR: Sonar server 'http://localhost:9000' can not be reached

If you use SonarScanner CLI with Docker, you may have this error because the SonarScanner container can not access to the Sonar UI container.

Note that you will have the same error with a simple curl from another container:

docker run --rm byrnedo/alpine-curl 127.0.0.1:9000
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection refused

The solution is to connect the SonarScanner container to the same docker network of your sonar instance, for instance with --network=host:

docker run --network=host -e SONAR_HOST_URL='http://127.0.0.1:9000' --user="$(id -u):$(id -g)" -v "$PWD:/usr/src" sonarsource/sonar-scanner-cli

(other parameters of this command comes from the SonarScanner CLI documentation)

Can I use multiple versions of jQuery on the same page?

You can have as many different jQuery versions on your page as you want.

Use jQuery.noConflict():

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script>
    var $i = jQuery.noConflict();
    alert($i.fn.jquery);
</script> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    var $j = jQuery.noConflict();
    alert($j.fn.jquery);
</script> 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
    var $k = jQuery.noConflict();
    alert($k.fn.jquery);
</script> 

DEMO | Source

Where can I find the API KEY for Firebase Cloud Messaging?

Enter here:

https: //console.firebase.google.com/project/your-project-name/overview

(replace your-project with your project-name) and click in "Add firebase in your web app"(the red circle icon) this action show you a dialog with:

  • apiKey
  • authDomain
  • databaseURL
  • storageBucket
  • messagingSenderId

How can get the text of a div tag using only javascript (no jQuery)

Actually you dont need to call document.getElementById() function to get access to your div.

You can use this object directly by id:

text = test.textContent || test.innerText;
alert(text);

Set disable attribute based on a condition for Html.TextBoxFor

if you dont want to use Html Helpers take look it my solution

disabled="@(your Expression that returns true or false")"

that it

@{
    bool isManager = (Session["User"] as User).IsManager;
}
<textarea rows="4" name="LetterManagerNotes" disabled="@(!isManager)"></textarea>

and I think the better way to do it is to do that check in the controller and save it within a variable that is accessible inside the view(Razor engine) in order to make the view free from business logic

How to display list items on console window in C#

I found this easier to understand:

List<string> names = new List<string> { "One", "Two", "Three", "Four", "Five" };
        for (int i = 0; i < names.Count; i++)
        {
            Console.WriteLine(names[i]);
        }

Failed to find 'ANDROID_HOME' environment variable

In Linux

First of all set ANDROID_HOME in .bashrc file

Run command

sudo gedit ~/.bashrc

set andoid sdk path where you have installed

export ANDROID_HOME=/opt/android-sdk-linux 
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

to reload file run command

source ~/.bashrc

Now check installed platform, run command

ionic platform

Output

Installed platforms:
  android 6.0.0
Available platforms: 
  amazon-fireos ~3.6.3 (deprecated)
  blackberry10 ~3.8.0
  browser ~4.1.0
  firefoxos ~3.6.3
  ubuntu ~4.3.4
  webos ~3.7.0

if android already installed then need to remove and install again

ionic platform rm android
ionic platform add android

If not installed already please add android platform

ionic platform add android

Please make sure you have added android platform without sudo command

if you still getting error in adding android platfrom like following

Error: EACCES: permission denied, open '/home/ubuntu/.cordova/lib/npm_cache/cordova-android/6.0.0/package/package.json'

Please go to /home/ubuntu/ and remove .cordova folder from there

cd /home/ubuntu/
sudo rm -r .cordova

Now run following command again

ionic platform add android

after adding platform successfully you will be able to build andoid in ionic.

Thanks

SELECT query with CASE condition and SUM()

To get each sum in a separate column:

Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
       SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash') 
and CDate<=SYSDATETIME() 
and CStatus='Active';

Using Linq to get the last N elements of a collection?

Below the real example how to take last 3 elements from a collection (array):

// split address by spaces into array
string[] adrParts = adr.Split(new string[] { " " },StringSplitOptions.RemoveEmptyEntries);
// take only 3 last items in array
adrParts = adrParts.SkipWhile((value, index) => { return adrParts.Length - index > 3; }).ToArray();

Google Forms file upload complete example

As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.

Matplotlib connect scatterplot points with line - Python

I think @Evert has the right answer:

plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()

Which is pretty much the same as

plt.plot(dates, values, '-o')
plt.show()

or whatever linestyle you prefer.

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

The onbeforeunload Microsoft-ism is the closest thing we have to a standard solution, but be aware that browser support is uneven; e.g. for Opera it only works in version 12 and later (still in beta as of this writing).

Also, for maximum compatibility, you need to do more than simply return a string, as explained on the Mozilla Developer Network.

Example: Define the following two functions for enabling/disabling the navigation prompt (cf. the MDN example):

function enableBeforeUnload() {
    window.onbeforeunload = function (e) {
        return "Discard changes?";
    };
}
function disableBeforeUnload() {
    window.onbeforeunload = null;
}

Then define a form like this:

<form method="POST" action="" onsubmit="disableBeforeUnload();">
    <textarea name="text"
              onchange="enableBeforeUnload();"
              onkeyup="enableBeforeUnload();">
    </textarea>
    <button type="submit">Save</button>
</form>

This way, the user will only be warned about navigating away if he has changed the text area, and will not be prompted when he's actually submitting the form.

JQuery: detect change in input field

Use jquery change event

Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

An example

$("input[type='text']").change( function() {
  // your code
});

The advantage that .change has over .keypress , .focus , .blur is that .change event will fire only when input has changed

What are the differences between a superkey and a candidate key?

Basically, a Candidate Key is a Super Key from which no more Attribute can be pruned.

A Super Key identifies uniquely rows/tuples in a table/relation of a database. It is composed by a set of attributes that combined can assume values unique over the rows/tuples of a table/relation. A Candidate Key is built by a Super Key, iteratively removing/pruning non-key attributes, keeping an invariant: the newly created Key still need to uniquely identifies the rows/tuples.

A Candidate Key might be seen as a minimal Super Key, in terms of attributes.

Candidate Keys can be used to reference uniquely rows/tuples but from the RDBMS engine perspective the burden to maintain indexes on them is far heavier.

Maximum number of threads per process in Linux?

It probably shouldn't matter. You are going to get much better performance designing your algorithm to use a fixed number of threads (eg, 4 or 8 if you have 4 or 8 processors). You can do this with work queues, asynchronous IO, or something like libevent.

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

Can a Byte[] Array be written to a file in C#?

There is a static method System.IO.File.WriteAllBytes

Java: How to Indent XML Generated by Transformer

The following code is working for me with Java 7. I set the indent (yes) and indent-amount (2) on the transformer (not the transformer factory) to get it working.

TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(source, result);

@mabac's solution to set the attribute didn't work for me, but @lapo's comment proved helpful.

How can I represent a range in Java?

You could use java.time.temporal.ValueRange which accepts long and would also work with int:

int a = 2147;

//Use java 8 java.time.temporal.ValueRange. The range defined
//is inclusive of both min and max 
ValueRange range = ValueRange.of(0, 2147483647);

if(range.isValidValue(a)) {
    System.out.println("in range");
}else {
    System.out.println("not in range");
}

Including external HTML file to another HTML file

You can use jquery load for that.

<script type="text/javascript">
$(document).ready(function(e) {
    $('#header').load('name.html',function(){alert('loaded')});
});
</script>

Don't forget to include jquery library befor above code.

Input placeholders for Internet Explorer

I found a quite simple solution using this method:

http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

it's a jquery hack, and it worked perfectly on my projects

Printing 1 to 1000 without loop or conditionals

Nobody said it shouldn't segfault afterwards, right?

Note: this works correctly on my 64-bit Mac OS X system. For other systems, you will need to change the args to setrlimit and the size of spacechew accordingly. ;-)

(I shouldn't need to include this, but just in case: this is clearly not an example of good programming practice. It does, however, have the advantage that it makes use of the name of this site.)

#include <sys/resource.h>
#include <stdio.h>

void recurse(int n)
{
    printf("%d\n", n);
    recurse(n + 1);
}

int main()
{
    struct rlimit rlp;
    char spacechew[4200];

    getrlimit(RLIMIT_STACK, &rlp);
    rlp.rlim_cur = rlp.rlim_max = 40960;
    setrlimit(RLIMIT_STACK, &rlp);

    recurse(1);
    return 0; /* optimistically */
}

Spring Boot - Handle to Hibernate SessionFactory

Another way similar to the yglodt's

In application.properties:

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

And in your configuration class:

@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
    return hemf.getSessionFactory();
}

Then you can autowire the SessionFactory in your services as usual:

@Autowired
private SessionFactory sessionFactory;

How do I redirect to the previous action in ASP.NET MVC?

Pass a returnUrl parameter (url encoded) to the change and login actions and inside redirect to this given returnUrl. Your login action might look something like this:

public ActionResult Login(string returnUrl) 
{
    // Do something...
    return Redirect(returnUrl);
}

python mpl_toolkits installation issue

It is not on PyPI and you should not be installing it via pip. If you have matplotlib installed, you should be able to import mpl_toolkits directly:

$ pip install --upgrade matplotlib
...

$ python
>>> import mpl_toolkits
>>> 

Does file_get_contents() have a timeout setting?

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

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

What is the difference between iterator and iterable and how to use them?

Iterable were introduced to use in for each loop in java

public interface Collection<E> extends Iterable<E>  

Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.

SQL Query to find the last day of the month

SQL Server 2012 introduces the eomonth function:

select eomonth('2013-05-31 00:00:00:000')
-->
2013-05-31

Format SQL in SQL Server Management Studio

Late answer, but hopefully worthwhile: The Poor Man's T-SQL Formatter is an open-source (free) T-SQL formatter with complete T-SQL batch/script support (any DDL, any DML), SSMS Plugin, command-line bulk formatter, and other options.

It's available for immediate/online use at http://poorsql.com, and just today graduated to "version 1.0" (it was in beta version for a few months), having just acquired support for MERGE statements, OUTPUT clauses, and other finicky stuff.

The SSMS Add-in allows you to set your own hotkey (default is Ctrl-K, Ctrl-F, to match Visual Studio), and formats the entire script or just the code you have selected/highlighted, if any. Output formatting is customizable.

In SSMS 2008 it combines nicely with the built-in intelli-sense, effectively providing more-or-less the same base functionality as Red Gate's SQL Prompt (SQL Prompt does, of course, have extra stuff, like snippets, quick object scripting, etc).

Feedback/feature requests are more than welcome, please give it a whirl if you get the chance!

Disclosure: This is probably obvious already but I wrote this library/tool/site, so this answer is also shameless self-promotion :)

What is the current choice for doing RPC in Python?

You could try Ladon. It serves up multiple web server protocols at once so you can offer more flexibility at the client side.

http://pypi.python.org/pypi/ladon

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

You will get this error when you call any of the setXxx() methods on PreparedStatement, while the SQL query string does not have any placeholders ? for this.

For example this is wrong:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

You need to fix the SQL query string accordingly to specify the placeholders.

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

Note the parameter index starts with 1 and that you do not need to quote those placeholders like so:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";

Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.

See also:

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How to link home brew python version and set it as default

I think you have to be precise with which version you want to link with the command brew link python like:

brew link python 3

It will give you an error like that:

Linking /usr/local/Cellar/python3/3.5.2... 
Error: Could not symlink bin/2to3-3.5
Target /usr/local/bin/2to3-3.5
already exists. 

You may want to remove it:

rm '/usr/local/bin/2to3-3.5'

To force the link and overwrite all conflicting files:

brew link --overwrite python3

To list all files that would be deleted:

brew link --overwrite --dry-run python3

but you have to copy/paste the command to force the link which is:

brew link --overwrite python3

I think that you must have the version (the newer) installed.

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

This issue is complicated because it's easy to confuse the root cause with whatever the immediate cause happens to be.

In my case, the immediate cause was that the solution is configured to use NuGet Package Restore, but the server was not connected to the internet, so NuGet was unable to download the dependencies when building for the first time.

I believe the root cause is simply that the solution is unable to resolve dependencies correctly. It may be an incorrect path configuration, or the wrong version of an assembly, or conflicting assemblies, or a partial deployment. But in all cases, the error is simply saying that it can't find the type specified in global.asax because it can't build it.

indexOf and lastIndexOf in PHP?

You need the following functions to do this in PHP:

strpos Find the position of the first occurrence of a substring in a string

strrpos Find the position of the last occurrence of a substring in a string

substr Return part of a string

Here's the signature of the substr function:

string substr ( string $string , int $start [, int $length ] )

The signature of the substring function (Java) looks a bit different:

string substring( int beginIndex, int endIndex )

substring (Java) expects the end-index as the last parameter, but substr (PHP) expects a length.

It's not hard, to get the desired length by the end-index in PHP:

$sub = substr($str, $start, $end - $start);

Here is the working code

$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
    $pt_password = substr($message, $start);
}
else {
    $end = strrpos($message, '-');
    $pt_password = substr($message, $start, $end - $start);
}

git checkout all the files

Other way which I found useful is:

git checkout <wildcard> 

Example:

git checkout *.html

More generally:

git checkout <branch> <filename/wildcard>

Oracle SqlDeveloper JDK path

On Windows,Close all the SQL Developer windows. Then You need to completely delete the SQL Developer and sqldeveloper folders located in user/AppData/Roaming. Finally, run the program, you will be prompted for new JDK.

Note that AppData is a hidden folder.

How to extract numbers from string in c?

here after a simple solution using sscanf:

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

char str[256]="ab234cid*(s349*(20kd";
char tmp[256];

int main()
{

    int x;
    tmp[0]='\0';
    while (sscanf(str,"%[^0123456789]%s",tmp,str)>1||sscanf(str,"%d%s",&x,str))
    {
        if (tmp[0]=='\0')
        {
            printf("%d\r\n",x);
        }
        tmp[0]='\0';

    }
}

List all files in one directory PHP

Check this out : readdir()

This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry\n";
        }
    }

    closedir($handle);
}

Edit: miah's solution is much more elegant than mine, you should use his solution instead.

Adding/removing items from a JavaScript object with jQuery

Well, it's just a javascript object, so you can manipulate data.items just like you would an ordinary array. If you do:

data.items.pop();

your items array will be 1 item shorter.

Simulating Key Press C#

Simple one, add before Main

[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

Code inside Main/Method:

string className = "IEFrame";
string windowName = "New Tab - Windows Internet Explorer";
IntPtr IE = FindWindow(className, windowName);
if (IE == IntPtr.Zero)
{
   return;
}
SetForegroundWindow(IE);
InputSimulator.SimulateKeyPress(VirtualKeyCode.F5);

Note:

  1. Add InputSimulator as reference. To download Click here

  2. To find Class & Window name, use WinSpy++. To download Click here

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

Application.Exit() kills your application but there are some instances that it won't close the application.

End is better than Application.Exit().

Why does background-color have no effect on this DIV?

This being a very old question but worth adding that I have just had a similar issue where a background colour on a footer element in my case didn't show. I added a position: relative which worked.

Create an empty list in python with certain size

Not technically a list but similar to a list in terms of functionality and it's a fixed length

from collections import deque
my_deque_size_10 = deque(maxlen=10)

If it's full, ie got 10 items then adding another item results in item @index 0 being discarded. FIFO..but you can also append in either direction. Used in say

  • a rolling average of stats
  • piping a list through it aka sliding a window over a list until you get a match against another deque object.

If you need a list then when full just use list(deque object)

How to close existing connections to a DB

Found it here: http://awesomesql.wordpress.com/2010/02/08/script-to-drop-all-connections-to-a-database/

DECLARE @dbname NVARCHAR(128)
SET @dbname = 'DB name here'
 -- db to drop connections 
DECLARE @processid INT 
SELECT  @processid = MIN(spid)
FROM    master.dbo.sysprocesses
WHERE   dbid = DB_ID(@dbname) 
WHILE @processid IS NOT NULL 
    BEGIN 
        EXEC ('KILL ' + @processid) 
        SELECT  @processid = MIN(spid)
        FROM    master.dbo.sysprocesses
        WHERE   dbid = DB_ID(@dbname) 
    END

Character Limit in HTML

There are 2 main solutions:

The pure HTML one:

<input type="text" id="Textbox" name="Textbox" maxlength="10" />

The JavaScript one (attach it to a onKey Event):

function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}

But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

Another simple solution for dynamic textarea control.

_x000D_
_x000D_
<!--JAVASCRIPT-->
<script type="text/javascript">
$('textarea').on('input', function () {
            this.style.height = "";
            this.style.height = this.scrollHeight + "px";
 });
</script>
_x000D_
_x000D_
_x000D_

Heroku: How to push different local Git branches to Heroku/master

Also note that if your using the git flow system and your feature branch might be called

feature/mobile_additions

and with a git remote called stagingtwo, then the command to push to heroku would be

git push stagingtwo feature/mobile_additions:master

DECODE( ) function in SQL Server

If I understand the question correctly, you want the equivalent of decode but in T-SQL

Select YourFieldAliasName =
CASE PC_SL_LDGR_CODE
    WHEN '02' THEN 'DR'
    ELSE 'CR'
END

Find the max of 3 numbers in Java with different data types

Like mentioned before, Math.max() only takes two arguments. It's not exactly compatible with your current syntax but you could try Collections.max().

If you don't like that you can always create your own method for it...

public class test {
    final static int MY_INT1 = 25;
    final static int MY_INT2 = -10;
    final static double MY_DOUBLE1 = 15.5;

    public static void main(String args[]) {
        double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
    }

    public static Object multiMax(Object... values) {
        Object returnValue = null;
        for (Object value : values)
            returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
                    : (value instanceof Double) ? (Double) value
                            : (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
                    : (returnValue instanceof Double) ? (Double) returnValue
                            : (Float) returnValue)) ? value : returnValue)
                    : value;
        return returnValue;
    }
}

This will take any number of mixed numeric arguments (Integer, Double and Float) but the return value is an Object so you would have to cast it to Integer, Double or Float.

It might also be throwing an error since there is no such thing as "MY_DOUBLE2".

javascript pushing element at the beginning of an array

Use .unshift() to add to the beginning of an array.

TheArray.unshift(TheNewObject);

See MDN for doc on unshift() and here for doc on other array methods.

FYI, just like there's .push() and .pop() for the end of the array, there's .shift() and .unshift() for the beginning of the array.

HTML code for INR

How about using fontawesome icon for Indian Rupee (INR).

Add font awesome CSS from CDN in the Head section of your HTML page:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

And then using the font like this:

<i class="fa fa-inr" aria-hidden="true"></i>

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

How to make the background image to fit into the whole page without repeating using plain css?

background:url(bgimage.jpg) no-repeat; background-size: cover;

This did the trick

Change the URL in the browser without loading the new page using JavaScript

my code is:

//change address bar
function setLocation(curLoc){
    try {
        history.pushState(null, null, curLoc);
        return false;
    } catch(e) {}
        location.hash = '#' + curLoc;
}

and action:

setLocation('http://example.com/your-url-here');

and example

$(document).ready(function(){
    $('nav li a').on('click', function(){
        if($(this).hasClass('active')) {

        } else {
            setLocation($(this).attr('href'));
        }
            return false;
    });
});

That's all :)

How many characters can you store with 1 byte?

1 byte may hold 1 character. For Example: Refer Ascii values for each character & convert into binary. This is how it works.

enter image description here value 255 is stored as (11111111) base 2. Visit this link for knowing more about binary conversion. http://acc6.its.brooklyn.cuny.edu/~gurwitz/core5/nav2tool.html

Size of Tiny Int = 1 Byte ( -128 to 127)

Int = 4 Bytes (-2147483648 to 2147483647)

Location of WSDL.exe

You'll get it as part of a Visual Studio install (if you included the SDK), or in a standalone SDK install. It'll live somewhere like C:\program files\Microsoft Visual Studio 8\SDK\v2.0\Bin

If you don't already have it, you can download the .NET SDKs from
http://msdn.microsoft.com/en-us/netframework/aa569263.aspx

How to extract the hostname portion of a URL in JavaScript

I would like to specify something. If someone want to get the whole url with path like I need, can use:

var fullUrl = window.location.protocol + "//" + window.location.hostname + window.location.pathname;

Customizing the template within a Directive

Here's what I ended up using.

I'm very new to AngularJS, so would love to see better / alternative solutions.

angular.module('formComponents', [])
    .directive('formInput', function() {
        return {
            restrict: 'E',
            scope: {},
            link: function(scope, element, attrs)
            {
                var type = attrs.type || 'text';
                var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
                var htmlText = '<div class="control-group">' +
                    '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                        '<div class="controls">' +
                        '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                        '</div>' +
                    '</div>';
                element.html(htmlText);
            }
        }
    })

Example usage:

<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>

How to convert int to date in SQL Server 2008

If your integer is timestamp in milliseconds use:

SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name

It will format milliseconds to yyyy-mm-dd string.

How to import existing *.sql files in PostgreSQL 8.4?

in command line first reach the directory where psql is present then write commands like this:

psql [database name] [username]

and then press enter psql asks for password give the user password:

then write

> \i [full path and file name with extension]

then press enter insertion done.

Spin or rotate an image on hover

here is the automatic spin and rotating zoom effect using css3

#obj1{
    float:right;
    width: 96px;
    height: 100px;
    -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
    animation: mymove 20s infinite;
    animation-delay:2s;
    background-image:url("obj1.png");
    transform: scale(1.5);
    -moz-transform: scale(1.5);
    -webkit-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5); /* IE 9 */
    margin-bottom: 70px;
}

#obj2{
    float:right;
    width: 96px;
    height: 100px;
    -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
    animation: mymove 20s infinite;
    animation-delay:2s;
    background-image:url("obj2.png");
    transform: scale(1.5);
    -moz-transform: scale(1.5);
    -webkit-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5); /* IE 9 */
    margin-bottom: 70px;
}

#obj6{
    float:right;
    width: 96px;
    height: 100px;
    -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
    animation: mymove 20s infinite;
    animation-delay:2s;
    background-image:url("obj6.png");
    transform: scale(1.5);
    -moz-transform: scale(1.5);
    -webkit-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5); /* IE 9 */
    margin-bottom: 70px;
}

/* Standard syntax */
@keyframes mymove {
    50% {transform: rotate(30deg);
}
<div style="width:100px; float:right; ">
    <div id="obj2"></div><br /><br /><br />
    <div id="obj6"></div><br /><br /><br />
    <div id="obj1"></div><br /><br /><br />
</div>

Here is the demo

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

Finaly I found another answer for this problem. and this is working for me. Just add below datas to the your webconfig file.

<configuration>
 <system.webServer>
  <security>
   <requestFiltering>
    <verbs allowUnlisted="true">
     <add verb="OPTIONS" allowed="false" />
    </verbs>
   </requestFiltering>
  </security>
 </system.webServer>
</configuration>

Form more information, you can visit this web site: http://www.iis.net/learn/manage/configuring-security/use-request-filtering

if you want to test your web site, is it working or not... You can use "HttpRequester" mozilla firefox plugin. for this plugin: https://addons.mozilla.org/En-us/firefox/addon/httprequester/

Android basics: running code in the UI thread

As of Android P you can use getMainExecutor():

getMainExecutor().execute(new Runnable() {
  @Override public void run() {
    // Code will run on the main thread
  }
});

From the Android developer docs:

Return an Executor that will run enqueued tasks on the main thread associated with this context. This is the thread used to dispatch calls to application components (activities, services, etc).

From the CommonsBlog:

You can call getMainExecutor() on Context to get an Executor that will execute its jobs on the main application thread. There are other ways of accomplishing this, using Looper and a custom Executor implementation, but this is simpler.

HttpClient 4.0.1 - how to release connection?

This seems to work great :

      if( response.getEntity() != null ) {
         response.getEntity().consumeContent();
      }//if

And don't forget to consume the entity even if you didn't open its content. For instance, you expect a HTTP_OK status from the response and don't get it, you still have to consume the entity !

How do you get total amount of RAM the computer has?

The Windows API function GlobalMemoryStatusEx can be called with p/invoke:

  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  private class MEMORYSTATUSEX
  {
     public uint dwLength;
     public uint dwMemoryLoad;
     public ulong ullTotalPhys;
     public ulong ullAvailPhys;
     public ulong ullTotalPageFile;
     public ulong ullAvailPageFile;
     public ulong ullTotalVirtual;
     public ulong ullAvailVirtual;
     public ulong ullAvailExtendedVirtual;
     public MEMORYSTATUSEX()
     {
        this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));
     }
  }


  [return: MarshalAs(UnmanagedType.Bool)]
  [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);

Then use like:

ulong installedMemory;
MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
if( GlobalMemoryStatusEx( memStatus))
{ 
   installedMemory = memStatus.ullTotalPhys;
}

Or you can use WMI (managed but slower) to query TotalPhysicalMemory in the Win32_ComputerSystem class.

How to implement onBackPressed() in Fragments?

Do not implement ft.addToBackStack() method so that when you pressed back button your activity will be finished.

proAddAccount = new ProfileAddAccount();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, proAddAccount);
//fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

How do I test if a recordSet is empty? isNull?

If temp_rst1.BOF and temp_rst1.EOF then the recordset is empty. This will always be true for an empty recordset, linked or local.

Create a day-of-week column in a Pandas dataframe using Python

Pandas 0.23+

Use pandas.Series.dt.day_name(), since pandas.Timestamp.weekday_name has been deprecated:

import pandas as pd


df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])

df['day_of_week'] = df['my_dates'].dt.day_name()

Output:

    my_dates  myvals day_of_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

Pandas 0.18.1+

As user jezrael points out below, dt.weekday_name was added in version 0.18.1 Pandas Docs

import pandas as pd

df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.weekday_name

Output:

    my_dates  myvals day_of_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

Original Answer:

Use this:

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.dayofweek.html

See this:

Get weekday/day-of-week for Datetime column of DataFrame

If you want a string instead of an integer do something like this:

import pandas as pd

df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.dayofweek

days = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'}

df['day_of_week'] = df['day_of_week'].apply(lambda x: days[x])

Output:

    my_dates  myvals day_of_week
0 2015-01-01       1       Thurs
1 2015-01-02       2         Fri
2 2015-01-01       3       Thurs

.NET code to send ZPL to Zebra printers

VB Version (using port 9100 - tested on Zebra ZM400)

Sub PrintZPL(ByVal pIP As String, ByVal psZPL As String)
    Dim lAddress As Net.IPEndPoint
    Dim lSocket As System.Net.Sockets.Socket = Nothing
    Dim lNetStream As System.Net.Sockets.NetworkStream = Nothing
    Dim lBytes As Byte()

    Try
        lAddress = New Net.IPEndPoint(Net.IPAddress.Parse(pIP), 9100)
        lSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, _                       ProtocolType.Tcp)
        lSocket.Connect(lAddress)
        lNetStream = New NetworkStream(lSocket)

        lBytes = System.Text.Encoding.ASCII.GetBytes(psZPL)
        lNetStream.Write(lBytes, 0, lBytes.Length)
    Catch ex As Exception When Not App.Debugging
        Msgbox ex.message & vbnewline & ex.tostring
    Finally
        If Not lNetStream Is Nothing Then
            lNetStream.Close()
        End If
        If Not lSocket Is Nothing Then
            lSocket.Close()
        End If
    End Try
End Sub

WAMP server, localhost is not working

If you have skype installed, close it completely.

If you have sql server installed, go to:

Control panel -> Administrative Tools -> Services

And stop SQL Server Reporting Services

Port 80 must be free now. Click on Wamp icon -> Restart All Services

How to unzip a file in Powershell?

ForEach Loop processes each ZIP file located within the $filepath variable

    foreach($file in $filepath)
    {
        $zip = $shell.NameSpace($file.FullName)
        foreach($item in $zip.items())
        {
            $shell.Namespace($file.DirectoryName).copyhere($item)
        }
        Remove-Item $file.FullName
    }

Set initial value in datepicker with jquery?

Use it after initialization code to get current date (in datepicker format):

$(".ui-datepicker-today").trigger("click");

Auto reloading python Flask app upon code changes

Use this method:

app.run(debug=True)

It will auto-reload the flask app when a code change happens.

Sample code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
   return "Hello World"


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

Well, if you want save time not reloading the webpage everytime when changes happen, then you can try the keyboard shortcut Ctrl + R to reload the page quickly.

Deleting rows with MySQL LEFT JOIN

DELETE FROM deadline where ID IN (
    SELECT d.ID FROM `deadline` d LEFT JOIN `job` ON deadline.job_id = job.job_id WHERE `status` =  'szamlazva' OR `status` = 'szamlazhato' OR `status` = 'fizetve' OR `status` = 'szallitva' OR `status` = 'storno');

I am not sure if that kind of sub query works in MySQL, but try it. I am assuming you have an ID column in your deadline table.

Gradle: Could not determine java version from '11.0.2'

I had the same problem here. In my case I need to use an old version of JDK and I'm using sdkmanager to manage the versions of JDK, so, I changed the version of the virtual machine to 1.8.

sdk use java 8.0.222.j9-adpt

After that, the app runs as expected here.

SQL Query for Student mark functionality

Just for fun, consider the different question one would get with a very literal interpretation of the OP's description: "Write a query to print the list of names of students who have scored the maximum mark in each subject."

Those who've answered here have written queries to list a student if he or she scored the maximum mark in any one subject, but not necessarily in all subjects. Since the question posed by the OP does not ask for subject names in the output, this is a plausible interpretation.

To list the names of students (if any) who have scored the maximum mark in all subjects (excluding subjects with no marks, since arguably there is then no maximum mark then), I think this works, using column names from Michael's SQL Fiddle, which I've adapted here.

select StudentName
from Student 
where not exists (
  select * from Subject
  where exists (
    select * from Mark as M1
    where M1.SubjectID = Subject.SubjectID
    and M1.StudentID <> Student.StudentID
    and not exists (
      select * from Mark as M2
      where M2.StudentID = Student.StudentID
      and M2.SubjectID = M1.SubjectID
      and M2.MarkRate >= M1.MarkRate
    )
  )
)

In other words, select a student X's name if there is no subject in which someone's mark for that subject is not matched or exceeded by some mark belonging to X for the same subject. (This query returns a student's name if the student has received more than one mark in a subject, so long as one of those marks is the highest for the subject.)

What is IPV6 for localhost and 0.0.0.0?

For use in a /etc/hosts file as a simple ad blocking technique to cause a domain to fail to resolve, the 0.0.0.0 address has been widely used because it causes the request to immediately fail without even trying, because it's not a valid or routable address. This is in comparison to using 127.0.0.1 in that place, where it will at least check to see if your own computer is listening on the requested port 80 before failing with 'connection refused.' Either of those addresses being used in the hosts file for the domain will stop any requests from being attempted over the actual network, but 0.0.0.0 has gained favor because it's more 'optimal' for the above reason. "127" IPs will attempt to hit your own computer, and any other IP will cause a request to be sent to the router to try to route it, but for 0.0.0.0 there's nowhere to even send a request to.

All that being said, having any IP listed in your hosts file for the domain to be blocked is sufficient, and you wouldn't need or want to also put an ipv6 address in your hosts file unless -- possibly -- you don't have ipv4 enabled at all. I'd be really surprised if that was the case, though. And still though, I think having the host appear in /etc/hosts with a bad ipv4 address when you don't have ipv4 enabled would still give you the result you are looking for which is for it to fail, instead of looking up the real DNS of say, adserver-example.com and getting back either a v4 or v6 IP.

How to redirect to another page using PHP

<?php 
include("config.php");
 
 
$id=$_GET['id'];

include("config.php");
if($insert = mysqli_query($con,"update  consumer_closeconnection set close_status='Pending' where id="$id"  "))
            {
?>
<script>
    window.location.href='ConsumerCloseConnection.php';

</script>
<?php
            }
            else
            {
?>
<script>
     window.location.href='ConsumerCloseConnection.php';
</script>
<?php            
    }
?>      

SELECT COUNT in LINQ to SQL C#

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

Declaring a boolean in JavaScript using just var

Types are dependent to your initialization:

var IsLoggedIn1 = "true"; //string
var IsLoggedIn2 = 1; //integer
var IsLoggedIn3 = true; //bool

But take a look at this example:

var IsLoggedIn1 = "true"; //string
IsLoggedIn1 = true; //now your variable is a boolean

Your variables' type depends on the assigned value in JavaScript.

Check if the number is integer

Here's a solution using simpler functions and no hacks:

all.equal(a, as.integer(a))

What's more, you can test a whole vector at once, if you wish. Here's a function:

testInteger <- function(x){
  test <- all.equal(x, as.integer(x), check.attributes = FALSE)
  if(test == TRUE){ return(TRUE) }
  else { return(FALSE) }
}

You can change it to use *apply in the case of vectors, matrices, etc.

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

If you use Guava (v11 minimum) in your project you can use Maps::transformValues.

Map<String, Column> newColumnMap = Maps.transformValues(
  originalColumnMap,
  Column::new // equivalent to: x -> new Column(x) 
)

Note: The values of this map are evaluated lazily. If the transformation is expensive you can copy the result to a new map like suggested in the Guava docs.

To avoid lazy evaluation when the returned map doesn't need to be a view, copy the returned map into a new map of your choosing.

React : difference between <Route exact path="/" /> and <Route path="/" />

In this example, nothing really. The exact param comes into play when you have multiple paths that have similar names:

For example, imagine we had a Users component that displayed a list of users. We also have a CreateUser component that is used to create users. The url for CreateUsers should be nested under Users. So our setup could look something like this:

<Switch>
  <Route path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

Now the problem here, when we go to http://app.com/users the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users route first and then return it. All good.

But, if we went to http://app.com/users/create, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users partially matches /users/create, so it would incorrectly return the Users route again!

The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

So in this case, we should add exact to our Users route so that it will only match on /users:

<Switch>
  <Route exact path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

The docs explain exact in detail and give other examples.

Adding image to JFrame

If you are using Netbeans to develop, use jLabel and change it's icon property.

Using cut command to remove multiple columns

You are able to cut all odd/even columns by using seq:

This would print all odd columns

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 1 2 10)

To print all even columns you could use

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 2 2 10)

By changing the second number of seq you can specify which columns to be printed.

If the specification which columns to print is more complex you could also use a "one-liner-if-clause" like

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(for i in $(seq 1 10); do if [[ $i -lt 10 && $i -lt 5 ]];then echo -n $i,; else echo -n $i;fi;done)

This would print all columns from 1 to 5 - you can simply modify the conditions to create more complex conditions to specify weather a column shall be printed.

How to remove title bar from the android activity?

Add in activity

requestWindowFeature(Window.FEATURE_NO_TITLE);

and add your style.xml file with the following two lines:

<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>

Swift programmatically navigate to another view controller/scene

All other answers sounds good, I would like to cover my case, where I had to make an animated LaunchScreen, then after 3 to 4 seconds of animation the next task was to move to Home screen. I tried segues, but that created problem for destination view. So at the end I accessed AppDelegates's Window property and I assigned a new NavigationController screen to it,

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let homeVC = storyboard.instantiateViewController(withIdentifier: "HomePageViewController") as! HomePageViewController

//Below's navigationController is useful if u want NavigationController in the destination View
let navigationController = UINavigationController(rootViewController: homeVC)
appDelegate.window!.rootViewController = navigationController

If incase, u don't want navigationController in the destination view then just assign as,

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let homeVC = storyboard.instantiateViewController(withIdentifier: "HomePageViewController") as! HomePageViewController
appDelegate.window!.rootViewController = homeVC

How to convert R Markdown to PDF?

For an option that looks more like what you get when you print from a browser, wkhtmltopdf provides one option.

On Ubuntu

sudo apt-get install wkhtmltopdf

And then the same command as for the pandoc example to get to the HTML:

RMDFILE=example-r-markdown  
Rscript -e "require(knitr); require(markdown); knit('$RMDFILE.rmd', '$RMDFILE.md'); markdownToHTML('$RMDFILE.md', '$RMDFILE.html', options=c('use_xhml'))"

and then

wkhtmltopdf example-r-markdown.html example-r-markdown.pdf

The resulting file looked like this. It did not seem to handle the MathJax (this issue is discussed here), and the page breaks are ugly. However, in some cases, such a style might be preferred over a more LaTeX style presentation.

Compare two objects' properties to find differences?

Compare NET Objects can help you!

CompareLogic logic = new CompareLogic();
var compare = logic.Compare(obj1, obj2);
comparacao.Differences.ForEach(diff => Debug.Write(diff.PropertyName));
// Or formatted summary
Debug.Write(comparacao.DifferencesString);

How to detect online/offline event cross-browser?

Today there's an open source JavaScript library that does this job: it's called Offline.js.

Automatically display online/offline indication to your users.

https://github.com/HubSpot/offline

Be sure to check the full README. It contains events that you can hook into.

Here's a test page. It's beautiful/has a nice feedback UI by the way! :)

Offline.js Simulate UI is an Offline.js plug-in that allows you to test how your pages respond to different connectivity states without having to use brute-force methods to disable your actual connectivity.

difference between variables inside and outside of __init__()

further to S.Lott's reply, class variables get passed to metaclass new method and can be accessed through the dictionary when a metaclass is defined. So, class variables can be accessed even before classes are created and instantiated.

for example:

class meta(type):
    def __new__(cls,name,bases,dicto):
          # two chars missing in original of next line ...
          if dicto['class_var'] == 'A':
             print 'There'
class proxyclass(object):
      class_var = 'A'
      __metaclass__ = meta
      ...
      ...

How to empty a list?

lst *= 0

has the same effect as

lst[:] = []

It's a little simpler and maybe easier to remember. Other than that there's not much to say

The efficiency seems to be about the same

How to do a SUM() inside a case statement in SQL server

The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.

Example

This one works!

     SELECT t.device,
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This one not (omitted t.device from the select)

     SELECT 
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This will produce your error complaining that I'm grouping for something that is not included in the select

Please, provide all the query to get more support.

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

HTTPScoop is awesome for inspecting the web traffic on your Mac. It's been incredibly helpful for me. I didn't think twice about the $15 price tag. There is a 14 day trial.

How do I setup a SSL certificate for an express.js server?

See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):

var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );

https.createServer({
    key: privateKey,
    cert: certificate
}, app).listen(port);

Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener

close fxml window by code, javafx

If you have a window which extends javafx.application.Application; you can use the following method. (This will close the whole application, not just the window. I misinterpreted the OP, thanks to the commenters for pointing it out).

Platform.exit();

Example:

public class MainGUI extends Application {
.........

Button exitButton = new Button("Exit");
exitButton.setOnAction(new ExitButtonListener());
.........

public class ExitButtonListener implements EventHandler<ActionEvent> {

  @Override
  public void handle(ActionEvent arg0) {
    Platform.exit();
  }
}

Edit for the beauty of Java 8:

 public class MainGUI extends Application {
    .........

    Button exitButton = new Button("Exit");
    exitButton.setOnAction(actionEvent -> Platform.exit());
 }

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Go to Control Panel -> Programs -> Programs and features

    Step 1 - Programs and features

  2. Go to Windows Features and disable Internet Explorer 11

    Step 2 - Windows Features

    Step 3 - Uncheck Internet Explorer 11

  3. Then click on Display installed updates

    Step 4 - Display installed updates

  4. Search for Internet explorer

  5. Right-click on Internet Explorer 11 -> Uninstall

    Step 5 - Uninstall Internet Explorer 11

  6. Do the same with Internet Explorer 10

  7. Restart your computer
  8. Install Internet Explorer 10 here (old broken link)

I think it will be okay.

How do I change Eclipse to use spaces instead of tabs?

And don't forget the ANT editor

For some reason Ant Editor does not show up in the search results for 'tab' or 'spaces' so can be missed.

Under Windows > Preferences

  • Ant » Editor » Formatter » Tab size: (set to 4)
  • Ant » Editor » Formatter » Use tab character instead of spaces (uncheck it)

How do I print bytes as hexadecimal?

Yet another answer, in case the byte array is defined as char[], uppercase and separated by spaces.

void debugArray(const unsigned char* data, size_t len) {
    std::ios_base::fmtflags f( std::cout.flags() );
    for (size_t i = 0; i < len; ++i)
        std::cout << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << (((int)data[i]) & 0xFF) << " ";
    std::cout << std::endl;
    std::cout.flags( f );
}

Example:

unsigned char test[]={0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
debugArray(test, sizeof(test));

Output:

01 02 03 04 05 06

How to send an object from one Android Activity to another using Intents?

implement serializable in your class

public class Place implements Serializable{
        private int id;
        private String name;

        public void setId(int id) {
           this.id = id;
        }
        public int getId() {
           return id;
        }
        public String getName() {
           return name;
        }

        public void setName(String name) {
           this.name = name;
        }
}

Then you can pass this object in intent

     Intent intent = new Intent(this, SecondAct.class);
     intent.putExtra("PLACE", Place);
     startActivity(intent);

int the second activity you can get data like this

     Place place= (Place) getIntent().getSerializableExtra("PLACE");

But when the data become large,this method will be slow.

How to do a logical OR operation for integer comparison in shell scripting?

Sometimes you need to use double brackets, otherwise you get an error like too many arguments

if [[ $OUTMERGE == *"fatal"* ]] || [[ $OUTMERGE == *"Aborting"* ]]
  then
fi

Response.Redirect with POST instead of Get?

Here's what I'd do :

Put the data in a standard form (with no runat="server" attribute) and set the action of the form to post to the target off-site page. Before submitting I would submit the data to my server using an XmlHttpRequest and analyze the response. If the response means you should go ahead with the offsite POSTing then I (the JavaScript) would proceed with the post otherwise I would redirect to a page on my site

Why do abstract classes in Java have constructors?

Two reasons for this:

1) Abstract classes have constructors and those constructors are always invoked when a concrete subclass is instantiated. We know that when we are going to instantiate a class, we always use constructor of that class. Now every constructor invokes the constructor of its super class with an implicit call to super().

2) We know constructor are also used to initialize fields of a class. We also know that abstract classes may contain fields and sometimes they need to be initialized somehow by using constructor.

How to add an image to a JPanel?

I think there is no need to subclass of anything. Just use a Jlabel. You can set an image into a Jlabel. So, resize the Jlabel then fill it with an image. Its OK. This is the way I do.

How can I return the difference between two lists?

List<String> l1 = new ArrayList<String>();
l1.add("apple");
l1.add("orange");
l1.add("banana");
l1.add("strawberry");

List<String> l2 = new ArrayList<String>();
l2.add("apple");
l2.add("orange");

System.out.println(l1);
System.out.println(l2);

for (String A: l2) {
  if (l1.contains(A))
    l1.remove(A);
}

System.out.println("output");
System.out.println(l1);

Output:

[apple, orange, banana, strawberry]
[apple, orange]
output
[banana, strawberry]

Hive Alter table change Column Name

Command works only if "use" -command has been first used to define the database where working in. Table column renaming syntax using DATABASE.TABLE throws error and does not work. Version: HIVE 0.12.

EXAMPLE:

hive> ALTER TABLE databasename.tablename CHANGE old_column_name new_column_name;

  MismatchedTokenException(49!=90)
        at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
        at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
        at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixExchangePartition(HiveParser.java:11492)
        ...

hive> use databasename;

hive> ALTER TABLE tablename CHANGE old_column_name new_column_name;

OK

Facebook Javascript SDK Problem: "FB is not defined"

I had a very messy cody that loaded facebook's javascript via AJAX and i had to make sure that the js file has been completely loaded before calling FB.init this seem to work for me

    $jQuery.load( document.location.protocol + '//connect.facebook.net/en_US/all.js',
      function (obj) {
        FB.init({
           appId  : 'YOUR APP ID',
           status : true, // check login status
           cookie : true, // enable cookies to allow the server to access the session
           xfbml  : true  // parse XFBML
        });
        //ANy other FB.related javascript here
      });

This code uses jquery to load the javascript and do the function callback onLoad of the javascript. it's a lot less messier than having creating an onLoad eventlistener for the block which in the end didn't work very well on IE6, 7 and 8

SQL Query - Change date format in query to DD/MM/YYYY

If you have a Date (or Datetime) column, look at http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

 SELECT DATE_FORMAT(datecolumn,'%d/%m/%Y') FROM ...

Should do the job for MySQL, for SqlServer I'm sure there is an analog function. If you have a VARCHAR column, you might have at first to convert it to a date, see STR_TO_DATE for MySQL.

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

Check InnoDB status for locks

SHOW ENGINE InnoDB STATUS;

Check MySQL open tables

SHOW OPEN TABLES WHERE In_use > 0;

Check pending InnoDB transactions

SELECT * FROM `information_schema`.`innodb_trx` ORDER BY `trx_started`; 

Check lock dependency - what blocks what

SELECT * FROM `information_schema`.`innodb_locks`;

After investigating the results above, you should be able to see what is locking what.

The root cause of the issue might be in your code too - please check the related functions especially for annotations if you use JPA like Hibernate.

For example, as described here, the misuse of the following annotation might cause locks in the database:

@Transactional(propagation = Propagation.REQUIRES_NEW) 

How to get main div container to align to centre?

Do not use the * selector as that will apply to all elements on the page. Suppose you have a structure like this:

...
<body>
    <div id="content">
        <b>This is the main container.</b>
    </div>
</body>
</html>

You can then center the #content div using:

#content {
    width: 400px;
    margin: 0 auto;
    background-color: #66ffff;
}

Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; } snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.

Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:

CSS: Set a background color which is 50% of the width of the window

In a past project that had to support IE8+ and I achieved this using a image encoded in data-url format.

The image was 2800x1px, half of the image white, and half transparent. Worked pretty well.

body {
    /* 50% right white */
    background: red url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACvAAAAABAQAAAAAqT0YHAAAAAnRSTlMAAHaTzTgAAAAOSURBVHgBYxhi4P/QAgDwrK5SDPAOUwAAAABJRU5ErkJggg==) center top repeat-y;

   /* 50% left white */
   background: red url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACvAAAAABAQAAAAAqT0YHAAAAAnRSTlMAAHaTzTgAAAAPSURBVHgBY/g/tADD0AIAIROuUgYu7kEAAAAASUVORK5CYII=) center top repeat-y;
}

You can see it working here JsFiddle. Hope it can help someone ;)

Android ADB commands to get the device properties

You should use adb shell getprop command and grep specific info about your current device, For additional information you can read documentation: Android Debug Bridge documentation

I added some examples below:

  1. language - adb shell getprop | grep language

    [persist.sys.language]: [en]

    [ro.product.locale.language]: [en]

  2. boot complete ( device ready after reset) - adb shell getprop | grep boot_completed

    [sys.boot_completed]: [1]

  3. device model - adb shell getprop | grep model

    [ro.product.model]: [Nexus 4]

  4. sdk version - adb shell getprop | grep sdk

    [ro.build.version.sdk]: [22]

  5. time zone - adb shell getprop | grep timezone

    [persist.sys.timezone]: [Asia/China]

  6. serial number - adb shell getprop | grep serialno

    [ro.boot.serialno]: [1234567]

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

I write code bewlow. It works well in product version. Supprot Swift 4.2 +

extension UIButton{
 enum ImageTitleRelativeLocation {
    case imageUpTitleDown
    case imageDownTitleUp
    case imageLeftTitleRight
    case imageRightTitleLeft
}
 func centerContentRelativeLocation(_ relativeLocation: 
                                      ImageTitleRelativeLocation,
                                   spacing: CGFloat = 0) {
    assert(contentVerticalAlignment == .center,
           "only works with contentVerticalAlignment = .center !!!")

    guard (title(for: .normal) != nil) || (attributedTitle(for: .normal) != nil) else {
        assert(false, "TITLE IS NIL! SET TITTLE FIRST!")
        return
    }

    guard let imageSize = self.currentImage?.size else {
        assert(false, "IMGAGE IS NIL! SET IMAGE FIRST!!!")
        return
    }
    guard let titleSize = titleLabel?
        .systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) else {
            assert(false, "TITLELABEL IS NIL!")
            return
    }

    let horizontalResistent: CGFloat
    // extend contenArea in case of title is shrink
    if frame.width < titleSize.width + imageSize.width {
        horizontalResistent = titleSize.width + imageSize.width - frame.width
        print("horizontalResistent", horizontalResistent)
    } else {
        horizontalResistent = 0
    }

    var adjustImageEdgeInsets: UIEdgeInsets = .zero
    var adjustTitleEdgeInsets: UIEdgeInsets = .zero
    var adjustContentEdgeInsets: UIEdgeInsets = .zero

    let verticalImageAbsOffset = abs((titleSize.height + spacing) / 2)
    let verticalTitleAbsOffset = abs((imageSize.height + spacing) / 2)

    switch relativeLocation {
    case .imageUpTitleDown:

        adjustImageEdgeInsets.top = -verticalImageAbsOffset
        adjustImageEdgeInsets.bottom = verticalImageAbsOffset
        adjustImageEdgeInsets.left = titleSize.width / 2 + horizontalResistent / 2
        adjustImageEdgeInsets.right = -titleSize.width / 2 - horizontalResistent / 2

        adjustTitleEdgeInsets.top = verticalTitleAbsOffset
        adjustTitleEdgeInsets.bottom = -verticalTitleAbsOffset
        adjustTitleEdgeInsets.left = -imageSize.width / 2 + horizontalResistent / 2
        adjustTitleEdgeInsets.right = imageSize.width / 2 - horizontalResistent / 2

        adjustContentEdgeInsets.top = spacing
        adjustContentEdgeInsets.bottom = spacing
        adjustContentEdgeInsets.left = -horizontalResistent
        adjustContentEdgeInsets.right = -horizontalResistent
    case .imageDownTitleUp:
        adjustImageEdgeInsets.top = verticalImageAbsOffset
        adjustImageEdgeInsets.bottom = -verticalImageAbsOffset
        adjustImageEdgeInsets.left = titleSize.width / 2 + horizontalResistent / 2
        adjustImageEdgeInsets.right = -titleSize.width / 2 - horizontalResistent / 2

        adjustTitleEdgeInsets.top = -verticalTitleAbsOffset
        adjustTitleEdgeInsets.bottom = verticalTitleAbsOffset
        adjustTitleEdgeInsets.left = -imageSize.width / 2 + horizontalResistent / 2
        adjustTitleEdgeInsets.right = imageSize.width / 2 - horizontalResistent / 2

        adjustContentEdgeInsets.top = spacing
        adjustContentEdgeInsets.bottom = spacing
        adjustContentEdgeInsets.left = -horizontalResistent
        adjustContentEdgeInsets.right = -horizontalResistent
    case .imageLeftTitleRight:
        adjustImageEdgeInsets.left = -spacing / 2
        adjustImageEdgeInsets.right = spacing / 2

        adjustTitleEdgeInsets.left = spacing / 2
        adjustTitleEdgeInsets.right = -spacing / 2

        adjustContentEdgeInsets.left = spacing
        adjustContentEdgeInsets.right = spacing
    case .imageRightTitleLeft:
        adjustImageEdgeInsets.left = titleSize.width + spacing / 2
        adjustImageEdgeInsets.right = -titleSize.width - spacing / 2

        adjustTitleEdgeInsets.left = -imageSize.width - spacing / 2
        adjustTitleEdgeInsets.right = imageSize.width + spacing / 2

        adjustContentEdgeInsets.left = spacing
        adjustContentEdgeInsets.right = spacing
    }

    imageEdgeInsets = adjustImageEdgeInsets
    titleEdgeInsets = adjustTitleEdgeInsets
    contentEdgeInsets = adjustContentEdgeInsets

    setNeedsLayout()
}
}

How to auto adjust table td width from the content

you could also use display: table insted of tables. Divs are way more flexible than tables.

Example:

_x000D_
_x000D_
.table {_x000D_
   display: table;_x000D_
   border-collapse: collapse;_x000D_
}_x000D_
 _x000D_
.table .table-row {_x000D_
   display: table-row;_x000D_
}_x000D_
 _x000D_
.table .table-cell {_x000D_
   display: table-cell;_x000D_
   text-align: left;_x000D_
   vertical-align: top;_x000D_
   border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test1123</div>_x000D_
 </div>_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test123</div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I join multiple SQL tables using the IDs?

You want something more like this:

SELECT TableA.*, TableB.*, TableC.*, TableD.*
FROM TableA
    JOIN TableB
        ON TableB.aID = TableA.aID
    JOIN TableC
        ON TableC.cID = TableB.cID
    JOIN TableD
        ON TableD.dID = TableA.dID
WHERE DATE(TableC.date)=date(now()) 

In your example, you are not actually including TableD. All you have to do is perform another join just like you have done before.

A note: you will notice that I removed many of your parentheses, as they really are not necessary in most of the cases you had them, and only add confusion when trying to read the code. Proper nesting is the best way to make your code readable and separated out.

How can I prevent the backspace key from navigating back?

Stop from navigating this code works!

$(document).on("keydown", function (event) {        
   if (event.keyCode === 8) {
      event.preventDefault();
    }
  });

But for not to restricting text fields but others

$(document).on("keydown", function (event) {
  if (event.which === 8 && !$(event.target).is("input, textarea")) {
   event.preventDefault();
  }
});

To prevent it for specific field simply use

$('#myOtherField').on("keydown", function (event) {
  if (event.keyCode === 8 || event.which === 8) { 
   event.preventDefault(); 
  } 
});

Referring to this one below!

Prevent BACKSPACE from navigating back with jQuery (Like Google's Homepage)

Returning first x items from array

You can use array_slice function, but do you will use another values? or only the first 5? because if you will use only the first 5 you can use the LIMIT on SQL.

Converting camel case to underscore case in ruby

Here's how Rails does it:

   def underscore(camel_cased_word)
     camel_cased_word.to_s.gsub(/::/, '/').
       gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
       gsub(/([a-z\d])([A-Z])/,'\1_\2').
       tr("-", "_").
       downcase
   end

Automate scp file transfer using a shell script

This will work:

#!/usr/bin/expect -f

spawn scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no file1 file2 file3 user@host:/path/
expect "password:"
send "xyz123\r"
expect "*\r"
expect "\r"
interact

How to "flatten" a multi-dimensional array to simple one in PHP?

A new approach based on the previous example function submited by chaos, which fixes the bug of overwritting string keys in multiarrays:

# Flatten a multidimensional array to one dimension, optionally preserving keys.
# $array - the array to flatten
# $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
# $out - internal use argument for recursion

function flatten_array($array, $preserve_keys = 2, &$out = array(), &$last_subarray_found) 
{
        foreach($array as $key => $child)
        {
            if(is_array($child))
            {
                $last_subarray_found = $key;
                $out = flatten_array($child, $preserve_keys, $out, $last_subarray_found);
            }
            elseif($preserve_keys + is_string($key) > 1)
            {
                if ($last_subarray_found)
                {
                    $sfinal_key_value = $last_subarray_found . "_" . $key;
                }
                else
                {
                    $sfinal_key_value = $key;
                }
                $out[$sfinal_key_value] = $child;
            }
            else
            {
                $out[] = $child;
            }
        }

        return $out;
}

Example:
$newarraytest = array();
$last_subarray_found = "";
$this->flatten_array($array, 2, $newarraytest, $last_subarray_found);

Does a valid XML file require an XML declaration?

It is only required if you aren't using the default values for version and encoding (which you are in that example).

Print specific part of webpage

Just use CSS to hide the content you do not want printed. When the user selects print - the page will look to the " media="print" CSS for instructions about the layout of the page.

The media="print" CSS has instructions to hide the content that we do not want printed.

<!-- CSS for the things we want to print (print view) -->
<style type="text/css" media="print">

#SCREEN_VIEW_CONTAINER{
        display: none;
    }
.other_print_layout{
        background-color:#FFF;
    }
</style>

<!-- CSS for the things we DO NOT want to print (web view) -->
<style type="text/css" media="screen">

   #PRINT_VIEW{
      display: none;
   }
.other_web_layout{
        background-color:#E0E0E0;
    }
</style>

<div id="SCREEN_VIEW_CONTAINER">
     the stuff I DO NOT want printed is here and will be hidden - 
     and not printed when the user selects print.
</div>

<div id="PRINT_VIEW">
     the stuff I DO want printed is here.
</div>

Jquery validation plugin - TypeError: $(...).validate is not a function

For me problem solved by changing http://ajax... into https://ajax... (add an S to http)

https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

In my index.js I added:

app.use((req, res, next) => {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
   next();
}) 

Adding extra zeros in front of a number using jQuery?

This is the function that I generally use in my code to prepend zeros to a number or string.

The inputs are the string or number (str), and the desired length of the output (len).

var PrependZeros = function (str, len) {
    if(typeof str === 'number' || Number(str)){
    str = str.toString();
    return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
    for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
    return str;
}

};

Examples:

PrependZeros('MR 3',3);    // MR 003
PrependZeros('MR 23',3);   // MR 023
PrependZeros('MR 123',3);  // MR 123
PrependZeros('foo bar 23',3);  // foo bar 023

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

100% width Twitter Bootstrap 3 template

This is the complete basic structure for 100% width layout in Bootstrap v3.0.0. You shouldn't wrap your <div class="row"> with container class. Cause container class will take lots of margin and this will not provide you full screen (100% width) layout where bootstrap has removed container-fluid class from their mobile-first version v3.0.0.

So just start writing <div class="row"> without container class and you are ready to go with 100% width layout.

<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap Basic 100% width Structure</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
  <script src="http://getbootstrap.com/assets/js/html5shiv.js"></script>
  <script src="http://getbootstrap.com/assets/js/respond.min.js"></script>
<![endif]-->
<style>
    .red{
        background-color: red;
    }
    .green{
        background-color: green;
    }
</style>
</head>
<body>
    <div class="row">
        <div class="col-md-3 red">Test content</div>
        <div class="col-md-9 green">Another Content</div>
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="//code.jquery.com/jquery.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>

To see the result by yourself I have created a bootply. See the live output there. http://bootply.com/82136 And the complete basic bootstrap 3 100% width layout I have created a gist. you can use that. Get the gist from here

Reply me if you need more further assistance. Thanks.

How can I avoid Java code in JSP files, using JSP 2?

Using scriptlets in JSPs is not a good practice.

Instead, you can use:

  1. JSTL tags
  2. EL expressions
  3. Custom Tags- you can define your own tags to use.

Please refer to:

  1. http://docs.oracle.com/javaee/1.4/tutorial/doc/JSTL3.html
  2. EL

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

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

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

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

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

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

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

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

How to get the wsdl file from a webservice's URL

To download the wsdl from a url using Developer Command Prompt for Visual Studio, run it in Administrator mode and enter the following command:

 svcutil /t:metadata http://[your-service-url-here]

You can now consume the downloaded wsdl in your project as you see fit.

encapsulation vs abstraction real world example

Abstraction

We use many abstractions in our day-to-day lives.Consider a car.Most of us have an abstract view of how a car works.We know how to interact with it to get it to do what we want it to do: we put in gas, turn a key, press some pedals, and so on. But we don't necessarily understand what is going on inside the car to make it move and we don't need to. Millions of us use cars everyday without understanding the details of how they work.Abstraction helps us get to school or work!

A program can be designed as a set of interacting abstractions. In Java, these abstractions are captured in classes. The creator of a class obviusly has to know its interface, just as the driver of a car can use the vehicle without knowing how the engine works.

Encapsulation

Consider a Banking system.Banking system have properties like account no,account type,balance ..etc. If someone is trying to change the balance of the account,attempt can be successful if there is no encapsulation. Therefore encapsulation allows class to have complete control over their properties.

Sublime Text 2 - View whitespace characters

I use Unicode Character Highlighter, can show whitespaces and some other special characters.

Add this by, Package Control

Install packages, unicode ...

jQuery How to Get Element's Margin and Padding?

Edit:

use jquery plugin: jquery.sizes.js

$('img').margin() or $('img').padding()

return:

{bottom: 10 ,left: 4 ,top: 0 ,right: 5}

get value:

$('img').margin().top

How to find time complexity of an algorithm

I know this question goes a way back and there are some excellent answers here, nonetheless I wanted to share another bit for the mathematically-minded people that will stumble in this post. The Master theorem is another usefull thing to know when studying complexity. I didn't see it mentioned in the other answers.

convert ArrayList<MyCustomClass> to JSONArray

With kotlin and Gson we can do it more easily:

  1. First, add Gson dependency:

implementation "com.squareup.retrofit2:converter-gson:2.3.0"

  1. Create a separate kotlin file, add the following methods
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

fun <T> Gson.convertToJsonString(t: T): String {
    return toJson(t).toString()
}

fun <T> Gson.convertToModel(jsonString: String, cls: Class<T>): T? {
    return try {
        fromJson(jsonString, cls)
    } catch (e: Exception) {
        null
    }
}

inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type)

Note: Do not add declare class, just add these methods, everything will work fine.

  1. Now to call:

create a reference of gson:

val gson=Gson()

To convert array to json string, call:

val jsonString=gson.convertToJsonString(arrayList)

To get array from json string, call:

val arrayList=gson.fromJson<ArrayList<YourModelClassName>>(jsonString)

To convert a model to json string, call:

val jsonString=gson.convertToJsonString(model)

To convert json string to model, call:

val model=gson.convertToModel(jsonString, YourModelClassName::class.java)

Create Local SQL Server database

You need to install a so-called Instance of MSSQL server on your computer. That is, installing all the needed files and services and database files. By default, there should be no MSSQL Server installed on your machine, assuming that you use a desktop Windows (7,8,10...).

You can start off with Microsoft SQL Server Express, which is a 10GB-limited, free version of MSSQL. It also lacks some other features (Server Agents, AFAIR), but it's good for some experiments.

Download it from the Microsoft Website and go through the installer process by choosing New SQL Server stand-alone installation .. after running the installer.

Click through the steps. For your scenario (it sounds like you mainly want to test some stuff), the default options should suffice.

Just give attention to the step Instance Configuration. There you will set the name of your MSSQL Server Instance. Call it something unique/descriptive like MY_TEST_INSTANCE or the like. Also, choose wisely the Instance root directory. In it, the database files will be placed, so it should be on a drive that has enough space.

Click further through the wizard, and when it's finished, your MSSQL instance will be up and running. It will also run at every boot if you have chosen the default settings for the services.

As soon as it's running in the background, you can connect to it with Management Studio by connecting to .\MY_TEST_INSTANCE, given that that's the name you chose for the instance.

Python map object is not subscriptable

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

Using this code to multiple order by in single query.

$this->db->from($this->table_name);
$this->db->order_by("column1 asc,column2 desc");
$query = $this->db->get(); 
return $query->result();

Generating random, unique values C#

Depending on what you are really after you can do something like this:

using System;
using System.Collections.Generic;
using System.Linq;

namespace SO14473321
{
    class Program
    {
        static void Main()
        {
            UniqueRandom u = new UniqueRandom(Enumerable.Range(1,10));
            for (int i = 0; i < 10; i++)
            {
                Console.Write("{0} ",u.Next());
            }
        }
    }

    class UniqueRandom
    {
        private readonly List<int> _currentList;
        private readonly Random _random = new Random();

        public UniqueRandom(IEnumerable<int> seed)
        {
            _currentList = new List<int>(seed);
        }

        public int Next()
        {
            if (_currentList.Count == 0)
            {
                throw new ApplicationException("No more numbers");
            }

            int i = _random.Next(_currentList.Count);
            int result = _currentList[i];
            _currentList.RemoveAt(i);
            return result;
        }
    }
}

Python: Get the first character of the first string in a list?

Try mylist[0][0]. This should return the first character.

Check if null Boolean is true results in exception

Boolean is the object wrapper class for the primitive boolean. This class, as any class, can indeed be null. For performance and memory reasons it is always best to use the primitive.

The wrapper classes in the Java API serve two primary purposes:

  1. To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
  2. To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.

http://en.wikipedia.org/wiki/Primitive_wrapper_class

Java, How to specify absolute value and square roots

Use the java.lang.Math class, and specifically for absolute value and square root:, the abs() and sqrt() methods.

What should I use to open a url instead of urlopen in urllib3

The new urllib3 library has a nice documentation here
In order to get your desired result you shuld follow that:

Import urllib3
from bs4 import BeautifulSoup

url = 'http://www.thefamouspeople.com/singers.php'

http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data.decode('utf-8'))

The "decode utf-8" part is optional. It worked without it when i tried, but i posted the option anyway.
Source: User Guide

What in layman's terms is a Recursive Function using PHP

Laymens terms:

A recursive function is a function that calls itself

A bit more in depth:

If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.

What was a good learning example for me, since I have a strong background in math, was factorial. By the comments below, it seems the factorial function may be a bit too much, I'll leave it here just in case you wanted it.

function fact($n) {
  if ($n === 0) { // our base case
     return 1;
  }
  else {
     return $n * fact($n-1); // <--calling itself.
  }
}

In regards to using recursive functions in web development, I do not personally resort to using recursive calls. Not that I would consider it bad practice to rely on recursion, but they shouldn't be your first option. They can be deadly if not used properly.

Although I cannot compete with the directory example, I hope this helps somewhat.

(4/20/10) Update:

It would also be helpful to check out this question, where the accepted answer demonstrates in laymen terms how a recursive function works. Even though the OP's question dealt with Java, the concept is the same,

Instagram: Share photo from webpage

Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.

POST https://instagram.com/api/v1/media/upload/

Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php

Use mysql_fetch_array() with foreach() instead of while()

the most obvious way to make foreach a possibility includes materializing the whole resultset in an array, which will probably kill you memory-wise, sooner or later. you'd need to turn to iterators to avoid that problem. see http://www.php.net/~helly/php/ext/spl/

How to do a non-greedy match in grep?

Actualy the .*? only works in perl. I am not sure what the equivalent grep extended regexp syntax would be. Fortunately you can use perl syntax with grep so grep -P would work but grep -E which is same as egrep would not work (it would be greedy).

See also: http://blog.vinceliu.com/2008/02/non-greedy-regular-expression-matching.html

Pass props in Link react-router

If you are just looking to replace the slugs in your routes, you can use generatePath that was introduced in react-router 4.3 (2018). As of today, it isn't included in the react-router-dom (web) documentation, but is in react-router (core). Issue#7679

// myRoutes.js
export const ROUTES = {
  userDetails: "/user/:id",
}


// MyRouter.jsx
import ROUTES from './routes'

<Route path={ROUTES.userDetails} ... />


// MyComponent.jsx
import { generatePath } from 'react-router-dom'
import ROUTES from './routes'

<Link to={generatePath(ROUTES.userDetails, { id: 1 })}>ClickyClick</Link>

It's the same concept that django.urls.reverse has had for a while.

What does DIM stand for in Visual Basic and BASIC?

It's short for Dimension, as it was originally used in BASIC to specify the size of arrays.

DIM — (short for dimension) define the size of arrays

Ref: http://en.wikipedia.org/wiki/Dartmouth_BASIC

A part of the original BASIC compiler source code, where it would jump when finding a DIM command, in which you can clearly see the original intention for the keyword:

DIM    LDA XR01             BACK OFF OBJECT POINTER
       SUB N3
       STA RX01
       LDA L        2       GET VARIABLE TO BE DIMENSIONED
       STA 3
       LDA S        3
       CAB N36              CHECK FOR $ ARRAY
       BRU *+7              NOT $
       ...

Ref: http://dtss.dartmouth.edu/scans/BASIC/BASIC%20Compiler.pdf

Later on it came to be used to declare all kinds of variables, when the possibility to specify the type for variables was added in more recent implementations.

To show a new Form on click of a button in C#

1.Click Add on your project file new item and add windows form, the default name will be Form2.

2.Create button in form1 (your original first form) and click it. Under that button add the above code i.e:

var form2 = new Form2();
form2.Show();

3.It will work.

Is there a way to set background-image as a base64 encoded image?

Try this, I have got success response ..it's working

$("#divId").css("background-image", "url('data:image/png;base64," + base64String + "')");

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I removed my .classpath file in my project directory to correct this issue. No need to remove the Maven Nature from the project in Eclipse.

The specific error I was getting was: Project 'my-project-name' is missing required Java project: 'org.some.package-9.3.0 But my project wasn't dependent on org.some.package in any way.

Perhaps an old version of the project relied on it and Maven wasn't properly updating the .classpath file.

Use css gradient over background image

body {
    margin: 0;
    padding: 0;
    background: url('img/background.jpg') repeat;
}

body:before {
    content: " ";
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    background: -webkit-radial-gradient(top center, ellipse cover, rgba(255,255,255,0.2) 0%,rgba(0,0,0,0.5) 100%);
}

PLEASE NOTE: This only using webkit so it will only work in webkit browsers.

try :

-moz-linear-gradient = (Firefox)
-ms-linear-gradient = (IE)
-o-linear-gradient = (Opera)
-webkit-linear-gradient = (Chrome & safari)

Disabled href tag

You can disable anchor tags by returning false. In my case Im using angular and ng-disabled for a Jquery accordion and I need to disable the sections.

So I created a little js snippet to fix this.

       <a class="opener" data-toggle="collapse"
                   data-parent="#shipping-detail"
                   id="shipping-detail-section"
                   href="#shipping-address"
                   aria-expanded="true"
                   ng-disabled="checkoutState.addressSec">
                   Shipping Address</a>
     <script>
          $("a.opener").on("click", function () {
           var disabled = $(this).attr("disabled");
           if (disabled === 'disabled') {
            return false;
           }
           });
     </script>

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

SELECT c1, c2, c3, c4, c5 FROM table1 WHERE c3 = (select max(c3) from table)

SELECT * FROM table1 WHERE c3 = (select max(c3) from table1)

Remove Object from Array using JavaScript

splice(i, 1) where i is the incremental index of the array will remove the object. But remember splice will also reset the array length so watch out for 'undefined'. Using your example, if you remove 'Kristian', then in the next execution within the loop, i will be 2 but someArray will be a length of 1, therefore if you try to remove "John" you will get an "undefined" error. One solution to this albeit not elegant is to have separate counter to keep track of index of the element to be removed.

What does "hashable" mean in Python?

From the Python glossary:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

Where is debug.keystore in Android Studio

You can use this command and will fetch all your key-stores, go to your terminal and in your android root directory run this:

./gradlew signingReport

it will give you something like this a list of key-store and their information:

enter image description here

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

I have tried your code and it works just fine. The file is being created without any problem, this is the code I used (it's your code, I just changed the datasource for testing):

    public ActionResult ExportToExcel()
    {
        var products = new System.Data.DataTable("teste");
        products.Columns.Add("col1", typeof(int));
        products.Columns.Add("col2", typeof(string));

        products.Rows.Add(1, "product 1");
        products.Rows.Add(2, "product 2");
        products.Rows.Add(3, "product 3");
        products.Rows.Add(4, "product 4");
        products.Rows.Add(5, "product 5");
        products.Rows.Add(6, "product 6");
        products.Rows.Add(7, "product 7");


        var grid = new GridView();
        grid.DataSource = products;
        grid.DataBind();

        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
        Response.ContentType = "application/ms-excel";

        Response.Charset = "";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        grid.RenderControl(htw);

        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

        return View("MyView");
    }

Can an Android App connect directly to an online mysql database

Yes definitely you can connect to the MySql online database for that you need to create a web service. This web service will provide you access to the MySql database. Then you can easily pull and push data to MySql Database. PHP will be a good option for creating web service its simple to implement. Good luck...

Angular JS - angular.forEach - How to get key of the object?

The first parameter to the iterator in forEach is the value and second is the key of the object.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});

In your example, the outer forEach is actually:

angular.forEach($scope.filters, function(filterObj , filterKey)

Set selected item of spinner programmatically

To find a value and select it:

private void selectValue(Spinner spinner, Object value) {
    for (int i = 0; i < spinner.getCount(); i++) {
        if (spinner.getItemAtPosition(i).equals(value)) {
            spinner.setSelection(i);
            break;
        }
    }
}

How to check internet access on Android? InetAddress never times out

Kotlin implementation

/**
* Function that uses ping, takes server name or ip as argument.
*
* @return [Double.MAX_VALUE] if server is not reachable. Average RTT if the server is reachable.
*
* Success output example
*
* PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
* 64 bytes from 8.8.8.8: icmp_seq=1 ttl=254 time=172 ms
* 64 bytes from 8.8.8.8: icmp_seq=2 ttl=254 time=166 ms
* 64 bytes from 8.8.8.8: icmp_seq=3 ttl=254 time=167 ms
* 64 bytes from 8.8.8.8: icmp_seq=4 ttl=254 time=172 ms
* 64 bytes from 8.8.8.8: icmp_seq=5 ttl=254 time=167 ms

* --- 8.8.8.8 ping statistics ---
* 5 packets transmitted, 5 received, 0% packet loss, time 4011ms
* rtt min/avg/max/mdev = 166.470/169.313/172.322/2.539 ms
*          |________________________|
* value to parse using it.split('=')[1].trim().split(' ')[0].trim().split('/')[1].toDouble()
*/
@ExperimentalStdlibApi
fun pingServerAverageRtt(host: String): Double {

    var aveRtt: Double = Double.MAX_VALUE

    try {
        // execute the command on the environment interface, timeout is set as 0.2 to get response faster.
        val pingProcess: Process = Runtime.getRuntime().exec("/system/bin/ping -i 0.2 -c 5 $host")
        // gets the input stream to get the output of the executed command
        val bufferedReader = BufferedReader(InputStreamReader(pingProcess.inputStream))

        bufferedReader.forEachLine {
            if (it.isNotEmpty() && it.contains("min/avg/max/mdev")) {  // when we get to the last line of executed ping command
                aveRtt = it.split('=')[1].trim()
                        .split(' ')[0].trim()
                        .split('/')[1].toDouble()
            }
        }
    } catch (e: IOException) {
        e.printStackTrace()
    }

    return aveRtt
}

Usage example


val latency = pingServerAverageRtt(ipString)
if (latency != Double.MAX_VALUE) { 
    //server reachable
} else {
    //server not reachable
}

Atom menu is missing. How do I re-enable

Open atom editor and then press Alt and menu bar will appear. Now click on View tab and then click on Toggle Menu Bar as seen on this screenshot.

Parameter "stratify" from method "train_test_split" (scikit Learn)

For my future self who comes here via Google:

train_test_split is now in model_selection, hence:

from sklearn.model_selection import train_test_split

# given:
# features: xs
# ground truth: ys

x_train, x_test, y_train, y_test = train_test_split(xs, ys,
                                                    test_size=0.33,
                                                    random_state=0,
                                                    stratify=ys)

is the way to use it. Setting the random_state is desirable for reproducibility.

Array or List in Java. Which is faster?

No, because technically, the array only stores the reference to the strings. The strings themselves are allocated in a different location. For a thousand items, I would say a list would be better, it is slower, but it offers more flexibility and it's easier to use, especially if you are going to resize them.

How many bits is a "word"?

"most convenient block of data" probably refers to the width (in bits) of the WORD, in correspondance to the system bus width, or whatever underlying "bandwidth" is available. On a 16 bit system, with WORD being defined as 16 bits wide, moving data around in chunks the size of a WORD will be the most efficient way. (On hardware or "system" level.)

With Java being more or less platform independant, it just defines a "WORD" as the next size from a "BYTE", meaning "full bandwidth". I guess any platform that's able to run Java will use 32 bits for a WORD.

PHP Checking if the current date is before or after a set date

I wanted to set a specific date so have used this to do stuff before 2nd December 2013

if(mktime(0,0,0,12,2,2013) > strtotime('now')) {
    // do stuff
}

The 0,0,0 is midnight, the 12 is the month, the 2 is the day and the 2013 is the year.

How do you test running time of VBA code?

Sub Macro1()
    Dim StartTime As Double
    StartTime = Timer

        ''''''''''''''''''''
            'Your Code'
        ''''''''''''''''''''
    MsgBox "RunTime : " & Format((Timer - StartTime) / 86400, "hh:mm:ss")
End Sub

Output:

RunTime : 00:00:02

How to initialize private static members in C++?

For future viewers of this question, I want to point out that you should avoid what monkey0506 is suggesting.

Header files are for declarations.

Header files get compiled once for every .cpp file that directly or indirectly #includes them, and code outside of any function is run at program initialization, before main().

By putting: foo::i = VALUE; into the header, foo:i will be assigned the value VALUE (whatever that is) for every .cpp file, and these assignments will happen in an indeterminate order (determined by the linker) before main() is run.

What if we #define VALUE to be a different number in one of our .cpp files? It will compile fine and we will have no way of knowing which one wins until we run the program.

Never put executed code into a header for the same reason that you never #include a .cpp file.

include guards (which I agree you should always use) protect you from something different: the same header being indirectly #included multiple times while compiling a single .cpp file

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

We have the following string which is a valid JSON ...

Clearly the JSON parser disagrees!

However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.

You need to find what JSON is actually being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for JsonParseException ... then find out what is in the ByteArrayInputStream that it is attempting to parse.

Get values from label using jQuery

Firstly, I don't think spaces for an id is valid.

So i'd change the id to not include spaces.

<label year="2010" month="6" id="currentMonth"> June &nbsp;2010</label>

then the jquery code is simple (keep in mind, its better to fetch the jquery object once and use over and over agian)

var label = $('#currentMonth');
var month = label.attr('month');
var year = label.attr('year');
var text = label.text();

Syntax for a single-line Bash infinite while loop

For simple process watching use watch instead

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

How to get access to job parameters from ItemReader, in Spring Batch?

As was stated, your reader needs to be 'step' scoped. You can accomplish this via the @Scope("step") annotation. It should work for you if you add that annotation to your reader, like the following:

import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("foo-reader")
@Scope("step")
public final class MyReader implements ItemReader<MyData> {
  @Override
  public MyData read() throws Exception {
    //...
  }

  @Value("#{jobParameters['fileName']}")
  public void setFileName(final String name) {
    //...
  }
}

This scope is not available by default, but will be if you are using the batch XML namespace. If you are not, adding the following to your Spring configuration will make the scope available, per the Spring Batch documentation:

<bean class="org.springframework.batch.core.scope.StepScope" />

how to specify local modules as npm package dependencies

At work we have a common library that is used by a few different projects all in a single repository. Originally we used the published (private) version (npm install --save rp-utils) but that lead to a lot of needless version updates as we developed. The library lives in a sister directory to the applications and we are able to use a relative path instead of a version. Instead of "rp-utils": "^1.3.34" in package.json it now is:

{ 
  "dependencies": { ...
    "rp-utils": "../rp-utils",
   ...

the rp-utils directory contains a publishable npm package

TypeError: unhashable type: 'dict', when dict used as a key for another dict

What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.

" app-release.apk" how to change this default generated apk name

android studio 4.1.1

applicationVariants.all { variant ->
  variant.outputs.all { output ->
    def reversion = "118"
    def date = new java.text.SimpleDateFormat("yyyyMMdd").format(new Date())
    def versionName = defaultConfig.versionName
    outputFileName = "MyApp_${versionName}_${date}_${reversion}.apk"
  }
}