Programs & Examples On #Virtual keyboard

A virtual keyboard is a software component that allows a user to enter characters. A virtual keyboard can usually be operated with multiple input devices, which may include a touchscreen, an actual Computer keyboard and a computer mouse.

Close virtual keyboard on button press

Try this...

  1. For Showing keyboard

    editText.requestFocus();
    InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    
  2. For Hide keyboard

    InputMethodManager inputManager = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE); 
    inputManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    

How do I make Visual Studio pause after executing a console application in debug mode?

Or you could use boost_test "Test Log Output."

http://www.boost.org/doc/libs/1_47_0/libs/test/doc/html/utf/user-guide/test-output/test-log.html

Then it won't matter whether the console window shows up at all AND your build logging can preserve the unit testing output as an artifact for examination on failed builds...

How to read barcodes with the camera on Android?

It's not built into the SDK, but you can use the Zxing library. It's free, open source, and Apache-licensed.

The 2016 recommendation is to use the Barcode API, which also works offline.

100% width background image with an 'auto' height

You can use the CSS property background-size and set it to cover or contain, depending your preference. Cover will cover the window entirely, while contain will make one side fit the window thus not covering the entire page (unless the aspect ratio of the screen is equal to the image).

Please note that this is a CSS3 property. In older browsers, this property is ignored. Alternatively, you can use javascript to change the CSS settings depending on the window size, but this isn't preferred.

body {
    background-image: url(image.jpg); /* image */
    background-position: center;      /* center the image */
    background-size: cover;           /* cover the entire window */
}

Razor View Without Layout

Use:

@{
    Layout = null;
 }

to get rid of the layout specified in _ViewStart.

How to detect IE11?

IE11 no longer reports as MSIE, according to this list of changes it's intentional to avoid mis-detection.

What you can do if you really want to know it's IE is to detect the Trident/ string in the user agent if navigator.appName returns Netscape, something like (the untested);

_x000D_
_x000D_
function getInternetExplorerVersion()_x000D_
{_x000D_
  var rv = -1;_x000D_
  if (navigator.appName == 'Microsoft Internet Explorer')_x000D_
  {_x000D_
    var ua = navigator.userAgent;_x000D_
    var re = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");_x000D_
    if (re.exec(ua) != null)_x000D_
      rv = parseFloat( RegExp.$1 );_x000D_
  }_x000D_
  else if (navigator.appName == 'Netscape')_x000D_
  {_x000D_
    var ua = navigator.userAgent;_x000D_
    var re  = new RegExp("Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})");_x000D_
    if (re.exec(ua) != null)_x000D_
      rv = parseFloat( RegExp.$1 );_x000D_
  }_x000D_
  return rv;_x000D_
}_x000D_
_x000D_
console.log('IE version:', getInternetExplorerVersion());
_x000D_
_x000D_
_x000D_

Note that IE11 (afaik) still is in preview, and the user agent may change before release.

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

Find size and free space of the filesystem containing a given file

For the second part of your question, "get usage statistics of the given partition", psutil makes this easy with the disk_usage(path) function. Given a path, disk_usage() returns a named tuple including total, used, and free space expressed in bytes, plus the percentage usage.

Simple example from documentation:

>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)

Psutil works with Python versions from 2.6 to 3.6 and on Linux, Windows, and OSX among other platforms.

Count the number of items in my array list

The number of itemIds in your list will be the same as the number of elements in your list:

int itemCount = list.size();

However, if you're looking to count the number of unique itemIds (per @pst) then you should use a set to keep track of them.

Set<String> itemIds = new HashSet<String>();

//...
itemId = p.getItemId();
itemIds.add(itemId);

//... later ...
int uniqueItemIdCount = itemIds.size();

How to detect a mobile device with JavaScript?

Similar to several of the answers above. This simple function, works very well for me. It is current as of 2019

function IsMobileCard()
{
var check =  false;

(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);

return check;   
}

Search in lists of lists by given index

I think using nested list comprehensions is the most elegant way to solve this, because the intermediate result is the position where the element is. An implementation would be:

list =[ ['a','b'], ['a','c'], ['b','d'] ]
search = 'c'
any([ (list.index(x),x.index(y)) for x in list for y in x if y == search ] )

Spring Boot War deployed to Tomcat

Solution for people using Gradle

Add plugin to build.gradle

apply plugin: 'war'

Add provided dependency to tomcat

dependencies {
    // other dependencies
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}

How do I register a DLL file on Windows 7 64-bit?

Well, you don't specify if it's a 32 or 64 bit dll and you don't include the error message, but I'll guess that it's the same issue as described in this KB article: Error Message When You Run Regsvr32.exe on 64-Bit Windows

Quote from that article:

This behavior occurs because the Regsvr32.exe file in the System32 folder is a 64-bit version. When you run Regsvr32 to register a DLL, you are using the 64-bit version by default.

Solution from that article:

To resolve this issue, run Regsvr32.exe from the %SystemRoot%\Syswow64 folder. For example, type the following commands to register the DLL: cd \windows\syswow64 regsvr32 c:\filename.dll

SQL to Entity Framework Count Group-By

Here is a simple example of group by in .net core 2.1

var query = this.DbContext.Notifications.
            Where(n=> n.Sent == false).
            GroupBy(n => new { n.AppUserId })
            .Select(g => new { AppUserId = g.Key, Count =  g.Count() });

var query2 = from n in this.DbContext.Notifications
            where n.Sent == false
            group n by n.AppUserId into g
            select new { id = g.Key,  Count = g.Count()};

Which translates to:

SELECT [n].[AppUserId], COUNT(*) AS [Count]
FROM [Notifications] AS [n]
WHERE [n].[Sent] = 0
GROUP BY [n].[AppUserId]

Apply CSS rules to a nested class inside a div

You use

#main_text .title {
  /* Properties */
}

If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text with the class name title. If you use > instead of a space, it will only select the direct child of the element, and not children of children, e.g.:

#main_text > .title {
  /* Properties */
}

Either will work in this case, but the first is more typically used.

How to use border with Bootstrap

What others have mentioned about border vs border box is definitely correct. You can still get this to work without having to create any custom classes though: http://jsfiddle.net/panchroma/yfzdD/

HTML

<div class="container">
<div class="row" >
    <div class="span12">
       <div class="row">
        <div class="span4"> 1 </div>
        <div class="span4"> 2 </div>
        <div class="span4"> 3 </div>
        </div><!-- end nested row -->
    </div><!-- end span 12 -->

</div> <!-- end row -->
</div><!-- end container -->

CSS

.span12{
border:solid 2px black;
background-color:grey;  
}  

Good luck!

Use curly braces to initialize a Set in Python

Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.

Excel: Search for a list of strings within a particular string using array formulas?

This will return the matching word or an error if no match is found. For this example I used the following.

List of words to search for: G1:G7
Cell to search in: A1

=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))

Enter as an array formula by pressing Ctrl+Shift+Enter.

This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

To return the row number of a matching word, you can use the following:

=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))

This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

Write / add data in JSON file using Node.js

Above example is also correct, but i provide simple example:

var fs = require("fs");
var sampleObject = {
    name: 'pankaj',
    member: 'stack',
    type: {
        x: 11,
        y: 22
    }
};

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {
        console.error(err);
        return;
    };
    console.log("File has been created");
});

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

Android : difference between invisible and gone?

For ListView or GridView there is an another difference, when visibility initially set to

INVISIBLE:

Adapter's getView() function called

GONE:

Adapter's getView() function didn't call, thus preventing views to load, when it is unnecessary

Bootstrap 3 panel header with buttons wrong position

You are part right. with <b>title</b> it looks fine, but I would like to use <h4>.

I have put <h4 style="display: inline;"> and it seams to work.

Now, I only need to add some vertival align.

placeholder for select tag

<select>

    <option selected="selected" class="Country">Country Name</option>

    <option value="1">India</option>

    <option value="2">us</option>

</select>

.country
{


    display:none;
}

</style>

Python: Assign print output to a variable

probably you need one of str,repr or unicode functions

somevar = str(tag.getArtist())

depending which python shell are you using

Attempt to write a readonly database - Django w/ SELinux error

This issue is caused by SELinux. After setting file ownership just as you did, I hit this issue. The audit2why(1) tool can be used to diagnose SELinux denials from the log:

(django)[f22-4:www/django/demo] ftweedal% sudo audit2why -a
type=AVC msg=audit(1437490152.208:407): avc:  denied  { write }
      for  pid=20330 comm="httpd" name="db.sqlite3" dev="dm-1" ino=52036
      scontext=system_u:system_r:httpd_t:s0
      tcontext=unconfined_u:object_r:httpd_sys_content_t:s0
      tclass=file permissive=0
    Was caused by:
    The boolean httpd_unified was set incorrectly. 
    Description:
    Allow httpd to unified

    Allow access by executing:
    # setsebool -P httpd_unified 1

Sure enough, running sudo setsebool -P httpd_unified 1 resolved the issue.

Looking into what httpd_unified is for, I came across a fedora-selinux-list post which explains:

This Boolean is off by default, turning it on will allow all httpd executables to have full access to all content labeled with a http file context. Leaving it off makes sure that one httpd service can not interfere with another.

So turning on httpd_unified lets you circumvent the default behaviour that prevents multiple httpd instances on the same server - all running as user apache - messing with each others' stuff.

In my case, I am only running one httpd, so it was fine for me to turn on httpd_unified. If you cannot do this, I suppose some more fine-grained labelling is needed.

Finding child element of parent pure javascript

Just adding another idea you could use a child selector to get immediate children

document.querySelectorAll(".parent > .child1");

should return all the immediate children with class .child1

error 1265. Data truncated for column when trying to load data from txt file

I had same problem. I wanted to edit ENUM values in table structure. Problem was because of rows that was saved before and new ENUM values doesn't contain saved values.

Solution was updating old saved rows in MySql table.

How to select all records from one table that do not exist in another table?

You can either do

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT name 
     FROM table1)

or

SELECT name 
FROM table2 
WHERE NOT EXISTS 
    (SELECT * 
     FROM table1 
     WHERE table1.name = table2.name)

See this question for 3 techniques to accomplish this

Why Maven uses JDK 1.6 but my java -version is 1.7

Please check the compatibility. I struggled with mvn 3.2.1 and jdk 1.6.0_37 for many hours. All variables were set but was not working. Finally I upgraded jdk to 1.8.0_60 and mvn 3.3.3 and that worked. Environment Variables as following:

JAVA_HOME=C:\ProgramFiles\Java\jdk1.8.0_60 
MVN_HOME=C:\ProgramFiles\apache-maven\apache-maven-3.3.3 
M2=%MVN_HOME%\bin extend system level Path- ;%M2%;%JAVA_HOME%\bin;

Creating a ZIP archive in memory using System.IO.Compression

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program`enter code here`
    {
        static void Main(string[] args)
        {
            using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                            writer.WriteLine("Information about this package.");
                            writer.WriteLine("========================");
                    }
                }
            }
        }
    }
}

Logger slf4j advantages of formatting with {} instead of string concatenation

It is about string concatenation performance. It's potentially significant if your have dense logging statements.

(Prior to SLF4J 1.7) But only two parameters are possible

Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.

For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }. There should be few enough of them that the performance is not as important.

why windows 7 task scheduler task fails with error 2147942667

I had the same problem, on Windows7.

I was getting error 2147942667 and a report of being unable to run c:\windows\system32\CMD.EXE. I tried with and without double quotes in the Script and Start-in and it made no difference. Then I tried replacing all path references to mapped network drives and with UNC references (\Server1\Sharexx\my_scripts\run_this.cmd) and that fixed it for me. Pat.

Get Application Name/ Label via ADB Shell or Terminal

Inorder to find an app's name (application label), you need to do the following:
(as shown in other answers)

  1. Find the APK path of the app whose name you want to find.
  2. Using aapt command, find the app label.

But devices don't ship with the aapt binary out-of-the-box.
So you will need to install it first. You can download it from here:
https://github.com/Calsign/APDE/tree/master/APDE/src/main/assets/aapt-binaries


Check this guide for complete steps:
How to find an app name using package name through ADB Android?
(Disclaimer: I am the author of that blog post)

Deny all, allow only one IP through htaccess

Just in addition to @David Brown´s answer, if you want to block an IP, you must first allow all then block the IPs as such:

    <RequireAll>
      Require all granted
      Require not ip 10.0.0.0/255.0.0.0
      Require not ip 172.16.0.0/12
      Require not ip 192.168
    </RequireAll>

First line allows all
Second line blocks from 10.0.0.0 to 10.255.255.255
Third line blocks from 172.16.0.0 to 172.31.255.255
Fourth line blocks from 192.168.0.0 to 192.168.255.255

You may use any of the notations mentioned above to suit you CIDR needs.

Bash write to file without echo?

awk ' BEGIN { print "Hello, world" } ' > test.txt

would do it

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

Getting the client's time zone (and offset) in JavaScript

On the new Date() you can get the offset, to get the timezone name you may do:

new Date().toString().replace(/(.*\((.*)\).*)/, '$2');

you get the value between () in the end of the date, that is the name of the timezone.

Internal vs. Private Access Modifiers

internal members are accessible within the assembly (only accessible in the same project)

private members are accessible within the same class

Example for Beginners

There are 2 projects in a solution (Project1, Project2) and Project1 has a reference to Project2.

  • Public method written in Project2 will be accessible in Project2 and the Project1
  • Internal method written in Project2 will be accessible in Project2 only but not in Project1
  • private method written in class1 of Project2 will only be accessible to the same class. It will neither be accessible in other classes of Project 2 not in Project 1.

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Basically, what this error is saying is that if you are going to use the GROUP BY clause, then your result is going to be a relation/table with a row for each group, so in your SELECT statement you can only "select" the column that you are grouping by and use aggregate functions on that column because the other columns will not appear in the resulting table.

How to convert a Java 8 Stream to an Array?

You can do it in a few ways.All the ways are technically the same but using Lambda would simplify some of the code. Lets say we initialize a List first with String, call it persons.

List<String> persons = new ArrayList<String>(){{add("a"); add("b"); add("c");}};
Stream<String> stream = persons.stream();

Now you can use either of the following ways.

  1. Using the Lambda Expresiion to create a new StringArray with defined size.

    String[] stringArray = stream.toArray(size->new String[size]);

  2. Using the method reference directly.

    String[] stringArray = stream.toArray(String[]::new);

Read and write a String from text file

For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground.

Swift 3.x - 5.x

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

    let fileURL = dir.appendingPathComponent(file)

    //writing
    do {
        try text.write(to: fileURL, atomically: false, encoding: .utf8)
    }
    catch {/* error handling here */}

    //reading
    do {
        let text2 = try String(contentsOf: fileURL, encoding: .utf8)
    }
    catch {/* error handling here */}
}

Swift 2.2

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
    let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)

    //writing
    do {
        try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
    }
    catch {/* error handling here */}

    //reading
    do {
        let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
    }
    catch {/* error handling here */}
}

Swift 1.x

let file = "file.txt"

if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
    let dir = dirs[0] //documents directory
    let path = dir.stringByAppendingPathComponent(file);
    let text = "some text"

    //writing
    text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

    //reading
    let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}

How to connect to my http://localhost web server from Android Emulator

The localhost refers to the device on which the code is running, in this case the emulator.

If you want to refer to the computer which is running the Android simulator, use the IP address 10.0.2.2 instead.

enter image description here

You can read more from here.

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

Use a Backbone.js or AngularJS-like JavaScript framework for UI design and fetch the data using a REST API. This will remove the Java dependency from the UI completely.

Calculating Page Table Size

My explanation uses elementary building blocks that helped me to understand. Note I am leveraging @Deepak Goyal's answer above since he provided clarity:

We were given a logical 32-bit address space (i.e. We have a 32 bit computer)

Consider a system with a 32-bit logical address space

We were also told that

each page size is 4 KB

  • 1 KB (kilobyte) = 1 x 1024 bytes = 2^10 bytes
  • 4 x 1024 bytes = 2^2 x 2^10 bytes => 4 KB (i.e. 2^12 bytes)
  • The size of each page is thus 4 KB (Kilobytes NOT kilobits).

As Depaak said, we calculate the number of pages in the page table with this formula:

Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size 
Num_Pages_in_PgTable =         2^32                           /    2^12
Num_Pages_in_PgTable = 2^20 (i.e. 1 million) 

The authors go on to give the case where each entry in the page table takes 4 bytes. That means that the total size of the page table in physical memory will be 4MB:

Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable
Memory_Required_Per_Page =           4                 x     2^20
Memory_Required_Per_Page =     4 MB (Megabytes)

So yes, each process would require at least 4MB of memory to run, in increments of 4MB.

Example

Now if a professor wanted to make the question a bit more challenging than the explanation from the book, they might ask about a 64-bit computer. Let's say they want memory in bits. To solve the question, we'd follow the same process, only being sure to convert MB to Mbits.

Let's step through this example.

Givens:

  • Logical address space: 64-bit
  • Page Size: 4KB
  • Entry_Size_Per_Page: 4 bytes

Recall: A 64-bit entry can point to one of 2^64 physical page frames - Since Page size is 4 KB, then we still have 2^12 byte page sizes

  • 1 KB (kilobyte) = 1 x 1024 bytes = 2^10 bytes
  • Size of each page = 4 x 1024 bytes = 2^2 x 2^10 bytes = 2^12 bytes

How Many pages In Page Table?

`Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size 
Num_Pages_in_PgTable =         2^64                            /    2^12
Num_Pages_in_PgTable =         2^52 
Num_Pages_in_PgTable =      2^2 x 2^50 
Num_Pages_in_PgTable =       4  x 2^50 `  

How Much Memory in BITS Per Page?

Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable 
Memory_Required_Per_Page =   4 bytes x 8 bits/byte    x     2^52
Memory_Required_Per_Page =     32 bits                x   2^2 x 2^50
Memory_Required_Per_Page =     32 bits                x    4  x 2^50
Memory_Required_Per_Page =     128 Petabits

[2]: Operating System Concepts (9th Ed) - Gagne, Silberschatz, and Galvin

npm start error with create-react-app

Add .env file with "SKIP_PREFLIGHT_CHECK=true" than npm start

twitter bootstrap navbar fixed top overlapping site

As others have stated adding a padding-top to body works great. But when you make the screen narrower (to cell phone widths) there is a gap between the navbar and the body. Also, a crowded navbar can wrap to a multi-line bar, overwriting some of the content again.

This solved these kinds of issues for me

body { padding-top: 40px; }
@media screen and (max-width: 768px) {
    body { padding-top: 0px; }
}

This makes a 40px padding by default and 0px when under 768px width (which according to bootstrap's docs is the cell phone layout cutoff where the gap would be created)

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

If the extra entries in the log bother you but an extra second of start-up time doesn't, just add this to your logging.properties and forget about it:

org.apache.jasper.servlet.TldScanner.level = WARNING

T-SQL: Looping through an array of known values

use a static cursor variable and a split function:

declare @comma_delimited_list varchar(4000)
set @comma_delimited_list = '4,7,12,22,19'

declare @cursor cursor
set @cursor = cursor static for 
  select convert(int, Value) as Id from dbo.Split(@comma_delimited_list) a

declare @id int
open @cursor
while 1=1 begin
  fetch next from @cursor into @id
  if @@fetch_status <> 0 break
  ....do something....
end
-- not strictly necessary w/ cursor variables since they will go out of scope like a normal var
close @cursor
deallocate @cursor

Cursors have a bad rep since the default options when declared against user tables can generate a lot of overhead.

But in this case the overhead is quite minimal, less than any other methods here. STATIC tells SQL Server to materialize the results in tempdb and then iterate over that. For small lists like this, it's the optimal solution.

Radio/checkbox alignment in HTML/CSS

There are several ways to implement it:

  1. For ASP.NET Standard CheckBox:

    .tdInputCheckBox
    { 
    position:relative;
    top:-2px;
    }
    <table>
            <tr>
                <td class="tdInputCheckBox">                  
                    <asp:CheckBox ID="chkMale" runat="server" Text="Male" />
                    <asp:CheckBox ID="chkFemale" runat="server" Text="Female" />
                </td>
            </tr>
    </table>
    
  2. For DevExpress CheckBox:

    <dx:ASPxCheckBox ID="chkAccept" runat="server" Text="Yes" Layout="Flow"/>
    <dx:ASPxCheckBox ID="chkAccept" runat="server" Text="No" Layout="Flow"/>
    
  3. For RadioButtonList:

    <asp:RadioButtonList ID="rdoAccept" runat="server" RepeatDirection="Horizontal">
       <asp:ListItem>Yes</asp:ListItem>
       <asp:ListItem>No</asp:ListItem>
    </asp:RadioButtonList>
    
  4. For Required Field Validators:

    <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="reqEmailId" runat="server" ErrorMessage="Email id is required." Display="Dynamic" ControlToValidate="txtEmailId"></asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator ID="regexEmailId" runat="server" ErrorMessage="Invalid Email Id." ControlToValidate="txtEmailId" Text="*"></asp:RegularExpressionValidator>`
    

How can I get the current contents of an element in webdriver

In Java its Webelement.getText() . Not sure about python.

Get the system date and split day, month and year

Without opening an IDE to check my brain works properly for syntax at this time of day...

If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.

So

DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");

would give you the date as a string in the format you request.

Error Code: 2013. Lost connection to MySQL server during query

I had this error message due to a problem after of upgrade Mysql. The error appeared immediately after I tried to do any query

Check mysql error log files in path /var/log/mysql (linux)

In my case reassigning Mysql owner to the Mysql system folder worked for me

chown -R mysql:mysql /var/lib/mysql

How to print pandas DataFrame without index

If you want to pretty print the data frames, then you can use tabulate package.

import pandas as pd
import numpy as np
from tabulate import tabulate

def pprint_df(dframe):
    print tabulate(dframe, headers='keys', tablefmt='psql', showindex=False)

df = pd.DataFrame({'col1': np.random.randint(0, 100, 10), 
    'col2': np.random.randint(50, 100, 10), 
    'col3': np.random.randint(10, 10000, 10)})

pprint_df(df)

Specifically, the showindex=False, as the name says, allows you to not show index. The output would look as follows:

+--------+--------+--------+
|   col1 |   col2 |   col3 |
|--------+--------+--------|
|     15 |     76 |   5175 |
|     30 |     97 |   3331 |
|     34 |     56 |   3513 |
|     50 |     65 |    203 |
|     84 |     75 |   7559 |
|     41 |     82 |    939 |
|     78 |     59 |   4971 |
|     98 |     99 |    167 |
|     81 |     99 |   6527 |
|     17 |     94 |   4267 |
+--------+--------+--------+

Unique device identification

It looks like the phoneGap plugin will allow you to get the device's uid.

http://docs.phonegap.com/en/3.0.0/cordova_device_device.md.html#device.uuid

Update: This is dependent on running native code. We used this solution writing javascript that was being compiled to native code for a native phone application we were creating.

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

Definitions:

  • Frame Layout: This is designed to block out an area on the screen to display a single item.
  • Linear Layout: A layout that arranges its children in a single column or a single row.
  • Relative Layout: This layout is a view group that displays child views in relative positions.
  • Table Layout: A layout that arranges its children into rows and columns.

More Information:

FrameLayout

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.

Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).

RelativeLayout

A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.

(Current docs here)

TableLayout

A TableLayout consists of a number of TableRow objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.

The width of a column is defined by the row with the widest cell in that column.


Note: Absolute Layout is deprecated.

How to include() all PHP files from a directory?

Here is the way I include lots of classes from several folders in PHP 5. This will only work if you have classes though.

/*Directories that contain classes*/
$classesDir = array (
    ROOT_DIR.'classes/',
    ROOT_DIR.'firephp/',
    ROOT_DIR.'includes/'
);
function __autoload($class_name) {
    global $classesDir;
    foreach ($classesDir as $directory) {
        if (file_exists($directory . $class_name . '.php')) {
            require_once ($directory . $class_name . '.php');
            return;
        }
    }
}

Receiving JSON data back from HTTP request

Install this nuget package from Microsoft System.Net.Http.Json. It contains extension methods.

Then add using System.Net.Http.Json

Now, you'll be able to see these methods:

enter image description here

So you can now do this:

await httpClient.GetFromJsonAsync<IList<WeatherForecast>>("weatherforecast");

Source: https://www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json

What's the easy way to auto create non existing dir in ansible

If you are running Ansible >= 2.0 there is also the dirname filter you can use to extract the directory part of a path. That way you can just use one variable to hold the entire path to make sure both tasks never get out of sync.

So for example if you have playbook with dest_path defined in a variable like this you can reuse the same variable:

- name: My playbook
  vars:
    dest_path: /home/ubuntu/some_dir/some_file.txt
  tasks:

    - name: Make sure destination dir exists
      file:
        path: "{{ dest_path | dirname }}"
        state: directory
        recurse: yes

    # now this task is always save to run no matter how dest_path get's changed arround
    - name: Add file or template to remote instance
      template: 
        src: foo.txt.j2
        dest: "{{ dest_path }}"

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

is there any PHP function for open page in new tab

You can use both PHP and javascript. Perform your php codes in the backend and redirect to a php page. On the php page you redirected to add the code below:

<?php if(condition_to_check_for){ ?>

    <script type="text/javascript">
       window.open('url_goes_here', '_blank');
    </script>

<?  } ?>

How do I convert uint to int in C#?

Take note of the checked and unchecked keywords.

It matters if you want the result truncated to the int or an exception raised if the result doesnt fit in signed 32 bits. The default is unchecked.

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

What's the difference between import java.util.*; and import java.util.Date; ?

Your program should work exactly the same with either import java.util.*; or import java.util.Date;. There has to be something else you did in between.

importing pyspark in python shell

Turns out that the pyspark bin is LOADING python and automatically loading the correct library paths. Check out $SPARK_HOME/bin/pyspark :

# Add the PySpark classes to the Python path:
export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH

I added this line to my .bashrc file and the modules are now correctly found!

Can anyone explain python's relative imports?

If you are going to call relative.py directly and i.e. if you really want to import from a top level module you have to explicitly add it to the sys.path list.
Here is how it should work:

# Add this line to the beginning of relative.py file
import sys
sys.path.append('..')

# Now you can do imports from one directory top cause it is in the sys.path
import parent

# And even like this:
from parent import Parent

If you think the above can cause some kind of inconsistency you can use this instead:

sys.path.append(sys.path[0] + "/..")

sys.path[0] refers to the path that the entry point was ran from.

T-SQL: How to Select Values in Value List that are NOT IN the Table?

You need to somehow create a table with these values and then use NOT IN. This can be done with a temporary table, a CTE (Common Table Expression) or a Table Values Constructor (available in SQL-Server 2008):

SELECT email
FROM
    ( VALUES 
        ('email1')
      , ('email2')
      , ('email3')
    ) AS Checking (email)
WHERE email NOT IN 
      ( SELECT email 
        FROM Users
      ) 

The second result can be found with a LEFT JOIN or an EXISTS subquery:

SELECT email
     , CASE WHEN EXISTS ( SELECT * 
                          FROM Users u
                          WHERE u.email = Checking.email
                        ) 
            THEN 'Exists'
            ELSE 'Not exists'
       END AS status 
FROM
    ( VALUES 
        ('email1')
      , ('email2')
      , ('email3')
    ) AS Checking (email)

How to configure socket connect timeout

it might be too late but there is neat solution based on Task.WaitAny (c# 5 +) :

 public static bool ConnectWithTimeout(this Socket socket, string host, int port, int timeout)
        {
            bool connected = false;
            Task result = socket.ConnectAsync(host, port);               
            int index = Task.WaitAny(new[] { result }, timeout);
            connected = socket.Connected;
            if (!connected) {
              socket.Close();
            }

            return connected;
        }

MySQL foreach alternative for procedure

This can be done with MySQL, although it's highly unintuitive:

CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
  DECLARE a,b INT;
  DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET b = 1;
  OPEN cur_1;
  REPEAT
    FETCH cur_1 INTO a;
    UNTIL b = 1
  END REPEAT;
  CLOSE cur_1;
  SET return_val = a;
END;//

Check out this guide: mysql-storedprocedures.pdf

Show Error on the tip of the Edit Text Android

I got the solution of my problem Hope this will help others also.I have used onTextChnaged it invokes When an object of a type is attached to an Editable, its methods will be called when the text is changed.

public class MainActivity extends Activity {
    TextView emailId;
    ImageView continuebooking;
    EditText firstName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        emailId = (TextView)findViewById(R.id.emailid);
        continuebooking = (ImageView)findViewById(R.id.continuebooking);
        firstName= (EditText)findViewById(R.id.firstName);
        emailId.setText("[email protected]");
        setTittle();
        continuebooking.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if(firstName.getText().toString().trim().equalsIgnoreCase("")){
                    firstName.setError("Enter FirstName");
                }

            }
        });
        firstName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                firstName.setError(null);

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                firstName.setError(null);

            }
        });
    }

How to execute a Python script from the Django shell?

Other way it's execute this one:

echo 'execfile("/path_to/myscript.py")' | python manage.py shell --settings=config.base

This is working on Python2.7 and Django1.9

How to use NULL or empty string in SQL

youe check null With IS NULL and string Empty With LEN(RTRIM(LTRIM(Column))) = 0 in

SELECT *
FROM AppInfra.Person
WHERE   LEN(RTRIM(LTRIM(NationalCode))) = 0 OR  NationalCode IS NULL

Get first element from a dictionary

convert to Array

var array = like.ToArray();
var first = array[0];

Re-assign host access permission to MySQL user

Similar issue where I was getting permissions failed. On my setup, I SSH in only. So What I did to correct the issue was

sudo MySQL
SELECT User, Host FROM mysql.user WHERE Host <> '%';
MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | 192.168.0.% |
| bar   | 192.168.0.% |
+-------+-------------+
4 rows in set (0.00 sec)

I need these users moved to 'localhost'. So I issued the following:

UPDATE mysql.user SET host = 'localhost' WHERE user = 'foo';
UPDATE mysql.user SET host = 'localhost' WHERE user = 'bar';

Run SELECT User, Host FROM mysql.user WHERE Host <> '%'; again and we see:

MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | localhost   |
| bar   | localhost   |
+-------+-------------+
4 rows in set (0.00 sec)

And then I was able to work normally again. Hope that helps someone.

$ mysql -u foo -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 74
Server version: 10.1.23-MariaDB-9+deb9u1 Raspbian 9.0

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

Twitter Bootstrap onclick event on buttons-radio

I searched so many pages: I found a beautiful solution. Check it out:

git link

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

    <script>
        $(function() {
            $("#my_launch_today_chk").change(function() {
                var chk = $(this).prop('checked');
                if(chk == true){
                    console.log("On");
                }else{
                    console.log("OFF");
                }
            });
        });
    </script>
</head>
<body >

<input type="checkbox" id="my_launch_today_chk" checked data-on="Launch" data-off="OFF" data-toggle="toggle" data-size="small">
</body>
</html>

how to make a full screen div, and prevent size to be changed by content?

I use this approach for drawing a modal overlay.

.fullDiv { width:100%; height:100%; position:fixed }

I believe the distinction here is the use of position:fixed which may or may not be applicable to your use case.

I also add z-index:1000; background:rgba(50,50,50,.7);

Then, the modal content can live inside that div, and any content that was already on the page remains visible in the background but covered by the overlay fully while scrolling.

Editor does not contain a main type in Eclipse

Make sure you do Run As > Java Application.

If not you could try a Project > Clean

Some more questions that deals with this that could be helpful, Refer this

Can we update primary key values of a table?

Primary key attributes are just as updateable as any other attributes of a table. Stability is often a desirable property of a key but definitely not an absolute requirement. If it makes sense from a business perpective to update a key then there's no fundamental reason why you shouldn't.

How to convert a plain object into an ES6 Map?

ES6

convert object to map:

const objToMap = (o) => new Map(Object.entries(o));

convert map to object:

const mapToObj = (m) => [...m].reduce( (o,v)=>{ o[v[0]] = v[1]; return o; },{} )

Note: the mapToObj function assumes map keys are strings (will fail otherwise)

What is the difference between lower bound and tight bound?

Big O is the upper bound, while Omega is the lower bound. Theta requires both Big O and Omega, so that's why it's referred to as a tight bound (it must be both the upper and lower bound).

For example, an algorithm taking Omega(n log n) takes at least n log n time, but has no upper limit. An algorithm taking Theta(n log n) is far preferential since it takes at least n log n (Omega n log n) and no more than n log n (Big O n log n).

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

How can I create an editable combo box in HTML/Javascript?

I know this question is already answered, a long time ago, but this is for other people that may end up here and are having trouble finding what they need. I had trouble finding an existing plugin that did exactly what I needed, so I wrote my own jQuery UI plugin to accomplish this task. It's based on the combobox example on the jQuery UI site. Hopefully it might help someone.

https://github.com/tmooney3979/jquery.ui.combify

HTML 5 input type="number" element for floating point numbers on Chrome

Try this

_x000D_
_x000D_
<input onkeypress='return event.charCode >= 48 && _x000D_
                          event.charCode <= 57 || _x000D_
                          event.charCode == 46'>
_x000D_
_x000D_
_x000D_

How to make a new line or tab in <string> XML (eclipse/android)?

You can use \n for new line and \t for tabs. Also, extra spaces/tabs are just copied the way you write them in Strings.xml so just give a couple of spaces where ever you want them.

A better way to reach this would probably be using padding/margin in your view xml and splitting up your long text in different strings in your string.xml

Android: adb pull file on desktop

Use a fully-qualified path to the desktop (e.g., /home/mmurphy/Desktop).

Example: adb pull sdcard/log.txt /home/mmurphy/Desktop

How to return the output of stored procedure into a variable in sql server

With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)

From this: 
declare @anID int
exec @anID = dbo.StoredProc_Fetch @ID, @anotherID, @finalID
exec dbo.ADifferentStoredProc @anID (no value here)

To this:
declare @t table(id int) 
declare @anID int
insert into @t exec dbo.StoredProc_Fetch @ID, @anotherID, @finalID
set @anID= (select Top 1 * from @t)

What do these operators mean (** , ^ , %, //)?

  • **: exponentiation
  • ^: exclusive-or (bitwise)
  • %: modulus
  • //: divide with integral result (discard remainder)

C# Interfaces. Implicit implementation versus Explicit implementation

One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.

The problem and solution are well explained in the article C# Internal Interface.

For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

If you dont find Hyper-V option in control panel as said in other responses here, try entering BIOS setup (restarting and pressing F-12 or ESC or other depending on your PC) and enabling Virtualization, located probably in CPU options.

Manifest Merger failed with multiple errors in Android Studio

Supplement the answer Phan Van Linh. I deleted these lines:

  android:icon="@mipmap/ic_launcher"
  android:label="name"

How to change the font color of a disabled TextBox?

You can try this. Override the OnPaint event of the TextBox.

    protected override void OnPaint(PaintEventArgs e)
{
     SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
     // Draw string to screen.
     e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property
}

set the ControlStyles to "UserPaint"

public MyTextBox()//constructor
{
     // This call is required by the Windows.Forms Form Designer.
     this.SetStyle(ControlStyles.UserPaint,true);

     InitializeComponent();

     // TODO: Add any initialization after the InitForm call
}

Refrence

Or you can try this hack

In Enter event set the focus

int index=this.Controls.IndexOf(this.textBox1);

this.Controls[index-1].Focus();

So your control will not focussed and behave like disabled.

Passing an Array as Arguments, not an Array, in PHP

For sake of completeness, as of PHP 5.1 this works, too:

<?php
function title($title, $name) {
    return sprintf("%s. %s\r\n", $title, $name);
}
$function = new ReflectionFunction('title');
$myArray = array('Dr', 'Phil');
echo $function->invokeArgs($myArray);  // prints "Dr. Phil"
?>

See: http://php.net/reflectionfunction.invokeargs

For methods you use ReflectionMethod::invokeArgs instead and pass the object as first parameter.

jQuery Set Selected Option Using Next

This is what i just used, i like how clean it is :-)

$('select').val(function(){
    var nextOption = $(this).children(':selected').next();
    return $(nextOption).val();
}).change();

Get int value from enum in C#

Try this one instead of convert enum to int:

public static class ReturnType
{
    public static readonly int Success = 1;
    public static readonly int Duplicate = 2;
    public static readonly int Error = -1;        
}

How do I close a single buffer (out of many) in Vim?

Close buffer without closing the window

If you want to close a buffer without destroying your window layout (current layout based on splits), you can use a Plugin like bbye. Based on this, you can just use

:Bdelete (instead of :bdelete)
:Bwipeout (instead of :bwipeout)

Or just create a mapping in your .vimrc for easier access like

:nnoremap <Leader>q :Bdelete<CR>

Advantage over vim's :bdelete and :bwipeout

From the plugin's documentation:

  • Close and remove the buffer.
  • Show another file in that window.
  • Show an empty file if you've got no other files open.
  • Do not leave useless [no file] buffers if you decide to edit another file in that window.
  • Work even if a file's open in multiple windows.
  • Work a-okay with various buffer explorers and tabbars.

:bdelete vs :bwipeout

From the plugin's documentation:

Vim has two commands for closing a buffer: :bdelete and :bwipeout. The former removes the file from the buffer list, clears its options, variables and mappings. However, it remains in the jumplist, so Ctrl-o takes you back and reopens the file. If that's not what you want, use :bwipeout or Bbye's equivalent :Bwipeout where you would've used :bdelete.

Http Post request with content type application/x-www-form-urlencoded not working in Spring

The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.

Then try the following:

@RequestMapping(value = "/patientdetails", method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public @ResponseBody List<PatientProfileDto> getPatientDetails(
        PatientProfileDto name) {


    List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
    list = service.getPatient(name);
    return list;
}

Note that removed the annotation @RequestBody

What is C# analog of C++ std::pair?

C# has tuples as of version 4.0.

In Java, how do I get the difference in seconds between 2 dates?

Not familiar with DateTime...

If you have two Dates you can call getTime on them to get millseconds, get the diff and divide by 1000. For example

Date d1 = ...;
Date d2 = ...;
long seconds = (d2.getTime()-d1.getTime())/1000;

If you have Calendar objects you can call

c.getTimeInMillis()

and do the same

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

Here's a better approach where you don't have to delete/move anything for Android Studio 3.+.

  1. Open Android Studio and click cancel/ignore for error prompts on missing SDK for each project.
  2. Close all your open projects. You can do this by File > Close Project.
  3. After you do step 1 for all projects, the Welcome screen appears.
  4. The welcome screen will detect you are missing the SDK and give you options to fix the problem, i.e., install the SDKs for you.

How to get the error message from the error code returned by GetLastError()?

Updated (11/2017) to take into consideration some comments.

Easy example:

wchar_t buf[256];
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
               NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
               buf, (sizeof(buf) / sizeof(wchar_t)), NULL);

RSpec: how to test if a method was called?

In the new rspec expect syntax this would be:

expect(subject).to receive(:bar).with("an argument I want")

Dictionary text file

There's also WordNet. Its data files format are well-documented.
I used it for building an embeddable dictionary library for iOS developers (www.lexicontext.com) and also in one of my apps.

xampp MySQL does not start

Try this: really quick + worked for me:

  1. Open Task Manager > Services Tab
  2. Find "mysqlweb" service > right-click it to stop service
  3. Launch Xampp again

ps: excuse image below for different language :)

enter image description here

Read JSON data in a shell script

There is jq for parsing json on the command line:

 jq '.Body'

Visit this for jq: https://stedolan.github.io/jq/

Insert data through ajax into mysql database

The ajax is going to be a javascript snippet that passes information to a small php file that does what you want. So in your page, instead of all that php, you want a little javascript, preferable jquery:

function fun()
{
    $.get('\addEmail.php', {email : $(this).val()}, function(data) {
        //here you would write the "you ve been successfully subscribed" div
    });
}

also you input would have to be:

<input type="button" value="subscribe" class="submit" onclick="fun();" />

last the file addEmail.php should look something like:

mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");

error_reporting(E_ALL && ~E_NOTICE);

$email=mysql_real_escape_string($_GET['email']);
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
 if(!$sql)
die(mysql_error());

mysql_close();

Also sergey is right, you should use mysqli. That's not everything, but enough to get you started.

Modifying local variable from inside lambda

I had a slightly different problem. Instead of incrementing a local variable in the forEach, I needed to assign an object to the local variable.

I solved this by defining a private inner domain class that wraps both the list I want to iterate over (countryList) and the output I hope to get from that list (foundCountry). Then using Java 8 "forEach", I iterate over the list field, and when the object I want is found, I assign that object to the output field. So this assigns a value to a field of the local variable, not changing the local variable itself. I believe that since the local variable itself is not changed, the compiler doesn't complain. I can then use the value that I captured in the output field, outside of the list.

Domain Object:

public class Country {

    private int id;
    private String countryName;

    public Country(int id, String countryName){
        this.id = id;
        this.countryName = countryName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

Wrapper object:

private class CountryFound{
    private final List<Country> countryList;
    private Country foundCountry;
    public CountryFound(List<Country> countryList, Country foundCountry){
        this.countryList = countryList;
        this.foundCountry = foundCountry;
    }
    public List<Country> getCountryList() {
        return countryList;
    }
    public void setCountryList(List<Country> countryList) {
        this.countryList = countryList;
    }
    public Country getFoundCountry() {
        return foundCountry;
    }
    public void setFoundCountry(Country foundCountry) {
        this.foundCountry = foundCountry;
    }
}

Iterate operation:

int id = 5;
CountryFound countryFound = new CountryFound(countryList, null);
countryFound.getCountryList().forEach(c -> {
    if(c.getId() == id){
        countryFound.setFoundCountry(c);
    }
});
System.out.println("Country found: " + countryFound.getFoundCountry().getCountryName());

You could remove the wrapper class method "setCountryList()" and make the field "countryList" final, but I did not get compilation errors leaving these details as-is.

Simple prime number generator in Python

re is powerful:

import re


def isprime(n):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * n) is None

print [x for x in range(100) if isprime(x)]

###########Output#############
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

Differences:

1) Implicit wait is set for the entire duration of the webDriver object. Suppose , you want to wait for a certain duration, let's say 5 seconds before each element or a lot of elements on the webpage load. Now, you wouldn't want to write the same code again and again. Hence, implicit wait. However, if you want to wait for only one element, use explicit.

2) You not only need web element to show up but also to be clickable or to satisfy certain other property of web elements. Such kind of flexibility can be provided by explicit wait only. Specially helpful if dynamic data is being loaded on webpage. You can wait for that element to be developed (not just show up on DOM) using explicit wait.

How to get user name using Windows authentication in asp.net?

These are the different variables you have access to and their values, depending on the IIS configuration.

Scenario 1: Anonymous Authentication in IIS with impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           ASPNET                   
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 2: Windows Authentication in IIS, impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1   
HttpContext.Current.Request.IsAuthenticated           True             
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1   
System.Environment.UserName                           ASPNET           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 3: Anonymous Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           IUSR_SERVER1           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\IUSR_SERVER1 

Scenario 4: Windows Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated           True          
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1
System.Environment.UserName                           USER1         
Security.Principal.WindowsIdentity.GetCurrent().Name  MYDOMAIN\USER1

Legend
SERVER1\ASPNET: Identity of the running process on server.
SERVER1\IUSR_SERVER1: Anonymous guest user defined in IIS.
MYDOMAIN\USER1: The user of the remote client.

Source

PHP: How to get current time in hour:minute:second?

Anytime you have a question about a particular function in PHP, the easiest way to get quick answers is by visiting php.net, which has great documentation on all of the language's capabilities.

Looking up a function is easy, just visit http://php.net/<function name> and it will forward you to the appropriate place. For the date function, we'll visit http://php.net/date.

We immediately learn a couple things about this function by examining its signature:

string date ( string $format [, int $timestamp = time() ] )

First, it returns a string. That's what the first string in the above code means. Secondly, the first parameter is expected to be a string containing the format. There is an optional second parameter for passing in your own timestamp (to construct strings from some time other than now).

date("d-m-Y") // produces something like 03-12-2012

In this code, d represents the day of the month (with a leading 0 is necessary). m represents the month, again with a leading zero if necessary. And Y represents the full 4-digit year. All of these are documented in the aforementioned link.

To satisfy your request of getting the hours, minutes, and seconds, we need to give a quick look at the documentation to see which characters represents those particular units of time. When we do that, we find the following:

h   12-hour format of an hour with leading zeros    01 through 12
i   Minutes with leading zeros                      00 to 59
s   Seconds, with leading zeros                     00 through 59

With this in mind, we can no create a new format string:

date("d-m-Y h:i:s"); // produces something like 03-12-2012 03:29:13

Hope this is helpful, and I hope you find the documentation has benefiting to your development as I have to mine.

Parse HTML in Android

Maybe you can use WebView, but as you can see in the doc WebView doesn't support javascript and other stuff like widgets by default.

http://developer.android.com/reference/android/webkit/WebView.html

I think that you can enable javascript if you need it.

How do you delete an ActiveRecord object?

There is delete, delete_all, destroy, and destroy_all.

The docs are: older docs and Rails 3.0.0 docs

delete doesn't instantiate the objects, while destroy does. In general, delete is faster than destroy.

Delete all records in a table of MYSQL in phpMyAdmin

'Truncate tableName' will fail on a table with key constraint defined. It will also not reindex the table AUTO_INCREMENT value. Instead, Delete all table entries and reset indexing back to 1 using this sql syntax:

DELETE FROM tableName;
ALTER TABLE tableName AUTO_INCREMENT = 1

How to access a dictionary key value present inside a list?

To get all the values from a list of dictionaries, use the following code :

list = [{'text': 1, 'b': 2}, {'text': 3, 'd': 4}, {'text': 5, 'f': 6}]
subtitle=[]
for value in list:
   subtitle.append(value['text'])

In LaTeX, how can one add a header/footer in the document class Letter?

After I removed

\usepackage{fontspec}% font selecting commands 
\usepackage{xunicode}% unicode character macros 
\usepackage{xltxtra} % some fixes/extras 

it seems to have worked "correctly".

It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.

FYI: MikTeX 2.7 under Vista

QUERY syntax using cell reference

Here is working code: =QUERY(Sheet1!$A1:$B581, "select B where A = '"&A1&"'")

In this scenario I needed the interval to stay fixed and the reference value to change when I drag it.

What does the ELIFECYCLE Node.js error mean?

I had the same error after I installed new packages or updated them:

...
npm ERR! code ELIFECYCLE
npm ERR! errno 1
...

It helped me to run installation command once again or a couple of times. After that, the error disappeared.

Is JavaScript a pass-by-reference or pass-by-value language?

Passing arguments to a function in JavaScript is analogous to passing parameters by pointer value in C:

/*
The following C program demonstrates how arguments
to JavaScript functions are passed in a way analogous
to pass-by-pointer-value in C. The original JavaScript
test case by @Shog9 follows with the translation of
the code into C. This should make things clear to
those transitioning from C to JavaScript.

function changeStuff(num, obj1, obj2)
{
    num = num * 10;
    obj1.item = "changed";
    obj2 = {item: "changed"};
}

var num = 10;
var obj1 = {item: "unchanged"};
var obj2 = {item: "unchanged"};
changeStuff(num, obj1, obj2);
console.log(num);
console.log(obj1.item);    
console.log(obj2.item);

This produces the output:

10
changed
unchanged
*/

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

struct obj {
    char *item;
};

void changeStuff(int *num, struct obj *obj1, struct obj *obj2)
{
    // make pointer point to a new memory location
    // holding the new integer value
    int *old_num = num;
    num = malloc(sizeof(int));
    *num = *old_num * 10;
    // make property of structure pointed to by pointer
    // point to the new value
    obj1->item = "changed";
    // make pointer point to a new memory location
    // holding the new structure value
    obj2 = malloc(sizeof(struct obj));
    obj2->item = "changed";
    free(num); // end of scope
    free(obj2); // end of scope
}

int num = 10;
struct obj obj1 = { "unchanged" };
struct obj obj2 = { "unchanged" };

int main()
{
    // pass pointers by value: the pointers
    // will be copied into the argument list
    // of the called function and the copied
    // pointers will point to the same values
    // as the original pointers
    changeStuff(&num, &obj1, &obj2);
    printf("%d\n", num);
    puts(obj1.item);
    puts(obj2.item);
    return 0;
}

How to express a NOT IN query with ActiveRecord/Rails?

FYI, In Rails 4, you can use not syntax:

Article.where.not(title: ['Rails 3', 'Rails 5'])

how to get list of port which are in use on the server

If you mean what ports are listening, you can open a command prompt and write:

netstat

You can write:

netstat /?

for an explanation of all options.

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

I had the command correct per above answers, what I missed on was on the Workbench, where we mention 'Limit Connectivity from Host' for the user, it defaults to "%" - change this to "localhost" and it connects fine thereafter!

Get the last non-empty cell in a column in Google Sheets

Here's another one:

=indirect("A"&max(arrayformula(if(A:A<>"",row(A:A),""))))

With the final equation being this:

=DAYS360(A2,indirect("A"&max(arrayformula(if(A:A<>"",row(A:A),"")))))

The other equations on here work, but I like this one because it makes getting the row number easy, which I find I need to do more often. Just the row number would be like this:

=max(arrayformula(if(A:A<>"",row(A:A),"")))

I originally tried to find just this to solve a spreadsheet issue, but couldn't find anything useful that just gave the row number of the last entry, so hopefully this is helpful for someone.

Also, this has the added advantage that it works for any type of data in any order, and you can have blank rows in between rows with content, and it doesn't count cells with formulas that evaluate to "". It can also handle repeated values. All in all it's very similar to the equation that uses max((G:G<>"")*row(G:G)) on here, but makes pulling out the row number a little easier if that's what you're after.

Alternatively, if you want to put a script on your sheet you can make it easy on yourself if you plan on doing this a lot. Here's that scirpt:

function lastRow(sheet,column) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  if (column == null) {
    if (sheet != null) {
       var sheet = ss.getSheetByName(sheet);
    } else {
      var sheet = ss.getActiveSheet();
    }
    return sheet.getLastRow();
  } else {
    var sheet = ss.getSheetByName(sheet);
    var lastRow = sheet.getLastRow();
    var array = sheet.getRange(column + 1 + ':' + column + lastRow).getValues();
    for (i=0;i<array.length;i++) {
      if (array[i] != '') {       
        var final = i + 1;
      }
    }
    if (final != null) {
      return final;
    } else {
      return 0;
    }
  }
}

Here you can just type in the following if you want the last row on the same of the sheet that you're currently editing:

=LASTROW()

or if you want the last row of a particular column from that sheet, or of a particular column from another sheet you can do the following:

=LASTROW("Sheet1","A")

And for the last row of a particular sheet in general:

=LASTROW("Sheet1")

Then to get the actual data you can either use indirect:

=INDIRECT("A"&LASTROW())

or you can modify the above script at the last two return lines (the last two since you would have to put both the sheet and the column to get the actual value from an actual column), and replace the variable with the following:

return sheet.getRange(column + final).getValue();

and

return sheet.getRange(column + lastRow).getValue();

One benefit of this script is that you can choose if you want to include equations that evaluate to "". If no arguments are added equations evaluating to "" will be counted, but if you specify a sheet and column they will now be counted. Also, there's a lot of flexibility if you're willing to use variations of the script.

Probably overkill, but all possible.

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component

ex:

<com.google.android.material.slider.Slider
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:valueFrom="20f"
        android:valueTo="70f"
        android:stepSize="10" />

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How to check if a radiobutton is checked in a radiogroup in Android?

Try to use the method isChecked();

Like,

selectedRadioButton.isChecked() -> returns boolean.

Refere here for more details on Radio Button

Webdriver findElements By xpath

The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.

or

To explicitly do this in XPath, you'd be looking at:

(//div[@id='container'])[1]

for the first one, for the second etc:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:

//div[@id='container']/parent::*

That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:

(//div[@id='container'])[1]/parent::*

Hope that helps!

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

If the type implements IDisposable, it automatically disposes that type.

Given:

public class SomeDisposableType : IDisposable
{
   ...implmentation details...
}

These are equivalent:

SomeDisposableType t = new SomeDisposableType();
try {
    OperateOnType(t);
}
finally {
    if (t != null) {
        ((IDisposable)t).Dispose();
    }
}
using (SomeDisposableType u = new SomeDisposableType()) {
    OperateOnType(u);
}

The second is easier to read and maintain.

Python Script Uploading files via FTP

I just answered a similar question here IMHO, if your FTP server is able to communicate with Fabric please us Fabric. It is far better than doing raw ftp.

I have an FTP account from dotgeek.com so I am not sure if this will work for other FTP accounts.

#!/usr/bin/python

from fabric.api import run, env, sudo, put

env.user = 'username'
env.hosts = ['ftp_host_name',]     # such as ftp.google.com

def copy():
    # assuming i have wong_8066.zip in the same directory as this script
    put('wong_8066.zip', '/www/public/wong_8066.zip')

save the file as fabfile.py and run fab copy locally.

yeukhon@yeukhon-P5E-VM-DO:~$ fab copy2
[1.ai] Executing task 'copy2'
[1.ai] Login password: 
[1.ai] put: wong_8066.zip -> /www/public/wong_8066.zip

Done.
Disconnecting from 1.ai... done.

Once again, if you don't want to input password all the time, just add

env.password = 'my_password'

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

Expand/collapse section in UITableView in iOS

I ended up just creating a headerView that contained a button ( i saw Son Nguyen's solution above after the fact, but heres my code.. it looks like a lot but it's pretty simple):

declare a couple bools for you sections

bool customerIsCollapsed = NO;
bool siteIsCollapsed = NO;

...code

now in your tableview delegate methods...

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _tblSearchResults.frame.size.width, 35)];

    UILabel *lblSection = [UILabel new];
    [lblSection setFrame:CGRectMake(0, 0, 300, 30)];
    [lblSection setFont:[UIFont fontWithName:@"Helvetica-Bold" size:17]];
    [lblSection setBackgroundColor:[UIColor clearColor]];
    lblSection.alpha = 0.5;
    if(section == 0)
    {
        if(!customerIsCollapsed)
            [lblSection setText:@"Customers    --touch to show--"];
        else
            [lblSection setText:@"Customers    --touch to hide--"];
    }
    else
    {
        if(!siteIsCollapsed)
            [lblSection setText:@"Sites    --touch to show--"];
        else
            [lblSection setText:@"Sites    --touch to hide--"];    }

    UIButton *btnCollapse = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnCollapse setFrame:CGRectMake(0, 0, _tblSearchResults.frame.size.width, 35)];
    [btnCollapse setBackgroundColor:[UIColor clearColor]];
    [btnCollapse addTarget:self action:@selector(touchedSection:) forControlEvents:UIControlEventTouchUpInside];
    btnCollapse.tag = section;


    [headerView addSubview:lblSection];
    [headerView addSubview:btnCollapse];

    return headerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if(section == 0)
    {
        if(customerIsCollapsed)
            return 0;
        else
            return _customerArray.count;
    }
    else if (section == 1)
    {
        if(siteIsCollapsed)
            return 0;
        else
        return _siteArray.count;

    }
    return 0;
}

and finally the function that gets called when you touch one of the section header buttons:

- (IBAction)touchedSection:(id)sender
{
    UIButton *btnSection = (UIButton *)sender;

    if(btnSection.tag == 0)
    {
        NSLog(@"Touched Customers header");
        if(!customerIsCollapsed)
            customerIsCollapsed = YES;
        else
            customerIsCollapsed = NO;

    }
    else if(btnSection.tag == 1)
    {
        NSLog(@"Touched Site header");
        if(!siteIsCollapsed)
            siteIsCollapsed = YES;
        else
            siteIsCollapsed = NO;

    }
    [_tblSearchResults reloadData];
}

How to create an on/off switch with Javascript/CSS?

You mean something like IPhone checkboxes? Try Thomas Reynolds' iOS Checkboxes script:

Once the files are available to your site, activating the script is very easy:

...

$(document).ready(function() {
  $(':checkbox').iphoneStyle();
});

Results:

How can I get my webapp's base URL in ASP.NET MVC?

This works fine for me (also with a load balancer):

@{
    var urlHelper = new UrlHelper(Html.ViewContext.RequestContext);
    var baseurl = urlHelper.Content(“~”);
}

<script>
    var base_url = "@baseurl";
</script>

Especially if you are using non-standard port numbers, using Request.Url.Authority appears like a good lead at first, but fails in a LB environment.

C# how to convert File.ReadLines into string array?

string[] lines = File.ReadLines("c:\\file.txt").ToArray();

Although one wonders why you'll want to do that when ReadAllLines works just fine.

Or perhaps you just want to enumerate with the return value of File.ReadLines:

var lines = File.ReadAllLines("c:\\file.txt");
foreach (var line in lines)
{
    Console.WriteLine("\t" + line);
}

Initialising mock objects - MockIto

There is a neat way of doing this.

  • If it's an Unit Test you can do this:

    @RunWith(MockitoJUnitRunner.class)
    public class MyUnitTest {
    
        @Mock
        private MyFirstMock myFirstMock;
    
        @Mock
        private MySecondMock mySecondMock;
    
        @Spy
        private MySpiedClass mySpiedClass = new MySpiedClass();
    
        // It's gonna inject the 2 mocks and the spied object per reflection to this object
        // The java doc of @InjectMocks explains it really well how and when it does the injection
        @InjectMocks
        private MyClassToTest myClassToTest;
    
        @Test
        public void testSomething() {
        }
    }
    
  • EDIT: If it's an Integration test you can do this(not intended to be used that way with Spring. Just showcase that you can initialize mocks with diferent Runners):

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("aplicationContext.xml")
    public class MyIntegrationTest {
    
        @Mock
        private MyFirstMock myFirstMock;
    
        @Mock
        private MySecondMock mySecondMock;
    
        @Spy
        private MySpiedClass mySpiedClass = new MySpiedClass();
    
        // It's gonna inject the 2 mocks and the spied object per reflection to this object
        // The java doc of @InjectMocks explains it really well how and when it does the injection
        @InjectMocks
        private MyClassToTest myClassToTest;
    
        @Before
        public void setUp() throws Exception {
              MockitoAnnotations.initMocks(this);
        }
    
        @Test
        public void testSomething() {
        }
    }
    

How to find which views are using a certain table in SQL Server (2008)?

select your table -> view dependencies -> Objects that depend on

How to affect other elements when one element is hovered

If the cube is directly inside the container:

#container:hover > #cube { background-color: yellow; }

If cube is next to (after containers closing tag) the container:

#container:hover + #cube { background-color: yellow; }

If the cube is somewhere inside the container:

#container:hover #cube { background-color: yellow; }

If the cube is a sibling of the container:

#container:hover ~ #cube { background-color: yellow; }

How do I check if a column is empty or null in MySQL?

Another method without WHERE, try this..

Will select both Empty and NULL values

SELECT ISNULL(NULLIF(fieldname,''))  FROM tablename

Fastest way to serialize and deserialize .NET objects

Having an interest in this, I decided to test the suggested methods with the closest "apples to apples" test I could. I wrote a Console app, with the following code:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace SerializationTests
{
    class Program
    {
        static void Main(string[] args)
        {
            var count = 100000;
            var rnd = new Random(DateTime.UtcNow.GetHashCode());
            Console.WriteLine("Generating {0} arrays of data...", count);
            var arrays = new List<int[]>();
            for (int i = 0; i < count; i++)
            {
                var elements = rnd.Next(1, 100);
                var array = new int[elements];
                for (int j = 0; j < elements; j++)
                {
                    array[j] = rnd.Next();
                }   
                arrays.Add(array);
            }
            Console.WriteLine("Test data generated.");
            var stopWatch = new Stopwatch();

            Console.WriteLine("Testing BinarySerializer...");
            var binarySerializer = new BinarySerializer();
            var binarySerialized = new List<byte[]>();
            var binaryDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                binarySerialized.Add(binarySerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("BinaryFormatter: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in binarySerialized)
            {
                binaryDeserialized.Add(binarySerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("BinaryFormatter: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);


            Console.WriteLine();
            Console.WriteLine("Testing ProtoBuf serializer...");
            var protobufSerializer = new ProtoBufSerializer();
            var protobufSerialized = new List<byte[]>();
            var protobufDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                protobufSerialized.Add(protobufSerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("ProtoBuf: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in protobufSerialized)
            {
                protobufDeserialized.Add(protobufSerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("ProtoBuf: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            Console.WriteLine();
            Console.WriteLine("Testing NetSerializer serializer...");
            var netSerializerSerializer = new ProtoBufSerializer();
            var netSerializerSerialized = new List<byte[]>();
            var netSerializerDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                netSerializerSerialized.Add(netSerializerSerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("NetSerializer: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in netSerializerSerialized)
            {
                netSerializerDeserialized.Add(netSerializerSerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("NetSerializer: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            Console.WriteLine("Press any key to end.");
            Console.ReadKey();
        }

        public class BinarySerializer
        {
            private static readonly BinaryFormatter Formatter = new BinaryFormatter();

            public byte[] Serialize(object toSerialize)
            {
                using (var stream = new MemoryStream())
                {
                    Formatter.Serialize(stream, toSerialize);
                    return stream.ToArray();
                }
            }

            public T Deserialize<T>(byte[] serialized)
            {
                using (var stream = new MemoryStream(serialized))
                {
                    var result = (T)Formatter.Deserialize(stream);
                    return result;
                }
            }
        }

        public class ProtoBufSerializer
        {
            public byte[] Serialize(object toSerialize)
            {
                using (var stream = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize(stream, toSerialize);
                    return stream.ToArray();
                }
            }

            public T Deserialize<T>(byte[] serialized)
            {
                using (var stream = new MemoryStream(serialized))
                {
                    var result = ProtoBuf.Serializer.Deserialize<T>(stream);
                    return result;
                }
            }
        }

        public class NetSerializer
        {
            private static readonly NetSerializer Serializer = new NetSerializer();
            public byte[] Serialize(object toSerialize)
            {
                return Serializer.Serialize(toSerialize);
            }

            public T Deserialize<T>(byte[] serialized)
            {
                return Serializer.Deserialize<T>(serialized);
            }
        }
    }
}

The results surprised me; they were consistent when run multiple times:

Generating 100000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 336.8392ms.
BinaryFormatter: Deserializing took 208.7527ms.

Testing ProtoBuf serializer...
ProtoBuf: Serializing took 2284.3827ms.
ProtoBuf: Deserializing took 2201.8072ms.

Testing NetSerializer serializer...
NetSerializer: Serializing took 2139.5424ms.
NetSerializer: Deserializing took 2113.7296ms.
Press any key to end.

Collecting these results, I decided to see if ProtoBuf or NetSerializer performed better with larger objects. I changed the collection count to 10,000 objects, but increased the size of the arrays to 1-10,000 instead of 1-100. The results seemed even more definitive:

Generating 10000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 285.8356ms.
BinaryFormatter: Deserializing took 206.0906ms.

Testing ProtoBuf serializer...
ProtoBuf: Serializing took 10693.3848ms.
ProtoBuf: Deserializing took 5988.5993ms.

Testing NetSerializer serializer...
NetSerializer: Serializing took 9017.5785ms.
NetSerializer: Deserializing took 5978.7203ms.
Press any key to end.

My conclusion, therefore, is: there may be cases where ProtoBuf and NetSerializer are well-suited to, but in terms of raw performance for at least relatively simple objects... BinaryFormatter is significantly more performant, by at least an order of magnitude.

YMMV.

How to rename HTML "browse" button of an input type=file?

The input type="file" field is very tricky because it behaves differently on every browser, it can't be styled, or can be styled a little, depending on the browser again; and it is difficult to resize (depending on the browser again, it may have a minimal size that can't be overwritten).

There are workarounds though. The best one is in my opinion this one (the result is here).

Rails: FATAL - Peer authentication failed for user (PG::Error)

This is the most foolproof way to get your rails app working with postgres in the development environment in Ubuntu 13.10.

1) Create rails app with postgres YAML and 'pg' gem in the Gemfile:

$ rails new my_application -d postgresql

2) Give it some CRUD functionality. If you're just seeing if postgres works, create a scaffold:

$ rails g scaffold cats name:string age:integer colour:string

3) As of rails 4.0.1 the -d postgresql option generates a YAML that doesn't include a host parameter. I found I needed this. Edit the development section and create the following parameters:

encoding: UTF-8
host: localhost
database: my_application_development
username: thisismynewusername
password: thisismynewpassword 

Note the database parameter is for a database that doesn't exit yet, and the username and password are credentials for a role that doesn't exist either. We'll create those later on!

This is how config/database.yml should look (no shame in copypasting :D ):

development:
  adapter: postgresql
  pool: 5
  # these are our new parameters
  encoding: UTF-8
  database: my_application_development
  host: localhost
  username: thisismynewusername
  password: thisismynewpassword

test:
  # this won't work 
  adapter: postgresql
  encoding: unicode
  database: my_application_test
  pool: 5
  username: my_application
  password:

production:
  # this won't work 
  adapter: postgresql
  encoding: unicode
  database: my_application_production
  pool: 5
  username: my_application
  password:

4) Start the postgres shell with this command:

$ psql

4a) You may get this error if your current user (as in your computer user) doesn't have a corresponding administration postgres role.

psql: FATAL:  role "your_username" does not exist

Now I've only installed postgres once, so I may be wrong here, but I think postgres automatically creates an administration role with the same credentials as the user you installed postgres as.

4b) So this means you need to change to the user that installed postgres to use the psql command and start the shell:

$ sudo su postgres

And then run

$ psql

5) You'll know you're in the postgres shell because your terminal will look like this:

$ psql
psql (9.1.10)
Type "help" for help.

postgres=# 

6) Using the postgresql syntax, let's create the user we specified in config/database.yml's development section:

postgres=# CREATE ROLE thisismynewusername WITH LOGIN PASSWORD 'thisismynewpassword';

Now, there's some subtleties here so let's go over them.

  • The role's username, thisismynewusername, does not have quotes of any kind around it
  • Specify the keyword LOGIN after the WITH. If you don't, the role will still be created, but it won't be able to log in to the database!
  • The role's password, thisismynewpassword, needs to be in single quotes. Not double quotes.
  • Add a semi colon on the end ;)

You should see this in your terminal:

postgres=#
CREATE ROLE
postgres=#

That means, "ROLE CREATED", but postgres' alerts seem to adopt the same imperative conventions of git hub.

7) Now, still in the postgres shell, we need to create the database with the name we set in the YAML. Make the user we created in step 6 its owner:

postgres=# CREATE DATABASE my_application_development OWNER thisismynewusername;

You'll know if you were successful because you'll get the output:

CREATE DATABASE

8) Quit the postgres shell:

\q

9) Now the moment of truth:

$ RAILS_ENV=development rake db:migrate

If you get this:

==  CreateCats: migrating =================================================
-- create_table(:cats)
   -> 0.0028s
==  CreateCats: migrated (0.0028s) ========================================

Congratulations, postgres is working perfectly with your app.

9a) On my local machine, I kept getting a permission error. I can't remember it exactly, but it was an error along the lines of

Can't access the files. Change permissions to 666.

Though I'd advise thinking very carefully about recursively setting write privaledges on a production machine, locally, I gave my whole app read write privileges like this:

9b) Climb up one directory level:

$ cd ..

9c) Set the permissions of the my_application directory and all its contents to 666:

$ chmod -R 0666 my_application

9d) And run the migration again:

$ RAILS_ENV=development rake db:migrate

==  CreateCats: migrating =================================================
-- create_table(:cats)
   -> 0.0028s
==  CreateCats: migrated (0.0028s) ========================================

Some tips and tricks if you muck up

Try these before restarting all of these steps:

The mynewusername user doesn't have privileges to CRUD to the my_app_development database? Drop the database and create it again with mynewusername as the owner:

1) Start the postgres shell:

$ psql

2) Drop the my_app_development database. Be careful! Drop means utterly delete!

postgres=# DROP DATABASE my_app_development;

3) Recreate another my_app_development and make mynewusername the owner:

postgres=# CREATE DATABASE my_application_development OWNER mynewusername;

4) Quit the shell:

postgres=# \q

The mynewusername user can't log into the database? Think you wrote the wrong password in the YAML and can't quite remember the password you entered using the postgres shell? Simply alter the role with the YAML password:

1) Open up your YAML, and copy the password to your clipboard:

 development:
      adapter: postgresql
      pool: 5
      # these are our new parameters
      encoding: UTF-8
      database: my_application_development
      host: localhost
      username: thisismynewusername
      password: musthavebeenverydrunkwheniwrotethis

2) Start the postgres shell:

$ psql    

3) Update mynewusername's password. Paste in the password, and remember to put single quotes around it:

postgres=# ALTER ROLE mynewusername PASSWORD `musthavebeenverydrunkwheniwrotethis`;

4) Quit the shell:

postgres=# \q

Trying to connect to localhost via a database viewer such as Dbeaver, and don't know what your postgres user's password is? Change it like this:

1) Run passwd as a superuser:

$ sudo passwd postgres

2) Enter your accounts password for sudo (nothing to do with postgres):

[sudo] password for starkers: myaccountpassword

3) Create the postgres account's new passwod:

Enter new UNIX password: databasesarefun
Retype new UNIX password: databasesarefun
passwd: password updated successfully

Getting this error message?:

Run `$ bin/rake db:create db:migrate` to create your database
$ rake db:create db:migrate
PG::InsufficientPrivilege: ERROR:  permission denied to create database

4) You need to give your user the ability to create databases. From the psql shell:

ALTER ROLE thisismynewusername WITH CREATEDB

DataTables fixed headers misaligned with columns in wide tables

I know there has been an answer flagged already, but for someone with similar problems that the above does not work for. I'm using it in conjunction with bootstrap theme.

There is a line that can be altered in the dataTables.fixedHeader.js file. the default layout of the function looks as follows.

    _matchWidths: function (from, to) {
        var get = function (name) {
            return $(name, from)
                .map(function () {
                    return $(this).width();
                }).toArray();
        };

        var set = function (name, toWidths) {
            $(name, to).each(function (i) {
                $(this).css({
                    width: toWidths[i],
                    minWidth: toWidths[i]
                });
            });
        };

        var thWidths = get('th');
        var tdWidths = get('td');

        set('th', thWidths);
        set('td', tdWidths);
    },

change the

    return $(this).width();

to

    return $(this).outerWidth();

outerWidth() is a function that is contained in jquery.dimensions.js if you are usingg a newer version of jquery. ie. jquery-3.1.1.js

what the above function does is it maps the th of the original table, then applies them to the "cloned" table(fixed header). in my case they were always off by about 5px to 8px when misaligned. Most probably not the best fix out there but provides a solution to all other tables in the solution without having to specify it per table declaration. It has only been tested in Chrome so far, but it should provide an adjudicate solution on all browsers.

LDAP Authentication using Java

// this class will authenticate LDAP UserName or Email

// simply call LdapAuth.authenticateUserAndGetInfo (username,password);

//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex 

import java.util.*;

import javax.naming.*;

import java.util.regex.*;

import javax.naming.directory.*;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;

public class LdapAuth {


private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";

private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

private  static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};


// see you active directory user OU's hirarchy 

private  static String[] ADSearchPaths = 

{ 

    "OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Migrated Users,OU=TES-Users"

};


private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided


private static void authenticateUserAndGetInfo (String user, String password) throws Exception {

    try {


        Hashtable<String,String> env = new Hashtable <String,String>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

        env.put(Context.PROVIDER_URL, ldapURI);     

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, user);

        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext ctx = new InitialDirContext(env);

        String filter = "(sAMAccountName="+user+")";  // default for search filter username

        if(user.contains("@"))  // if user name is a email then
        {
            //String parts[] = user.split("\\@");
            //use different filter for email
            filter = "(userPrincipalName="+user+")";
        }

        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningAttributes(requiredAttributes);

        NamingEnumeration userInfo = null;


        Integer i = 0;
        do
        {
            userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
            i++;

        } while(!userInfo.hasMore() && i < ADSearchPaths.length );

        if (userInfo.hasMore()) {

            SearchResult UserDetails = (SearchResult) userInfo.next();
            Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());

            System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());

            System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());

            System.out.println("name = "+userAttr.get("cn").get(0).toString());

            System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());

        }

        userInfo.close();

    }
    catch (javax.naming.AuthenticationException e) {

    }
}   
}

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Try this:

location / {
    root /path/to/root;
    expires 30d;
    access_log off;
}

location ~* ^.*\.php$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php should be forwared to Apache if only a corresponding .php file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.

ERROR 2003 (HY000): Can't connect to MySQL server (111)

/etc/mysql$ sudo nano my.cnf

Relevant portion that works for me:

#skip-networking
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address            = MY_IP

MY_IP can be found using ifconfig or curl -L whatismyip.org |grep blue.

Restart mysql to ensure the new config is loaded:

/etc/mysql$ sudo service mysql restart

Ajax LARAVEL 419 POST error

I received this error when I had a config file with <?php on the second line instead of the first.

How to create JSON Object using String?

JSONArray may be what you want.

String message;
JSONObject json = new JSONObject();
json.put("name", "student");

JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);

json.put("course", array);

message = json.toString();

// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}

Specifying java version in maven - differences between properties and compiler plugin

None of the solutions above worked for me straight away. So I followed these steps:

  1. Add in pom.xml:
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>
  1. Go to Project Properties > Java Build Path, then remove the JRE System Library pointing to JRE1.5.

  2. Force updated the project.

Copying text to the clipboard using Java

This works for me and is quite simple:

Import these:

import java.awt.datatransfer.StringSelection;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;

And then put this snippet of code wherever you'd like to alter the clipboard:

String myString = "This text will be copied into clipboard";
StringSelection stringSelection = new StringSelection(myString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);

How to render an array of objects in React?

Try this:

_x000D_
_x000D_
class First extends React.Component {
  constructor (props){
    super(props);

  }

  render() {
     const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
    
    return (
      <div>
      {listItems}
      </div>
    );
  }
} 
_x000D_
_x000D_
_x000D_

How to use the addr2line command in Linux?

You can also use gdb instead of addr2line to examine memory address. Load executable file in gdb and print the name of a symbol which is stored at the address. 16 Examining the Symbol Table.

(gdb) info symbol 0x4005BDC 

how to overwrite css style

Just add

.flex-control-thumbs li {
width: auto; 
}

JSON date to Java date?

If you need to support more than one format you will have to pattern match your input and parse accordingly.

final DateFormat fmt;
if (dateString.endsWith("Z")) {
    fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
} else {
    fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
}

I'd guess you're dealing with a bug in the API you're using which has quoted the Z timezone date pattern somewhere...

What does bundle exec rake mean?

It should probably be mentioned, that there are ways to omit bundle exec (they are all stated in chapter 3.6.1 of Michael Hartls Ruby on Rails Tutorial book).

The simplest is to just use a sufficiently up-to-date version of RVM (>= 1.11.x).

If you're restricted to an earlier version of RVM, you can always use this method also mentioned by calasyr:

$ rvm get head && rvm reload
$ chmod +x $rvm_path/hooks/after_cd_bundler
$ bundle install --binstubs=./bundler_stubs

The bundler_stubs directory should then also be added to the .gitignore file.

A third option is to use the rubygems-bundler gem if you're not using RVM:

$ gem install rubygems-bundler
$ gem regenerate_binstubs

Uncaught ReferenceError: function is not defined with onclick

I got this resolved in angular with (click) = "someFuncionName()" in the .html file for the specific component.

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB intended to retain character-based data.

JAX-RS / Jersey how to customize error handling?

One obvious solution: take in a String, convert to Date yourself. That way you can define format you want, catch exceptions and either re-throw or customize error being sent. For parsing, SimpleDateFormat should work fine.

I am sure there are ways to hook handlers for data types too, but perhaps little bit of simple code is all you need in this case.

Difference between "include" and "require" in php

You find the differences explained in the detailed PHP manual on the page of require:

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

See @efritz's answer for an example

How to open link in new tab on html?

When to use target='_blank' :

The HTML version (Some devices not support it):

<a href="http://chriscoyier.net" target="_blank">This link will open in new window/tab</a>

The JavaScript version for all Devices :

The use of rel="external" is perfectly valid

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    $('a[rel="external"]').attr('target', '_blank');
</script>

and for Jquery can try with the below one:

$("#content a[href^='http://']").attr("target","_blank");

If browser setting don't allow you to open in new windows :

href = "google.com";
onclick="window.open (this.href, ''); return false";

Does Android keep the .apk files? if so where?

Another way to get the apks you can't find, on a rooted device is with rom tool box.

Make a backup using app manager then go to storage/emulated/appmanager and check either system app backup or user app backup.

Git Bash: Could not open a connection to your authentication agent

It seems you need to run ssh-agent before using it:

eval `ssh-agent -s`

That question was answered in this topic: Could not open a connection to your authentication agent

Cleanest way to write retry logic?

You should try Polly. It's a .NET library written by me that allows developers to express transient exception handling policies such as Retry, Retry Forever, Wait and Retry or Circuit Breaker in a fluent manner.

Example

Policy
    .Handle<SqlException>(ex => ex.Number == 1205)
    .Or<ArgumentException>(ex => ex.ParamName == "example")
    .WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(3))
    .Execute(() => DoSomething());

Set Session variable using javascript in PHP

In JavaScript:

jQuery('#div_session_write').load('session_write.php?session_name=new_value');

In session_write.php file:

<?
session_start();

if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>

In HTML:

<div id='div_session_write'> </div>

TypeError: tuple indices must be integers, not str

SQlite3 has a method named row_factory. This method would allow you to access the values by column name.

https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

for more extendability for large scale apps use oop style with encapsulated fields.

Simple way :-

  class Fruit implements JsonSerializable {

        private $type = 'Apple', $lastEaten = null;

        public function __construct() {
            $this->lastEaten = new DateTime();
        }

        public function jsonSerialize() {
            return [
                'category' => $this->type,
                'EatenTime' => $this->lastEaten->format(DateTime::ISO8601)
            ];
        }
    }

echo json_encode(new Fruit()); //which outputs:

{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}

Real Gson on PHP :-

  1. http://jmsyst.com/libs/serializer
  2. http://symfony.com/doc/current/components/serializer.html
  3. http://framework.zend.com/manual/current/en/modules/zend.serializer.html
  4. http://fractal.thephpleague.com/ - serialize only

How to change max_allowed_packet size

This error come because of your data contain larger then set value.

Just write down the max_allowed_packed=500M or you can calculate that 500*1024k and use that instead of 500M if you want.

Now just restart the MySQL.

Printing Python version in output

Try

import sys
print(sys.version)

This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.

Visual Studio Code Tab Key does not insert a tab

Maybe another program is interfering? Closing Teamviewer fixed the problem for me.

How to add Tomcat Server in eclipse

Do as this:

Windows -> Show View -> Servers

Then in the Servers view, right-click and add new. It will show a pop up containing many server vendors. Under Apache select Tomcat v7.0 (Depending upon your downloaded server version). And in the run time configuration point it to the Tomcat folder you have downloaded.

You can try this article. It has the info you want !!

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

Change directory command in Docker?

You can run a script, or a more complex parameter to the RUN. Here is an example from a Dockerfile I've downloaded to look at previously:

RUN cd /opt && unzip treeio.zip && mv treeio-master treeio && \
    rm -f treeio.zip && cd treeio && pip install -r requirements.pip

Because of the use of '&&', it will only get to the final 'pip install' command if all the previous commands have succeeded.

In fact, since every RUN creates a new commit & (currently) an AUFS layer, if you have too many commands in the Dockerfile, you will use up the limits, so merging the RUNs (when the file is stable) can be a very useful thing to do.

javascript set cookie with expire time

Your browser may be configured to accept only session cookies; if this is your case, any expiry time is transformed into session by your browser, you can change this setting of your browser or try another browser without such a configuration

Python "expected an indented block"

in python .....intendation matters, e.g.:

if a==1:
    print("hey")

if a==2:
   print("bye")

print("all the best")

In this case "all the best" will be printed if either of the two conditions executes, but if it would have been like this

if a==2:
   print("bye")
   print("all the best")

then "all the best" will be printed only if a==2

Is there a macro to conditionally copy rows to another worksheet?

If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?

MongoDB Aggregation: How to get total records count?

If you don't want to group, then use the following method:

db.collection.aggregate( [ { $match : { score : { $gt : 70, $lte : 90 } } }, { $count: 'count' } ] );

Object Dump JavaScript

For Chrome/Chromium

console.log(myObj)

or it's equivalent

console.debug(myObj)

How to get the last five characters of a string using Substring() in C#?

static void Main()
    {
        string input = "OneTwoThree";

            //Get last 5 characters
        string sub = input.Substring(6);
        Console.WriteLine("Substring: {0}", sub); // Output Three. 
    }
  • Substring(0, 3) - Returns substring of first 3 chars. //One

  • Substring(3, 3) - Returns substring of second 3 chars. //Two

  • Substring(6) - Returns substring of all chars after first 6. //Three

Jersey Exception : SEVERE: A message body reader for Java class

To make it work you only need two things. Check if you are missing:

  1. First of all, you need @XmlRootElement annotation for your object class/entity.
  2. You need to add dependency for jersey-json if you are missing.For your reference I added this dependency into my pom.xml.

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.17.1</version>
    </dependency>
    

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

file element has and array call files it contain all necessary stuff you need

var file = document.getElementById("upload");

file.addEventListener("change", function() {
    for (var i = 0; i < file.files.length; i++) {
        console.log(file.files[i].name);
    }
}, false);

How do I get the color from a hexadecimal color code using .NET?

If you mean HashCode as in .GetHashCode(), I'm afraid you can't go back. Hash functions are not bi-directional, you can go 'forward' only, not back.

Follow Oded's suggestion if you need to get the color based on the hexadecimal value of the color.

How to get folder directory from HTML input type "file" or any other way?

You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" /> control doesn't handle that.

If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change event then strip the filename portion and save the path somewhere--but that's about as good as it gets.

Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.

SQL Server Case Statement when IS NULL

You can use IIF (I think from SQL Server 2012)

SELECT IIF(B.[STAT] IS NULL, C.[EVENT DATE]+10, '-') AS [DATE]

How to create EditText accepts Alphabets only in android?

Add this line with your EditText tag.

android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

Your EditText tag should look like:

<EditText
        android:id="@+id/editText1"
        android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

How to bind inverse boolean properties in WPF?

Don't know if this is relevant to XAML, but in my simple Windows app I created the binding manually and added a Format event handler.

public FormMain() {
  InitializeComponent();

  Binding argBinding = new Binding("Enabled", uxCheckBoxArgsNull, "Checked", false, DataSourceUpdateMode.OnPropertyChanged);
  argBinding.Format += new ConvertEventHandler(Binding_Format_BooleanInverse);
  uxTextBoxArgs.DataBindings.Add(argBinding);
}

void Binding_Format_BooleanInverse(object sender, ConvertEventArgs e) {
  bool boolValue = (bool)e.Value;
  e.Value = !boolValue;
}

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

I tried the solutions above, but had no luck. I noticed this line in my project's package.json:

 "bin": {
"webpack-dev-server": "bin/webpack-dev-server.js"

},

I looked at bin/webpack-dev-server.js and found this line:

.describe("port", "The port").default("port", 8080)

I changed the port to 3000. A bit of a brute force approach, but it worked for me.

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

I had the same problem, I had to update MVC Future (Microsoft.AspNet.Mvc.Futures)

Install-Package Microsoft.AspNet.Mvc.Futures

CSS: How to position two elements on top of each other, without specifying a height?

First of all, you really should be including the position on absolutely positioned elements or you will come across odd and confusing behavior; you probably want to add top: 0; left: 0 to the CSS for both of your absolutely positioned elements. You'll also want to have position: relative on .container_row if you want the absolutely positioned elements to be positioned with respect to their parent rather than the document's body:

If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed' ...

Your problem is that position: absolute removes elements from the normal flow:

It is removed from the normal flow entirely (it has no impact on later siblings). An absolutely positioned box establishes a new containing block for normal flow children and absolutely (but not fixed) positioned descendants. However, the contents of an absolutely positioned element do not flow around any other boxes.

This means that absolutely positioned elements have no effect whatsoever on their parent element's size and your first <div class="container_row"> will have a height of zero.

So you can't do what you're trying to do with absolutely positioned elements unless you know how tall they're going to be (or, equivalently, you can specify their height). If you can specify the heights then you can put the same heights on the .container_row and everything will line up; you could also put a margin-top on the second .container_row to leave room for the absolutely positioned elements. For example:

http://jsfiddle.net/ambiguous/zVBDc/

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

1067 error on attempt to start MySQL

In my instance it had nothing to do with spaces in the file name. I used the MSI installer custom configuration and opted to exclude the default databases, assuming it was just something like Northwind/Adventureworks. Nope, it includes the core MySql system database... once I added that to the installation it worked.

Simple mediaplayer play mp3 from file path?

I use this class for Audio play. If your audio location is raw folder.

Call method for play:

new AudioPlayer().play(mContext, getResources().getIdentifier(alphabetItemList.get(mPosition)
                        .getDetail().get(0).getAudio(),"raw", getPackageName()));

AudioPlayer.java class:

public class AudioPlayer {

    private MediaPlayer mMediaPlayer;

    public void stop() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
    // mothod for raw folder (R.raw.fileName)
    public void play(Context context, int rid){
        stop();

        mMediaPlayer = MediaPlayer.create(context, rid);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

    // mothod for other folder 
    public void play(Context context, String name) {
        stop();

        //mMediaPlayer = MediaPlayer.create(c, rid);
        mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

}

Beamer: How to show images as step-by-step images

This is what I did:

\begin{frame}{series of images}
\begin{center}
\begin{overprint}

\only<2>{\includegraphics[scale=0.40]{image1.pdf}}
\hspace{-0.17em}\only<3>{\includegraphics[scale=0.40]{image2.pdf}}
\hspace{-0.34em}\only<4>{\includegraphics[scale=0.40]{image3.pdf}}
\hspace{-0.17em}\only<5>{\includegraphics[scale=0.40]{image4.pdf}}

\only<2-5>{\mbox{\structure{Figure:} something}}

\end{overprint}
\end{center}
\end{frame}

Programmatically Creating UILabel

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];

String length in bytes in JavaScript

This would work for BMP and SIP/SMP characters.

    String.prototype.lengthInUtf8 = function() {
        var asciiLength = this.match(/[\u0000-\u007f]/g) ? this.match(/[\u0000-\u007f]/g).length : 0;
        var multiByteLength = encodeURI(this.replace(/[\u0000-\u007f]/g)).match(/%/g) ? encodeURI(this.replace(/[\u0000-\u007f]/g, '')).match(/%/g).length : 0;
        return asciiLength + multiByteLength;
    }

    'test'.lengthInUtf8();
    // returns 4
    '\u{2f894}'.lengthInUtf8();
    // returns 4
    '???? ?????'.lengthInUtf8();
    // returns 19, each Arabic/Persian alphabet character takes 2 bytes. 
    '??,JavaScript ??'.lengthInUtf8();
    // returns 26, each Chinese character/punctuation takes 3 bytes. 

Convert JSON string to array of JSON objects in Javascript

As simple as that.

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
 dataObj = JSON.parse(str);

How to use store and use session variables across pages?

Reasoning from the comments to this question, it appears a lack of an adjusted session.save_path causes this misbehavior of PHP’s session handler. Just specify a directory (outside your document root directory) that exists and is both readable and writeable by PHP to fix this.

What is newline character -- '\n'

I see a lot of sed answers, but none for vim. To be fair, vim's treatment of newline characters is a little confusing. Search for \n but replace with \r. I recommend RTFM: :help pattern in general and :help NL-used-for-Nul in particular.

To do what you want with a :substitute command,

:%s/\_$/\r

although I think most people would use something like

:g/^/put=''

for the same effect.

Here is a way to find the answer for yourself. Run your file through xxd, which is part of the standard vim distribution.

:%!xxd

You get

0000000: 4361 6c69 666f 726e 6961 0a4d 6173 7361  California.Massa
0000010: 6368 7573 6574 7473 0a41 7269 7a6f 6e61  chusetts.Arizona
0000020: 0a                                       .

This shows that 46 is the hex code for C, 61 is the code for a, and so on. In particular, 0a (decimal 10) is the code for \n. Just for kicks, try

:set ff=dos

before filtering through xxd. You will see 0d0a (CRLF) as the line terminator.

:help /\_$
:help :g
:help :put
:help :!
:help 23.4

How can I recover the return value of a function passed to multiprocessing.Process?

The pebble package has a nice abstraction leveraging multiprocessing.Pipe which makes this quite straightforward:

from pebble import concurrent

@concurrent.process
def function(arg, kwarg=0):
    return arg + kwarg

future = function(1, kwarg=1)

print(future.result())

Example from: https://pythonhosted.org/Pebble/#concurrent-decorators