Programs & Examples On #Textcolor

textColor is an attribute used for setting a font color, typically used in TextViews xml definitions.

How to set textColor of UILabel in Swift

The text field placeholder and the "is really" label is hard to see at night. So i change their color depending one what time of day it is.

Also make sure you connect the new IBOutlet isReallyLabel. To do so open Main.storybaord and control-drag from "Convert" view controller to the "is really" text field and select the isReallyLabel under Outlets.

WARNING: I have not tested to see if the application is open while the time of day swaps.

_x000D_
_x000D_
@IBOutlet var isReallyLabel: UILabel! _x000D_
  _x000D_
override func viewWillAppear(animated: Bool) {_x000D_
 let calendar = NSCalendar.currentCalendar()_x000D_
 let hour = calendar.component(.Hour, fromDate: NSDate())_x000D_
  _x000D_
 let lightColor = UIColor.init(red: 0.961, green: 0.957, blue: 0945, alpha: 1)_x000D_
 let darkColor = UIColor.init(red: 0.184, green: 0.184 , blue: 0.188, alpha: 1)_x000D_
_x000D_
  _x000D_
 switch hour {_x000D_
 case 8...18:_x000D_
  isReallyLabel.textColor = UIColor.blackColor()_x000D_
  view.backgroundColor = lightColor_x000D_
 default:_x000D_
  let string = NSAttributedString(string: "Value", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])_x000D_
  textField.attributedPlaceholder = string_x000D_
  isReallyLabel.textColor = UIColor.whiteColor()_x000D_
  view.backgroundColor = darkColor_x000D_
 }_x000D_
}
_x000D_
_x000D_
_x000D_

How do you use NSAttributedString?

I made a library that makes this a lot easier. Check out ZenCopy.

You can create Style objects, and/or set them to keys to reference later. Like this:

ZenCopy.manager.config.setStyles {
    return [
        "token": Style(
            color: .blueColor(), // optional
            // fontName: "Helvetica", // optional
            fontSize: 14 // optional
        )
    ]
}

Then, you can easily construct strings AND style them AND have params :)

label.attributedText = attributedString(
                                ["$0 ".style("token") "is dancing with ", "$1".style("token")], 
                          args: ["JP", "Brock"]
)

You can also style things easily with regex searches!

let atUserRegex = "(@[A-Za-z0-9_]*)"
mutableAttributedString.regexFind(atUserRegex, addStyle: "token")

This will style all words with '@' in front of it with the 'token' style. (e.g. @jpmcglone)

I need to still get it working w/ everything NSAttributedString has to offer, but I think fontName, fontSize and color cover the bulk of it. Expect lots of updates soon :)

I can help you get started with this if you need. Also looking for feedback, so if it makes your life easier, I'd say mission accomplished.

UILabel with text of two different colors

Since iOS 6, UIKit supports drawing attributed strings, so no extension or replacement is needed.

From UILabel:

@property(nonatomic, copy) NSAttributedString *attributedText;

You just need to build up your NSAttributedString. There are basically two ways:

  1. Append chunks of text with the same attributes - for each part create one NSAttributedString instance and append them to one NSMutableAttributedString

  2. Create attributed text from plain string and then add attributed for given ranges – find the range of your number (or whatever) and apply different color attribute on that.

How to change the Text color of Menu item in Android?

Sephy's solution doesn't work. It's possible to override the options menu item text appearance using the method described above, but not the item or menu. To do that there are essentially 3 ways:

  1. How to change the background color of the options menu?
  2. Write your own view to display and override onCreateOptionsMenu and onPrepareOptionsMenu to get the results you want. I state this generally because you can generally do whatever you want in these methods, but you probably won't want to call into super().
  3. Copy code from the open-source SDK and customize for your behavior. The default menu implementation used by Activity will no longer apply.

See Issue 4441: Custom Options Menu Theme for more clues.

UIButton title text color

In Swift:

Changing the label text color is quite different than changing it for a UIButton. To change the text color for a UIButton use this method:

self.headingButton.setTitleColor(UIColor(red: 107.0/255.0, green: 199.0/255.0, blue: 217.0/255.0), forState: UIControlState.Normal)

How can I change default dialog button text color in android 5

There are two ways to change the dialog button color.

Basic Way

If you just want to change in an activity, write the below two lines after alertDialog.show();

alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimaryDark));

Recommended

I'll recommend adding a theme for AlertDialog in styles.xml so you don't have to write the same code again and again in each activity/dialog call. You can just create a style and apply that theme on the dialog box. So whenever you want to change the color of AlertDialog box, just change color in styles.xml and all the dialog boxes will be updated in the whole application.

<style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@color/colorPrimary</item>
</style>

And apply the theme in AlertDialog.Builder

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogTheme);

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

In addition to @Connor Leech's answer.

If you want to create a new custom typography type of your own, define the following in your css file.

.text-foo {
  .text-emphasis-variant(#FFFFFF);
}

The mixin text-emphasis-variant is defined in Bootstrap's mixins.less file.

Angular pass callback function to child component as @Input similar to AngularJS way

UPDATE

This answer was submitted when Angular 2 was still in alpha and many of the features were unavailable / undocumented. While the below will still work, this method is now entirely outdated. I strongly recommend the accepted answer over the below.

Original Answer

Yes in fact it is, however you will want to make sure that it is scoped correctly. For this I've used a property to ensure that this means what I want it to.

@Component({
  ...
  template: '<child [myCallback]="theBoundCallback"></child>',
  directives: [ChildComponent]
})
export class ParentComponent{
  public theBoundCallback: Function;

  public ngOnInit(){
    this.theBoundCallback = this.theCallback.bind(this);
  }

  public theCallback(){
    ...
  }
}

@Component({...})
export class ChildComponent{
  //This will be bound to the ParentComponent.theCallback
  @Input()
  public myCallback: Function; 
  ...
}

Find JavaScript function definition in Chrome

Another way to navigate to the location of a function definition would be to break in debugger somewhere you can access the function and enter the functions fully qualified name in the console. This will print the function definition in the console and give a link which on click opens the script location where the function is defined.

Disable JavaScript error in WebBrowser control

I just found this :

 private static bool TrySetSuppressScriptErrors(WebBrowser webBrowser, bool value)
    {
        FieldInfo field = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
        if (field != null)
        {
            object axIWebBrowser2 = field.GetValue(webBrowser);
            if (axIWebBrowser2 != null)
            {
                axIWebBrowser2.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, axIWebBrowser2, new object[] { value });
                return true;
            }
        }

        return false;
    }

usage example to set webBrowser to silent : TrySetSuppressScriptErrors(webBrowser,true)

What is .htaccess file?

.htaccess is a configuration file for use on web servers running the Apache Web Server software.

When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software.

These .htaccess files can be used to alter the configuration of the Apache Web Server software to enable/disable additional functionality and features that the Apache Web Server software has to offer.

These facilities include basic redirect functionality, for instance if a 404 file not found error occurs, or for more advanced functions such as content password protection or image hot link prevention.

Whenever any request is sent to the server it always passes through .htaccess file. There are some rules are defined to instruct the working.

Multiline string literal in C#

Add multiple lines : use @

string query = @"SELECT foo, bar
FROM table
WHERE id = 42";

Add String Values to the middle : use $

string text ="beer";
string query = $"SELECT foo {text} bar ";

Multiple line string Add Values to the middle: use $@

string text ="Customer";
string query = $@"SELECT foo, bar
FROM {text}Table
WHERE id = 42";

How can you determine a point is between two other points on a line segment?

Ok, lots of mentions of linear algebra (cross product of vectors) and this works in a real (ie continuous or floating point) space but the question specifically stated that the two points were expressed as integers and thus a cross product is not the correct solution although it can give an approximate solution.

The correct solution is to use Bresenham's Line Algorithm between the two points and to see if the third point is one of the points on the line. If the points are sufficiently distant that calculating the algorithm is non-performant (and it'd have to be really large for that to be the case) I'm sure you could dig around and find optimisations.

How to remove spaces from a string using JavaScript?

Regex + Replace()

Although regex can be slower, in many use cases the developer is only manipulating a few strings at once so considering speed is irrelevant. Even though / / is faster than /\s/, having the '\s' explains what is going on to another developer perhaps more clearly.

let string = '/var/www/site/Brand new document.docx';
let path = string.replace(/\s/g, '');
// path => '/var/www/site/Brandnewdocument.docx'

Split() + Join()

Using Split + Join allows for further chained manipulation of the string.

let string = '/var/www/site/Brand new document.docx';
let path => string.split('').map(char => /(\s|\.)/.test(char) ? '/' : char).join('');
// "/var/www/site/Brand/new/document/docx";

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

In SQL*Plus putting SET DEFINE ? at the top of the script will normally solve this. Might work for Oracle SQL Developer as well.

Rotating a point about another point (2D)

This is the answer by Nils Pipenbrinck, but implemented in c# fiddle.

https://dotnetfiddle.net/btmjlG

using System;

public class Program
{
    public static void Main()
    {   
        var angle = 180 * Math.PI/180;
        Console.WriteLine(rotate_point(0,0,angle,new Point{X=10, Y=10}).Print());
    }

    static Point rotate_point(double cx, double cy, double angle, Point p)
    {
        double s = Math.Sin(angle);
        double c = Math.Cos(angle);
        // translate point back to origin:
        p.X -= cx;
        p.Y -= cy;
        // rotate point
        double Xnew = p.X * c - p.Y * s;
        double Ynew = p.X * s + p.Y * c;
        // translate point back:
        p.X = Xnew + cx;
        p.Y = Ynew + cy;
        return p;
    }

    class Point
    {
        public double X;
        public double Y;

        public string Print(){
            return $"{X},{Y}";
        }
    }
}

Ps: Apparently I can’t comment, so I’m obligated to post it as an answer ...

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

what is .subscribe in angular?

subscribe() -Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. -Observable- representation of any set of values over any amount of time.

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

You will need to add external Repository to your pom, since this is using Mulsoft-Release repository not Maven Central

<project>
   ...
    <repositories>
        <repository>
            <id>mulesoft-releases</id>
            <name>MuleSoft Repository</name>
            <url>http://repository.mulesoft.org/releases/</url>
            <layout>default</layout>
        </repository>
    </repositories>
  ...
</project>

Dependency

Apache Maven - Setting up Multiple Repositories

Retrieving a List from a java.util.stream.Stream in Java 8

In case someone (like me) out there is looking for ways deal with Objects instead of primitive types then use mapToObj()

String ss = "An alternative way is to insert the following VM option before "
        + "the -vmargs option in the Eclipse shortcut properties(edit the "
        + "field Target inside the Shortcut tab):";

List<Character> ll = ss
                        .chars()
                        .mapToObj(c -> new Character((char) c))
                        .collect(Collectors.toList());

System.out.println("List type: " + ll.getClass());
System.out.println("Elem type: " + ll.get(0).getClass());
ll.stream().limit(50).forEach(System.out::print);

prints:

List type: class java.util.ArrayList
Elem type: class java.lang.Character
An alternative way is to insert the following VM o

How to run a program without an operating system?

Runnable examples

Let's create and run some minuscule bare metal hello world programs that run without an OS on:

We will also try them out on the QEMU emulator as much as possible, as that is safer and more convenient for development. The QEMU tests have been on an Ubuntu 18.04 host with the pre-packaged QEMU 2.11.1.

The code of all x86 examples below and more is present on this GitHub repo.

How to run the examples on x86 real hardware

Remember that running examples on real hardware can be dangerous, e.g. you could wipe your disk or brick the hardware by mistake: only do this on old machines that don't contain critical data! Or even better, use cheap semi-disposable devboards such as the Raspberry Pi, see the ARM example below.

For a typical x86 laptop, you have to do something like:

  1. Burn the image to an USB stick (will destroy your data!):

    sudo dd if=main.img of=/dev/sdX
    
  2. plug the USB on a computer

  3. turn it on

  4. tell it to boot from the USB.

    This means making the firmware pick USB before hard disk.

    If that is not the default behavior of your machine, keep hitting Enter, F12, ESC or other such weird keys after power-on until you get a boot menu where you can select to boot from the USB.

    It is often possible to configure the search order in those menus.

For example, on my T430 I see the following.

After turning on, this is when I have to press Enter to enter the boot menu:

enter image description here

Then, here I have to press F12 to select the USB as the boot device:

enter image description here

From there, I can select the USB as the boot device like this:

enter image description here

Alternatively, to change the boot order and choose the USB to have higher precedence so I don't have to manually select it every time, I would hit F1 on the "Startup Interrupt Menu" screen, and then navigate to:

enter image description here

Boot sector

On x86, the simplest and lowest level thing you can do is to create a Master Boot Sector (MBR), which is a type of boot sector, and then install it to a disk.

Here we create one with a single printf call:

printf '\364%509s\125\252' > main.img
sudo apt-get install qemu-system-x86
qemu-system-x86_64 -hda main.img

Outcome:

enter image description here

Note that even without doing anything, a few characters are already printed on the screen. Those are printed by the firmware, and serve to identify the system.

And on the T430 we just get a blank screen with a blinking cursor:

enter image description here

main.img contains the following:

  • \364 in octal == 0xf4 in hex: the encoding for a hlt instruction, which tells the CPU to stop working.

    Therefore our program will not do anything: only start and stop.

    We use octal because \x hex numbers are not specified by POSIX.

    We could obtain this encoding easily with:

    echo hlt > a.S
    as -o a.o a.S
    objdump -S a.o
    

    which outputs:

    a.o:     file format elf64-x86-64
    
    
    Disassembly of section .text:
    
    0000000000000000 <.text>:
       0:   f4                      hlt
    

    but it is also documented in the Intel manual of course.

  • %509s produce 509 spaces. Needed to fill in the file until byte 510.

  • \125\252 in octal == 0x55 followed by 0xaa.

    These are 2 required magic bytes which must be bytes 511 and 512.

    The BIOS goes through all our disks looking for bootable ones, and it only considers bootable those that have those two magic bytes.

    If not present, the hardware will not treat this as a bootable disk.

If you are not a printf master, you can confirm the contents of main.img with:

hd main.img

which shows the expected:

00000000  f4 20 20 20 20 20 20 20  20 20 20 20 20 20 20 20  |.               |
00000010  20 20 20 20 20 20 20 20  20 20 20 20 20 20 20 20  |                |
*
000001f0  20 20 20 20 20 20 20 20  20 20 20 20 20 20 55 aa  |              U.|
00000200

where 20 is a space in ASCII.

The BIOS firmware reads those 512 bytes from the disk, puts them into memory, and sets the PC to the first byte to start executing them.

Hello world boot sector

Now that we have made a minimal program, let's move to a hello world.

The obvious question is: how to do IO? A few options:

  • ask the firmware, e.g. BIOS or UEFI, to do it for us

  • VGA: special memory region that gets printed to the screen if written to. Can be used in Protected Mode.

  • write a driver and talk directly to the display hardware. This is the "proper" way to do it: more powerful, but more complex.

  • serial port. This is a very simple standardized protocol that sends and receives characters from a host terminal.

    On desktops, it looks like this:

    enter image description here

    Source.

    It is unfortunately not exposed on most modern laptops, but is the common way to go for development boards, see the ARM examples below.

    This is really a shame, since such interfaces are really useful to debug the Linux kernel for example.

  • use debug features of chips. ARM calls theirs semihosting for example. On real hardware, it requires some extra hardware and software support, but on emulators it can be a free convenient option. Example.

Here we will do a BIOS example as it is simpler on x86. But note that it is not the most robust method.

main.S

.code16
    mov $msg, %si
    mov $0x0e, %ah
loop:
    lodsb
    or %al, %al
    jz halt
    int $0x10
    jmp loop
halt:
    hlt
msg:
    .asciz "hello world"

GitHub upstream.

link.ld

SECTIONS
{
    /* The BIOS loads the code from the disk to this location.
     * We must tell that to the linker so that it can properly
     * calculate the addresses of symbols we might jump to.
     */
    . = 0x7c00;
    .text :
    {
        __start = .;
        *(.text)
        /* Place the magic boot bytes at the end of the first 512 sector. */
        . = 0x1FE;
        SHORT(0xAA55)
    }
}

Assemble and link with:

as -g -o main.o main.S
ld --oformat binary -o main.img -T link.ld main.o
qemu-system-x86_64 -hda main.img

Outcome:

enter image description here

And on the T430:

enter image description here

Tested on: Lenovo Thinkpad T430, UEFI BIOS 1.16. Disk generated on an Ubuntu 18.04 host.

Besides the standard userland assembly instructions, we have:

  • .code16: tells GAS to output 16-bit code

  • cli: disable software interrupts. Those could make the processor start running again after the hlt

  • int $0x10: does a BIOS call. This is what prints the characters one by one.

The important link flags are:

  • --oformat binary: output raw binary assembly code, don't wrap it inside an ELF file as is the case for regular userland executables.

To better understand the linker script part, familiarize yourself with the relocation step of linking: What do linkers do?

Cooler x86 bare metal programs

Here are a few more complex bare metal setups that I've achieved:

Use C instead of assembly

Summary: use GRUB multiboot, which will solve a lot of annoying problems you never thought about. See the section below.

The main difficulty on x86 is that the BIOS only loads 512 bytes from the disk to memory, and you are likely to blow up those 512 bytes when using C!

To solve that, we can use a two-stage bootloader. This makes further BIOS calls, which load more bytes from the disk into memory. Here is a minimal stage 2 assembly example from scratch using the int 0x13 BIOS calls:

Alternatively:

  • if you only need it to work in QEMU but not real hardware, use the -kernel option, which loads an entire ELF file into memory. Here is an ARM example I've created with that method.
  • for the Raspberry Pi, the default firmware takes care of the image loading for us from an ELF file named kernel7.img, much like QEMU -kernel does.

For educational purposes only, here is a one stage minimal C example:

main.c

void main(void) {
    int i;
    char s[] = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
    for (i = 0; i < sizeof(s); ++i) {
        __asm__ (
            "int $0x10" : : "a" ((0x0e << 8) | s[i])
        );
    }
    while (1) {
        __asm__ ("hlt");
    };
}

entry.S

.code16
.text
.global mystart
mystart:
    ljmp $0, $.setcs
.setcs:
    xor %ax, %ax
    mov %ax, %ds
    mov %ax, %es
    mov %ax, %ss
    mov $__stack_top, %esp
    cld
    call main

linker.ld

ENTRY(mystart)
SECTIONS
{
  . = 0x7c00;
  .text : {
    entry.o(.text)
    *(.text)
    *(.data)
    *(.rodata)
    __bss_start = .;
    /* COMMON vs BSS: https://stackoverflow.com/questions/16835716/bss-vs-common-what-goes-where */
    *(.bss)
    *(COMMON)
    __bss_end = .;
  }
  /* https://stackoverflow.com/questions/53584666/why-does-gnu-ld-include-a-section-that-does-not-appear-in-the-linker-script */
  .sig : AT(ADDR(.text) + 512 - 2)
  {
      SHORT(0xaa55);
  }
  /DISCARD/ : {
    *(.eh_frame)
  }
  __stack_bottom = .;
  . = . + 0x1000;
  __stack_top = .;
}

run

set -eux
as -ggdb3 --32 -o entry.o entry.S
gcc -c -ggdb3 -m16 -ffreestanding -fno-PIE -nostartfiles -nostdlib -o main.o -std=c99 main.c
ld -m elf_i386 -o main.elf -T linker.ld entry.o main.o
objcopy -O binary main.elf main.img
qemu-system-x86_64 -drive file=main.img,format=raw

C standard library

Things get more fun if you also want to use the C standard library however, since we don't have the Linux kernel, which implements much of the C standard library functionality through POSIX.

A few possibilities, without going to a full-blown OS like Linux, include:

  • Write your own. It's just a bunch of headers and C files in the end, right? Right??

  • Newlib

    Detailed example at: https://electronics.stackexchange.com/questions/223929/c-standard-libraries-on-bare-metal/223931

    Newlib implements all the boring non-OS specific things for you, e.g. memcmp, memcpy, etc.

    Then, it provides some stubs for you to implement the syscalls that you need yourself.

    For example, we can implement exit() on ARM through semihosting with:

    void _exit(int status) {
        __asm__ __volatile__ ("mov r0, #0x18; ldr r1, =#0x20026; svc 0x00123456");
    }
    

    as shown at in this example.

    For example, you could redirect printf to the UART or ARM systems, or implement exit() with semihosting.

  • embedded operating systems like FreeRTOS and Zephyr.

    Such operating systems typically allow you to turn off pre-emptive scheduling, therefore giving you full control over the runtime of the program.

    They can be seen as a sort of pre-implemented Newlib.

GNU GRUB Multiboot

Boot sectors are simple, but they are not very convenient:

  • you can only have one OS per disk
  • the load code has to be really small and fit into 512 bytes
  • you have to do a lot of startup yourself, like moving into protected mode

It is for those reasons that GNU GRUB created a more convenient file format called multiboot.

Minimal working example: https://github.com/cirosantilli/x86-bare-metal-examples/tree/d217b180be4220a0b4a453f31275d38e697a99e0/multiboot/hello-world

I also use it on my GitHub examples repo to be able to easily run all examples on real hardware without burning the USB a million times.

QEMU outcome:

enter image description here

T430:

enter image description here

If you prepare your OS as a multiboot file, GRUB is then able to find it inside a regular filesystem.

This is what most distros do, putting OS images under /boot.

Multiboot files are basically an ELF file with a special header. They are specified by GRUB at: https://www.gnu.org/software/grub/manual/multiboot/multiboot.html

You can turn a multiboot file into a bootable disk with grub-mkrescue.

Firmware

In truth, your boot sector is not the first software that runs on the system's CPU.

What actually runs first is the so-called firmware, which is a software:

  • made by the hardware manufacturers
  • typically closed source but likely C-based
  • stored in read-only memory, and therefore harder / impossible to modify without the vendor's consent.

Well known firmwares include:

  • BIOS: old all-present x86 firmware. SeaBIOS is the default open source implementation used by QEMU.
  • UEFI: BIOS successor, better standardized, but more capable, and incredibly bloated.
  • Coreboot: the noble cross arch open source attempt

The firmware does things like:

  • loop over each hard disk, USB, network, etc. until you find something bootable.

    When we run QEMU, -hda says that main.img is a hard disk connected to the hardware, and hda is the first one to be tried, and it is used.

  • load the first 512 bytes to RAM memory address 0x7c00, put the CPU's RIP there, and let it run

  • show things like the boot menu or BIOS print calls on the display

Firmware offers OS-like functionality on which most OS-es depend. E.g. a Python subset has been ported to run on BIOS / UEFI: https://www.youtube.com/watch?v=bYQ_lq5dcvM

It can be argued that firmwares are indistinguishable from OSes, and that firmware is the only "true" bare metal programming one can do.

As this CoreOS dev puts it:

The hard part

When you power up a PC, the chips that make up the chipset (northbridge, southbridge and SuperIO) are not yet initialized properly. Even though the BIOS ROM is as far removed from the CPU as it could be, this is accessible by the CPU, because it has to be, otherwise the CPU would have no instructions to execute. This does not mean that BIOS ROM is completely mapped, usually not. But just enough is mapped to get the boot process going. Any other devices, just forget it.

When you run Coreboot under QEMU, you can experiment with the higher layers of Coreboot and with payloads, but QEMU offers little opportunity to experiment with the low level startup code. For one thing, RAM just works right from the start.

Post BIOS initial state

Like many things in hardware, standardization is weak, and one of the things you should not rely on is the initial state of registers when your code starts running after BIOS.

So do yourself a favor and use some initialization code like the following: https://stackoverflow.com/a/32509555/895245

Registers like %ds and %es have important side effects, so you should zero them out even if you are not using them explicitly.

Note that some emulators are nicer than real hardware and give you a nice initial state. Then when you go run on real hardware, everything breaks.

El Torito

Format that can be burnt to CDs: https://en.wikipedia.org/wiki/El_Torito_%28CD-ROM_standard%29

It is also possible to produce a hybrid image that works on either ISO or USB. This is can be done with grub-mkrescue (example), and is also done by the Linux kernel on make isoimage using isohybrid.

ARM

In ARM, the general ideas are the same.

There is no widely available semi-standardized pre-installed firmware like BIOS for us to use for the IO, so the two simplest types of IO that we can do are:

  • serial, which is widely available on devboards
  • blink the LED

I have uploaded:

Some differences from x86 include:

  • IO is done by writing to magic addresses directly, there is no in and out instructions.

    This is called memory mapped IO.

  • for some real hardware, like the Raspberry Pi, you can add the firmware (BIOS) yourself to the disk image.

    That is a good thing, as it makes updating that firmware more transparent.

Resources

How to handle ETIMEDOUT error?

We could look at error object for a property code that mentions the possible system error and in cases of ETIMEDOUT where a network call fails, act accordingly.

if (err.code === 'ETIMEDOUT') {
    console.log('My dish error: ', util.inspect(err, { showHidden: true, depth: 2 }));
}

list.clear() vs list = new ArrayList<Integer>();

Tried the below program , With both the approach. 1. With clearing the arraylist obj in for loop 2. creating new New Arraylist in for loop.

List al= new ArrayList();
        for(int i=0;i<100;i++)
        {
            //List al= new ArrayList();

            for(int j=0;j<10;j++)
            {
                al.add(Integer.parseInt("" +j+i));
                //System.out.println("Obj val " +al.get(j));
            }
            //System.out.println("Hashcode : " + al.hashCode());
            al.clear();

        }

and to my surprise. the memory allocation didnt change much.

With New Arraylist approach.

Before loop total free memory: 64,909 ::

After loop total free memory: 64,775 ::

with Clear approach,

Before loop total free memory: 64,909 :: After loop total free memory: 64,765 ::

So this says there is not much difference in using arraylist.clear from memory utilization perspective.

How to check if a file is empty in Bash?

[[ -s file ]] --> Checks if file has size greater than 0

if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi

If needed, this checks all the *.txt files in the current directory; and reports all the empty file:

for file in *.txt; do if [[ ! -s $file ]]; then echo $file; fi; done

Getting all request parameters in Symfony 2

With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;

    class SampleController extends Controller
    {


        public function indexAction(Request $request) {

           var_dump($request->request->all());
        }

    }

How large is a DWORD with 32- and 64-bit code?

Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit.

In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size.

You can find the official list here: http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx

All the platform-dependent types that changed with the transition from 32-bit to 64-bit end with _PTR (DWORD_PTR will be 32-bit on 32-bit Windows and 64-bit on 64-bit Windows).

Remove lines that contain certain string

I have used this to remove unwanted words from text files:

bad_words = ['abc', 'def', 'ghi', 'jkl']

with open('List of words.txt') as badfile, open('Clean list of words.txt', 'w') as cleanfile:
    for line in badfile:
        clean = True
        for word in bad_words:
            if word in line:
                clean = False
        if clean == True:
            cleanfile.write(line)

Or to do the same for all files in a directory:

import os

bad_words = ['abc', 'def', 'ghi', 'jkl']

for root, dirs, files in os.walk(".", topdown = True):
    for file in files:
        if '.txt' in file:
            with open(file) as filename, open('clean '+file, 'w') as cleanfile:
                for line in filename:
                    clean = True
                    for word in bad_words:
                        if word in line:
                            clean = False
                    if clean == True:
                        cleanfile.write(line)

I'm sure there must be a more elegant way to do it, but this did what I wanted it to.

Dropdownlist width in IE

I tried all of these solutions and none worked completely for me. This is what I came up with

$(document).ready(function () {

var clicknum = 0;

$('.dropdown').click(
        function() {
            clicknum++;
            if (clicknum == 2) {
                clicknum = 0;
                $(this).css('position', '');
                $(this).css('width', '');
            }
        }).blur(
        function() {
            $(this).css('position', '');
            $(this).css('width', '');
            clicknum = 0;
        }).focus(
        function() {
            $(this).css('position', 'relative');
            $(this).css('width', 'auto');
        }).mousedown(
        function() {
            $(this).css('position', 'relative');
            $(this).css('width', 'auto');
        });
})(jQuery);

Be sure to add a dropdown class to each dropdown in your html

The trick here is using the specialized click function (I found it here Fire event each time a DropDownList item is selected with jQuery). Many of the other solutions on here use the event handler change, which works well but won't trigger if the user selects the same option as was previously selected.

Like many of the other solutions, focus and mousedown is for when the user puts the dropdown in focus, blur is for when they click away.

You may also want to stick some kind of browser detection in this so it only effects ie. It doesn't look bad in other browsers though

How to clear radio button in Javascript?

In my case this got the job done:

const chbx = document.getElementsByName("input_name");

for(let i=0; i < chbx.length; i++) {
    chbx[i].checked = false;
}

How to download file in swift?

Yes you can very easily downloads Files from the remote Url Using this code. This Code is working Fine for Me.

func DownlondFromUrl(){
   // Create destination URL 
let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")

//Create URL to the source file you want to download
let fileURL = URL(string: "https://s3.amazonaws.com/learn-swift/IMG_0001.JPG")

let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)

let request = URLRequest(url:fileURL!)

let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
    if let tempLocalUrl = tempLocalUrl, error == nil {
        // Success
        if let statusCode = (response as? HTTPURLResponse)?.statusCode {
            print("Successfully downloaded. Status code: \(statusCode)")
        }

        do {
            try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
        } catch (let writeError) {
            print("Error creating a file \(destinationFileUrl) : \(writeError)")
        }

    } else {
        print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
    }
}
task.resume()
}

Setting the selected value on a Django forms.ChoiceField

Dave - any luck finding a solution to the browser problem? Is there a way to force a refresh?

As for the original problem, try the following when initializing the form:

def __init__(self, *args, **kwargs):
  super(MyForm, self).__init__(*args, **kwargs)   
  self.base_fields['MyChoiceField'].initial = initial_value

How do you run a command as an administrator from the Windows command line?

Browse to C:\windows\System32 and right click on cmd.exe and run as Administrator. Worked for me on Windows 7.

If you are trying to run a script with elevated privileges you could do the same for the script file or use the scheduler's run as a different user option to run the script.

How do I get a string format of the current date time, in python?

#python3

import datetime
print(
    '1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( date=datetime.datetime.now() )
    )

d = datetime.datetime.now()
print( "2a: {:%B %d, %Y}".format(d))

# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")

print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")

1: test-2018-02-14_16:40:52.txt

2a: March 04, 2018

2b: March 04, 2018

3: Today is 2018-11-11 yay


Description:

Using the new string format to inject value into a string at placeholder {}, value is the current time.

Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.

https://docs.python.org/3/library/string.html#formatexamples

Prevent Caching in ASP.NET MVC for specific actions using an attribute

Here's the NoCache attribute proposed by mattytommo, simplified by using the information from Chris Moschini's answer:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : OutputCacheAttribute
{
    public NoCacheAttribute()
    {
        this.Duration = 0;
    }
}

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

When do I use the PHP constant "PHP_EOL"?

There is one obvious place where it might be useful: when you are writing code that predominantly uses single quote strings. Its arguable as to whether:

echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;  
echo 'this other $one'."\n";

The art of it is to be consistent. The problem with mix and matching '' and "" is that when you get long strings, you don't really want to have to go hunting for what type of quote you used.

As with all things in life, it depends on the context.

Set up an HTTP proxy to insert a header

Rather than using a proxy, I'm using the Firefox plugin "Modify Headers" to insert headers (in my case, to fake a login using the Single Sign On so I can test as different people).

Find if a textbox is disabled or not using jquery

.prop('disabled') will return a Boolean:

var isDisabled = $('textbox').prop('disabled');

Here's the fiddle: http://jsfiddle.net/unhjM/

What is the easiest way to push an element to the beginning of the array?

You can use insert:

a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]

Where the first argument is the index to insert at and the second is the value.

How to add a string to a string[] array? There's no .Add function

to clear the array and make the number of it's elements = 0 at the same time, use this..

System.Array.Resize(ref arrayName, 0);

Unable to read repository at http://download.eclipse.org/releases/indigo

In my case, I discovered that the major issue why my eclipse won't connect to internet is my Internet Service Provider. I was only able to browse some websites but unable to browse other website. Fixing the issue with the ISP worked.

Barcode scanner for mobile phone for Website in form

We have an app in Google Play and the App Store that will scan barcodes into a web site. The app is called Scan to Web. http://berrywing.com/scantoweb.html

You can even embed a link or button to start the scanner yourself within your web page.

<a href="bwstw://startscanner">Link to start scanner</a>

The developer documentation website for the app covers how to use the app and use JavaScript for processing the barcode scan. http://berrywing.com/scantoweb/#htmlscanbutton

Reference jars inside a jar

if you do not want to create a custom class loader. You can read the jar file stream. And transfer it to a File object. Then you can get the url of the File. Send it to the URLClassLoader, you can load the jar file as you want. sample:

InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("example"+ ".jar");
final File tempFile = File.createTempFile("temp", ".jar");
tempFile.deleteOnExit();  // you can delete the temp file or not
try (FileOutputStream out = new FileOutputStream(tempFile)) {
    IOUtils.copy(resourceAsStream, out);
}
IOUtils.closeQuietly(resourceAsStream);
URL url = tempFile.toURI().toURL();
URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url});
urlClassLoader.loadClass()
...

How to stop VBA code running?

This is an old post, but given the title of this question, the END option should be described in more detail. This can be used to stop ALL PROCEDURES (not just the subroutine running). It can also be used within a function to stop other Subroutines (which I find useful for some add-ins I work with).

As Microsoft states:

Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables*. I noticed that the END method is not described in much detail. This can be used to stop ALL PROCEDURES (not just the subroutine running).

Here is an illustrative example:

Sub RunSomeMacros()

    Call FirstPart
    Call SecondPart

    'the below code will not be executed if user clicks yes during SecondPart.
    Call ThirdPart
    MsgBox "All of the macros have been run."

End Sub

Private Sub FirstPart()
    MsgBox "This is the first macro"

End Sub

Private Sub SecondPart()
    Dim answer As Long
    answer = MsgBox("Do you want to stop the macros?", vbYesNo)

    If answer = vbYes Then
        'Stops All macros!
        End
    End If

    MsgBox "You clicked ""NO"" so the macros are still rolling..."
End Sub

Private Sub ThirdPart()
    MsgBox "Final Macro was run."
End Sub

How to center canvas in html5

Add text-align: center; to the parent tag of <canvas>. That's it.

Example:

<div style="text-align: center">
    <canvas width="300" height="300">
        <!--your canvas code -->
    </canvas>
</div>

Browser: Identifier X has already been declared

I had a very close issue but in my case, it was Identifier 'e' has already been declared.

In my case caused because of using try {} catch (e) { var e = ... } where letter e is generated via minifier (uglifier).

So better solution could be use catch(ex){} (ex as an Excemption)

Hope somebody who searched with the similar question could find this question helpful.

Can I delete a git commit but keep the changes?

2020 Simple way :

git reset <commit_hash>

(The commit hash of the last commit you want to keep).

If the commit was pushed, you can then do :

git push -f

You will keep the now uncommitted changes locally

Android: Tabs at the BOTTOM

I was having the same problem with android tabs when trying to place them on the bottom of the screen. My scenario was to not use a layout file and create the tabs in code, I was also looking to fire activities from each tab which seemed a bit too complex using other approaches so, here is the sample code to overcome the problem:

adding-tabs-in-android-and-placing-them

Batch file to copy files from one folder to another folder

Look at rsync based Windows tool NASBackup. It will be a bonus if you are acquainted with rsync commands.

Ruby Hash to array of values

It is as simple as

hash.values
#=> [["a", "b", "c"], ["b", "c"]]

this will return a new array populated with the values from hash

if you want to store that new array do

array_of_values = hash.values
#=> [["a", "b", "c"], ["b", "c"]]

array_of_values
 #=> [["a", "b", "c"], ["b", "c"]]

Calling variable defined inside one function from another function

def anotherFunction(word):
    for letter in word:              
        print("_", end=" ")

def oneFunction(lists):
    category = random.choice(list(lists.keys()))
    word = random.choice(lists[category])
    return anotherFunction(word)

dynamic_cast and static_cast in C++

The following is not really close to what you get from C++'s dynamic_cast in terms of type checking but maybe it will help you understand its purpose a little bit better:

struct Animal // Would be a base class in C++
{
    enum Type { Dog, Cat };
    Type type;
};

Animal * make_dog()
{
   Animal * dog = new Animal;
   dog->type = Animal::Dog;
   return dog;
}
Animal * make_cat()
{
   Animal * cat = new Animal;
   cat->type = Animal::Cat;
   return cat;
}

Animal * dyn_cast(AnimalType type, Animal * animal)
{
    if(animal->type == type)
        return animal;
    return 0;
}

void bark(Animal * dog)
{
    assert(dog->type == Animal::Dog);

    // make "dog" bark
}

int main()
{
    Animal * animal;
    if(rand() % 2)
        animal = make_dog();
    else
        animal = make_cat();

    // At this point we have no idea what kind of animal we have
    // so we use dyn_cast to see if it's a dog

    if(dyn_cast(Animal::Dog, animal))
    {
        bark(animal); // we are sure the call is safe
    }

    delete animal;
}

How can I validate google reCAPTCHA v2 using javascript/jQuery?

You cannot validate alone with JS only. But if you want to check in the submit button that reCAPTCHA is validated or not that is user has clicked on reCAPTCHA then you can do that using below code.

 let recaptchVerified = false;
firebase.initializeApp(firebaseConfig);
firebase.auth().languageCode = 'en';
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container',{
    'callback': function(response) {
        recaptchVerified = true;
        // reCAPTCHA solved, allow signInWithPhoneNumber.
        // ...
    },
    'expired-callback': function() {
        // Response expired. Ask user to solve reCAPTCHA again.
        // ...
    }
});

Here I have used a variable recaptchVerified where I make it initially false and when Recaptcha is validated then I make it true.

So I can use recaptchVerified variable when the user click on the submit button and check if he had verified the captcha or not.

What is the mouse down selector in CSS?

I think you mean the active state

 button:active{
  //some styling
 }

These are all the possible pseudo states a link can have in CSS:

a:link {color:#FF0000;}    /* unvisited link, same as regular 'a' */
a:hover {color:#FF00FF;}   /* mouse over link */
a:focus {color:#0000FF;}   /* link has focus */
a:active {color:#0000FF;}  /* selected link */
a:visited {color:#00FF00;} /* visited link */

See also: http://www.w3.org/TR/selectors/#the-user-action-pseudo-classes-hover-act

Why is the gets function so dangerous that it should not be used?

I read recently, in a USENET post to comp.lang.c, that gets() is getting removed from the Standard. WOOHOO

You'll be happy to know that the committee just voted (unanimously, as it turns out) to remove gets() from the draft as well.

React Native version mismatch

In your build.gradle file add the following

implementation ("com.facebook.react:react-native:0.51.0") {
    force = true;
}

replace 0.51.0 with the version in your package.json

Ruby on Rails: How do I add placeholder text to a f.text_field?

In your view template, set a default value:

f.text_field :password, :value => "password"

In your Javascript (assuming jquery here):

$(document).ready(function() {
  //add a handler to remove the text
});

Recursive query in SQL Server

Something like this (not tested)

with match_groups as (

  select product_id, 
         matching_product_id,
         product_id as group_id
  from matches
  where product_id not in (select matching_product_id from matches)

  union all

  select m.product_id, m.matching_product_id, p.group_id
  from matches m
    join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;

Best way to generate a random float in C#

One more version... (I think this one is pretty good)

static float NextFloat(Random random)
{
    (float)(float.MaxValue * 2.0 * (rand.NextDouble()-0.5));
}

//inline version
float myVal = (float)(float.MaxValue * 2.0 * (rand.NextDouble()-0.5));

I think this...

  • is the 2nd fastest (see benchmarks)
  • is evenly distributed

And One more version...(not as good but posting anyway)

static float NextFloat(Random random)
{
    return float.MaxValue * ((rand.Next() / 1073741824.0f) - 1.0f);
}

//inline version
float myVal = (float.MaxValue * ((rand.Next() / 1073741824.0f) - 1.0f));

I think this...

  • is the fastest (see benchmarks)
  • is evenly distributed however because Next() is a 31 bit random value it will only return 2^31 values. (50% of the neighbor values will have the same value)

Testing of most of the functions on this page: (i7, release, without debug, 2^28 loops)

 Sunsetquest1: min: 3.402823E+38  max: -3.402823E+38 time: 3096ms
 SimonMourier: min: 3.402823E+38  max: -3.402819E+38 time: 14473ms
 AnthonyPegram:min: 3.402823E+38  max: -3.402823E+38 time: 3191ms
 JonSkeet:     min: 3.402823E+38  max: -3.402823E+38 time: 3186ms
 Sixlettervar: min: 1.701405E+38  max: -1.701410E+38 time: 19653ms
 Sunsetquest2: min: 3.402823E+38  max: -3.402823E+38 time: 2930ms

How to Flatten a Multidimensional Array?

Solution for 2 dimensional array

Please try this :

$array  = your array

$result = call_user_func_array('array_merge', $array);

echo "<pre>";
print_r($result);

EDIT : 21-Aug-13

Here is the solution which works for multi-dimensional array :

function array_flatten($array) {
    $return = array();
    foreach ($array as $key => $value) {
        if (is_array($value)){
            $return = array_merge($return, array_flatten($value));
        } else {
            $return[$key] = $value;
        }
    }

    return $return;
}

$array  = Your array

$result = array_flatten($array);

echo "<pre>";
print_r($result);

Ref: http://php.net/manual/en/function.call-user-func-array.php

How can I select checkboxes using the Selenium Java WebDriver?

Selecting a checkbox is similar to clicking a button.

driver.findElement(By.id("idOfTheElement")).click();

will do.

However, you can also see whether the checkbox is already checked. The following snippet checks whether the checkbox is selected or not. If it is not selected, then it selects.

if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
     driver.findElement(By.id("idOfTheElement")).click();
}

Image UriSource and Data Binding

The problem with the answer that was chosen here is that when navigating back and forth, the converter will get triggered every time the page is shown.

This causes new file handles to be created continuously and will block any attempt to delete the file because it is still in use. This can be verified by using Process Explorer.

If the image file might be deleted at some point, a converter such as this might be used: using XAML to bind to a System.Drawing.Image into a System.Windows.Image control

The disadvantage with this memory stream method is that the image(s) get loaded and decoded every time and no caching can take place: "To prevent images from being decoded more than once, assign the Image.Source property from an Uri rather than using memory streams" Source: "Performance tips for Windows Store apps using XAML"

To solve the performance issue, the repository pattern can be used to provide a caching layer. The caching could take place in memory, which may cause memory issues, or as thumbnail files that reside in a temp folder that can be cleared when the app exits.

Multiline strings in VB.NET

this was a really helpful article for me, but nobody mentioned how to concatenate in case you want to send some variables, which is what you need to do 99% of the time.

... <%= variable %> ...

Here's how you do it:

<SQL> SELECT * FROM MyTable WHERE FirstName='<%= EnteredName %>' </SQL>.Value

How to change the Push and Pop animations in a navigation based app

I did the following and it works fine.. and is simple and easy to understand..

CATransition* transition = [CATransition animation];
transition.duration = 0.5;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade; //kCATransitionMoveIn; //, kCATransitionPush, kCATransitionReveal, kCATransitionFade
//transition.subtype = kCATransitionFromTop; //kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom
[self.navigationController.view.layer addAnimation:transition forKey:nil];
[[self navigationController] popViewControllerAnimated:NO];

And the same thing for push..


Swift 3.0 version:

let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
self.navigationController?.view.layer.add(transition, forKey: nil)
_ = self.navigationController?.popToRootViewController(animated: false)

Bootstrap date time picker

Try This:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>_x000D_
  <script src="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
  <div class="container">_x000D_
    <div class="row">_x000D_
      <div class='col-sm-6'>_x000D_
        <div class="form-group">_x000D_
          <div class='input-group date' id='datetimepicker1'>_x000D_
            <input type='text' class="form-control" />_x000D_
            <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
            </span>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
      <script type="text/javascript">_x000D_
        $(function() {_x000D_
          $('#datetimepicker1').datetimepicker();_x000D_
        });_x000D_
      </script>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Hibernate, @SequenceGenerator and allocationSize

Steve Ebersole & other members,
Would you kindly explain the reason for an id with a larger gap(by default 50)? I am using Hibernate 4.2.15 and found the following code in org.hibernate.id.enhanced.OptimizerFactory cass.

if ( lo > maxLo ) {
   lastSourceValue = callback.getNextValue();
   lo = lastSourceValue.eq( 0 ) ? 1 : 0;
   hi = lastSourceValue.copy().multiplyBy( maxLo+1 ); 
}  
value = hi.copy().add( lo++ );

Whenever it hits the inside of the if statement, hi value is getting much larger. So, my id during the testing with the frequent server restart generates the following sequence ids:
1, 2, 3, 4, 19, 250, 251, 252, 400, 550, 750, 751, 752, 850, 1100, 1150.

I know you already said it didn't conflict with the spec, but I believe this will be very unexpected situation for most developers.

Anyone's input will be much helpful.

Jihwan

UPDATE: ne1410s: Thanks for the edit.
cfrick: OK. I will do that. It was my first post here and wasn't sure how to use it.

Now, I understood better why maxLo was used for two purposes: Since the hibernate calls the DB sequence once, keep increase the id in Java level, and saves it to the DB, the Java level id value should consider how much was changed without calling the DB sequence when it calls the sequence next time.

For example, sequence id was 1 at a point and hibernate entered 5, 6, 7, 8, 9 (with allocationSize = 5). Next time, when we get the next sequence number, DB returns 2, but hibernate needs to use 10, 11, 12... So, that is why "hi = lastSourceValue.copy().multiplyBy( maxLo+1 )" is used to get a next id 10 from the 2 returned from the DB sequence. It seems only bothering thing was during the frequent server restart and this was my issue with the larger gap.

So, when we use the SEQUENCE ID, the inserted id in the table will not match with the SEQUENCE number in DB.

How to declare a type as nullable in TypeScript?

Union type is in my mind best option in this case:

interface Employee{
   id: number;
   name: string;
   salary: number | null;
}

// Both cases are valid
let employe1: Employee = { id: 1, name: 'John', salary: 100 };
let employe2: Employee = { id: 1, name: 'John', salary: null };

EDIT : For this to work as expected, you should enable the strictNullChecks in tsconfig.

How to check if an element is visible with WebDriver

try this

public boolean isPrebuiltTestButtonVisible() {
    try {

        if (preBuiltTestButton.isEnabled()) {

            return true;

        } else {

            return false;
        }

    } catch (Exception e) {

        e.printStackTrace();
        return false;
    }
}

How to set a radio button in Android

btnDisplay.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

            // get selected radio button from radioGroup
        int selectedId = radioSexGroup.getCheckedRadioButtonId();

        // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);

        Toast.makeText(MyAndroidAppActivity.this,
            radioSexButton.getText(), Toast.LENGTH_SHORT).show();

    }

});

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

Please note you get error 419 if you are trying to upload a big file that exceeds the post file size limit. In this case you can increase both upload_max_filesize and post_max_size to a reasonable amount, (e.g. 10M or 20M depends on your use case and resources), check here: https://stackoverflow.com/a/2184541/2100489

But this may cause resource consumption issues, e.g bandwidth and storage. As a solution you can check the file size before submitting the form and show a warning message.

How to get an MD5 checksum in PowerShell

Another built-in command that's long been installed in Windows by default dating back to 2003 is Certutil, which of course can be invoked from PowerShell, too.

CertUtil -hashfile file.foo MD5

(Caveat: MD5 should be in all caps for maximum robustness)

jquery find closest previous sibling with class

Try:

$('li.current_sub').prevAll("li.par_cat:first");

Tested it with your markup:

$('li.current_sub').prevAll("li.par_cat:first").text("woohoo");

will fill up the closest previous li.par_cat with "woohoo".

TypeError: 'str' object cannot be interpreted as an integer

You will have to put:

X = input("give starting number") 
X = int(X)
Y = input("give ending number") 
Y = int(Y)

How do I set the icon for my application in visual studio 2008?

The important thing is that the icon you want to be displayed as the application icon ( in the title bar and in the task bar ) must be the FIRST icon in the resource script file

The file is in the res folder and is named (applicationName).rc

/////////////////////////////////////////////////////////////////////////////
//
// Icon
//

// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
(icon ID )          ICON                    "res\\filename.ico"

Installing Tomcat 7 as Service on Windows Server 2008

  1. Edit service.bat – Swap two lines so that they appear in following order: if not “%JAVA_HOME%“ == ““ goto got JdkHome if not “%JRE_HOME%“ == ““ goto got JreHome
  2. Open cmd and run command service.bat install
  3. Open Services and find Apache Tomcat 7.0 Tomcat7. Right click and Properties. Change its startup type to Automatic (with delay).
  4. Reboot machine to verify if the service started automatically

How to pass multiple parameters in thread in VB

Dim evaluator As New Thread(Sub() Me.testthread(goodList, 1))
With evaluator
.IsBackground = True ' not necessary...
.Start()
End With

ASP.Net MVC: How to display a byte array image from model

If you want to present the image, add a method as a helper class or to the model itself and allow the method to convert the byte array image to a image format like PNG or JPG then convert to Base64 string. Once you have that, bind the base64 value on your view in the format

"data:image/[image file type extension];base64,[your base64 string goes here]"

The above is assigned to the img tag's src attribute.

The only issue I have with this is the base64 string being too long. So, I would not recommend it for multiple models being shown in a view.

PHP header(Location: ...): Force URL change in address bar

you may want to put a break; after your location:

header("HTTP/1.1 301 Moved Permanently");
header('Location:  '.  $YourArrayName["YourURL"]  );
break;

Reactjs - Form input validation

Cleaner way is to use joi-browser package. In the state you should have errors object that includes all the errors in the form. Initially it shoud be set to an empty object. Create schema;

import Joi from "joi-browser";
schema = {
    username: Joi.string()
      .required()
      .label("Username")
      .email(),
    password: Joi.string()
      .required()
      .label("Password")
      .min(8)
      .regex(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,1024}$/) //special/number/capital
   };

Then validate the form with the schema:

validate = () => {
    const options = { abortEarly: false };
    const result = Joi.validate(this.state.data, this.schema, options);
    console.log(data) // always analyze your data
    if (!result.error) return null; 
    const errors = {};
    for (let item of result.error.details) errors[item.path[0]] = item.message; //in details array, there are 2 properties,path and message.path is the name of the input, message is the error message for that input.
    return errors;
  };

Before submitting the form, check the form:

handleSubmit = e => {
    e.preventDefault();
    const errors = this.validate(); //will return an object
    console.log(errors);
    this.setState({ errors: errors || {} }); //in line 9 if we return {}, we dont need {} here
    if (errors) return;
    //so we dont need to call the server
    alert("success");
    //if there is no error call the server
    this.dosubmit();
  };

Converting any object to a byte array in java

Yeah. Just use binary serialization. You have to have each object use implements Serializable but it's straightforward from there.

Your other option, if you want to avoid implementing the Serializable interface, is to use reflection and read and write data to/from a buffer using a process this one below:

/** 
 * Sets all int fields in an object to 0.
 *
 * @param obj The object to operate on.
 *
 * @throws RuntimeException If there is a reflection problem.
 */
 public static void initPublicIntFields(final Object obj) {
    try {
       Field[] fields = obj.getClass().getFields();
       for (int idx = 0; idx < fields.length; idx++) {
          if (fields[idx].getType() == int.class) {
              fields[idx].setInt(obj, 0);
          }
       }
    } catch (final IllegalAccessException ex) {
       throw new RuntimeException(ex);
    }
 }

Source.

String length in bytes in JavaScript

Took me a while to find a solution for React Native so I'll put it here:

First install the buffer package:

npm install --save buffer

Then user the node method:

const { Buffer } = require('buffer');
const length = Buffer.byteLength(string, 'utf-8');

Difference between View and ViewGroup in Android

View

  1. View objects are the basic building blocks of User Interface(UI) elements in Android.
  2. View is a simple rectangle box which responds to the user's actions.
  3. Examples are EditText, Button, CheckBox etc..
  4. View refers to the android.view.View class, which is the base class of all UI classes.

ViewGroup

  1. ViewGroup is the invisible container. It holds View and ViewGroup
  2. For example, LinearLayout is the ViewGroup that contains Button(View), and other Layouts also.
  3. ViewGroup is the base class for Layouts.

What is the syntax for Typescript arrow functions with generics?

I found the example above confusing. I am using React and JSX so I think it complicated the scenario.

I got clarification from TypeScript Deep Dive, which states for arrow generics:

Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, this came from a simpler example that helped me.

    const identity = < T extends {} >(arg: T): T => { return arg; }

Where to find extensions installed folder for Google Chrome on Mac?

The default locations of Chrome's profile directory are defined at http://www.chromium.org/user-experience/user-data-directory. For Chrome on Mac, it's

~/Library/Application\ Support/Google/Chrome/Default

The actual location can be different, by setting the --user-data-dir=path/to/directory flag.
If only one user is registered in Chrome, look in the Default/Extensions subdirectory. Otherwise, look in the <profile user name>/Extensions directory.

If that didn't help, you can always do a custom search.

  1. Go to chrome://extensions/, and find out the ID of an extension (32 lowercase letters) (if not done already, activate "Developer mode" first).

  2. Open the terminal, cd to the directory which is most likely a parent of your Chrome profile (if unsure, try ~ then /).

  3. Run find . -type d -iname "<EXTENSION ID HERE>", for example:

    find . -type d -iname jifpbeccnghkjeaalbbjmodiffmgedin
    

    Result:

    ./Library/Application Support/Google/Chrome/Default/Extensions/jifpbeccnghkjeaalbbjmodiffmgedin

Unable to cast object of type 'System.DBNull' to type 'System.String`

You can use C#'s null coalescing operator

return accountNumber ?? string.Empty;

Git "error: The branch 'x' is not fully merged"

I tried sehe's answer and it did not work.

To find the commits that have not been merged simply use:

git log feature-branch ^master --no-merges

How to adjust layout when soft keyboard appears

I use this Extended class frame And when I need to recalculate the height size onLayout I override onmeasure and subtract keyboardHeight using getKeyboardHeight()

My create frame who needs resize with softkeyboard

SizeNotifierFrameLayout frameLayout = new SizeNotifierFrameLayout(context) {
            private boolean first = true;

            @Override
            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                super.onLayout(changed, left, top, right, bottom);

                if (changed) {
                    fixLayoutInternal(first);
                    first = false;
                }
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) - getKeyboardHeight(), MeasureSpec.EXACTLY));
            }

            @Override
            protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
                boolean result = super.drawChild(canvas, child, drawingTime);
                if (child == actionBar) {
                    parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
                }
                return result;
            }


        };

SizeNotifierFrameLayout

public class SizeNotifierFrameLayout extends FrameLayout {

    public interface SizeNotifierFrameLayoutDelegate {
        void onSizeChanged(int keyboardHeight, boolean isWidthGreater);
    }

    private Rect                            rect            = new Rect();
    private Drawable                        backgroundDrawable;
    private int                             keyboardHeight;
    private int                             bottomClip;
    private SizeNotifierFrameLayoutDelegate delegate;
    private boolean                         occupyStatusBar = true;

    public SizeNotifierFrameLayout(Context context) {
        super(context);
        setWillNotDraw(false);
    }

    public Drawable getBackgroundImage() {
        return backgroundDrawable;
    }

    public void setBackgroundImage(Drawable bitmap) {
        backgroundDrawable = bitmap;
        invalidate();
    }

    public int getKeyboardHeight() {
        View rootView = getRootView();
        getWindowVisibleDisplayFrame(rect);
        int usableViewHeight = rootView.getHeight() - (rect.top != 0 ? AndroidUtilities.statusBarHeight : 0) - AndroidUtilities.getViewInset(rootView);
        return usableViewHeight - (rect.bottom - rect.top);
    }

    public void notifyHeightChanged() {
        if (delegate != null) {
            keyboardHeight = getKeyboardHeight();
            final boolean isWidthGreater = AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y;
            post(new Runnable() {
                @Override
                public void run() {
                    if (delegate != null) {
                        delegate.onSizeChanged(keyboardHeight, isWidthGreater);
                    }
                }
            });
        }
    }

    public void setBottomClip(int value) {
        bottomClip = value;
    }

    public void setDelegate(SizeNotifierFrameLayoutDelegate delegate) {
        this.delegate = delegate;
    }

    public void setOccupyStatusBar(boolean value) {
        occupyStatusBar = value;
    }

    protected boolean isActionBarVisible() {
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (backgroundDrawable != null) {
            if (backgroundDrawable instanceof ColorDrawable) {
                if (bottomClip != 0) {
                    canvas.save();
                    canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight() - bottomClip);
                }
                backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
                backgroundDrawable.draw(canvas);
                if (bottomClip != 0) {
                    canvas.restore();
                }
            } else if (backgroundDrawable instanceof BitmapDrawable) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) backgroundDrawable;
                if (bitmapDrawable.getTileModeX() == Shader.TileMode.REPEAT) {
                    canvas.save();
                    float scale = 2.0f / AndroidUtilities.density;
                    canvas.scale(scale, scale);
                    backgroundDrawable.setBounds(0, 0, (int) Math.ceil(getMeasuredWidth() / scale), (int) Math.ceil(getMeasuredHeight() / scale));
                    backgroundDrawable.draw(canvas);
                    canvas.restore();
                } else {
                    int actionBarHeight =
                            (isActionBarVisible() ? ActionBar.getCurrentActionBarHeight() : 0) + (Build.VERSION.SDK_INT >= 21 && occupyStatusBar ? AndroidUtilities.statusBarHeight : 0);
                    int   viewHeight = getMeasuredHeight() - actionBarHeight;
                    float scaleX     = (float) getMeasuredWidth() / (float) backgroundDrawable.getIntrinsicWidth();
                    float scaleY     = (float) (viewHeight + keyboardHeight) / (float) backgroundDrawable.getIntrinsicHeight();
                    float scale      = scaleX < scaleY ? scaleY : scaleX;
                    int   width      = (int) Math.ceil(backgroundDrawable.getIntrinsicWidth() * scale);
                    int   height     = (int) Math.ceil(backgroundDrawable.getIntrinsicHeight() * scale);
                    int   x          = (getMeasuredWidth() - width) / 2;
                    int   y          = (viewHeight - height + keyboardHeight) / 2 + actionBarHeight;
                    canvas.save();
                    canvas.clipRect(0, actionBarHeight, width, getMeasuredHeight() - bottomClip);
                    backgroundDrawable.setBounds(x, y, x + width, y + height);
                    backgroundDrawable.draw(canvas);
                    canvas.restore();
                }
            }
        } else {
            super.onDraw(canvas);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        notifyHeightChanged();
    }
}

FirstOrDefault: Default value other than null

Use DefaultIfEmpty() instead of FirstOrDefault().

Recyclerview and handling different type of row inflation

getItemViewType(int position) is the key

In my opinion,the starting point to create this kind of recyclerView is the knowledge of this method. Since this method is optional to override therefore it is not visible in RecylerView class by default which in turn makes many developers(including me) wonder where to begin. Once you know that this method exists, creating such RecyclerView would be a cakewalk.

enter image description here

How to do it ?

You can create a RecyclerView with any number of different Views(ViewHolders). But for better readability lets take an example of RecyclerView with two Viewholders.
Remember these 3 simple steps and you will be good to go.

  • Override public int getItemViewType(int position)
  • Return different ViewHolders based on the ViewType in onCreateViewHolder() method
  • Populate View based on the itemViewType in onBindViewHolder() method

    Here is a code snippet for you

    public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    
        private static final int LAYOUT_ONE= 0;
        private static final int LAYOUT_TWO= 1;
    
        @Override
        public int getItemViewType(int position)
        {
            if(position==0)
               return LAYOUT_ONE;
            else
               return LAYOUT_TWO;
        }
    
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    
            View view =null;
            RecyclerView.ViewHolder viewHolder = null;
    
            if(viewType==LAYOUT_ONE)
            {
               view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
               viewHolder = new ViewHolderOne(view);
            }
            else
            {
               view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
               viewHolder= new ViewHolderTwo(view);
            }
    
            return viewHolder;
        }
    
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    
           if(holder.getItemViewType()== LAYOUT_ONE)
           {
               // Typecast Viewholder 
               // Set Viewholder properties 
               // Add any click listener if any 
           }
           else {
    
               ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
               vaultItemHolder.name.setText(displayText);
               vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       .......
                   }
               });
    
           }
    
       }
    
       /****************  VIEW HOLDER 1 ******************//
    
       public class ViewHolderOne extends RecyclerView.ViewHolder {
    
           public TextView name;
    
           public ViewHolderOne(View itemView) {
           super(itemView);
           name = (TextView)itemView.findViewById(R.id.displayName);
           }
       }
    
    
      //****************  VIEW HOLDER 2 ******************//
    
      public class ViewHolderTwo extends RecyclerView.ViewHolder{
    
           public ViewHolderTwo(View itemView) {
           super(itemView);
    
               ..... Do something
           }
      }
    }
    

GitHub Code:

Here is a project where I have implemented a RecyclerView with multiple ViewHolders.

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

Appending to list in Python dictionary

dates_dict[key] = dates_dict.get(key, []).append(date) sets dates_dict[key] to None as list.append returns None.

In [5]: l = [1,2,3]

In [6]: var = l.append(3)

In [7]: print var
None

You should use collections.defaultdict

import collections
dates_dict = collections.defaultdict(list)

Getting JSONObject from JSONArray

Make use of Android Volly library as much as possible. It maps your JSON reponse in respective class objects. You can add getter setter for that response model objects. And then you can access these JSON values/parameter using .operator like normal JAVA Object. It makes response handling very simple.

How to dismiss a Twitter Bootstrap popover by clicking outside?

$('html').on('click.popover', function (e) {
    var allpopins = $('.popover.in');
    if (allpopins.has(e.target).length > 0 &&
        !$('.btn', allpopins).is(e.target))
        return;
    // recognise pop-up 
    var id = $(e.target).attr('aria-describedby');
    var popin = $("#" + id);
    //on any button click in entire pop-up hide this pop-ups
    $(popin).on(".btn", function () { popin.remove(); });
    // on any place out of entire popup hide all pop-ups 
    $('.popover.in').not(popin).remove();
});

This is my the best performance solution. Cheers.

Illegal pattern character 'T' when parsing a date string to java.util.Date

tl;dr

Use java.time.Instant class to parse text in standard ISO 8601 format, representing a moment in UTC.

Instant.parse( "2010-10-02T12:23:23Z" )

ISO 8601

That format is defined by the ISO 8601 standard for date-time string formats.

Both:

…use ISO 8601 formats by default for parsing and generating strings.

You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.

java.time

Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

Instant instant = Instant.parse( "2010-10-02T12:23:23Z" );  // `Instant` is always in UTC.

Convert to the old class.

java.util.Date date = java.util.Date.from( instant );  // Pass an `Instant` to the `from` method.

Time Zone

If needed, you can assign a time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );  // Assign a time zone adjustment from UTC.

Convert.

java.util.Date date = java.util.Date.from( zdt.toInstant() );  // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.

Here is some example code in Joda-Time 2.8.

org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC );  // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.

Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.

java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.

Time Zone

If needed, you can assign a time zone.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

What is the difference/usage of homebrew, macports or other package installation tools?

By default, Homebrew installs packages to your /usr/local. Macport commands require sudo to install and upgrade (similar to apt-get in Ubuntu).

For more detail:

This site suggests using Hombrew: http://deephill.com/macports-vs-homebrew/

whereas this site lists the advantages of using Macports: http://arstechnica.com/civis/viewtopic.php?f=19&t=1207907

I also switched from Ubuntu recently, and I enjoy using homebrew (it's simple and easy to use!), but if you feel attached to using sudo, Macports might be the better way to go!

Using onBackPressed() in Android Fragments

I didn't find any good answer about this problem, so this is my solution.

If you want to get backPress in each fragment do the following.

create interface OnBackPressedListener

public interface OnBackPressedListener {
    void onBackPressed();
}

That each fragment that wants to be informed of backPress implements this interface.

In parent activity , you can override onBackPressed()

@Override
public void onBackPressed() {
    List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
    if (fragmentList != null) {
        //TODO: Perform your logic to pass back press here
        for(Fragment fragment : fragmentList){
           if(fragment instanceof OnBackPressedListener){
               ((OnBackPressedListener)fragment).onBackPressed();
           }
        }
    }
}

How to install "ifconfig" command in my ubuntu docker image?

On a fresh ubuntu docker image, run

apt-get update
apt-get install net-tools

These can be executed by logging into the docker container or add this to your dockerfile to build an image with the same.

How does a hash table work?

A hash table totally works on the fact that practical computation follows random access machine model i.e. value at any address in memory can be accessed in O(1) time or constant time.

So, if I have a universe of keys (set of all possible keys that I can use in a application, e.g. roll no. for student, if it's 4 digit then this universe is a set of numbers from 1 to 9999), and a way to map them to a finite set of numbers of size I can allocate memory in my system, theoretically my hash table is ready.

Generally, in applications the size of universe of keys is very large than number of elements I want to add to the hash table(I don't wanna waste a 1 GB memory to hash ,say, 10000 or 100000 integer values because they are 32 bit long in binary reprsentaion). So, we use this hashing. It's sort of a mixing kind of "mathematical" operation, which maps my large universe to a small set of values that I can accomodate in memory. In practical cases, often space of a hash table is of the same "order"(big-O) as the (number of elements *size of each element), So, we don't waste much memory.

Now, a large set mapped to a small set, mapping must be many-to-one. So, different keys will be alloted the same space(?? not fair). There are a few ways to handle this, I just know the popular two of them:

  • Use the space that was to be allocated to the value as a reference to a linked list. This linked list will store one or more values, that come to reside in same slot in many to one mapping. The linked list also contains keys to help someone who comes searching. It's like many people in same apartment, when a delivery-man comes, he goes to the room and asks specifically for the guy.
  • Use a double hash function in an array which gives the same sequence of values every time rather than a single value. When I go to store a value, I see whether the required memory location is free or occupied. If it's free, I can store my value there, if it's occupied I take next value from the sequence and so on until I find a free location and I store my value there. When searching or retreiving the value, I go back on same path as given by the sequence and at each location ask for the vaue if it's there until I find it or search all possible locations in the array.

Introduction to Algorithms by CLRS provides a very good insight on the topic.

How do I do a HTTP GET in Java?

If you dont want to use external libraries, you can use URL and URLConnection classes from standard Java API.

An example looks like this:

String urlString = "http://wherever.com/someAction?param1=value1&param2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream

Why is Maven downloading the maven-metadata.xml every time?

It is possibly to use the flag -o,--offline "Work offline" to prevent that.

Like this:

maven compile -o

String delimiter in string.split method

The problem is because you are adding quotes to your delimiter. It should be removed, and it will work fine.

public void setDelimiter(String delimiter) {
    char[] c = delimiter.toCharArray();
    this.delimiter = "\\" + c[0] + "\\" + c[1];
    System.out.println("Delimiter string is: " + this.delimiter);
}

Non-static variable cannot be referenced from a static context

  • The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.

  • Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class

  • As a corollary to the above

    1. variables within a method can not be static
    2. static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
  • The lifetime of a static field/method is equivalent to the lifetime of your application

E.g. Say, car has the property colour, and exhibits the behaviour 'motion'. An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.

Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.

HTH

Run PHP Task Asynchronously

Unfortunately PHP does not have any kind of native threading capabilities. So I think in this case you have no choice but to use some kind of custom code to do what you want to do.

If you search around the net for PHP threading stuff, some people have come up with ways to simulate threads on PHP.

Is there a way to list all resources in AWS

I know it is old question but I would like to help too.

Actually, we have AWS Config, which help us to search for all resources in our cloud. You can perform SQL queries too.

I really encourage you all to know this awesome service.

Declare global variables in Visual Studio 2010 and VB.NET

You could just add a new Variable under the properties of your project Each time you want to get that variable you just have to use

My.Settings.(Name of variable)

That'll work for the entire Project in all forms

Rendering raw html with reactjs

export class ModalBody extends Component{
    rawMarkup(){
        var rawMarkup = this.props.content
        return { __html: rawMarkup };
    }
    render(){
        return(
                <div className="modal-body">
                     <span dangerouslySetInnerHTML={this.rawMarkup()} />

                </div>
            )
    }
}

XSL if: test with multiple test conditions

Try to use the empty() function:

<xsl:if test="empty(node/ABC/node()) and empty(node/DEF/node())">
    <xsl:text>This should work</xsl:text>
</xsl:if>

This identifies ABC and DEF as empty in the sense that they do not have any child nodes (no elements, no text nodes, no processing instructions, no comments).

But, as pointed out by @Ian, your elements might not be empty really or that might not be your actual problem - you did not show what your input XML looks like.

Another cause of error could be your relative position in the tree. This way of testing conditions only works if the surrounding template matches the parent element of node or if you iterate over the parent element of node.

Removing packages installed with go get

It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src and the package file under $GOPATH/pkg/<architecture>, for example: $GOPATH/pkg/windows_amd64.

Inserting string at position x of another string

try

a.slice(0,position) + b + a.slice(position)

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.slice(0,position) + b + a.slice(position);_x000D_
_x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

or regexp solution

"I want apple".replace(/^(.{6})/,"$1 an")

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.replace(new RegExp(`^(.{${position}})`),"$1"+b);_x000D_
_x000D_
console.log(r);_x000D_
console.log("I want apple".replace(/^(.{6})/,"$1 an"));
_x000D_
_x000D_
_x000D_

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

SignalR provides ConnectionId for each connection. To find which connection belongs to whom (the user), we need to create a mapping between the connection and the user. This depends on how you identify a user in your application.

In SignalR 2.0, this is done by using the inbuilt IPrincipal.Identity.Name, which is the logged in user identifier as set during the ASP.NET authentication.

However, you may need to map the connection with the user using a different identifier instead of using the Identity.Name. For this purpose this new provider can be used with your custom implementation for mapping user with the connection.

Example of Mapping SignalR Users to Connections using IUserIdProvider

Lets assume our application uses a userId to identify each user. Now, we need to send message to a specific user. We have userId and message, but SignalR must also know the mapping between our userId and the connection.

To achieve this, first we need to create a new class which implements IUserIdProvider:

public class CustomUserIdProvider : IUserIdProvider
{
     public string GetUserId(IRequest request)
    {
        // your logic to fetch a user identifier goes here.

        // for example:

        var userId = MyCustomUserClass.FindUserId(request.User.Identity.Name);
        return userId.ToString();
    }
}

The second step is to tell SignalR to use our CustomUserIdProvider instead of the default implementation. This can be done in the Startup.cs while initializing the hub configuration:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var idProvider = new CustomUserIdProvider();

        GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);          

        // Any connection or hub wire up and configuration should go here
        app.MapSignalR();
    }
}

Now, you can send message to a specific user using his userId as mentioned in the documentation, like:

public class MyHub : Hub
{
   public void Send(string userId, string message)
   {
      Clients.User(userId).send(message);
   }
}

Hope this helps.

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

Just to add a bit to the discussion from my experience working with Volley:

  1. Volley does not handle streaming uploads or downloads in any sense. That is, the entire request body has to be in memory and you cannot use an OutputStream to write the request body to the underlying socket, nor can you use an InputStream to read the response body, as basic HttpURLConnection does. So, Volley is a poor choice for uploading or downloading large files. Your requests and responses should be small. This is one of the biggest limitations of Volley that I have personally encountered. For what it's worth, OkHttp does have interfaces for working with streams.

  2. The lack of official documentation is annoying, although I have been able to work around that by reading the source code, which is pretty easy to follow. What is more bothersome is that, as far as I can tell, Volley has no official release versions and no Maven or Gradle artifact, and therefore managing it as a dependency becomes more of a headache than, say, any of the libraries Square has released. You just clone a repo, build a jar, and you're on your own. Looking for a bug fix? Fetch and hope it's there. You might get some other stuff, too; it won't be documented. In my opinion, this effectively means that Volley is an unsupported 3rd party library, even though the code base is reasonably active. Caveat emptor.

  3. As a nit, having the Content-Type tied to the class/request type (JsonObjectRequest, ImageRequest, etc.) is kind of awkward and reduces the flexibility of the calling code a bit, as you are tied to Volley's existing Request type hierarchy. I like the straightforwardness of just setting Content-Type as a header like any other (don't do this with Volley, by the way; you'll end up with two Content-Type headers!). That's just my personal opinion, though, and it can be worked around.

That is not to say that Volley does not have some useful features. It certainly does. Easily customizable retry policies, transparent caching, a cancellation API, and support for request scheduling and concurrent connections are great features. Just know that it's not intended for all HTTP use cases (see item 1 above), and that there are some headaches involved in putting Volley into production use in your app (item 2).

Assign multiple values to array in C

If you really to assign values (as opposed to initialize), you can do it like this:

 GLfloat coordinates[8]; 
 static const GLfloat coordinates_defaults[8] = {1.0f, 0.0f, 1.0f ....};
 ... 
 memcpy(coordinates, coordinates_defaults, sizeof(coordinates_defaults));

 return coordinates; 

Paste in insert mode?

If you set Vim to use the system clipboard (:set clipboard=unnamed), then any text you copy in Vim can be pasted using Shift + Insert. Shift + Insert is simply an OS-wide paste key-combination (Ctrl + Insert is the corresponding 'copy').

IntelliJ Organize Imports

Ctrl + Alt + O (Code ? Optimize Imports...) is what you're looking for, both on Windows/Linux and macOS keymaps.

It says "Optimize", but, if configured to do so, it will also:

  • organize existing imports
  • remove unneeded imports
  • add new required imports
  • add unambiguous imports on the fly

You can tune the auto-import settings under "Settings ? Editor ? General ? Auto Import" as described by Dave.

You can also modify how the imports are auto-ordered under "Settings ? Editor ? Code Style ? Java ? Imports"

How to launch another aspx web page upon button click?

This button post to the current page while at the same time opens OtherPage.aspx in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.

<asp:Button ID="myBtn" runat="server" Text="Click me" 
     onclick="myBtn_Click" OnClientClick="window.open('OtherPage.aspx', 'OtherPage');" />

set date in input type date

var today = new Date().toISOString().split('T')[0];
$("#datePicker").val(today);

Above code will work.

What does "dereferencing" a pointer mean?

Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.

int a = 10;
int* ptr = &a;

printf("%d", *ptr); // With *ptr I'm dereferencing the pointer. 
                    // Which means, I am asking the value pointed at by the pointer.
                    // ptr is pointing to the location in memory of the variable a.
                    // In a's location, we have 10. So, dereferencing gives this value.

// Since we have indirect control over a's location, we can modify its content using the pointer. This is an indirect way to access a.

 *ptr = 20;         // Now a's content is no longer 10, and has been modified to 20.

How to find the array index with a value?

Here is my take on it, seems like most peoples solutions don't check if the item exists and it removes random values if it does not exist.

First check if the element exists by looking for it's index. If it does exist, remove it by its index using the splice method

elementPosition = array.indexOf(value);

if(elementPosition != -1) {
  array.splice(elementPosition, 1);
}

Pythonic way to return list of every nth item in a larger list

From manual: s[i:j:k] slice of s from i to j with step k

li = range(100)
sub = li[0::10]

>>> sub
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

jQuery selector regular expressions

You can use the filter function to apply more complicated regex matching.

Here's an example which would just match the first three divs:

_x000D_
_x000D_
$('div')_x000D_
  .filter(function() {_x000D_
    return this.id.match(/abc+d/);_x000D_
  })_x000D_
  .html("Matched!");
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="abcd">Not matched</div>_x000D_
<div id="abccd">Not matched</div>_x000D_
<div id="abcccd">Not matched</div>_x000D_
<div id="abd">Not matched</div>
_x000D_
_x000D_
_x000D_

TypeError: Image data can not convert to float

The error occurred when I unknowingly tried plotting the image path instead of the image.

My code :

import cv2 as cv
from matplotlib import pyplot as plt
import pytesseract
from resizeimage import resizeimage

img = cv.imread("D:\TemplateMatch\\fitting.png") ------>"THIS IS THE WRONG USAGE"
#cv.rectangle(img,(29,2496),(604,2992),(255,0,0),5)
plt.imshow(img)

Correction: img = cv.imread("fitting.png") --->THIS IS THE RIGHT USAGE"

PostgreSQL database default location on Linux

The command pg_lsclusters (at least under Linux / Ubuntu) can be used to list the existing clusters and with it also the data directory:

Ver Cluster Port Status Owner    Data directory               Log file
9.5 main    5433 down   postgres /var/lib/postgresql/9.5/main /var/log/postgresql/postgresql-9.5-main.log
10  main    5432 down   postgres /var/lib/postgresql/10/main  /var/log/postgresql/postgresql-10-main.log

Find first element in a sequence that matches a predicate

I don't think there's anything wrong with either solutions you proposed in your question.

In my own code, I would implement it like this though:

(x for x in seq if predicate(x)).next()

The syntax with () creates a generator, which is more efficient than generating all the list at once with [].

How to import/include a CSS file using PHP code and not HTML code?

I don't know why you would need this but to do this, you could edit your css file:-

<style type="text/css">
body{
...;
...;
}
</style>

You have just added here and saved it as main.php. You can continue with main.css but it is better as .php since it does not remain a css file after you do that edit


Then edit your HTML file like this. NOTE: Make the include statement inside the tag

<html>
<head>
 <title>Sample</title>
 <?php inculde('css/main.css');>
</head>
<body>
...
...
</body>
</html>

What is the proper way to re-throw an exception in C#?

The first is better. If you try to debug the second and look at the call stack you won't see where the original exception came from. There are tricks to keep the call-stack intact (try search, it's been answered before) if you really need to rethrow.

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

Format date with Moment.js

Include moment.js and using the below code you can format your date

var formatDate= 1399919400000;

var responseDate = moment(formatDate).format('DD/MM/YYYY');

My output is "13/05/2014"

How to remove all debug logging calls before building the release version of an Android app?

the simplest way;

use DebugLog

All logs are disabled by DebugLog when the app is released.

https://github.com/MustafaFerhan/DebugLog

jQuery get the id/value of <li> element after click function

you can get the value of the respective li by using this method after click

HTML:-

<!DOCTYPE html>
<html>
<head>
    <title>show the value of li</title>
    <link rel="stylesheet"  href="pathnameofcss">
</head>
<body>

    <div id="user"></div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <ul id="pageno">
    <li value="1">1</li>
    <li value="2">2</li>
    <li value="3">3</li>
    <li value="4">4</li>
    <li value="5">5</li>
    <li value="6">6</li>
    <li value="7">7</li>
    <li value="8">8</li>
    <li value="9">9</li>
    <li value="10">10</li>

    </ul>

    <script src="pathnameofjs" type="text/javascript"></script>
</body>
</html>

JS:-

$("li").click(function ()
{       
var a = $(this).attr("value");

$("#user").html(a);//here the clicked value is showing in the div name user
console.log(a);//here the clicked value is showing in the console
});

CSS:-

ul{
display: flex;
list-style-type:none;
padding: 20px;
}

li{
padding: 20px;
}

Submit HTML form, perform javascript function (alert then redirect)

Looks like your form is submitting which is the default behaviour, you can stop it with this:

<form action="" method="post" onsubmit="completeAndRedirect();return false;">

Get table names using SELECT statement in MySQL

To insert, update and delete do the following:

$teste = array('LOW_PRIORITY', 'DELAYED', 'HIGH_PRIORITY', 'IGNORE', 'INTO', 'INSERT', 'UPDATE', 'DELETE', 'QUICK', 'FROM');
$teste1 = array("\t", "\n", "\r", "\0", "\x0B");
$strsql = trim(str_ireplace($teste1, ' ', str_ireplace($teste, '', $strsql)));
$nomeTabela = substr($strsql, 0, strpos($strsql, ' '));

print($nomeTabela);
exit;

How to get the path of a running JAR file?

To obtain the File for a given Class, there are two steps:

  1. Convert the Class to a URL
  2. Convert the URL to a File

It is important to understand both steps, and not conflate them.

Once you have the File, you can call getParentFile to get the containing folder, if that is what you need.

Step 1: Class to URL

As discussed in other answers, there are two major ways to find a URL relevant to a Class.

  1. URL url = Bar.class.getProtectionDomain().getCodeSource().getLocation();

  2. URL url = Bar.class.getResource(Bar.class.getSimpleName() + ".class");

Both have pros and cons.

The getProtectionDomain approach yields the base location of the class (e.g., the containing JAR file). However, it is possible that the Java runtime's security policy will throw SecurityException when calling getProtectionDomain(), so if your application needs to run in a variety of environments, it is best to test in all of them.

The getResource approach yields the full URL resource path of the class, from which you will need to perform additional string manipulation. It may be a file: path, but it could also be jar:file: or even something nastier like bundleresource://346.fwk2106232034:4/foo/Bar.class when executing within an OSGi framework. Conversely, the getProtectionDomain approach correctly yields a file: URL even from within OSGi.

Note that both getResource("") and getResource(".") failed in my tests, when the class resided within a JAR file; both invocations returned null. So I recommend the #2 invocation shown above instead, as it seems safer.

Step 2: URL to File

Either way, once you have a URL, the next step is convert to a File. This is its own challenge; see Kohsuke Kawaguchi's blog post about it for full details, but in short, you can use new File(url.toURI()) as long as the URL is completely well-formed.

Lastly, I would highly discourage using URLDecoder. Some characters of the URL, : and / in particular, are not valid URL-encoded characters. From the URLDecoder Javadoc:

It is assumed that all characters in the encoded string are one of the following: "a" through "z", "A" through "Z", "0" through "9", and "-", "_", ".", and "*". The character "%" is allowed but is interpreted as the start of a special escaped sequence.

...

There are two possible ways in which this decoder could deal with illegal strings. It could either leave illegal characters alone or it could throw an IllegalArgumentException. Which approach the decoder takes is left to the implementation.

In practice, URLDecoder generally does not throw IllegalArgumentException as threatened above. And if your file path has spaces encoded as %20, this approach may appear to work. However, if your file path has other non-alphameric characters such as + you will have problems with URLDecoder mangling your file path.

Working code

To achieve these steps, you might have methods like the following:

/**
 * Gets the base location of the given class.
 * <p>
 * If the class is directly on the file system (e.g.,
 * "/path/to/my/package/MyClass.class") then it will return the base directory
 * (e.g., "file:/path/to").
 * </p>
 * <p>
 * If the class is within a JAR file (e.g.,
 * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the
 * path to the JAR (e.g., "file:/path/to/my-jar.jar").
 * </p>
 *
 * @param c The class whose location is desired.
 * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}.
 */
public static URL getLocation(final Class<?> c) {
    if (c == null) return null; // could not load the class

    // try the easy way first
    try {
        final URL codeSourceLocation =
            c.getProtectionDomain().getCodeSource().getLocation();
        if (codeSourceLocation != null) return codeSourceLocation;
    }
    catch (final SecurityException e) {
        // NB: Cannot access protection domain.
    }
    catch (final NullPointerException e) {
        // NB: Protection domain or code source is null.
    }

    // NB: The easy way failed, so we try the hard way. We ask for the class
    // itself as a resource, then strip the class's path from the URL string,
    // leaving the base path.

    // get the class's raw resource path
    final URL classResource = c.getResource(c.getSimpleName() + ".class");
    if (classResource == null) return null; // cannot find class resource

    final String url = classResource.toString();
    final String suffix = c.getCanonicalName().replace('.', '/') + ".class";
    if (!url.endsWith(suffix)) return null; // weird URL

    // strip the class's path from the URL string
    final String base = url.substring(0, url.length() - suffix.length());

    String path = base;

    // remove the "jar:" prefix and "!/" suffix, if present
    if (path.startsWith("jar:")) path = path.substring(4, path.length() - 2);

    try {
        return new URL(path);
    }
    catch (final MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
} 

/**
 * Converts the given {@link URL} to its corresponding {@link File}.
 * <p>
 * This method is similar to calling {@code new File(url.toURI())} except that
 * it also handles "jar:file:" URLs, returning the path to the JAR file.
 * </p>
 * 
 * @param url The URL to convert.
 * @return A file path suitable for use with e.g. {@link FileInputStream}
 * @throws IllegalArgumentException if the URL does not correspond to a file.
 */
public static File urlToFile(final URL url) {
    return url == null ? null : urlToFile(url.toString());
}

/**
 * Converts the given URL string to its corresponding {@link File}.
 * 
 * @param url The URL to convert.
 * @return A file path suitable for use with e.g. {@link FileInputStream}
 * @throws IllegalArgumentException if the URL does not correspond to a file.
 */
public static File urlToFile(final String url) {
    String path = url;
    if (path.startsWith("jar:")) {
        // remove "jar:" prefix and "!/" suffix
        final int index = path.indexOf("!/");
        path = path.substring(4, index);
    }
    try {
        if (PlatformUtils.isWindows() && path.matches("file:[A-Za-z]:.*")) {
            path = "file:/" + path.substring(5);
        }
        return new File(new URL(path).toURI());
    }
    catch (final MalformedURLException e) {
        // NB: URL is not completely well-formed.
    }
    catch (final URISyntaxException e) {
        // NB: URL is not completely well-formed.
    }
    if (path.startsWith("file:")) {
        // pass through the URL as-is, minus "file:" prefix
        path = path.substring(5);
        return new File(path);
    }
    throw new IllegalArgumentException("Invalid URL: " + url);
}

You can find these methods in the SciJava Common library:

Using AND/OR in if else PHP statement

You have 2 issues here.

  1. use == for comparison. You've used = which is for assignment.

  2. use && for "and" and || for "or". and and or will work but they are unconventional.

null terminating a string

To your first question: I would go with Paul R's comment and terminate with '\0'. But the value 0 itself works also fine. A matter of taste. But don't use the MACRO NULLwhich is meant for pointers.

To your second question: If your string is not terminated with\0, it might still print the expected output because following your string is a non-printable character in your memory. This is a really nasty bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'.

jQuery or JavaScript auto click

First i tried with this sample code:

$(document).ready(function(){ 
     $('#upload-file').click(); 
});

It didn't work for me. Then after, tried with this

$(document).ready(function(){ 
     $('#upload-file')[0].click(); 
});

No change. At last, tried with this

$(document).ready(function(){ 
     $('#upload-file')[0].click(function(){
     }); 
});

Solved my problem. Helpful for anyone.

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

$data = array( 
    'name'      => $_POST['name'] , 
    'groupname' => $_POST['groupname'], 
    'age'       => $_POST['age']
);

$this->db->where('id', $_POST['id']);

$this->db->update('tbl_user', $data);

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

Try setting

npm config set strict-ssl false

and then try running,

npm install -g @angular/cli

Root element is missing

If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.

I wrote a quick console app to run your code and parse the file and it works fine for me.

Is a GUID unique 100% of the time?

GUID stands for Global Unique Identifier

In Brief: (the clue is in the name)

In Detail: GUIDs are designed to be unique; they are calculated using a random method based on the computers clock and computer itself, if you are creating many GUIDs at the same millisecond on the same machine it is possible they may match but for almost all normal operations they should be considered unique.

Copy/Paste from Excel to a web page

In response to the answer by Tatu I have created a quick jsFiddle for showcasing his solution:

http://jsfiddle.net/duwood/sTX7y/

HTML

<p>Paste excel data here:</p>  
<textarea name="excel_data" style="width:250px;height:150px;"></textarea><br>
<input type="button" onclick="javascript:generateTable()" value="Genereate Table"/>
<br><br>
    <p>Table data will appear below</p>
<hr>
<div id="excel_table"></div>

JS

function generateTable() {
    var data = $('textarea[name=excel_data]').val();
    console.log(data);
    var rows = data.split("\n");

    var table = $('<table />');

    for(var y in rows) {
    var cells = rows[y].split("\t");
    var row = $('<tr />');
    for(var x in cells) {
        row.append('<td>'+cells[x]+'</td>');
    }
    table.append(row);
}

// Insert into DOM
$('#excel_table').html(table);
}

Split string into tokens and save them in an array

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

int main ()
{
    char buf[] ="abc/qwe/ccd";
    int i = 0;
    char *p = strtok (buf, "/");
    char *array[3];

    while (p != NULL)
    {
        array[i++] = p;
        p = strtok (NULL, "/");
    }

    for (i = 0; i < 3; ++i) 
        printf("%s\n", array[i]);

    return 0;
}

Stack array using pop() and push()

 public class Stack {
     int[] arr;
     int MAX_SIZE;
     int top;

public Stack(int n){
    MAX_SIZE = n;
    arr = new int[MAX_SIZE];
    top=0;
}

    public boolean isEmpty(){
        if(top ==0)
            return true;
      else
        return false;
   }

public boolean push(int ele){

    if(top<MAX_SIZE){
        arr[top] = ele;
        top++;
        return true;
    }
    else{
        System.out.println("Stack is full");
        return false;
    }
}
public void show(){
    for(int element:arr){
        System.out.print(element+" ");
    }
}
public int size(){
    return top;
}
   public int peek(){
        if(!isEmpty()){
            int peekTest = arr[top-1];
            return peekTest;
                    }
   else{
       System.out.println("Stack is empty");
       return 0;
   } 
}
public int pop(){
    if(isEmpty()){
        System.out.println("Stack is Emmpty");
        return 0;
    }
    else{
        int element = arr[--top];
        return element;
    }
}

}

How can I concatenate strings in VBA?

The main (very interesting) difference for me is that:
"string" & Null -> "string"
while
"string" + Null -> Null

But that's probably more useful in database apps like Access.

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

Following is a simple code to read from SQL database. Database names is "database1". Table name is "table1". It contain two columns "uname" and "pass". Dont forget to add "sqljdbc4.jar" to your project. Download sqljdbc4.jar

public class NewClass {

    public static void main(String[] args) {

        Connection conn = null;
        String dbName = "database1";
        String serverip="192.168.100.100";
        String serverport="1433";
        String url = "jdbc:sqlserver://"+serverip+"\\SQLEXPRESS:"+serverport+";databaseName="+dbName+"";
        Statement stmt = null;
        ResultSet result = null;
        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        String databaseUserName = "admin";
        String databasePassword = "root";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, databaseUserName, databasePassword);
            stmt = conn.createStatement();
            result = null;
            String pa,us;
            result = stmt.executeQuery("select * from table1 ");

            while (result.next()) {
                us=result.getString("uname");
                pa = result.getString("pass");              
                System.out.println(us+"  "+pa);
            }

            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Override hosts variable of Ansible playbook from the command line

I am using ansible 2.5 (2.5.3 exactly), and it seems that the vars file is loaded before the hosts param is executed. So you can set the host in a vars.yml file and just write hosts: {{ host_var }} in your playbook

For example, in my playbook.yml:

---
- hosts: "{{ host_name }}"
  become: yes
  vars_files:
    - vars/project.yml
  tasks:
    ... 

And inside vars/project.yml:

---

# general
host_name: your-fancy-host-name

Multi-gradient shapes

You CAN do it using only xml shapes - just use layer-list AND negative padding like this:

    <layer-list>

        <item>
            <shape>
                <solid android:color="#ffffff" />

                <padding android:top="20dp" />
            </shape>
        </item>

        <item>
            <shape>
                <gradient android:endColor="#ffffff" android:startColor="#efefef" android:type="linear" android:angle="90" />

                <padding android:top="-20dp" />
            </shape>
        </item>

    </layer-list>

PostgreSQL: Why psql can't connect to server?

quick howto on debian to remotely access postgres database on server from the psql client: (the changed config is doc'd in the files):

  1. edit /etc/postgresql/10/main/postgresql.conf with listen_address *
  2. edit /etc/postgresql/10/main/pg_hba.conf and add line in the end with host all all 0/0 md5
  3. create login role postgres=# CREATE ROLE remoteuser LOGIN WITH PASSWORD 'foo'
  4. sudo /etc/init.d/postgresql restart changes take effect

  5. login from clientside with psql --host=ipofserver --port=5432 --username=remoteuser --password --dbname=mydb

  6. the password is interactivly asked which in this case is foo

String in function parameter

function("MyString");

is similar to

char *s = "MyString";
function(s);

"MyString" is in both cases a string literal and in both cases the string is unmodifiable.

function("MyString");

passes the address of a string literal to function as an argument.

Random alpha-numeric string in JavaScript?

When I saw this question I thought of when I had to generate UUIDs. I can't take credit for the code, as I am sure I found it here on stackoverflow. If you dont want the dashes in your string then take out the dashes. Here is the function:

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uuid.toUpperCase();
}

Fiddle: http://jsfiddle.net/nlviands/fNPvf/11227/

T-SQL datetime rounded to nearest minute and nearest hours with using functions

"Rounded" down as in your example. This will return a varchar value of the date.

DECLARE @date As DateTime2
SET @date = '2007-09-22 15:07:38.850'

SELECT CONVERT(VARCHAR(16), @date, 120) --2007-09-22 15:07
SELECT CONVERT(VARCHAR(13), @date, 120) --2007-09-22 15

Download all stock symbol list of a market

This may be old, but... if you change the link in google stock list as below:

https://www.google.com/finance?q=%5B(exchange%20%3D%3D%20%22NASDAQ%22)%5D&restype=company&noIL=1&num=30000

  • note for the noIL=1&num=30000

It means, starting for row 1 to 30000. It shows all results in one page.

You may automate it using any language or just export the table to excel.

Hope it helps.

How to reshape data from long to wide format

The new (in 2014) tidyr package also does this simply, with gather()/spread() being the terms for melt/cast.

Edit: Now, in 2019, tidyr v 1.0 has launched and set spread and gather on a deprecation path, preferring instead pivot_wider and pivot_longer, which you can find described in this answer. Read on if you want a brief glimpse into the brief life of spread/gather.

library(tidyr)
spread(dat1, key = numbers, value = value)

From github,

tidyr is a reframing of reshape2 designed to accompany the tidy data framework, and to work hand-in-hand with magrittr and dplyr to build a solid pipeline for data analysis.

Just as reshape2 did less than reshape, tidyr does less than reshape2. It's designed specifically for tidying data, not the general reshaping that reshape2 does, or the general aggregation that reshape did. In particular, built-in methods only work for data frames, and tidyr provides no margins or aggregation.

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I'm adding an answer with the same direction as the accepted answer but with small (important) differences and adding more details.

Consider the configuration below:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": ["arn:aws:s3:::<Bucket-Name>"]
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:DeleteObject"
      ],
      "Resource": ["arn:aws:s3:::<Bucket-Name>/*"]
    }
  ]
}

The policy grants programmatic write-delete access and is separated into two parts:
The ListBucket action provides permissions on the bucket level and the other PutObject/DeleteObject actions require permissions on the objects inside the bucket.

The first Resource element specifies arn:aws:s3:::<Bucket-Name> for the ListBucket action so that applications can list all objects in the bucket.

The second Resource element specifies arn:aws:s3:::<Bucket-Name>/* for the PutObject, and DeletObject actions so that applications can write or delete any objects in the bucket.

The separation into two different 'arns' is important from security reasons in order to specify bucket-level and object-level fine grained permissions.

Notice that if I would have specified just GetObject in the 2nd block what would happen is that in cases of programmatic access I would receive an error like:

Upload failed: <file-name> to <bucket-name>:<path-in-bucket> An error occurred (AccessDenied) when calling the PutObject operation: Access Denied.

Why doesn't C++ have a garbage collector?

Imposing garbage collection is really a low level to high level paradigm shift.

If you look at the way strings are handled in a language with garbage collection, you will find they ONLY allow high level string manipulation functions and do not allow binary access to the strings. Simply put, all string functions first check the pointers to see where the string is, even if you are only drawing out a byte. So if you are doing a loop that processes each byte in a string in a language with garbage collection, it must compute the base location plus offset for each iteration, because it cannot know when the string has moved. Then you have to think about heaps, stacks, threads, etc etc.

Rails DateTime.now without Time

If you're happy to require 'active_support/core_ext', then you can use

DateTime.now.midnight # => Sat, 19 Nov 2011 00:00:00 -0800

how do you view macro code in access?

In Access 2010, go to the Create tab on the ribbon. Click Macro. An "Action Catalog" panel should appear on the right side of the screen. Underneath, there's a section titled "In This Database." Clicking on one of the macro names should display its code.

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

How do I duplicate a line or selection within Visual Studio Code?

For Windows :

To Copy Up - shift+alt+up

To Copy Down - shift+alt+down

For mac :

To Copy Up - shift+option+up

To Copy Down - shift+option+down

For linux :

To Copy Up - ctrl+shift+alt+8

To Copy Down - ctrl+shift+alt+2

Note : You may change your keyboard shortcuts keybinding for visual studio code by pressing ctrl+shift+p, then type open keyboard shortcut in the pallet and then hit enter so new file will be opened (Key board shortcut file) you can see all the shortcuts over their and can change keybindings by clicking twice over the respective keybinding and then by entering your own keybinding, finally hit enter.

Hope this will help somebody!

How to convert a double to long without casting?

Simply by the following:

double d = 394.000;
long l = d * 1L;

PHP form send email to multiple recipients

If you need to add emails as CC or BCC, add the following part in the variable you use as for your header :

$headers .= "CC: [email protected]".PHP_EOL;
$headers .= "BCC: [email protected]".PHP_EOL;

Regards

What is "String args[]"? parameter in main method Java

in public static void main(String args[]) args is an array of console line argument whose data type is String. in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan"; arg[1]="Royal"; you can do this manually also inside the program, when you don't call them at the command line.

.htaccess not working on localhost with XAMPP

Just had a similar issue

Resolved it by checking in httpd.conf

     # AllowOverride controls what directives may be placed in .htaccess files.
     # It can be "All", "None", or any combination of the keywords:
     #   Options FileInfo AuthConfig Limit
     #
     AllowOverride All   <--- make sure this is not set to "None"

It is worth bearing in mind I tried (from Mark's answer) the "put garbage in the .htaccess" which did give a server error - but even though it was being read, it wasn't being acted on due to no overrides allowed.

Run chrome in fullscreen mode on Windows

You can also add --disable-session-crashed-bubble to eliminate the errors that come up after a crash or improper shutdown.

What is the difference between HAVING and WHERE in SQL?

When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.

However, when GROUP BY is used:

  • The WHERE clause is used to filter records from a result. The filtering occurs before any groupings are made.
  • The HAVING clause is used to filter values from a group (i.e., to check conditions after aggregation into groups has been performed).

Change location of log4j.properties

In Eclipse you can set a VM argument to:

-Dlog4j.configuration=file:///${workspace_loc:/MyProject/log4j-full-debug.properties}

Can I send a ctrl-C (SIGINT) to an application on Windows?

The closest that I've come to a solution is the SendSignal 3rd party app. The author lists source code and an executable. I've verified that it works under 64-bit windows (running as a 32-bit program, killing another 32-bit program), but I've not figured out how to embed the code into a windows program (either 32-bit or 64-bit).

How it works:

After much digging around in the debugger I discovered that the entry point that actually does the behavior associated with a signal like ctrl-break is kernel32!CtrlRoutine. The function had the same prototype as ThreadProc, so it can be used with CreateRemoteThread directly, without having to inject code. However, that's not an exported symbol! It's at different addresses (and even has different names) on different versions of Windows. What to do?

Here is the solution I finally came up with. I install a console ctrl handler for my app, then generate a ctrl-break signal for my app. When my handler gets called, I look back at the top of the stack to find out the parameters passed to kernel32!BaseThreadStart. I grab the first param, which is the desired start address of the thread, which is the address of kernel32!CtrlRoutine. Then I return from my handler, indicating that I have handled the signal and my app should not be terminated. Back in the main thread, I wait until the address of kernel32!CtrlRoutine has been retrieved. Once I've got it, I create a remote thread in the target process with the discovered start address. This causes the ctrl handlers in the target process to be evaluated as if ctrl-break had been pressed!

The nice thing is that only the target process is affected, and any process (even a windowed process) can be targeted. One downside is that my little app can't be used in a batch file, since it will kill it when it sends the ctrl-break event in order to discover the address of kernel32!CtrlRoutine.

(Precede it with start if running it in a batch file.)

Android: how to handle button click

To make things easier asp Question 2 stated, you can make use of lambda method like this to save variable memory and to avoid navigating up and down in your view class

//method 1
findViewById(R.id.buttonSend).setOnClickListener(v -> {
          // handle click
});

but if you wish to apply click event to your button at once in a method.

you can make use of Question 3 by @D. Tran answer. But do not forget to implement your view class with View.OnClickListener.

In other to use Question #3 properly

C# Creating and using Functions

static void Main(string[] args)
    {
        Console.WriteLine("geef een leeftijd");
        int a = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("geef een leeftijd");
        int b = Convert.ToInt32(Console.ReadLine());

        int einde = Sum(a, b);
        Console.WriteLine(einde);
    }
    static int Sum(int x, int y)
    {
        int result = x + y;
        return result;

How to Get Element By Class in JavaScript?

_x000D_
_x000D_
var elems = document.querySelectorAll('.one');_x000D_
_x000D_
for (var i = 0; i < elems.length; i++) {_x000D_
    elems[i].innerHTML = 'content';_x000D_
};
_x000D_
_x000D_
_x000D_

Trees in Twitter Bootstrap

Another great Treeview jquery plugin is http://www.jstree.com/

For an advance view you should check jquery-treetable
http://ludo.cubicphuse.nl/jquery-plugins/treeTable/doc/

How should I escape commas and speech marks in CSV files so they work in Excel?

Even after double quotes, I had this problem for a few days.

Replaced Pipe Delimiter with Comma, then things worked fine.

Inverse dictionary lookup in Python

Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:

key = next(key for key, value in dd.items() if value == 'value')

where dd is the dict. Will raise StopIteration if no match is found, so you might want to catch that and return a more appropriate exception like ValueError or KeyError.

PHP Error: Cannot use object of type stdClass as array (array and object issues)

If you're iterating over an object instead of an array, you'll need to access the properties using:

$id = $blog->id;
$title = $blog->title;
$content = $blog->content;

That, or change your object to an array.

php return 500 error but no error log

Here is another reason why errors might not be visible:

I had the same issue. In my case, I had copied the source from a production environment. Hence the ENVIRONMENT variable defined in index.php was set to 'production'. This caused error_reporting to be set to 0 (no logging). Just set it to 'development' and you should start seeing error messages in apache log.

Turned out the 500 was due to a semi colon missing in database config :-)

What are sessions? How do they work?

HTTP is stateless connection protocol, that is, the server cannot differentiate between different connections of different users.

Hence comes cookie, once a client connects first time to a server, the server generates a new session id, which later will be sent to the client as cookie value. And from now on, this session id will identify that client connection, because within each HTTP request it will see the appropriate session id inside cookies.

Now for each session id, the server keeps some data structure, which enables him to store data specific to user, this data structure you can abstractly call session.

How to create a toggle button in Bootstrap

If you don't mind changing your HTML, you can use the data-toggle attribute on <button>s. See the Single toggle section of the button examples:

<button type="button" class="btn btn-primary" data-toggle="button">
    Single toggle
</button>

Easiest way to detect Internet connection on iOS?

Replacement for Apple's Reachability re-written in Swift with closures, inspired by tonymillion: https://github.com/ashleymills/Reachability.swift

  1. Drop the file Reachability.swift into your project. Alternatively, use CocoaPods or Carthage - See the Installation section of the project's README.

  2. Get notifications about network connectivity:

    //declare this property where it won't go out of scope relative to your listener
    let reachability = Reachability()!
    
    reachability.whenReachable = { reachability in
        if reachability.isReachableViaWiFi {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    }
    
    reachability.whenUnreachable = { _ in
        print("Not reachable")
    }
    
    do {
        try reachability.startNotifier()
    } catch {
        print("Unable to start notifier")
    }
    

    and for stopping notifications

    reachability.stopNotifier()
    

Defining a HTML template to append using JQuery

In order to solve this problem, I recognize two solutions:

  • The first one goes with AJAX, with which you'll have to load the template from another file and just add everytime you want with .clone().

    $.get('url/to/template', function(data) {
        temp = data
        $('.search').keyup(function() {
            $('.list-items').html(null);
    
            $.each(items, function(index) {
                 $(this).append(temp.clone())
            });
    
        });
    });
    

    Take into account that the event should be added once the ajax has completed to be sure the data is available!

  • The second one would be to directly add it anywhere in the original html, select it and hide it in jQuery:

    temp = $('.list_group_item').hide()
    

    You can after add a new instance of the template with

    $('.search').keyup(function() {
        $('.list-items').html(null);
    
        $.each(items, function(index) {
            $(this).append(temp.clone())
        });
    });
    
  • Same as the previous one, but if you don't want the template to remain there, but just in the javascript, I think you can use (have not tested it!) .detach() instead of hide.

    temp = $('.list_group_item').detach()
    

    .detach() removes elements from the DOM while keeping the data and events alive (.remove() does not!).

SQL UPDATE all values in a field with appended string CONCAT not working

UPDATE 
    myTable
SET 
    col = CONCAT( col , "string" )

Could not work it out. The request syntax was correct, but "0 line affected" when executed.

The solution was :

UPDATE 
    myTable 
SET 
    col = CONCAT( myTable.col , "string" )

That one worked.

How can I get the MAC and the IP address of a connected client in PHP?

You can get MAC Address or Physical Address using this code

$d = explode('Physical Address. . . . . . . . .',shell_exec ("ipconfig/all"));  
$d1 = explode(':',$d[1]);  
$d2 = explode(' ',$d1[1]);  
return $d2[1];

I used explode many time because shell_exec ("ipconfig/all") return complete detail of all network. so you have to split one by one. when you run this code then you will get
your MAC Address 00-##-##-CV-12 //this is fake address for show only.

Can Python test the membership of multiple values in a list?

[x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]

The reason I think this is better than the chosen answer is that you really don't need to call the 'all()' function. Empty list evaluates to False in IF statements, non-empty list evaluates to True.

if [x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]:
    ...Do something...

Example:

>>> [x for x in ['a','b'] if x in ['b', 'a', 'foo', 'bar']]
['a', 'b']
>>> [x for x in ['G','F'] if x in ['b', 'a', 'foo', 'bar']]
[]

ArrayList of int array in java

First of all, for initializing a container you cannot use a primitive type (i.e. int; you can use int[] but as you want just an array of integers, I see no use in that). Instead, you should use Integer, as follows:

ArrayList<Integer> arl = new ArrayList<Integer>();

For adding elements, just use the add function:

arl.add(1);  
arl.add(22);
arl.add(-2);

Last, but not least, for printing the ArrayList you may use the build-in functionality of toString():

System.out.println("Arraylist contains: " + arl.toString());  

If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :

int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));

I suggest reading first on Java Containers, before starting to work with them.

How to initialize a List<T> to a given size (as opposed to capacity)?

Why are you using a List if you want to initialize it with a fixed value ? I can understand that -for the sake of performance- you want to give it an initial capacity, but isn't one of the advantages of a list over a regular array that it can grow when needed ?

When you do this:

List<int> = new List<int>(100);

You create a list whose capacity is 100 integers. This means that your List won't need to 'grow' until you add the 101th item. The underlying array of the list will be initialized with a length of 100.

How do I echo and send console output to a file in a bat script?

I like atn's answer, but it was not as trivial for me to download as wintee, which is also open source and only gives the tee functionality (useful if you just want tee and not the entire set of unix utilities). I learned about this from davor's answer to Displaying Windows command prompt output and redirecting it to a file, where you also find reference to the unix utilities.

Drop multiple tables in one shot in MySQL

declare @sql1 nvarchar(max) 
SELECT @sql1 =
  STUFF(
         (
           select ' drop table dbo.[' + name + ']'

           FROM sys.sysobjects AS sobjects
           WHERE (xtype = 'U') AND (name LIKE 'GROUP_BASE_NEW_WORK_%')
           for xml path('')
        ),
     1, 1, '')

  execute sp_executesql @sql1

Display milliseconds in Excel

I've discovered in Excel 2007, if the results are a Table from an embedded query, the ss.000 does not work. I can paste the query results (from SQL Server Management Studio), and format the time just fine. But when I embed the query as a Data Connection in Excel, the format always gives .000 as the milliseconds.

jQuery each loop in table row

In jQuery just use:

$('#tblOne > tbody  > tr').each(function() {...code...});

Using the children selector (>) you will walk over all the children (and not all descendents), example with three rows:

$('table > tbody  > tr').each(function(index, tr) { 
   console.log(index);
   console.log(tr);
});

Result:

0
<tr>
1 
<tr>
2
<tr>

In VanillaJS you can use document.querySelectorAll() and walk over the rows using forEach()

[].forEach.call(document.querySelectorAll('#tblOne > tbody  > tr'), function(index, tr) {
    /* console.log(index); */
    /* console.log(tr); */
});

How to remove the first and the last character of a string

if you need to remove the first leter of string

string.slice(1, 0)

and for remove last letter

string.slice(0, -1)

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

Javascript Object push() function

push() is for arrays, not objects, so use the right data structure.

var data = [];
// ...
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
// ...
var tempData = [];
for ( var index=0; index<data.length; index++ ) {
    if ( data[index].Status == "Valid" ) {
        tempData.push( data );
    }
}
data = tempData;

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

How can I replace every occurrence of a String in a file with PowerShell?

This is what I use, but it is slow on large text files.

get-content $pathToFile | % { $_ -replace $stringToReplace, $replaceWith } | set-content $pathToFile

If you are going to be replacing strings in large text files and speed is a concern, look into using System.IO.StreamReader and System.IO.StreamWriter.

try
{
   $reader = [System.IO.StreamReader] $pathToFile
   $data = $reader.ReadToEnd()
   $reader.close()
}
finally
{
   if ($reader -ne $null)
   {
       $reader.dispose()
   }
}

$data = $data -replace $stringToReplace, $replaceWith

try
{
   $writer = [System.IO.StreamWriter] $pathToFile
   $writer.write($data)
   $writer.close()
}
finally
{
   if ($writer -ne $null)
   {
       $writer.dispose()
   }
}

(The code above has not been tested.)

There is probably a more elegant way to use StreamReader and StreamWriter for replacing text in a document, but that should give you a good starting point.

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

If, like me, you need to target v4 but can only build with .net 3.5, follow the instruction here. Just replace in your web.config the whole content of the <configSections> with:

<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
  <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
    <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions,  Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
      <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
      <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
      <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    </sectionGroup>
  </sectionGroup>
</sectionGroup>

JFrame.dispose() vs System.exit()

JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.

If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:

Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()

Find common substring between two strings

For completeness, difflib in the standard-library provides loads of sequence-comparison utilities. For instance find_longest_match which finds the longest common substring when used on strings. Example use:

from difflib import SequenceMatcher

string1 = "apple pie available"
string2 = "come have some apple pies"

match = SequenceMatcher(None, string1, string2).find_longest_match(0, len(string1), 0, len(string2))

print(match)  # -> Match(a=0, b=15, size=9)
print(string1[match.a: match.a + match.size])  # -> apple pie
print(string2[match.b: match.b + match.size])  # -> apple pie

Google maps Places API V3 autocomplete - select first option on enter

Here is an example of a real, non-hacky, solution. It doesn't use any browser hacks etc, just methods from the public API provided by Google and documented here: Google Maps API

The only downside is that additional requests to Google are required if the user doesn't select an item from the list. The upside is that the result will always be correct as the query is performed identically to the query inside the AutoComplete. Second upside is that by only using public API methods and not relying on the internal HTML structure of the AutoComplete widget, we can be sure that our product won't break if Google makes changes.

var input = /** @type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);  
// These are my options for the AutoComplete
autocomplete.setTypes(['(cities)']);
autocomplete.setComponentRestrictions({'country': 'es'});

google.maps.event.addListener(autocomplete, 'place_changed', function() {
    result = autocomplete.getPlace();
    if(typeof result.address_components == 'undefined') {
        // The user pressed enter in the input 
        // without selecting a result from the list
        // Let's get the list from the Google API so that
        // we can retrieve the details about the first result
        // and use it (just as if the user had actually selected it)
        autocompleteService = new google.maps.places.AutocompleteService();
        autocompleteService.getPlacePredictions(
            {
                'input': result.name,
                'offset': result.name.length,
                // I repeat the options for my AutoComplete here to get
                // the same results from this query as I got in the 
                // AutoComplete widget
                'componentRestrictions': {'country': 'es'},
                'types': ['(cities)']
            },
            function listentoresult(list, status) {
                if(list == null || list.length == 0) {
                    // There are no suggestions available.
                    // The user saw an empty list and hit enter.
                    console.log("No results");
                } else {
                    // Here's the first result that the user saw
                    // in the list. We can use it and it'll be just
                    // as if the user actually selected it
                    // themselves. But first we need to get its details
                    // to receive the result on the same format as we
                    // do in the AutoComplete.
                    placesService = new google.maps.places.PlacesService(document.getElementById('placesAttribution'));
                    placesService.getDetails(
                        {'reference': list[0].reference},
                        function detailsresult(detailsResult, placesServiceStatus) {
                            // Here's the first result in the AutoComplete with the exact
                            // same data format as you get from the AutoComplete.
                            console.log("We selected the first item from the list automatically because the user didn't select anything");
                            console.log(detailsResult);
                        }
                    );
                }
            }
        );
    } else {
        // The user selected a result from the list, we can 
        // proceed and use it right away
        console.log("User selected an item from the list");
        console.log(result);
    }
});

Visual Studio 2010 shortcut to find classes and methods?

Try Alt+F12 in Visual Studio 2010.

It opens up the Find Symbol dialogue which allows you to search for methods, classes, etc.

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

Using ls to list directories and their total sizes

This is one I like

update: I didnt like the previous one because it didn't show files in the current directory, it only listed directories.

Example output for /var on ubuntu:

sudo du -hDaxd1 /var | sort -h | tail -n10

4.0K    /var/lock
4.0K    /var/run
4.0K    /var/www
12K     /var/spool
3.7M    /var/backups
33M     /var/log
45M     /var/webmin
231M    /var/cache
1.4G    /var/lib
1.7G    /var

Unsupported major.minor version 52.0

If you have a problem in Android Studio and you have installed Android N, change the Android rendering version with an older one and the problem will disappear.

Enter image description here

Make div 100% Width of Browser Window

If width:100% works in any cases, just use that, otherwise you can use vw in this case which is relative to 1% of the width of the viewport.

That means if you want to cover off the width, just use 100vw.

Look at the image I draw for you here:

enter image description here

Try the snippet I created for you as below:

_x000D_
_x000D_
.full-width {_x000D_
  width: 100vw;_x000D_
  height: 100px;_x000D_
  margin-bottom: 40px;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.one-vw-width {_x000D_
  width: 1vw;_x000D_
  height: 100px;_x000D_
  background-color: red;_x000D_
}
_x000D_
<div class="full-width"></div>_x000D_
<div class="one-vw-width"></div>
_x000D_
_x000D_
_x000D_

How can I show line numbers in Eclipse?

click on window tab and click on preferences

click on window tab

do this and check show line number

check show line number

jQuery UI dialog box not positioned center screen

Digging up an old grave here but for new Google searchers.

You can maintain the position of the model window when the users scrolls by adding this event to your dialog. This will change it from absolutely positioned to fixed. No need to monitor scrolling events.

open: function(event, ui) {
    $(this).parent().css('position', 'fixed');
}

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

1.create a lib folder in your project file,

2.copy your jarFiles to the lib folder

3.right click on to your jarFile go to build path>Add to build path (now your jar file is part of your refrerenced libraries )

4.open command prompt and navigate to your project directory and write

mvn install: install-file "-Dfile=<yourJarFileName>.jar" "-DgroupId=<yourGroupID>" "-DartifactId=<yourArtifactId>" "-Dversion=<yourVersion>" "-Dpackaging=jar" 

6.Rebuild your local repository index by opening in eclipse- go to window>show view>other>maven>maven Repositories. Right click on local Repositores and hit "RebuildIndex"

5.open your pom.xml file and add your dependency

    <dependency>
        <groupId><yourGroupID></groupId>
        <artifactId><yourArtifactId></artifactId>
        <version><yourVersion></version>
    </dependency>

and run

mvn clean
mvn compile 
mvn test