Programs & Examples On #Universal binary

POI setting Cell Background to a Custom Color

See http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors.

Custom colors

HSSF:

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("Default Palette");

//apply some colors from the standard palette,
// as in the previous examples.
//we'll use red text on a lime background

HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

HSSFFont font = wb.createFont();
font.setColor(HSSFColor.RED.index);
style.setFont(font);

cell.setCellStyle(style);

//save with the default palette
FileOutputStream out = new FileOutputStream("default_palette.xls");
wb.write(out);
out.close();

//now, let's replace RED and LIME in the palette
// with a more attractive combination
// (lovingly borrowed from freebsd.org)

cell.setCellValue("Modified Palette");

//creating a custom palette for the workbook
HSSFPalette palette = wb.getCustomPalette();

//replacing the standard red with freebsd.org red
palette.setColorAtIndex(HSSFColor.RED.index,
        (byte) 153,  //RGB red (0-255)
        (byte) 0,    //RGB green
        (byte) 0     //RGB blue
);
//replacing lime with freebsd.org gold
palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);

//save with the modified palette
// note that wherever we have previously used RED or LIME, the
// new colors magically appear
out = new FileOutputStream("modified_palette.xls");
wb.write(out);
out.close();

XSSF:

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell( 0);
cell.setCellValue("custom XSSF colors");

XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
style1.setFillPattern(CellStyle.SOLID_FOREGROUND);

Using the "animated circle" in an ImageView while loading stuff

Simply put this block of xml in your activity layout file:

<RelativeLayout
    android:id="@+id/loadingPanel"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="true" />
</RelativeLayout>

And when you finish loading, call this one line:

findViewById(R.id.loadingPanel).setVisibility(View.GONE);

The result (and it spins too):

enter image description here

How do I programmatically force an onchange event on an input?

In jQuery I mostly use:

$("#element").trigger("change");

What's the difference between @Component, @Repository & @Service annotations in Spring?

Difference between @Component, @Repository, @Controller & @Service annotations

@Component – generic and can be used across application.
@Service – annotate classes at service layer level.
@Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
@Repository – annotate classes at persistence layer, which will act as database repository.

@Controller = @Component ( Internal Annotation ) + Presentation layer Features
@Service = @Component ( Internal Annotation ) + Service layer Features
@Component = Actual Components ( Beans )
@Repository = @Component ( Internal Annotation ) + Data Layer Features ( use for handling the Domain Beans )

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

Delete package-lock.json file and then try to install

Returning from a void function

The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.

I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?

I would be severly annoyed by such a pointless extra return statement at the end of a void function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.

Persist javascript variables across pages?

You could use the window’s name window.name to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.

Python [Errno 98] Address already in use

Yes, it is intended. Here you can read detailed explanation. It is possible to override this behavior by setting SO_REUSEADDR option on a socket. For example:

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

I was looking at this post to find the answer but... I think everyone on this post was facing the same scenario as me: scrollToPosition() was fully ignored, for an evident reason.

What I was using?

recyclerView.scrollToPosition(items.size());

... what WORKED?

recyclerView.scrollToPosition(items.size() - 1);

Create an array of strings

Another option:

names = repmat({'Sample Text'}, 10, 1)

Make body have 100% of the browser height

Please check this:

* {margin: 0; padding: 0;}    
html, body { width: 100%; height: 100%;}

Or try new method Viewport height :

html, body { width: 100vw; height: 100vh;}

Viewport: If your using viewport means whatever size screen content will come full height fo the screen.

Rollback one specific migration in Laravel

It's quite easy to roll back just a specific migration.
Since the command php artisan migrate:rollback, undo the last database migration, and the order of the migrations execution is stored in the batch field in the migrations table.

You can edit the batch value of the migration that you want to rollback and set it as the higher. Then you can rollback that migration with a simple:

php artisan migrate:rollback

After editing the same migration you can execute it again with a simple

php artisan migrate

NOTICE: if two or more migrations have the same higher value, they will be all rolled back at the same time.

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

How to make scipy.interpolate give an extrapolated result beyond the input range?

What about scipy.interpolate.splrep (with degree 1 and no smoothing):

>> tck = scipy.interpolate.splrep([1, 2, 3, 4, 5], [1, 4, 9, 16, 25], k=1, s=0)
>> scipy.interpolate.splev(6, tck)
34.0

It seems to do what you want, since 34 = 25 + (25 - 16).

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

Linux delete file with size 0

find . -type f -empty -exec rm -f {} \;

How to get the user input in Java?

You can use any of the following options based on the requirements.

Scanner class

import java.util.Scanner; 
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();

BufferedReader and InputStreamReader classes

import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);

DataInputStream class

import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();

The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader


Console class

import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

Apparently, this method does not work well in some IDEs.

java.lang.NoClassDefFoundError: Could not initialize class XXX

I encounter the same problem. I inited a bean object in static block like below:

static {
    try{
        mqttConfiguration = SpringBootBeanUtils.<MqttConfiguration>getBean(MqttConfiguration.class);
    }catch (Throwable e){
        System.out.println(e);
    }
 }

Just because the process the my bean obejct inition caused a NPE, I get trouble into it. So I think you should check you static code block carefully.

Regex to match only uppercase "words" with some exceptions

I'm not a regex guru by any means. But try:

<[A-Z0-9][A-Z0-9]+>

<           start of word
[A-Z0-9]    one character
[A-Z0-9]+   and one or more of them
>           end of word

I won't try for the bonus points of the whole upper case sentence. hehe

Executing JavaScript after X seconds

onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"

Change 1000 to the number of milliseconds you want to delay.

How and when to use SLEEP() correctly in MySQL?

If you don't want to SELECT SLEEP(1);, you can also DO SLEEP(1); It's useful for those situations in procedures where you don't want to see output.

e.g.

SELECT ...
DO SLEEP(5);
SELECT ...

What is "android.R.layout.simple_list_item_1"?

As mentioned by Klap "android.R.layout.simple_list_item_1 is a reference to an built-in XML layout document that is part of the Android OS"
All the layouts are located in: sdk\platforms\android-xx\data\res\layout
To view the XML of layout :
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select "Open declaration in layout/simple_list_item_1.xml". It'll direct you to the contents of the XML.
Android Studio: Project Window -> External Libraries -> Android X Platform -> res -> layout, and here you will see a list of available layouts.
enter image description here

Android Webview - Webpage should fit the device screen

This seems like an XML problem. Open the XML document containing your Web-View. Delete the padding code at the top.

Then in the layout , add

android:layout_width="fill_parent"
android:layout_height="fill_parent"

In the Web-View, add

android:layout_width="fill_parent"
android:layout_height="fill_parent" 

This makes the Web-View fit the device screen.

What languages are Windows, Mac OS X and Linux written in?

Mac OS X uses large amounts of C++ inside some libraries, but it isn't exposed as they're afraid of the ABI breaking.

Run parallel multiple commands at once in the same terminal

Based on comment of @alessandro-pezzato. Run multiples commands by using & between the commands.

Example:

$ sleep 3 & sleep 5 & sleep 2 &

It's will execute the commands in background.

How do I instantiate a Queue object in java?

Queue is an interface in java, you could not do that. try:

Queue<Integer> Q = new LinkedList<Integer>();

Why use the 'ref' keyword when passing an object?

Pass a ref if you want to change what the object is:

TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);

void DoSomething(ref TestRef t)
{
  t = new TestRef();
  t.Something = "Not just a changed t, but a completely different TestRef object";
}

After calling DoSomething, t does not refer to the original new TestRef, but refers to a completely different object.

This may be useful too if you want to change the value of an immutable object, e.g. a string. You cannot change the value of a string once it has been created. But by using a ref, you could create a function that changes the string for another one that has a different value.

It is not a good idea to use ref unless it is needed. Using ref gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.

Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the ref keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. int), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:

int x = 1;
Change(ref x);
Debug.Assert(x == 5);
WillNotChange(x);
Debug.Assert(x == 5); // Note: x doesn't become 10

void Change(ref int x)
{
  x = 5;
}

void WillNotChange(int x)
{
  x = 10;
}

SMTP connect() failed PHPmailer - PHP

 $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

Open a file with Notepad in C#

this will open the file with the default windows program (notepad if you haven't changed it);

Process.Start(@"c:\myfile.txt")

CSS On hover show another element

we just can show same label div on hovering like this

<style>
#b {
    display: none;
}

#content:hover~#b{
    display: block;
}

</style>

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

Permission is only granted to system app

Preferences --> EditorEditor --> Inspections --> Android Lint --> uncheck item Using System app permissio

How can I use regex to get all the characters after a specific character, e.g. comma (",")

You can try with the following:

new_string = your_string.split(',').pop().trim();

This is how it works:

  • split(',') creates an array made of the different parts of your_string

(e.g. if the string is "'SELECT___100E___7',24", the array would be ["'SELECT___100E___7'", "24"]).

  • pop() gets the last element of the array

(in the example, it would be "24").

This would already be enough, but in case there might be some spaces (not in the case of the OP, but more in general), we could have:

  • trim() that would remove the spaces around the string (in case it would be " 24 ", it would become simply "24")

It's a simple solution and surely easier than a regexp.

How can I print literal curly-brace characters in a string and also use .format on it?

You can do this by using raw string method by simply adding character 'r' without quotes before the string.

# to print '{I am inside braces}'
print(r'{I am inside braces}')

Preventing console window from closing on Visual Studio C/C++ Console application

In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to "Console (/SUBSYSTEM:CONSOLE)" under Configuration Properties.

  1. Go to "View" then select "Property Manager"
  2. Right click on the project/solution and select "Property". This opens a Test property page
  3. Navigate to the linker then select "System"
  4. Click on "SubSystem" and a drop down appears
  5. Choose "Console (/SUBSYSTEM:CONSOLE)"
  6. Apply and save
  7. The next time you run your code with "CTRL +F5", you should see the output.

Maximum number of rows in an MS Access database engine table?

Some comments:

  1. Jet/ACE files are organized in data pages, which means there is a certain amount of slack space when your record boundaries are not aligned with your data pages.

  2. Row-level locking will greatly reduce the number of possible records, since it forces one record per data page.

  3. In Jet 4, the data page size was increased to 4KBs (from 2KBs in Jet 3.x). As Jet 4 was the first Jet version to support Unicode, this meant that you could store 1GB of double-byte data (i.e., 1,000,000,000 double-byte characters), and with Unicode compression turned on, 2GBs of data. So, the number of records is going to be affected by whether or not you have Unicode compression on.

  4. Since we don't know how much room in a Jet/ACE file is taken up by headers and other metadata, nor precisely how much room index storage takes, the theoretical calculation is always going to be under what is practical.

  5. To get the most efficient possible storage, you'd want to use code to create your database rather than the Access UI, because Access creates certain properties that pure Jet does not need. This is not to say there are a lot of these, as properties set to the Access defaults are usually not set at all (the property is created only when you change it from the default value -- this can be seen by cycling through a field's properties collection, i.e., many of the properties listed for a field in the Access table designer are not there in the properties collection because they haven't been set), but you might want to limit yourself to Jet-specific data types (hyperlink fields are Access-only, for instance).

I just wasted an hour mucking around with this using Rnd() to populate 4 fields defined as type byte, with composite PK on the four fields, and it took forever to append enough records to get up to any significant portion of 2GBs. At over 2 million records, the file was under 80MBs. I finally quit after reaching just 700K 7 MILLION records and the file compacted to 184MBs. The amount of time it would take to get up near 2GBs is just more than I'm willing to invest!

How do I open a Visual Studio project in design view?

You can double click directly on the .cs file representing your form in the Solution Explorer :

Solution explorer with Design View circled

This will open Form1.cs [Design], which contains the drag&drop controls.

If you are directly in the code behind (The file named Form1.cs, without "[Design]"), you can press Shift + F7 (or only F7 depending on the project type) instead to open it.

From the design view, you can switch back to the Code Behind by pressing F7.

Calculate correlation with cor(), only for numerical columns

if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:

set.seed(10)

x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]

cor(x)

Error in cor(x) : 'x' must be numeric

but

cor(x[sapply(x, is.numeric)])

             V1         V2          V3          V4          V5          V6          V7
V1   1.00000000  0.3025766 -0.22473884 -0.72468776  0.18890578  0.14466161  0.05325308
V2   0.30257657  1.0000000 -0.27871430 -0.29075170  0.16095258  0.10538468 -0.15008158
V3  -0.22473884 -0.2787143  1.00000000 -0.22644156  0.07276013 -0.35725182 -0.05859479
V4  -0.72468776 -0.2907517 -0.22644156  1.00000000 -0.19305921  0.16948333 -0.01025698
V5   0.18890578  0.1609526  0.07276013 -0.19305921  1.00000000  0.07339531 -0.31837954
V6   0.14466161  0.1053847 -0.35725182  0.16948333  0.07339531  1.00000000  0.02514081
V7   0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954  0.02514081  1.00000000
V8   0.44705527  0.1698571  0.39970105 -0.42461411  0.63951574  0.23065830 -0.28967977
V9   0.21006372 -0.4418132 -0.18623823 -0.25272860  0.15921890  0.36182579 -0.18437981
V10  0.02326108  0.4618036 -0.25205899 -0.05117037  0.02408278  0.47630138 -0.38592733
              V8           V9         V10
V1   0.447055266  0.210063724  0.02326108
V2   0.169857120 -0.441813231  0.46180357
V3   0.399701054 -0.186238233 -0.25205899
V4  -0.424614107 -0.252728595 -0.05117037
V5   0.639515737  0.159218895  0.02408278
V6   0.230658298  0.361825786  0.47630138
V7  -0.289679766 -0.184379813 -0.38592733
V8   1.000000000  0.001023392  0.11436143
V9   0.001023392  1.000000000  0.15301699
V10  0.114361431  0.153016985  1.00000000

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

What is key=lambda

A lambda is an anonymous function:

>>> f = lambda: 'foo'
>>> print f()
foo

It is often used in functions such as sorted() that take a callable as a parameter (often the key keyword parameter). You could provide an existing function instead of a lambda there too, as long as it is a callable object.

Take the sorted() function as an example. It'll return the given iterable in sorted order:

>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']

but that sorts uppercased words before words that are lowercased. Using the key keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:

>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']

We had to create a separate function for that, we could not inline the def lowercased() line into the sorted() expression:

>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
  File "<stdin>", line 1
    sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
                                                           ^
SyntaxError: invalid syntax

A lambda on the other hand, can be specified directly, inline in the sorted() expression:

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']

Lambdas are limited to one expression only, the result of which is the return value.

There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.

How to create a localhost server to run an AngularJS project

Use local-web-server npm package.

https://www.npmjs.com/package/local-web-server

$ npm install -g local-web-server
$ cd <your-app-folder>
$ ws

Also, you can run

$ ws -p 8181

-p defines the port you want to use

After that, just go to your browser and access http:localhost:8181/

Java: Find .txt files in specified folder

Try:

List<String> textFiles(String directory) {
  List<String> textFiles = new ArrayList<String>();
  File dir = new File(directory);
  for (File file : dir.listFiles()) {
    if (file.getName().endsWith((".txt"))) {
      textFiles.add(file.getName());
    }
  }
  return textFiles;
}

You want to do a case insensitive search in which case:

    if (file.getName().toLowerCase().endsWith((".txt"))) {

If you want to recursively search for through a directory tree for text files, you should be able to adapt the above as either a recursive function or an iterative function using a stack.

How to reload the datatable(jquery) data?

You can use a simple approach...

$('YourDataTableID').dataTable()._fnAjaxUpdate();

It will refresh the data by making an ajax request with the same parameters. Very simple.

How to simulate a touch event in Android?

Here is a monkeyrunner script that sends touch and drags to an application. I have been using this to test that my application can handle rapid repetitive swipe gestures.

# This is a monkeyrunner jython script that opens a connection to an Android
# device and continually sends a stream of swipe and touch gestures.
#
# See http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html
#
# usage: monkeyrunner swipe_monkey.py
#

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

# Connects to the current device
device = MonkeyRunner.waitForConnection()

# A swipe left from (x1, y) to (x2, y) in 2 steps
y = 400
x1 = 100
x2 = 300
start = (x1, y)
end = (x2, y)
duration = 0.2
steps = 2
pause = 0.2

for i in range(1, 250):
    # Every so often inject a touch to spice things up!
    if i % 9 == 0:
        device.touch(x2, y, 'DOWN_AND_UP')
        MonkeyRunner.sleep(pause)
    # Swipe right
    device.drag(start, end, duration, steps)
    MonkeyRunner.sleep(pause)
    # Swipe left
    device.drag(end, start, duration, steps)
    MonkeyRunner.sleep(pause)

Application_Start not firing?

The following helps in any case (no matter if you're using IIS, Cassini or whatever):

  1. Set your breakpoint in Application_Start
  2. Start debugging (breakpoint most probably is not hit) -> a page is shown in the browser
  3. Change web.config (e.g. enter a blank line) and save it
  4. Reload the page in the browser -> breakpoint is hit!

Why does this work? When web.config is changed, the web server (IIS, Cassini, etc.) does a recycle, but in this case (for whatever reason), the process keeps the same, so you keep attached to it with the debugger (Visual Studio).

How to use <md-icon> in Angular Material?

It actually works now from bower.

bower install material-design-icons --save

It downloads 37.1 KBs. Then it extracts and installs. You will see a folder called material-design-icons in bower_components folder. The total size is around 299KBs

How to save RecyclerView's scroll position using RecyclerView.State?

Activity.java:

public RecyclerView.LayoutManager mLayoutManager;

Parcelable state;

    mLayoutManager = new LinearLayoutManager(this);


// Inside `onCreate()` lifecycle method, put the below code :

    if(state != null) {
    mLayoutManager.onRestoreInstanceState(state);

    } 

    @Override
    protected void onResume() {
        super.onResume();

        if (state != null) {
            mLayoutManager.onRestoreInstanceState(state);
        }
    }   

   @Override
    protected void onPause() {
        super.onPause();

        state = mLayoutManager.onSaveInstanceState();

    }   

Why I'm using OnSaveInstanceState() in onPause() means, While switch to another activity onPause would be called.It will save that scroll position and restore the position when we coming back from another activity.

How to save S3 object to a file using boto3

# Preface: File is json with contents: {'name': 'Android', 'status': 'ERROR'}

import boto3
import io

s3 = boto3.resource('s3')

obj = s3.Object('my-bucket', 'key-to-file.json')
data = io.BytesIO()
obj.download_fileobj(data)

# object is now a bytes string, Converting it to a dict:
new_dict = json.loads(data.getvalue().decode("utf-8"))

print(new_dict['status']) 
# Should print "Error"

Rename multiple files by replacing a particular pattern in the filenames using a shell script

You can try this:

for file in *.jpg;
do
  mv $file $somestring_${file:((-7))}
done

You can see "parameter expansion" in man bash to understand the above better.

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

a MySQL-only solution would be something like this:

SELECT IF (UNIX_TIMESTAMP(`field`) > UNIX_TIMESTAMP(), `field`,'GO AHEAD') as `yourdate`
FROM `table`

How to print a string multiple times?

So I take it if the user enters 2, you want the output to be something like:

!!
!!
!!
!!

Correct?

To get that, you would need something like:

rows = 4
times_to_repeat = int(raw_input("How many times to repeat per row? ")

for i in range(rows):
    print "!" * times_to_repeat

That would result in:

How many times to repeat per row?
>> 4
!!!!
!!!!
!!!!
!!!!

I have not tested this, but it should run error free.

What is the difference between '/' and '//' when used for division?

5.0//2 results in 2.0, and not 2 because the return type of the return value from // operator follows python coercion (type casting) rules.

Python promotes conversion of lower datatype (integer) to higher data type (float) to avoid data loss.

Find files and tar them (with spaces)

Why not give something like this a try: tar cvf scala.tar `find src -name *.scala`

how to modify the size of a column

This was done using Toad for Oracle 12.8.0.49

ALTER TABLE SCHEMA.TABLENAME 
    MODIFY (COLUMNNAME NEWDATATYPE(LENGTH)) ;

For example,

ALTER TABLE PAYROLL.EMPLOYEES 
    MODIFY (JOBTITLE VARCHAR2(12)) ;

JavaFX and OpenJDK

JavaFX is part of OpenJDK

The JavaFX project itself is open source and is part of the OpenJDK project.

Update Dec 2019

For current information on how to use Open Source JavaFX, visit https://openjfx.io. This includes instructions on using JavaFX as a modular library accessed from an existing JDK (such as an Open JDK installation).

The open source code repository for JavaFX is at https://github.com/openjdk/jfx.

At the source location linked, you can find license files for open JavaFX (currently this license matches the license for OpenJDK: GPL+classpath exception).

The wiki for the project is located at: https://wiki.openjdk.java.net/display/OpenJFX/Main

If you want a quick start to using open JavaFX, the Belsoft Liberica JDK distributions provide pre-built binaries of OpenJDK that (currently) include open JavaFX for a variety of platforms.

For distribution as self-contained applications, Java 14, is scheduled to implement JEP 343: Packaging Tool, which "Supports native packaging formats to give end users a natural installation experience. These formats include msi and exe on Windows, pkg and dmg on macOS, and deb and rpm on Linux.", for deployment of OpenJFX based applications with native installers and no additional platform dependencies (such as a pre-installed JDK).


Older information which may become outdated over time

Building JavaFX from the OpenJDK repository

You can build an open version of OpenJDK (including JavaFX) completely from source which has no dependencies on the Oracle JDK or closed source code.

Update: Using a JavaFX distribution pre-built from OpenJDK sources

As noted in comments to this question and in another answer, the Debian Linux distributions offer a JavaFX binary distibution based upon OpenJDK:

(currently this only works for Java 8 as far as I know).

Differences between Open JDK and Oracle JDK with respect to JavaFX

The following information was provided for Java 8. As of Java 9, VP6 encoding is deprecated for JavaFX and the Oracle WebStart/Browser embedded application deployment technology is also deprecated. So future versions of JavaFX, even if they are distributed by Oracle, will likely not include any technology which is not open source.

Oracle JDK includes some software which is not usable from the OpenJDK. There are two main components which relate to JavaFX.

  1. The ON2 VP6 video codec, which is owned by Google and Google has not open sourced.
  2. The Oracle WebStart/Browser Embedded application deployment technology.

This means that an open version of JavaFX cannot play VP6 FLV files. This is not a big loss as it is difficult to find VP6 encoders or media encoded in VP6.

Other more common video formats, such as H.264 will playback fine with an open version of JavaFX (as long as you have the appropriate codecs pre-installed on the target machine).

The lack of WebStart/Browser Embedded deployment technology is really something to do with OpenJDK itself rather than JavaFX specifically. This technology can be used to deploy non-JavaFX applications.

It would be great if the OpenSource community developed a deployment technology for Java (and other software) which completely replaced WebStart and Browser Embedded deployment methods, allowing a nice light-weight, low impact user experience for application distribution. I believe there have been some projects started to serve such a goal, but they have not yet reached a high maturity and adoption level.

Personally, I feel that WebStart/Browser Embedded deployments are legacy technology and there are currently better ways to deploy many JavaFX applications (such as self-contained applications).

Update Dec, 2019:

An open source version of WebStart for JDK 11+ has been developed and is available at https://openwebstart.com.

Who needs to create Linux OpenJDK Distributions which include JavaFX

It is up to the people which create packages for Linux distributions based upon OpenJDK (e.g. Redhat, Ubuntu etc) to create RPMs for the JDK and JRE that include JavaFX. Those software distributors, then need to place the generated packages in their standard distribution code repositories (e.g. fedora/red hat network yum repositories). Currently this is not being done, but I would be quite surprised if Java 8 Linux packages did not include JavaFX when Java 8 is released in March 2014.

Update, Dec 2019:

Now that JavaFX has been separated from most binary JDK and JRE distributions (including Oracle's distribution) and is, instead, available as either a stand-alone SDK, set of jmods or as a library dependencies available from the central Maven repository (as outlined as https://openjfx.io), there is less of a need for standard Linux OpenJDK distributions to include JavaFX.

If you want a pre-built JDK which includes JavaFX, consider the Liberica JDK distributions, which are provided for a variety of platforms.

Advice on Deployment for Substantial Applications

I advise using Java's self-contained application deployment mode.

A description of this deployment mode is:

Application is installed on the local drive and runs as a standalone program using a private copy of Java and JavaFX runtimes. The application can be launched in the same way as other native applications for that operating system, for example using a desktop shortcut or menu entry.

You can build a self-contained application either from the Oracle JDK distribution or from an OpenJDK build which includes JavaFX. It currently easier to do so with an Oracle JDK.

As a version of Java is bundled with your application, you don't have to care about what version of Java may have been pre-installed on the machine, what capabilities it has and whether or not it is compatible with your program. Instead, you can test your application against an exact Java runtime version, and distribute that with your application. The user experience for deploying your application will be the same as installing a native application on their machine (e.g. a windows .exe or .msi installed, an OS X .dmg, a linux .rpm or .deb).

Note: The self-contained application feature was only available for Java 8 and 9, and not for Java 10-13. Java 14, via JEP 343: Packaging Tool, is scheduled to again provide support for this feature from OpenJDK distributions.

Update, April 2018: Information on Oracle's current policy towards future developments

How to fit a smooth curve to my data in R?

In ggplot2 you can do smooths in a number of ways, for example:

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  geom_smooth(method = "gam", formula = y ~ poly(x, 2)) 
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  geom_smooth(method = "loess", span = 0.3, se = FALSE) 

enter image description here enter image description here

jQuery - how to write 'if not equal to' (opposite of ==)

!=

For example,

if ("apple" != "orange")
  // true, the string "apple" is not equal to the string "orange"

Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1') [not equal])

The declared package does not match the expected package ""

Make sure that You have created a correct package.You might get a chance to create folder instead of package

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

For me, something different worked, that I found in on this answer from a similar question. Probably won't help OP, but maybe someone like me that had a similar problem.

You should indeed use rvm, but as no one explained to you how to do this without rvm, here you go:

sudo gem install tzinfo builder memcache-client rack rack-test rack-mount \
  abstract erubis activesupport mime-types mail text-hyphen text-format   \
  thor i18n rake bundler arel railties rails --prerelease --force

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

I was running into a similar issue where the whole ../lib/utils directory couldn't be found when I tried executing Mocha via npm test. I tried the mentioned solutions here with no luck. Ultimately I ended up uninstalling and reinstalling the Mocha package that was a dependency in the npm project I was working in and it worked after that. So if anyone's having this issue with an npm package installed as a dependency, try uninstalling and reinstalling the package if you haven't already!

HttpServletRequest - how to obtain the referring URL?

As all have mentioned it is

request.getHeader("referer");

I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.

More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them.

The Source Origin check recommended here relies on three of these protected headers: Origin, Referer, and Host, making it a pretty strong CSRF defense all on its own.

You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

Docker error cannot delete docker container, conflict: unable to remove repository reference

Remove docker images >

List all containers

docker container ls

List all images

docker image ls

Stop container by container id

docker container stop <container_id>

Remove container by container id

docker container rm <container_id>

If don't want stop and remove, can force remove

docker container rm -f <container_id>

Remove image

docker image rm <image_id>

Done!

Select row and element in awk

Since awk and perl are closely related...


Perl equivalents of @Dennis's awk solutions:

To print the second line:
perl -ne 'print if $. == 2' file

To print the second field:
perl -lane 'print $F[1]' file

To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file


Perl equivalent of @Glenn's solution:

Print the j'th field of the i'th line

perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file


Perl equivalents of @Hai's solutions:

if you are looking for second columns that contains abc:

perl -lane 'print if $F[1] =~ /abc/' foo

... and if you want to print only a particular column:

perl -lane 'print $F[2] if $F[1] =~ /abc/' foo

... and for a particular line number:

perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo


-l removes newlines, and adds them back in when printing
-a autosplits the input line into array @F, using whitespace as the delimiter
-n loop over each line of the input file
-e execute the code within quotes
$F[1] is the second element of the array, since Perl starts at 0
$. is the line number

How to get current user in asp.net core

It would appear that as of now (April of 2017) that the following works:

public string LoggedInUser => User.Identity.Name;

At least while within a Controller

Get keys from HashMap in Java

private Map<String, Integer> _map= new HashMap<String, Integer>();
Iterator<Map.Entry<String,Integer>> itr=  _map.entrySet().iterator();
                //please check 
                while(itr.hasNext())
                {
                    System.out.println("key of : "+itr.next().getKey()+" value of      Map"+itr.next().getValue());
                }

React-Redux: Actions must be plain objects. Use custom middleware for async actions

You have to dispatch after the async request ends.

This would work:

export function bindComments(postId) {
    return function(dispatch) {
        return API.fetchComments(postId).then(comments => {
            // dispatch
            dispatch({
                type: BIND_COMMENTS,
                comments,
                postId
            });
        });
    };
}

for loop in Python

Here are some example to iterate over integer range and string:

#(initial,final but not included,gap)
for i in range(1,10,2): 
  print(i); 
1,3,5,7,9

# (initial, final but not included)  
# note: 4 not included
for i in range (1,4): 
   print(i);
1,2,3 

#note: 5 not included
for i in range (5):
  print (i);
0,1,2,3,4 

# you can also iterate over strings
myList = ["ml","ai","dl"];  

for i in myList:
  print(i);
output:  ml,ai,dl

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

set environment variable in python script

There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using shell=True as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3's shlex.quote() to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).

shell=False is always the default where you pass an argument array.

Now the safe solutions...

Method #1

Change your own process's environment - the new environment will apply to python itself and all subprocesses.

os.environ['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Method #2

Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.

myenv = os.environ.copy()
myenv['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command, env=myenv)

Method #3

Unix only: Execute env to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.

command = ['env', 'LD_LIBRARY_PATH=my_path', 'sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Of course if var1 contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior with shell=True you must compose a command array that contain the splitted string:

command = ['sqsub', '-np'] + var1.split() + ['/homedir/anotherdir/executable']

How to keep :active css style after clicking an element

If you want to keep your links to look like they are :active class, you should define :visited class same as :active so if you have a links in .example then you do something like this:

a.example:active, a.example:visited {
/* Put your active state style code here */ }

The Link visited Pseudo Class is used to select visited links as says the name.

MySql : Grant read only options?

If you want the view to be read only after granting the read permission you can use the ALGORITHM = TEMPTABLE in you view DDL definition.

Maven2: Best practice for Enterprise Project (EAR file)

I've been searching high and low for an end-to-end example of a complete maven-based ear-packaged application and finally stumbled upon this. The instructions say to select option 2 when running through the CLI but for your purposes, use option 1.

Pseudo-terminal will not be allocated because stdin is not a terminal

Also with option -T from manual

Disable pseudo-tty allocation

How to remove pip package after deleting it manually

I met the same issue while experimenting with my own Python library and what I've found out is that pip freeze will show you the library as installed if your current directory contains lib.egg-info folder. And pip uninstall <lib> will give you the same error message.

  1. Make sure your current directory doesn't have any egg-info folders
  2. Check pip show <lib-name> to see the details about the location of the library, so you can remove files manually.

copying all contents of folder to another folder using batch file?

I have written a .bat file to copy and paste file to a temporary folder and make it zip and transfer into a smb mount point, Hope this would help,

    @echo off
    if not exist "C:\Temp Backup\" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
    if not exist "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP"
    if not exist "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
    xcopy /s/e/q "C:\Source" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
   Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
    "C:\Program Files (x86)\WinRAR\WinRAR.exe" a  "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP\ZIP_Backup_%date:~-4,4%_%date:~-10,2%_%date:~-7,2%.rar" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\TELIUM"
    "C:\Program Files (x86)\WinRAR\WinRAR.exe" a  "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP\ZIP_Backup_Log_%date:~-4,4%_%date:~-10,2%_%date:~-7,2%.rar" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
    NET USE \\IP\IPC$ /u:IP\username password
    ROBOCOPY "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP"  "\\IP\Backup Folder" /z /MIR /unilog+:"C:\backup_log_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log"
    NET USE \\172.20.10.103\IPC$ /D
    RMDIR /S /Q "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"

Including dependencies in a jar with Maven

This post may be a bit old, but I also had the same problem recently. The first solution proposed by John Stauffer is a good one, but I had some problems as I am working this spring. The spring's dependency-jars I use have some property files and xml-schemas declaration which share the same paths and names. Although these jars come from the same versions, the jar-with-dependencies maven-goal was overwriting theses file with the last file found.

In the end, the application was not able to start as the spring jars could not find the correct properties files. In this case the solution propose by Rop have solved my problem.

Also since then, the spring-boot project now exist. It has a very cool way to manage this problem by providing a maven goal which overload the package goal and provide its own class loader. See spring-boots Reference Guide

How to change text color of simple list item

Create an xml file in res/values and copy the below code

<style name="BlackText">
<item name="android:textColor">#000000</item>
</style>

and the specify the style in activity in Manifest like below

 android:theme="@style/BlackText"

Detecting input change in jQuery?

// .blur is triggered when element loses focus

$('#target').blur(function() {
  alert($(this).val());
});

// To trigger manually use:

$('#target').blur();

Month name as a string

A sample way to get the date and time in this format "2018 Nov 01 16:18:22" use this

DateFormat dateFormat = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
        Date date = new Date();
         dateFormat.format(date);

How can I set the color of a selected row in DataGrid

I spent the better part of a day fiddling with this problem. Turned out the RowBackground Property on the DataGrid - which I had set - was overriding all attempts to change it in . As soon as I deleted it, everything worked. (Same goes for Foreground set in DataGridTextColumn, by the way).

remote rejected master -> master (pre-receive hook declined)

I got the same error and looked into activity. Where I found that I had two package lock files which was causing the error.

How to set the Default Page in ASP.NET?

If using IIS 7 or IIS 7.5 you can use

<system.webServer>
    <defaultDocument>
        <files>
            <clear />
            <add value="CreateThing.aspx" />
        </files>
    </defaultDocument>
</system.webServer>

https://docs.microsoft.com/en-us/iis/configuration/system.webServer/defaultDocument/

How to set app icon for Electron / Atom Shell App

Updated package.json:

"build": {
  "appId": "com.my-website.my-app",
  "productName": "MyApp",
  "copyright": "Copyright © 2019 ${author}",
  "mac": {
    "icon": "./public/icons/mac/icon.icns",     <---------- set Mac Icons
    "category": "public.app-category.utilities"
  },
  "win": {
    "icon": "./public/icons/png/256x256.png" <---------- set Win Icon
  },
  "files": [
    "./build/**/*",
    "./dist/**/*",
    "./node_modules/**/*",
    "./public/**/*",       <---------- need for get access to icons
    "*.js"
  ],
  "directories": {
    "buildResources": "public" <---------- folder where placed icons
  }
},

After build application you can see icons. This solution don't show icons in developer mode. I don't setup icons in new BrowserWindow().

Python POST binary data

This has nothing to do with a malformed upload. The HTTP error clearly specifies 401 unauthorized, and tells you the CSRF token is invalid. Try sending a valid CSRF token with the upload.

More about csrf tokens here:

What is a CSRF token ? What is its importance and how does it work?

Can anyone explain python's relative imports?

Checking it out in python3:

python -V
Python 3.6.5

Example1:

.
+-- parent.py
+-- start.py
+-- sub
    +-- relative.py

- start.py
import sub.relative

- parent.py
print('Hello from parent.py')

- sub/relative.py
from .. import parent

If we run it like this(just to make sure PYTHONPATH is empty):

PYTHONPATH='' python3 start.py

Output:

Traceback (most recent call last):
  File "start.py", line 1, in <module>
    import sub.relative
  File "/python-import-examples/so-example-v1/sub/relative.py", line 1, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/relative.py

- sub/relative.py
import parent

If we run it like this:

PYTHONPATH='' python3 start.py

Output:

Hello from parent.py

Example2:

.
+-- parent.py
+-- sub
    +-- relative.py
    +-- start.py

- parent.py
print('Hello from parent.py')

- sub/relative.py
print('Hello from relative.py')

- sub/start.py
import relative
from .. import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 2, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/start.py:

- sub/start.py
import relative
import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 3, in <module>
    import parent
ModuleNotFoundError: No module named 'parent'

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

Also it's better to use import from root folder, i.e.:

- sub/start.py
import sub.relative
import parent

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

How to test if a list contains another list?

Here is my version:

def contains(small, big):
    for i in xrange(len(big)-len(small)+1):
        for j in xrange(len(small)):
            if big[i+j] != small[j]:
                break
        else:
            return i, i+len(small)
    return False

It returns a tuple of (start, end+1) since I think that is more pythonic, as Andrew Jaffe points out in his comment. It does not slice any sublists so should be reasonably efficient.

One point of interest for newbies is that it uses the else clause on the for statement - this is not something I use very often but can be invaluable in situations like this.

This is identical to finding substrings in a string, so for large lists it may be more efficient to implement something like the Boyer-Moore algorithm.

Delete multiple rows by selecting checkboxes using PHP

<?php $sql = "SELECT * FROM guest_book";
                            $res = mysql_query($sql);
                            if (mysql_num_rows($res)) {
                            $query = mysql_query("SELECT * FROM guest_book ORDER BY id");
                            $i=1;
                            while($row = mysql_fetch_assoc($query)){
                            ?>


<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>"  />

<?php $i++; }} ?>


<input type="submit" value="Delete" name="Delete" />

if($_REQUEST['Delete'] != '')
{
    if(!empty($_REQUEST['checkboxstatus'])) {
        $checked_values = $_REQUEST['checkboxstatus'];
        foreach($checked_values as $val) {
            $sqldel = "DELETE from guest_book WHERE id = '$val'";
           mysql_query($sqldel);

        }
    }
} 

How to limit the maximum value of a numeric field in a Django model?

Here is the best solution if you want some extra flexibility and don't want to change your model field. Just add this custom validator:

#Imports
from django.core.exceptions import ValidationError      

class validate_range_or_null(object):
    compare = lambda self, a, b, c: a > c or a < b
    clean = lambda self, x: x
    message = ('Ensure this value is between %(limit_min)s and %(limit_max)s (it is %(show_value)s).')
    code = 'limit_value'

    def __init__(self, limit_min, limit_max):
        self.limit_min = limit_min
        self.limit_max = limit_max

    def __call__(self, value):
        cleaned = self.clean(value)
        params = {'limit_min': self.limit_min, 'limit_max': self.limit_max, 'show_value': cleaned}
        if value:  # make it optional, remove it to make required, or make required on the model
            if self.compare(cleaned, self.limit_min, self.limit_max):
                raise ValidationError(self.message, code=self.code, params=params)

And it can be used as such:

class YourModel(models.Model):

    ....
    no_dependents = models.PositiveSmallIntegerField("How many dependants?", blank=True, null=True, default=0, validators=[validate_range_or_null(1,100)])

The two parameters are max and min, and it allows nulls. You can customize the validator if you like by getting rid of the marked if statement or change your field to be blank=False, null=False in the model. That will of course require a migration.

Note: I had to add the validator because Django does not validate the range on PositiveSmallIntegerField, instead it creates a smallint (in postgres) for this field and you get a DB error if the numeric specified is out of range.

Hope this helps :) More on Validators in Django.

PS. I based my answer on BaseValidator in django.core.validators, but everything is different except for the code.

Android WSDL/SOAP service client

I’ve created a new SOAP client for the Android platform, it is use a JAX-WS generated interfaces, but it is only a proof-of-concept yet.

If you are interested, please try the example and/or watch the source: http://wiki.javaforum.hu/display/ANDROIDSOAP/Home

Update: the version 0.0.4 is out with tutorial:

http://wiki.javaforum.hu/display/ANDROIDSOAP/2012/04/16/Version+0.0.4+released

http://wiki.javaforum.hu/display/ANDROIDSOAP/Step+by+step+tutorial

Difference between @click and v-on:click Vuejs

They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.

Source: official documentation.

JQuery show/hide when hover

This code also works.

_x000D_
_x000D_
$(".circle").hover(function() {$(this).hide(200).show(200);});
_x000D_
.circle{_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    border-radius:50px;_x000D_
    font-size:20px;_x000D_
    color:black;_x000D_
    line-height:100px;_x000D_
    text-align:center;_x000D_
    background:yellow_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>_x000D_
<div class="circle">hover me</div>
_x000D_
_x000D_
_x000D_

isPrime Function for Python Language

def fun(N):#prime test
if N>1 :
    for _ in xrange(5):
        Num=randint(1,N-1)
        if pow(Num,N-1,N)!=1:
            return False
    return True
return False

True if the number is prime otherwise false

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

For OS X and Sublime Text

Make subl available.

Put this in ~/.bash_profile

[[ -s ~/.bashrc ]] && source ~/.bashrc

Put this in ~/.bashrc

export EDITOR=subl

Converting Epoch time into the datetime

First a bit of info in epoch from man gmtime

The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar  time.   When  inter-
       preted  as  an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal
       Time (UTC).

to understand how epoch should be.

>>> time.time()
1347517171.6514659
>>> time.gmtime(time.time())
(2012, 9, 13, 6, 19, 34, 3, 257, 0)

just ensure the arg you are passing to time.gmtime() is integer.

How to download a Nuget package without nuget.exe or Visual Studio extension?

Either make an account on the Nuget.org website, then log in, browse to the package you want and click on the Download link on the left menu.


Or guess the URL. They have the following format:

https://www.nuget.org/api/v2/package/{packageID}/{packageVersion}

Then simply unzip the .nupkg file and extract the contents you need.

How to combine multiple inline style objects?

Need to merge the properties in object. For Example,

const boxStyle = {
  width : "50px",
  height : "50px"
};
const redBackground = {
  ...boxStyle,
  background: "red",
};
const blueBackground = {
  ...boxStyle,
  background: "blue",
}




 <div style={redBackground}></div>
 <div style={blueBackground}></div>

Add item to Listview control

Simple one, just do like this..

ListViewItem lvi = new ListViewItem(pet.Name);
    lvi.SubItems.Add(pet.Type);
    lvi.SubItems.Add(pet.Age);
    listView.Items.Add(lvi);

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

How can I print the contents of an array horizontally?

public static void Main(string[] args)
{
    int[] numbers = new int[10];

    Console.Write("index ");

    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = i;
        Console.Write(numbers[i] + " ");
    }

    Console.WriteLine("");
    Console.WriteLine("");
    Console.Write("value ");

    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = numbers.Length - i;
        Console.Write(numbers[i] + " ");
    }

    Console.ReadKey();
}

OraOLEDB.Oracle provider is not registered on the local machine

I had the same issue after installing the 64 bit Oracle client on Windows 7 64 bit. The solution that worked for me:

  1. Open a command prompt in administrator mode
  2. cd \oracle\product\11.2.0\client_64\BIN
  3. c:\Windows\system32\regsvr32.exe OraOLEDB11.dll

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

Navigation properties are typically defined as virtual so that they can take advantage of certain Entity Framework functionality such as lazy loading.

If a navigation property can hold multiple entities (as in many-to-many or one-to-many relationships), its type must be a list in which entries can be added, deleted, and updated, such as ICollection.

https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

How to determine whether a year is a leap year?

The whole formula can be contained in a single expression:

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

print n, " is a leap year" if is_leap_year(n) else " is not a leap year"

How to iterate through SparseArray?

Simple as Pie. Just make sure you fetch array size before actually performing the loop.

for(int i = 0, arraySize= mySparseArray.size(); i < arraySize; i++) {
   Object obj = mySparseArray.get(/* int key = */ mySparseArray.keyAt(i));
}

Hope this helps.

SSRS the definition of the report is invalid

I got this error on a report I copied from another project and changed the data source. I solved it by opening the properties of my dataset, going to the Parameters section, and literally just reselecting all the parameters in the right column, like I just clicked the dropdown and selected the same column. Then I hit preview, and it worked!

Xpath for href element

This will get you the generic link:

selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do')")).Click();

If you want to have it specify a parameter then you will have to test for each one:

...
int i = 1;

selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do?camp=" + i.ToString() + "')")).Click();
...

The above could utilize a for loop which navigates to and from each camp numbers' page, which could verify a static list of camps.

Please excuse if the code is not perfect, I have not tested myself.

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

How to get char from string by index?

Another recommended exersice for understanding lists and indexes:

L = ['a', 'b', 'c']
for index, item in enumerate(L):
    print index + '\n' + item

0
a
1
b
2
c 

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Properties -> FormBorderStyle -> FixedSingle

if you can not find your Properties tool. Go to View -> Properties Window

Black transparent overlay on image hover with only CSS?

I'd suggest using a pseudo element in place of the overlay element. Because pseudo elements can't be added on enclosed img elements, you would still need to wrap the img element though.

LIVE EXAMPLE HERE -- EXAMPLE WITH TEXT

<div class="image">
    <img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>

As for the CSS, set optional dimensions on the .image element, and relatively position it. If you are aiming for a responsive image, just omit the dimensions and this will still work (example). It's just worth noting that the dimensions must be on the parent element as opposed to the img element itself, see.

.image {
    position: relative;
    width: 400px;
    height: 400px;
}

Give the child img element a width of 100% of the parent and add vertical-align:top to fix the default baseline alignment issues.

.image img {
    width: 100%;
    vertical-align: top;
}

As for the pseudo element, set a content value and absolutely position it relative to the .image element. A width/height of 100% will ensure that this works with varying img dimensions. If you want to transition the element, set an opacity of 0 and add the transition properties/values.

.image:after {
    content: '\A';
    position: absolute;
    width: 100%; height:100%;
    top:0; left:0;
    background:rgba(0,0,0,0.6);
    opacity: 0;
    transition: all 1s;
    -webkit-transition: all 1s;
}

Use an opacity of 1 when hovering over the pseudo element in order to facilitate the transition:

.image:hover:after {
    opacity: 1;
}

END RESULT HERE


If you want to add text on hover:

For the simplest approach, just add the text as the pseudo element's content value:

EXAMPLE HERE

.image:after {
    content: 'Here is some text..';
    color: #fff;

    /* Other styling.. */
}

That should work in most instances; however, if you have more than one img element, you might not want the same text to appear on hover. You could therefore set the text in a data-* attribute and therefore have unique text for every img element.

EXAMPLE HERE

.image:after {
    content: attr(data-content);
    color: #fff;
}

With a content value of attr(data-content), the pseudo element adds the text from the .image element's data-content attribute:

<div data-content="Text added on hover" class="image">
    <img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>

You can add some styling and do something like this:

EXAMPLE HERE

In the above example, the :after pseudo element serves as the black overlay, while the :before pseudo element is the caption/text. Since the elements are independent of each other, you can use separate styling for more optimal positioning.

.image:after, .image:before {
    position: absolute;
    opacity: 0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
}
.image:after {
    content: '\A';
    width: 100%; height:100%;
    top: 0; left:0;
    background:rgba(0,0,0,0.6);
}
.image:before {
    content: attr(data-content);
    width: 100%;
    color: #fff;
    z-index: 1;
    bottom: 0;
    padding: 4px 10px;
    text-align: center;
    background: #f00;
    box-sizing: border-box;
    -moz-box-sizing:border-box;
}
.image:hover:after, .image:hover:before {
    opacity: 1;
}

JFrame background image

You can do:

setContentPane(new JLabel(new ImageIcon("resources/taverna.jpg")));

At first line of the Jframe class constructor, that works fine for me

MongoDB vs. Cassandra

I haven't used Cassandra, but I have used MongoDB and think it's awesome.

If you're after simple setup, this is it: You simply untar MongoDB and run the mongod daemon and that's it ... it's running.

Obviously that's only a starter, but to get you started it's easy.

Docker: adding a file from a parent directory

If you are using skaffold, use 'context:' to specify context location for each image dockerfile - context: ../../../

            apiVersion: skaffold/v2beta4
            kind: Config
            metadata:
                name: frontend
            build:
                artifacts:
                    - image: nginx-angular-ui
                      context: ../../../
                      sync:
                          # A local build will update dist and sync it to the container
                          manual:
                              - src: './dist/apps'
                                dest: '/usr/share/nginx/html'
                      docker:
                          dockerfile: ./tools/pipelines/dockerfile/nginx.dev.dockerfile
                    - image: webapi/image
                      context: ../../../../api/
                      docker:
                          dockerfile: ./dockerfile
            deploy:
                kubectl:
                    manifests:
                        - ./.k8s/*.yml

skaffold run -f ./skaffold.yaml

Passing a variable to a powershell script via command line

Make this in your test.ps1, at the first line

param(
[string]$a
)

Write-Host $a

Then you can call it with

./Test.ps1 "Here is your text"

Found here (English)

How to set the default value of an attribute on a Laravel model

The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    // auto-sets values on creation
    static::creating(function ($query) {
        $query->is_voicemail = $query->is_voicemail ?? true;
    });
}

TypeError: 'module' object is not callable

check the import statements since a module is not callable. In Python, everything (including functions, methods, modules, classes etc.) is an object.

What's the u prefix in a Python string?

The u in u'Some String' means that your string is a Unicode string.

Q: I'm in a terrible, awful hurry and I landed here from Google Search. I'm trying to write this data to a file, I'm getting an error, and I need the dead simplest, probably flawed, solution this second.

A: You should really read Joel's Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) essay on character sets.

Q: sry no time code pls

A: Fine. try str('Some String') or 'Some String'.encode('ascii', 'ignore'). But you should really read some of the answers and discussion on Converting a Unicode string and this excellent, excellent, primer on character encoding.

Android: Clear the back stack

for me adding Intent.FLAG_ACTIVITY_CLEAR_TASK solved the problem

Intent i = new Intent(SettingsActivity.this, StartPage.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP  | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
finish();

Where is the application.properties file in a Spring Boot project?

You will need to add the application.properties file in your classpath.

If you are using Maven or Gradle, you can just put the file under src/main/resources.
If you are not using Maven or any other build tools, put that under your src folder and you should be fine.

Then you can just add an entry server.port = xxxx in the properties file.

Putting an if-elif-else statement on one line?

Just nest another if clause in the else statement. But that doesn't make it look any prettier.

>>> x=5
>>> x if x>0 else ("zero" if x==0 else "invalid value")
5
>>> x = 0
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'zero'
>>> x = -1
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'invalid value'

How to get the system uptime in Windows?

I use this little PowerShell snippet:

function Get-SystemUptime {
    $operatingSystem = Get-WmiObject Win32_OperatingSystem
    "$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}

which then yields something like the following:

PS> Get-SystemUptime
6.20:40:40.2625526

Convert string to float?

Try this:

String yourVal = "20.5";
float a = (Float.valueOf(yourVal)).floatValue(); 
System.out.println(a);

Node.js Best Practice Exception Handling

I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post.

You can also use something like Bugsnag to track your uncaught exceptions and be notified via email, chatroom or have a ticket created for an uncaught exception (I am the co-founder of Bugsnag).

How to get current memory usage in android?

Here is a way to calculate memory usage of currently running application:

public static long getUsedMemorySize() {

    long freeSize = 0L;
    long totalSize = 0L;
    long usedSize = -1L;
    try {
        Runtime info = Runtime.getRuntime();
        freeSize = info.freeMemory();
        totalSize = info.totalMemory();
        usedSize = totalSize - freeSize;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return usedSize;

}

Joda DateTime to Timestamp conversion

Actually this is not a duplicate question. And this how i solve my problem after several times :

   int offset = DateTimeZone.forID("anytimezone").getOffset(new DateTime());

This is the way to get offset from desired timezone.

Let's return to our code, we were getting timestamp from a result set of query, and using it with timezone to create our datetime.

   DateTime dt = new DateTime(rs.getTimestamp("anytimestampcolumn"),
                         DateTimeZone.forID("anytimezone"));

Now we will add our offset to the datetime, and get the timestamp from it.

    dt = dt.plusMillis(offset);
    Timestamp ts = new Timestamp(dt.getMillis());

May be this is not the actual way to get it, but it solves my case. I hope it helps anyone who is stuck here.

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

I made a mistake by adding a service into imports array instead of providers array.

@NgModule({
  imports: [
    MyService // wrong here
  ],
  providers: [
    MyService // should add here
  ]
})
export class AppModule { }

Angular says you need to add Injectables into providers array.

Is JavaScript object-oriented?

I think when you can follow the same or similar design patterns as a true OO language like Java/C#, you can pretty much call it an OO language. Some aspects are obviously different but you can still use very well established OO design pattersn.

Create Test Class in IntelliJ

I think you can always try the Ctrl + Shift + A to find the action/command you need.
Here you can try to press Ctrl + Shift + A and input «test» to find the command.

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

Also to note you can see your android dependencies, by going to your Android Studio Gradle view, and selecting the target "androidDependencies".

One more tip: I was having this issue, until I removed the v4 support lib from the libs folder in both the project and my related module/library project(s).

jQuery Set Cursor Position in Text Area

I have two functions:

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) {
  setSelectionRange(input, pos, pos);
}

Then you can use setCaretToPos like this:

setCaretToPos(document.getElementById("YOURINPUT"), 4);

Live example with both a textarea and an input, showing use from jQuery:

_x000D_
_x000D_
function setSelectionRange(input, selectionStart, selectionEnd) {_x000D_
  if (input.setSelectionRange) {_x000D_
    input.focus();_x000D_
    input.setSelectionRange(selectionStart, selectionEnd);_x000D_
  } else if (input.createTextRange) {_x000D_
    var range = input.createTextRange();_x000D_
    range.collapse(true);_x000D_
    range.moveEnd('character', selectionEnd);_x000D_
    range.moveStart('character', selectionStart);_x000D_
    range.select();_x000D_
  }_x000D_
}_x000D_
_x000D_
function setCaretToPos(input, pos) {_x000D_
  setSelectionRange(input, pos, pos);_x000D_
}_x000D_
_x000D_
$("#set-textarea").click(function() {_x000D_
  setCaretToPos($("#the-textarea")[0], 10)_x000D_
});_x000D_
$("#set-input").click(function() {_x000D_
  setCaretToPos($("#the-input")[0], 10);_x000D_
});
_x000D_
<textarea id="the-textarea" cols="40" rows="4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
<br><input type="button" id="set-textarea" value="Set in textarea">_x000D_
<br><input id="the-input" type="text" size="40" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit">_x000D_
<br><input type="button" id="set-input" value="Set in input">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

As of 2016, tested and working on Chrome, Firefox, IE11, even IE8 (see that last here; Stack Snippets don't support IE8).

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

Powershell handles tasks like this fairly handily:

$productCode = (gwmi win32_product | `
                ? { $_.Name -Like "<PRODUCT NAME HERE>*" } | `
                % { $_.IdentifyingNumber } | `
                Select-Object -First 1)

You can then use it to get the uninstall information as well:

$wow = ""
$is32BitInstaller = $True # or $False

if($is32BitInstaller -and [System.Environment]::Is64BitOperatingSystem) 
{
    $wow = "\Wow6432Node" 
}

$regPath = "HKEY_LOCAL_MACHINE\SOFTWARE$wow\Microsoft\Windows\CurrentVersion\Uninstall"

dir "HKLM:\SOFTWARE$wow\Microsoft\Windows\CurrentVersion\Uninstall" | `
? { $_.Name -Like "$regPath\$productCode"  }

Which characters need to be escaped in HTML?

If you're inserting text content in your document in a location where text content is expected1, you typically only need to escape the same characters as you would in XML. Inside of an element, this just includes the entity escape ampersand & and the element delimiter less-than and greater-than signs < >:

& becomes &amp;
< becomes &lt;
> becomes &gt;

Inside of attribute values you must also escape the quote character you're using:

" becomes &quot;
' becomes &#39;

In some cases it may be safe to skip escaping some of these characters, but I encourage you to escape all five in all cases to reduce the chance of making a mistake.

If your document encoding does not support all of the characters that you're using, such as if you're trying to use emoji in an ASCII-encoded document, you also need to escape those. Most documents these days are encoded using the fully Unicode-supporting UTF-8 encoding where this won't be necessary.

In general, you should not escape spaces as &nbsp;. &nbsp; is not a normal space, it's a non-breaking space. You can use these instead of normal spaces to prevent a line break from being inserted between two words, or to insert          extra        space       without it being automatically collapsed, but this is usually a rare case. Don't do this unless you have a design constraint that requires it.


1 By "a location where text content is expected", I mean inside of an element or quoted attribute value where normal parsing rules apply. For example: <p>HERE</p> or <p title="HERE">...</p>. What I wrote above does not apply to content that has special parsing rules or meaning, such as inside of a script or style tag, or as an element or attribute name. For example: <NOT-HERE>...</NOT-HERE>, <script>NOT-HERE</script>, <style>NOT-HERE</style>, or <p NOT-HERE="...">...</p>.

In these contexts, the rules are more complicated and it's much easier to introduce a security vulnerability. I strongly discourage you from ever inserting dynamic content in any of these locations. I have seen teams of competent security-aware developers introduce vulnerabilities by assuming that they had encoded these values correctly, but missing an edge case. There's usually a safer alternative, such as putting the dynamic value in an attribute and then handling it with JavaScript.

If you must, please read the Open Web Application Security Project's XSS Prevention Rules to help understand some of the concerns you will need to keep in mind.

How to format LocalDate to string?

With the help of ProgrammersBlock posts I came up with this. My needs were slightly different. I needed to take a string and return it as a LocalDate object. I was handed code that was using the older Calendar and SimpleDateFormat. I wanted to make it a little more current. This is what I came up with.

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;


    void ExampleFormatDate() {

    LocalDate formattedDate = null;  //Declare LocalDate variable to receive the formatted date.
    DateTimeFormatter dateTimeFormatter;  //Declare date formatter
    String rawDate = "2000-01-01";  //Test string that holds a date to format and parse.

    dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;

    //formattedDate.parse(String string) wraps the String.format(String string, DateTimeFormatter format) method.
    //First, the rawDate string is formatted according to DateTimeFormatter.  Second, that formatted string is parsed into
    //the LocalDate formattedDate object.
    formattedDate = formattedDate.parse(String.format(rawDate, dateTimeFormatter));

}

Hopefully this will help someone, if anyone sees a better way of doing this task please add your input.

How can I list all foreign keys referencing a given table in SQL Server?

You should also mind the references to other objects.

If the table was highly referenced by other tables than it’s probably also highly referenced by other objects such as views, stored procedures, functions and more.

I’d really recommend GUI tool such as ‘view dependencies’ dialog in SSMS or free tool like ApexSQL Search for this because searching for dependencies in other objects can be error prone if you want to do it only with SQL.

If SQL is the only option you could try doing it like this.

select O.name as [Object_Name], C.text as [Object_Definition]
from sys.syscomments C
inner join sys.all_objects O ON C.id = O.object_id
where C.text like '%table_name%'

MySQL Select Date Equal to Today

You can use the CONCAT with CURDATE() to the entire time of the day and then filter by using the BETWEEN in WHERE condition:

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE (users.signup_date BETWEEN CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59'))

How to use the ProGuard in Android Studio?

You can configure your build.gradle file for proguard implementation. It can be at module level or the project level.

 buildTypes {

    debug {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'

    }

}

The configuration shown is for debug level but you can write you own build flavors like shown below inside buildTypes:

    myproductionbuild{
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }

Better to have your debug with minifyEnabled false and productionbuild and other builds as minifyEnabled true.

Copy your proguard-rules.txt file in the root of your module or project folder like

$YOUR_PROJECT_DIR\YoutProject\yourmodule\proguard-rules.txt

You can change the name of your file as you want. After configuration use one of the three options available to generate your build as per the buildType

  1. Go to gradle task in right panel and search for assembleRelease/assemble(#your_defined_buildtype) under module tasks

  2. Go to Build Variant in Left Panel and select the build from drop down

  3. Go to project root directory in File Explorer and open cmd/terminal and run

Linux ./gradlew assembleRelease or assemble(#your_defined_buildtype)

Windows gradlew assembleRelease or assemble(#your_defined_buildtype)

You can find apk in your module/build directory.

More about the configuration and proguard files location is available at the link

http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Running-ProGuard

JPanel Padding in Java

When you need padding inside the JPanel generally you add padding with the layout manager you are using. There are cases that you can just expand the border of the JPanel.

PostgreSQL: role is not permitted to log in

try to run

sudo su - postgres
psql
ALTER ROLE 'dbname'

How to call a shell script from python code?

Subprocess module is a good module to launch subprocesses. You can use it to call shell commands as this:

subprocess.call(["ls","-l"]);
#basic syntax
#subprocess.call(args, *)

You can see its documentation here.

If you have your script written in some .sh file or a long string, then you can use os.system module. It is fairly simple and easy to call:

import os
os.system("your command here")
# or
os.system('sh file.sh')

This command will run the script once, to completion, and block until it exits.

SQL Server : export query as a .txt file

The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.

.bat Example:

C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch

-q MUST be used in the presence of quotations within the query itself.

BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.

Netbeans how to set command line arguments in Java

I am guessing that you are running the file using Run | Run File (or shift-F6) rather than Run | Run Main Project. The NetBeans 7.1 help file (F1 is your friend!) states for the Arguments parameter:

Add arguments to pass to the main class during application execution. Note that arguments cannot be passed to individual files.

I verified this with a little snippet of code:

public class Junk
{
    public static void main(String[] args)
    {
        for (String s : args)
            System.out.println("arg -> " + s);
    }
}

I set Run -> Arguments to x y z. When I ran the file by itself I got no output. When I ran the project the output was:

arg -> x
arg -> y
arg -> z

Format a JavaScript string using placeholders and an object of substitutions?

As with modern browser, placeholder is supported by new version of Chrome / Firefox, similar as the C style function printf().

Placeholders:

  • %s String.
  • %d,%i Integer number.
  • %f Floating point number.
  • %o Object hyperlink.

e.g.

console.log("generation 0:\t%f, %f, %f", a1a1, a1a2, a2a2);

BTW, to see the output:

  • In Chrome, use shortcut Ctrl + Shift + J or F12 to open developer tool.
  • In Firefox, use shortcut Ctrl + Shift + K or F12 to open developer tool.

@Update - nodejs support

Seems nodejs don't support %f, instead, could use %d in nodejs. With %d number will be printed as floating number, not just integer.

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }

Build error: "The process cannot access the file because it is being used by another process"

Deleting Obj, retail and debug folder of the .NET project and re-building again worked for me.

Group By Eloquent ORM

try: ->unique('column')

example:

$users = User::get()->unique('column');

How to pass parameter to a promise function

Try this:

function someFunction(username, password) {
      return new Promise((resolve, reject) => {
        // Do something with the params username and password...
        if ( /* everything turned out fine */ ) {
          resolve("Stuff worked!");
        } else {
          reject(Error("It didn't work!"));
        }
      });
    }
    
    someFunction(username, password)
      .then((result) => {
        // Do something...
      })
      .catch((err) => {
        // Handle the error...
      });

How can I clear console

If you're on Windows:

HANDLE h;
CHAR_INFO v3;
COORD v4;
SMALL_RECT v5;
CONSOLE_SCREEN_BUFFER_INFO v6;
if ((h = (HANDLE)GetStdHandle(0xFFFFFFF5), (unsigned int)GetConsoleScreenBufferInfo(h, &v6)))
{
    v5.Right = v6.dwSize.X;
    v5.Bottom = v6.dwSize.Y;
    v3.Char.UnicodeChar = 32;
    v4.Y = -v6.dwSize.Y;
    v3.Attributes = v6.wAttributes;
    v4.X = 0;
    *(DWORD *)&v5.Left = 0;
    ScrollConsoleScreenBufferW(h, &v5, 0, v4, &v3);
    v6.dwCursorPosition = { 0 };
    HANDLE v1 = GetStdHandle(0xFFFFFFF5);
    SetConsoleCursorPosition(v1, v6.dwCursorPosition);
}

This is what the system("cls"); does without having to create a process to do it.

jQuery checkbox check/uncheck

Use .prop() instead and if we go with your code then compare like this:

Look at the example jsbin:

  $("#news_list tr").click(function () {
    var ele = $(this).find(':checkbox');
    if ($(':checked').length) {
      ele.prop('checked', false);
      $(this).removeClass('admin_checked');
    } else {
      ele.prop('checked', true);
      $(this).addClass('admin_checked');
    }
 });

Changes:

  1. Changed input to :checkbox.
  2. Comparing the length of the checked checkboxes.

Regular expression for URL validation (in JavaScript)

In the accepted answer bobince got it right: validating only the scheme name, ://, and spaces and double quotes is usually enough. Here is how the validation can be implemented in JavaScript:

var url = 'http://www.google.com';
var valid = /^(ftp|http|https):\/\/[^ "]+$/.test(url);
// true

or

var r = /^(ftp|http|https):\/\/[^ "]+$/;
r.test('http://www.goo le.com');
// false

or

var url = 'http:www.google.com';
var r = new RegExp(/^(ftp|http|https):\/\/[^ "]+$/);
r.test(url);
// false

References for syntax:

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

How to upgrade Git to latest version on macOS?

the simplest way I found so far is from git official website. It just computed dependencies and downloaded all of the required libraries/tools

http://git-scm.com/book/en/Getting-Started-Installing-Git

The other major way is to install Git via MacPorts (http://www.macports.org). If you have MacPorts installed, install Git via

$ sudo port install git-core +svn +doc +bash_completion +gitweb

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

Makefile If-Then Else and Loops

Conditional Forms

Simple

conditional-directive
text-if-true
endif

Moderately Complex

conditional-directive
text-if-true
else
text-if-false
endif

More Complex

conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif

Conditional Directives

If Equal Syntax

ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"

If Not Equal Syntax

ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"

If Defined Syntax

ifdef variable-name

If Not Defined Syntax

ifndef variable-name  

foreach Function

foreach Function Syntax

$(foreach var, list, text)  

foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.

Reading a key from the Web.Config using ConfigurationManager

Also you can try this line to get string value from app.config file.

var strName= ConfigurationManager.AppSettings["stringName"];

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

Just in caser anyone ends here like me. In may case despite having enabled unsecure access to my google account, it refused to send the email throwing an SMTP ERROR: Password command failed: 534-5.7.14.

(Solution found at https://know.mailsbestfriend.com/smtp_error_password_command_failed_5345714-1194946499.shtml)

Steps:

  1. log into your google account

  2. Go to https://accounts.google.com/b/0/DisplayUnlockCaptcha and click continue to enable.

  3. Setup your phpmailer as smtp with ssl:

    $mail = new PHPMailer(true);
    
    $mail->CharSet  ="utf-8";
    $mail->SMTPDebug = SMTP::DEBUG_SERVER; // or 0 for no debuggin at all        
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 465; 
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; 
    $mail->SMTPAuth   = true;
    $mail->Username = 'yourgmailaccount';
    $mail->Password = 'yourpassword';
    

And the other $mail object properties as needed.

Hope it helps someone!!

What is the best way to programmatically detect porn images?

A graduate student from National Cheng Kung University in Taiwan did a research on this subject in 2004. He was able to achieve success rate of 89.79% in detecting nude pictures downloaded from the Internet. Here is the link to his thesis: The Study on Naked People Image Detection Based on Skin Color
It's in Chinese therefore you may need a translator in case you can't read it.

CSS-Only Scrollable Table with fixed headers

If you have the option of giving a fixed width to the table cells (and a fixed height to the header), you can used the position: fixed option:

http://jsfiddle.net/thundercracker/ZxPeh/23/

You would just have to stick it in an iframe. You could also have horizontal scrolling by giving the iframe a scrollbar (I think).


Edit 2015

If you can live with a pre-defining the width of your table cells (by percentage), then here's a bit more elegant (CSS-only) solution:

http://jsfiddle.net/7UBMD/77/

Can you test google analytics on a localhost address?

Updated for 2014

This can now be achieved by simply setting the domain to none.

ga('create', 'UA-XXXX-Y', 'none');

See: https://developers.google.com/analytics/devguides/collection/analyticsjs/domains#localhost

const char* concatenation

First of all, you have to create some dynamic memory space. Then you can just strcat the two strings into it. Or you can use the c++ "string" class. The old-school C way:

  char* catString = malloc(strlen(one)+strlen(two)+1);
  strcpy(catString, one);
  strcat(catString, two);
  // use the string then delete it when you're done.
  free(catString);

New C++ way

  std::string three(one);
  three += two;

Performing a Stress Test on Web Application?

I tried WebLoad it's a pretty neat tool. It comes with and test script IDE which allows you to record user action on a website. It also draws a graph as it perform stress test on your web server. Try it out, I highly recommend it.

PHP str_replace replace spaces with underscores

For one matched character replace, use str_replace:

$string = str_replace(' ', '_', $string);

For all matched character replace, use preg_replace:

$string = preg_replace('/\s+/', '_', $string);

How to loop through an associative array and get the key?

Use $key => $val to get the keys:

<?php

$arr = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10",
);

foreach ($arr as $key => $val) {
   print "$key\n";
}

?>

fatal: could not create work tree dir 'kivy'

I had the same error on Debian and all I had to do was:

sudo su

and then run the command again and it worked.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

Output ("echo") a variable to a text file

The simplest Hello World example...

$hello = "Hello World"
$hello | Out-File c:\debug.txt

In c# what does 'where T : class' mean?

It's a type constraint on T, specifying that it must be a class.

The where clause can be used to specify other type constraints, e.g.:

where T : struct // T must be a struct
where T : new()  // T must have a default parameterless constructor
where T : IComparable // T must implement the IComparable interface

For more information, check out MSDN's page on the where clause, or generic parameter constraints.

var functionName = function() {} vs function functionName() {}

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:

_x000D_
_x000D_
// TypeError: functionOne is not a function_x000D_
functionOne();_x000D_
_x000D_
var functionOne = function() {_x000D_
  console.log("Hello!");_x000D_
};
_x000D_
_x000D_
_x000D_

And, a function declaration:

_x000D_
_x000D_
// Outputs: "Hello!"_x000D_
functionTwo();_x000D_
_x000D_
function functionTwo() {_x000D_
  console.log("Hello!");_x000D_
}
_x000D_
_x000D_
_x000D_

Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.

_x000D_
_x000D_
'use strict';    _x000D_
{ // note this block!_x000D_
  function functionThree() {_x000D_
    console.log("Hello!");_x000D_
  }_x000D_
}_x000D_
functionThree(); // ReferenceError
_x000D_
_x000D_
_x000D_

How to select all elements with a particular ID in jQuery?

I would use Different IDs but assign each DIV the same class.

<div id="c-1" class="countdown"></div>
<div id="c-2" class="countdown"></div>

This also has the added benefit of being able to reconstruct the IDs based off of the return of jQuery('.countdown').length


Ok what about adding multiple classes to each countdown timer. IE:

<div class="countdown c-1"></div>
<div class="countdown c-2"></div>
<div class="countdown c-1"></div>

That way you get the best of both worlds. It even allows repeat 'IDS'

javascript function wait until another function to finish

There are several ways I can think of to do this.

Use a callback:

 function FunctInit(someVarible){
      //init and fill screen
      AndroidCallGetResult();  // Enables Android button.
 }

 function getResult(){ // Called from Android button only after button is enabled
      //return some variables
 }

Use a Timeout (this would probably be my preference):

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      if (inited) {
           //return some variables
      } else {
           setTimeout(getResult, 250);
      }
 }

Wait for the initialization to occur:

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      var a = 1;
      do { a=1; }
      while(!inited);
      //return some variables
 }

GridView sorting: SortDirection always Ascending

Automatic bidirectional sorting only works with the SQL data source. Unfortunately, all the documentation in MSDN assumes you are using that, so GridView can get a bit frustrating.

The way I do it is by keeping track of the order on my own. For example:

    protected void OnSortingResults(object sender, GridViewSortEventArgs e)
    {
        // If we're toggling sort on the same column, we simply toggle the direction. Otherwise, ASC it is.
        // e.SortDirection is useless and unreliable (only works with SQL data source).
        if (_sortBy == e.SortExpression)
            _sortDirection = _sortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;
        else
            _sortDirection = SortDirection.Ascending;

        _sortBy = e.SortExpression;

        BindResults();
    }

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

Mi helped: windows defender settings >> device security >> core insulation (details) >> Memory integrity >> Disable (OFF) SYSTEM RESTART ! this solution is better for me

Can't ping a local VM from the host

I had the same issue. Fixed it by adding a static route on my host to my VM via the VMnet8 adapter:

route ADD VM_addr MASK 255.255.255.255 VMnet8_addr

As previously mentioned, you need a bridged connection.

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html

geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.

ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()

Working with huge files in VIM

emacs works very well with files into the 100's of megabytes, I've used it on log files without too much trouble.

But generally when I have some kind of analysis task, I find writing a perl script a better choice.

How to convert numbers to words without using num2word library?

Use python library called num2words Link -> HERE

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I link to a specific glibc version?

In my opinion, the laziest solution (especially if you don't rely on latest bleeding edge C/C++ features, or latest compiler features) wasn't mentioned yet, so here it is:

Just build on the system with the oldest GLIBC you still want to support.

This is actually pretty easy to do nowadays with technologies like chroot, or KVM/Virtualbox, or docker, even if you don't really want to use such an old distro directly on any pc. In detail, to make a maximum portable binary of your software I recommend following these steps:

  1. Just pick your poison of sandbox/virtualization/... whatever, and use it to get yourself a virtual older Ubuntu LTS and compile with the gcc/g++ it has in there by default. That automatically limits your GLIBC to the one available in that environment.

  2. Avoid depending on external libs outside of foundational ones: like, you should dynamically link ground-level system stuff like glibc, libGL, libxcb/X11/wayland things, libasound/libpulseaudio, possibly GTK+ if you use that, but otherwise preferrably statically link external libs/ship them along if you can. Especially mostly self-contained libs like image loaders, multimedia decoders, etc can cause less breakage on other distros (breakage can be caused e.g. if only present somewhere in a different major version) if you statically ship them.

With that approach you get an old-GLIBC-compatible binary without any manual symbol tweaks, without doing a fully static binary (that may break for more complex programs because glibc hates that, and which may cause licensing issues for you), and without setting up any custom toolchain, any custom glibc copy, or whatever.

Bloomberg BDH function with ISIN

I had the same problem. Here's what I figured out:

=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")

A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.

How to take the nth digit of a number in python

I was curious about the relative speed of the two popular approaches - casting to string and using modular arithmetic - so I profiled them and was surprised to see how close they were in terms of performance.

(My use-case was slightly different, I wanted to get all digits in the number.)

The string approach gave:

         10000002 function calls in 1.113 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.113    0.000    1.113    0.000 sandbox.py:1(get_digits_str)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

While the modular arithmetic approach gave:


         10000002 function calls in 1.102 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.102    0.000    1.102    0.000 sandbox.py:6(get_digits_mod)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

There were 10^7 tests run with a max number size less than 10^28.

Code used for reference:

def get_digits_str(num):
    for n_str in str(num):
        yield int(n_str)


def get_digits_mod(num, radix=10):

    remaining = num
    yield remaining % radix

    while remaining := remaining // radix:
        yield remaining % radix


if __name__ == '__main__':

    import cProfile
    import random

    random_inputs = [random.randrange(0, 10000000000000000000000000000) for _ in range(10000000)]

    with cProfile.Profile() as str_profiler:
        for rand_num in random_inputs:
            get_digits_str(rand_num)

    str_profiler.print_stats(sort='cumtime')

    with cProfile.Profile() as mod_profiler:
        for rand_num in random_inputs:
            get_digits_mod(rand_num)

    mod_profiler.print_stats(sort='cumtime')

milliseconds to days

For simple cases like this, TimeUnit should be used. TimeUnit usage is a bit more explicit about what is being represented and is also much easier to read and write when compared to doing all of the arithmetic calculations explicitly. For example, to calculate the number days from milliseconds, the following statement would work:

    long days = TimeUnit.MILLISECONDS.toDays(milliseconds);

For cases more advanced, where more finely grained durations need to be represented in the context of working with time, an all encompassing and modern date/time API should be used. For JDK8+, java.time is now included (here are the tutorials and javadocs). For earlier versions of Java joda-time is a solid alternative.

Expand and collapse with angular js

You can solve this fully in the html:

<div>
  <input ng-model=collapse type=checkbox>Title
  <div ng-show=collapse>
     Only shown when checkbox is clicked
  </div>
</div>

This also works well with ng-repeat since it will create a local scope for each member.

<table>
  <tbody ng-repeat='m in members'>
    <tr>
       <td><input type=checkbox ng-model=collapse></td>
       <td>{{m.title}}</td>
    </tr>
    <tr ng-show=collapse>
      <td> </td>
      <td>{{ m.content }}</td>
    </tr>
  </tbody>
</table>

Be aware that even though a repeat has its own scope, initially it will inherit the value from collapse from super scopes. This allows you to set the initial value in one place but it can be surprising.

You can of course restyle the checkbox. See http://jsfiddle.net/azD5m/5/

Updated fiddle: http://jsfiddle.net/azD5m/374/ Original fiddle used closing </input> tags to add the HTML text label instead of using <label> tags.

Why can't non-default arguments follow default arguments?

Let me clear two points here :

  • firstly non-default argument should not follow default argument , it means you can't define (a=b,c) in function the order of defining parameter in function are :
    • positional parameter or non-default parameter i.e (a,b,c)
    • keyword parameter or default parameter i.e (a="b",r="j")
    • keyword-only parameter i.e (*args)
    • var-keyword parameter i.e (**kwargs)

def example(a, b, c=None, r="w" , d=[], *ae, **ab):

(a,b) are positional parameter

(c=none) is optional parameter

(r="w") is keyword parameter

(d=[]) is list parameter

(*ae) is keyword-only

(**ab) is var-keyword parameter

  • now secondary thing is if i try something like this : def example(a, b, c=a,d=b):

argument is not defined when default values are saved,Python computes and saves default values when you define the function

c and d are not defined, does not exist, when this happens (it exists only when the function is executed)

"a,a=b" its not allowed in parameter.

How to access custom attributes from event object in React?

You can simply use event.target.dataset object . This will give you the object with all data attributes.

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using %lf, %lg or %le (or %la in C99) to read in doubles.

ImportError: numpy.core.multiarray failed to import

Try sudo pip install numpy --upgrade --ignore-installed.

It work in Mac OS 10.11.

You should close The 'Rootless' if above shell isn't work.

Access cell value of datatable

data d is in row 0 and column 3 for value d :

DataTable table;
String d = (String)table.Rows[0][3];

github changes not staged for commit

This command may solve the problem :

git add -A

All the files and subdirectories will be added to be tracked.

Hope it helps

How to check for null in a single statement in scala?

Try to avoid using null in Scala. It's really there only for interoperability with Java. In Scala, use Option for things that might be empty. If you're calling a Java API method that might return null, wrap it in an Option immediately.

def getObject : Option[QueueObject] = {
  // Wrap the Java result in an Option (this will become a Some or a None)
  Option(someJavaObject.getResponse)
}

Note: You don't need to put it in a val or use an explicit return statement in Scala; the result will be the value of the last expression in the block (in fact, since there's only one statement, you don't even need a block).

def getObject : Option[QueueObject] = Option(someJavaObject.getResponse)

Besides what the others have already shown (for example calling foreach on the Option, which might be slightly confusing), you could also call map on it (and ignore the result of the map operation if you don't need it):

getObject map QueueManager.add

This will do nothing if the Option is a None, and call QueueManager.add if it is a Some.

I find using a regular if however clearer and simpler than using any of these "tricks" just to avoid an indentation level. You could also just write it on one line:

if (getObject.isDefined) QueueManager.add(getObject.get)

or, if you want to deal with null instead of using Option:

if (getObject != null) QueueManager.add(getObject)

edit - Ben is right, be careful to not call getObject more than once if it has side-effects; better write it like this:

val result = getObject
if (result.isDefined) QueueManager.add(result.get)

or:

val result = getObject
if (result != null) QueueManager.add(result)

How to write data to a text file without overwriting the current data

Look into the File class.

You can create a streamwriter with

StreamWriter sw = File.Create(....) 

You can open an existing file with

File.Open(...)

You can append text easily with

File.AppendAllText(...);

How to extract closed caption transcript from YouTube video?

(Obligatory 'this is probably an internal youtube.com interface and might break at any time')

Instead of linking to another tool that does this, here's an answer to the question of "how to do this"

Use fiddler or your browser devtools (e.g. Chrome) to inspect the youtube.com HTTP traffic, and there's a response from /api/timedtext that contains the closed caption info as XML.

It seems that a response like this:

    <p t="0" d="5430" w="1">
        <s p="2" ac="136">we&#39;ve</s>
        <s t="780" ac="252"> got</s>
    </p>
    <p t="2280" d="7170" w="1">
        <s ac="243">we&#39;re</s>
        <s t="810" ac="233"> going</s>
    </p>

means at time 0 is the word we've and at time 0+780 is the word got and at time 2280+810 is the word going, etc. This time is in milliseconds so for time 3090 you'd want to append &t=3 to the URL.

You can use any tool to stitch together the XML into something readable, but here's my Power BI Desktop script to find words like "privilege":

let
    Source = Xml.Tables(File.Contents("C:\Download\body.xml")),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Attribute:format", Int64.Type}}),
    body = #"Changed Type"{0}[body],
    p = body{0}[p],
    #"Changed Type1" = Table.TransformColumnTypes(p,{{"Attribute:t", Int64.Type}, {"Attribute:d", Int64.Type}, {"Attribute:w", Int64.Type}, {"Attribute:a", Int64.Type}, {"Attribute:p", Int64.Type}}),
    #"Expanded s" = Table.ExpandTableColumn(#"Changed Type1", "s", {"Attribute:ac", "Attribute:p", "Attribute:t", "Element:Text"}, {"s.Attribute:ac", "s.Attribute:p", "s.Attribute:t", "s.Element:Text"}),
    #"Changed Type2" = Table.TransformColumnTypes(#"Expanded s",{{"s.Attribute:t", Int64.Type}}),
    #"Removed Other Columns" = Table.SelectColumns(#"Changed Type2",{"s.Attribute:t", "s.Element:Text", "Attribute:t"}),
    #"Replaced Value" = Table.ReplaceValue(#"Removed Other Columns",null,0,Replacer.ReplaceValue,{"s.Attribute:t"}),
    #"Filtered Rows" = Table.SelectRows(#"Replaced Value", each [#"s.Element:Text"] <> null),
    #"Added Custom" = Table.AddColumn(#"Filtered Rows", "Time", each [#"Attribute:t"] + [#"s.Attribute:t"]),
    #"Filtered Rows1" = Table.SelectRows(#"Added Custom", each ([#"s.Element:Text"] = " privilege" or [#"s.Element:Text"] = " privileged" or [#"s.Element:Text"] = " privileges" or [#"s.Element:Text"] = "privilege" or [#"s.Element:Text"] = "privileges"))
in
    #"Filtered Rows1"

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

Parse JSON with R

RJSONIO from Omegahat is another package which provides facilities for reading and writing data in JSON format.

rjson does not use S4/S3 methods and so is not readily extensible, but still useful. Unfortunately, it does not used vectorized operations and so is too slow for non-trivial data. Similarly, for reading JSON data into R, it is somewhat slow and so does not scale to large data, should this be an issue.

Update (new Package 2013-12-03):

jsonlite: This package is a fork of the RJSONIO package. It builds on the parser from RJSONIO but implements a different mapping between R objects and JSON strings. The C code in this package is mostly from the RJSONIO Package, the R code has been rewritten from scratch. In addition to drop-in replacements for fromJSON and toJSON, the package has functions to serialize objects. Furthermore, the package contains a lot of unit tests to make sure that all edge cases are encoded and decoded consistently for use with dynamic data in systems and applications.

How to sort a Pandas DataFrame by index?

Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

Note:

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

Communicating between a fragment and an activity - best practices

It is implemented by a Callback interface:

First of all, we have to make an interface:

public interface UpdateFrag {
     void updatefrag();
}

In the Activity do the following code:

UpdateFrag updatfrag ;

public void updateApi(UpdateFrag listener) {
        updatfrag = listener;
}

from the event from where the callback has to fire in the Activity:

updatfrag.updatefrag();

In the Fragment implement the interface in CreateView do the following code:

 ((Home)getActivity()).updateApi(new UpdateFrag() {
        @Override
        public void updatefrag() {
              .....your stuff......
        }
 });

Convert JS object to JSON string

convert str => obj

const onePlusStr = '[{"brand":"oneplus"},{"model":"7T"}]';

const onePLusObj = JSON.parse(onePlusStr);

convert obj => str

const onePLusObjToStr = JSON.stringify(onePlusStr);

References of JSON parsing in JS:
JSON.parse() : click
JSON.stringify() : click

Change output format for MySQL command line results to CSV

How about using sed? It comes standard with most (all?) Linux OS.

sed 's/\t/<your_field_delimiter>/g'.

This example uses GNU sed (Linux). For POSIX sed (AIX/Solaris)I believe you would type a literal TAB instead of \t

Example (for CSV output):

#mysql mysql -B -e "select * from user" | while read; do sed 's/\t/,/g'; done

localhost,root,,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,,,,,0,0,0,0,,
localhost,bill,*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,,,,,0,0,0,0,,
127.0.0.1,root,,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,,,,,0,0,0,0,,
::1,root,,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,,,,,0,0,0,0,,
%,jim,*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,,,,,0,0,0,0,,

How to find integer array size in java

Integer Array doesn't contain size() or length() method. Try the below code, it'll work. ArrayList contains size() method. String contains length(). Since you have used int array[], so it will be array.length

public class Example {

    int array[] = {1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554, 22, 22, 211};

    public void Printrange() {

        for (int i = 0; i < array.length; i++) {
            if (array[i] > 100 && array[i] < 500) {
                System.out.println("numbers with in range" + i);
            }
        }
    }
}