Programs & Examples On #Code security

Find a line in a file and remove it

Old question, but an easy way is to:

  • Iterate through file, adding each line to an new array list
  • iterate through the array, find matching String, then call the remove method.
  • iterate through array again, printing each line to the file, boolean for append should be false, which basically replaces the file

How to check if an object is an array?

easiest and fastest way to check if an Object is an Array or not.

 var arr = [];
  arr.constructor.name ==='Array'  //return true;

or

arr.constructor ===Array //return true;

or you can make a utility function:

const isArray = (obj)=> !!obj && obj.constructor ===Array;

usage:

isArray(arr); //return true

Are there any style options for the HTML5 Date picker?

I used a combination of the above solutions and some trial and error to come to this solution. Took me an annoying amount of time so I hope this can help someone else in the future. I also noticed that the date picker input is not at all supported by Safari...

I am using styled-components to render a transparent date picker input as shown in the image below:

image of date picker input

const StyledInput = styled.input`
  appearance: none;
  box-sizing: border-box;
  border: 1px solid black;
  background: transparent;
  font-size: 1.5rem;
  padding: 8px;
  ::-webkit-datetime-edit-text { padding: 0 2rem; }
  ::-webkit-datetime-edit-month-field { text-transform: uppercase; }
  ::-webkit-datetime-edit-day-field { text-transform: uppercase; }
  ::-webkit-datetime-edit-year-field { text-transform: uppercase; }
  ::-webkit-inner-spin-button { display: none; }
  ::-webkit-calendar-picker-indicator { background: transparent;}
`

How can I disable editing cells in a WPF Datagrid?

The DataGrid has an XAML property IsReadOnly that you can set to true:

<my:DataGrid
    IsReadOnly="True"
/>

Datatables on-the-fly resizing

You should try this one.

var table = $('#example').DataTable();
table.columns.adjust().draw();

Link: column adjust in datatable

Remove item from list based on condition

If your collection type is a List<stuff>, then the best approach is probably the following:

prods.RemoveAll(s => s.ID == 1)

This only does one pass (iteration) over the list, so should be more efficient than other methods.

If your type is more generically an ICollection<T>, it might help to write a short extension method if you care about performance. If not, then you'd probably get away with using LINQ (calling Where or Single).

Is it possible to set a custom font for entire of application?

I would also like to improve weston's answer for API 21 Android 5.0.

I had the same issue on my Samsung s5, when using DEFAULT font. (with the others fonts it's working fine)

I managed to make it working by setting the typeface ("sans" for example) in XML files, for each Textview or Button

<TextView
android:layout_width="match_parent"
android:layout_height="39dp"
android:textColor="@color/abs__background_holo_light"
android:textSize="12sp"
android:gravity="bottom|center"
android:typeface="sans" />

and in MyApplication Class :

public class MyApplication extends Application {
    @Override
    public void onCreate() {
    TypefaceUtil.overrideFont(getApplicationContext(), "SANS_SERIF",
    "fonts/my_font.ttf");
    }
}

Hope it helps.

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag

The rules for turning on the carry flag in binary/integer math are two:

  1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

  2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

    • 0111 + 0001 = 1000 (carry flag is turned off [zero])
    • 1000 - 0001 = 0111 (carry flag is turned off [zero])

In unsigned arithmetic, watch the carry flag to detect errors.

In signed arithmetic, the carry flag tells you nothing interesting.

Overflow Flag

The rules for turning on the overflow flag in binary/integer math are two:

  1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

  2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

Otherwise the "overflow" flag is turned off

  • 0100 + 0001 = 0101 (overflow flag is turned off)
  • 0110 + 1001 = 1111 (overflow flag turned off)
  • 1000 + 0001 = 1001 (overflow flag turned off)
  • 1100 + 1100 = 1000 (overflow flag is turned off)

Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

Spring MVC: Complex object as GET @RequestParam

Accepted answer works like a charm but if the object has a list of objects it won't work as expected so here is my solution after some digging.

Following this thread advice, here is how I've done.

  • Frontend: stringify your object than encode it in base64 for submission.
  • Backend: decode base64 string then convert the string json into desired object.

It isn't the best for debugging your API with postman but it is working as expected for me.

Original object: { page: 1, size: 5, filters: [{ field: "id", value: 1, comparison: "EQ" }

Encoded object: eyJwYWdlIjoxLCJzaXplIjo1LCJmaWx0ZXJzIjpbeyJmaWVsZCI6ImlkUGFyZW50IiwiY29tcGFyaXNvbiI6Ik5VTEwifV19

@GetMapping
fun list(@RequestParam search: String?): ResponseEntity<ListDTO> {
    val filter: SearchFilterDTO = decodeSearchFieldDTO(search)
    ...
}

private fun decodeSearchFieldDTO(search: String?): SearchFilterDTO {
    if (search.isNullOrEmpty()) return SearchFilterDTO()
    return Gson().fromJson(String(Base64.getDecoder().decode(search)), SearchFilterDTO::class.java)
}

And here the SearchFilterDTO and FilterDTO

class SearchFilterDTO(
    var currentPage: Int = 1,
    var pageSize: Int = 10,
    var sort: Sort? = null,
    var column: String? = null,
    var filters: List<FilterDTO> = ArrayList<FilterDTO>(),
    var paged: Boolean = true
)

class FilterDTO(
    var field: String,
    var value: Any,
    var comparison: Comparison
)

How can I use a batch file to write to a text file?

  • You can use copy con to write a long text
  • Example:

    C:\COPY CON [drive:][path][File name]

    .... Content

    F6

    1 file(s) is copied

Could not find server 'server name' in sys.servers. SQL Server 2014

I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in sys.servers still had the old server name.

I had to drop the old server name and add the new server name to sys.servers on the new server

sp_dropserver 'Server_A'
GO
sp_addserver  'Server',local
GO

SQL Server - SELECT FROM stored procedure

use OPENQUERY and befor Execute set 'SET FMTONLY OFF; SET NOCOUNT ON;'

Try this sample code:

SELECT top(1)*
FROM
OPENQUERY( [Server], 'SET FMTONLY OFF; SET NOCOUNT ON; EXECUTE  [database].[dbo].[storedprocedure]  value,value ')

How do I convert certain columns of a data frame to become factors?

Given the following sample

myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)  

then

myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)

or you could select your columns altogether and wrap it up nicely:

# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))

levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")

To obtain

> myData
      A   B Pulse
1  long 1kg    20
2 short 2kg    21
3  long 3kg    22
4 short 1kg    23
5  long 2kg    24
6 short 3kg    25

Timeout function if it takes too long to finish

The process for timing out an operations is described in the documentation for signal.

The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.

Note that this will only work on UNIX.

Here's an implementation that creates a decorator (save the following code as timeout.py).

from functools import wraps
import errno
import os
import signal

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

This creates a decorator called @timeout that can be applied to any long running functions.

So, in your application code, you can use the decorator like so:

from timeout import timeout

# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
    ...

# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
    ...

# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
    ...

ListView with OnItemClickListener

1) Check if you are using OnItemClickListener or OnClickListener (which is not supported for ListView)
Documentation Android Developers ListView

2) Check if you added Listener to your ListView properly. It's hooked on ListView not on ListAdapter!

ListView.setOnItemClickListener(listener);

3) If you need to use OnClickListener, check if you do use DialogInterface.OnClickListener or View.OnClickListener (they can be easily exchanged if not validated or if using both of them)

Getting multiple selected checkbox values in a string in javascript and PHP

This code work fine for me, Here i contvert array to string with ~ sign

    <input type="checkbox" value="created" name="today_check"><strong>&nbsp;Created&nbsp;&nbsp;</strong>
    <input type="checkbox" value="modified" name="today_check"><strong>&nbsp;Modified&nbsp;</strong>    
 <a class="get_tody_btn">Submit</a>

<script type="text/javascript">
        $('.get_tody_btn').click(function(){
            var ck_string = "";
            $.each($("input[name='today_check']:checked"), function(){  
                ck_string += "~"+$(this).val();  
            });
            if (ck_string ){
                ck_string = ck_string .substring(1);
            }else{
                alert('Please choose atleast one value.');
            }


        });
    </script>

Finding the last index of an array

LINQ provides Last():

csharp> int[] nums = {1,2,3,4,5};
csharp> nums.Last();              
5

This is handy when you don't want to make a variable unnecessarily.

string lastName = "Abraham Lincoln".Split().Last();

No module named Image

You can this query:

pip install image 

I had pillow installed, and still, I got the error that you mentioned. But after I executed the above command, the error vanished. And My program worked perfectly.

How do I get the picture size with PIL?

Followings gives dimensions as well as channels:

import numpy as np
from PIL import Image

with Image.open(filepath) as img:
    shape = np.array(img).shape

How can I use JavaScript in Java?

Java includes a scripting language extension package starting with version 6.

See the Rhino project documentation for embedding a JavaScript interpreter in Java.

[Edit]

Here is a small example of how you can expose Java objects to your interpreted script:

public class JS {
  public static void main(String args[]) throws Exception {
    ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
    Bindings bindings = js.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("stdout", System.out);
    js.eval("stdout.println(Math.cos(Math.PI));");
    // Prints "-1.0" to the standard output stream.
  }
}

Cannot use Server.MapPath

Firt add a reference to System.web, if you don't have. Do that in the References folder.

You can then use Hosting.HostingEnvironment.MapPath(path);

What is the difference between And and AndAlso in VB.NET?

In addition to the answers above, AndAlso provides a conditioning process known as short circuiting. Many programming languages have this functionality built in like vb.net does, and can provide substantial performance increases in long condition statements by cutting out evaluations that are unneccessary.

Another similar condition is the OrElse condition which would only check the right condition if the left condition is false, thus cutting out unneccessary condition checks after a true condition is found.

I would advise you to always use short circuiting processes and structure your conditional statements in ways that can benefit the most by this. For example, test your most efficient and fastest conditions first so that you only run your long conditions when you absolutely have to and short circuit the other times.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

You need to decode data from input string into unicode, before using it, to avoid encoding problems.

field.text = data.decode("utf8")

Laravel 5.4 create model, controller and migration in single artisan command

You can do it with the following command:

php artisan make:model post -mcr

Brief :

-m, to create migration

-c to create controller

-r to specify the controller has resource

Creating a div element inside a div element in javascript

'b' should be in capital letter in document.getElementById modified code jsfiddle

function test()
{

var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
 //document.body.appendChild(element);
 }

How to get query parameters from URL in Angular 5?

Query and Path Params (Angular 8)

For url like https://myapp.com/user/666/read?age=23 use

import { combineLatest } from 'rxjs';
// ...

combineLatest( [this.route.paramMap, this.route.queryParamMap] )
  .subscribe( ([pathParams, queryParams]) => {
    let userId = pathParams.get('userId');    // =666
    let age    = queryParams.get('age');      // =23
    // ...
  })

UPDATE

In case when you use this.router.navigate([someUrl]); and your query parameters are embedded in someUrl string then angular encodes a URL and you get something like this https://myapp.com/user/666/read%3Fage%323 - and above solution will give wrong result (queryParams will be empty, and path params can be glued to last path param if it is on the path end). In this case change the way of navigation to this

this.router.navigateByUrl(someUrl);

Jump to function definition in vim

TL;DR:

Modern way is to use COC for intellisense-like completion and one or more language servers (LS) for jump-to-definition (and way way more). For even more functionality (but it's not needed for jump-to-definition) you can install one or more debuggers and get a full blown IDE experience.

Quick-start:

  1. install vim-plug to manage your VIM plug-ins
  2. add COC and (optionally) Vimspector at the top of ~/.vimrc:
    call plug#begin()
    Plug 'neoclide/coc.nvim', {'branch': 'release'}
    Plug 'puremourning/vimspector'
    call plug#end()
    
    " key mappings example
    nmap <silent> gd <Plug>(coc-definition)
    nmap <silent> gD <Plug>(coc-implementation)
    nmap <silent> gr <Plug>(coc-references)
    " there's way more, see `:help coc-key-mappings@en'
    
  3. call :source $MYVIMRC | PlugInstall to reload VIM config and download plug-ins
  4. restart vim and call :CocInstall coc-marketplace to get easy access to COC extensions
  5. call :CocList marketplace and search for language servers, e.g.:
  • type python to find coc-jedi,
  • type php to find coc-phpls, etc.
  1. (optionally) see install_gadget.py --help for available debuggers, e.g.:
  • ./install_gadget.py --enable-python,
  • ./install_gadget.py --force-enable-php, etc.

You can jump to definition with gd, to interface implementation with gD, find all references with gr. More keybindings in :help coc-key-mappings@en.

Full answer:

Language server (LS) is a separate standalone application (one for each programming language) that runs in the background and analyses your whole project in real time exposing extra capabilities to your editor (any editor, not only vim). You get things like:

  • namespace aware tag completion
  • jump to definition
  • jump to next / previous error
  • find all references to an object
  • find all interface implementations
  • rename across a whole project
  • documentation on hover
  • snippets, code actions, formatting, linting and more...

Communication with language servers takes place via Language Server Protocol (LSP). Both nvim and vim8 (or higher) support LSP through plug-ins, the most popular being Conquer of Completion (COC).

List of actively developed language servers and their capabilities is available on Lang Server website. Not all of those are provided by COC extensions. If you want to use one of those you can either write a COC extension yourself or install LS manually and use the combo of following VIM plug-ins as alternative to COC:

Communication with debuggers takes place via Debug Adapter Protocol (DAP). The most popular DAP plug-in for VIM is Vimspector.

Language Server Protocol (LSP) was created by Microsoft for Visual Studio Code and released as an open source project with a permissive MIT license (standardized by collaboration with Red Hat and Codenvy). Later on Microsoft released Debug Adapter Protocol (DAP) as well. Any language supported by VSCode is supported in VIM.

I personally recommend using COC + language servers provided by COC extensions + ALE for extra linting (but with LSP support disabled to avoid conflicts with COC) + Vimspector + debuggers provided by Vimspector (called "gadgets") + following VIM plug-ins:

call plug#begin()
Plug 'neoclide/coc.nvim'
Plug 'dense-analysis/ale'
Plug 'puremourning/vimspector'
Plug 'scrooloose/nerdtree'
Plug 'scrooloose/nerdcommenter'
Plug 'sheerun/vim-polyglot'
Plug 'yggdroot/indentline'
Plug 'tpope/vim-surround'
Plug 'kana/vim-textobj-user'
  \| Plug 'glts/vim-textobj-comment'
Plug 'janko/vim-test'
Plug 'vim-scripts/vcscommand.vim'
Plug 'mhinz/vim-signify'
call plug#end()

You can google each to see what they do.

Also, pipe character | separates VIM commands put in one line which makes it perfect to set up plug-in dependencies, i.e. vim-textobj-comment doesn't work without vim-textobj-user so if installation of vim-textobj-user fails the rest of the line isn't executed. Here pipe is escaped with backslash \ because it's in a new line but for VIM it's still a one-liner.

How to select specific form element in jQuery?

I know the question is about setting a input but just in case if you want to set a combobox then (I search net for it and didn't find anything and this place seems a right place to guide others)

If you had a form with ID attribute set (e.g. frm1) and you wanted to set a specific specific combobox, with no ID set but name attribute set (e.g. district); then use

_x000D_
_x000D_
$("#frm1 select[name='district'] option[value='NWFP']").attr('selected', true);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <form id="frm1">_x000D_
        <select name="district">_x000D_
            <option value="" disabled="" selected="" hidden="">Area ...</option>_x000D_
            <option value="NWFP">NWFP</option>_x000D_
            <option value="FATA">FATA</option>_x000D_
        </select>_x000D_
    </form>
_x000D_
_x000D_
_x000D_

MySQL/Writing file error (Errcode 28)

I had this same error and the problem was simply not enough space on my virtual machine. I deleted some unnecessary files and it started working again.

my memory/disk space allocation looked something like this

df -h
Filesystem               Size  Used Avail Use% Mounted on
/dev/mapper/centos-root   37G   37G  127M 100% /
...

Reset CSS display property to default value

A browser's default styles are defined in its user agent stylesheet, the sources of which you can find here. Unfortunately, the Cascading and Inheritance level 3 spec does not appear to propose a way to reset a style property to its browser default. However there are plans to reintroduce a keyword for this in Cascading and Inheritance level 4 — the working group simply hasn't settled on a name for this keyword yet (the link currently says revert, but it is not final). Information about browser support for revert can be found on caniuse.com.

While the level 3 spec does introduce an initial keyword, setting a property to its initial value resets it to its default value as defined by CSS, not as defined by the browser. The initial value of display is inline; this is specified here. The initial keyword refers to that value, not the browser default. The spec itself makes this note under the all property:

For example, if an author specifies all: initial on an element it will block all inheritance and reset all properties, as if no rules appeared in the author, user, or user-agent levels of the cascade.

This can be useful for the root element of a "widget" included in a page, which does not wish to inherit the styles of the outer page. Note, however, that any "default" style applied to that element (such as, e.g. display: block from the UA style sheet on block elements such as <div>) will also be blown away.

So I guess the only way right now using pure CSS is to look up the browser default value and set it manually to that:

div.foo { display: inline-block; }
div.foo.bar { display: block; }

(An alternative to the above would be div.foo:not(.bar) { display: inline-block; }, but that involves modifying the original selector rather than an override.)

Getting Image from API in Angular 4/5+?

You should set responseType: ResponseContentType.Blob in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.

Here is an working example:

Create image.service.ts and put following code:

Angular 4:

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

Angular 5+:

getImage(imageUrl: string): Observable<Blob> {
  return this.httpClient.get(imageUrl, { responseType: 'blob' });
}

Important: Since Angular 5+ you should use the new HttpClient.

The new HttpClient returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'. Read more about that here.

Now you need to create some function in your image.component.ts to get image and show it in html.

For creating an image from Blob you need to use JavaScript's FileReader. Here is function which creates new FileReader and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:

imageToShow: any;

createImageFromBlob(image: Blob) {
   let reader = new FileReader();
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result;
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

Now you should use your created ImageService to get image from api. You should to subscribe to data and give this data to createImageFromBlob-function. Here is an example function:

getImageFromService() {
      this.isImageLoading = true;
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      }, error => {
        this.isImageLoading = false;
        console.log(error);
      });
}

Now you can use your imageToShow-variable in HTML template like this:

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

I hope this description is clear to understand and you can use it in your project.

See the working example for Angular 5+ here.

C++ equivalent of java's instanceof

dynamic_cast is known to be inefficient. It traverses up the inheritance hierarchy, and it is the only solution if you have multiple levels of inheritance, and need to check if an object is an instance of any one of the types in its type hierarchy.

But if a more limited form of instanceof that only checks if an object is exactly the type you specify, suffices for your needs, the function below would be a lot more efficient:

template<typename T, typename K>
inline bool isType(const K &k) {
    return typeid(T).hash_code() == typeid(k).hash_code();
}

Here's an example of how you'd invoke the function above:

DerivedA k;
Base *p = &k;

cout << boolalpha << isType<DerivedA>(*p) << endl;  // true
cout << boolalpha << isType<DerivedB>(*p) << endl;  // false

You'd specify template type A (as the type you're checking for), and pass in the object you want to test as the argument (from which template type K would be inferred).

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Try

ALLOWED_HOSTS = ['*']

Less secure if you're not firewalled off or on a public LAN, but it's what I use and it works.

EDIT: Interestingly enough I've been needing to add this to a few of my 1.8 projects even when DEBUG = True. Very unsure why.

EDIT: This is due to a Django security update as mentioned in my comment.

Convert JSONObject to Map

use Jackson (https://github.com/FasterXML/jackson) from http://json.org/

HashMap<String,Object> result =
       new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);

pip3: command not found

You would need to install pip3.

On Linux, the command would be: sudo apt install python3-pip

On Mac, using brew, first brew install python3
Then brew postinstall python3

Try calling pip3 -V to see if it worked.

What do *args and **kwargs mean?

Notice the cool thing in S.Lott's comment - you can also call functions with *mylist and **mydict to unpack positional and keyword arguments:

def foo(a, b, c, d):
  print a, b, c, d

l = [0, 1]
d = {"d":3, "c":2}

foo(*l, **d)

Will print: 0 1 2 3

MVC4 input field placeholder

The correct solution to get the Prompt value in a non-templated control context is:

@Html.TextBoxFor(model => model.Email, 
    new { placeholder = ModelMetadata.FromLambdaExpression(m => m.Email, ViewData).Watermark }
)

This will also not double-escape the watermark text.

Android emulator doesn't take keyboard input - SDK tools rev 20

I have used an emulator for API Level 23, which does not take keyboard input for installed apk. So I have created new emulator for API Level 29, and then it works. Following is the step to install new emulator.

  1. Open "Android Virtual Device Manager"
  2. Create new Virtual Device.
  3. When you select a system image, please choose and download the last version(API Level29) on "Virtual Device Configuration" window

How to get a json string from url?

AFAIK JSON.Net does not provide functionality for reading from a URL. So you need to do this in two steps:

using (var webClient = new System.Net.WebClient()) {
    var json = webClient.DownloadString(URL);
    // Now parse with JSON.Net
}

How do I find the version of Apache running without access to the command line?

Warning, some Apache servers do not always send their version number when using HEAD, like in this case:

HTTP/1.1 200 OK
Date: Fri, 03 Oct 2008 13:09:45 GMT
Server: Apache
X-Powered-By: PHP/5.2.6RC4-pl0-gentoo
Set-Cookie: PHPSESSID=a97a60f86539b5502ad1109f6759585c; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Connection: close
Content-Type: text/html



Connection to host lost.

If PHP is installed then indeed, just use the php info command:

<?php phpinfo(); ?>

How to return a value from try, catch, and finally?

Here is another example that return's a boolean value using try/catch.

private boolean doSomeThing(int index){
    try {
        if(index%2==0) 
            return true; 
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
    }finally {
        System.out.println("Finally!!! ;) ");
    }
    return false; 
}

ng-change not working on a text input

Maybe you can try something like this:

Using a directive

directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

So here is a simple example of how to use classes: Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:

class bankaccount():
    def __init__(self, name, money):
        self.name = name
        self.money = money

    def earn_money(self, amount):
        self.money += amount

    def withdraw_money(self, amount):
        self.money -= amount

    def show_balance(self):
        print self.money

Now you have an abstract model of a simple account and its mechanism. The def __init__(self, name, money) is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:

spidermans_account = bankaccount("SpiderMan", 1000)

If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw method on his account:

spidermans_account.withdraw_money(100)

If he wants to see the balance he calls:

spidermans_account.show_balance()

The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

increase legend font size ggplot2

You can use theme_get() to display the possible options for theme. You can control the legend font size using:

+ theme(legend.text=element_text(size=X))

replacing X with the desired size.

Is it safe to delete a NULL pointer?

It is safe unless you overloaded the delete operator. if you overloaded the delete operator and not handling null condition then it is not safe at all.

VarBinary vs Image SQL Server Data Type to Store Binary Data?

Since image is deprecated, you should use varbinary.

per Microsoft (thanks for the link @Christopher)

ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.

Why doesn't java.util.Set have get(int index)?

If you are going to do lots of random accesses by index in a set, you can get an array view of its elements:

Object[] arrayView = mySet.toArray();
//do whatever you need with arrayView[i]

There are two main drawbacks though:

  1. It's not memory efficient, as an array for the whole set needs to be created.
  2. If the set is modified, the view becomes obsolete.

Creating Scheduled Tasks

You can use Task Scheduler Managed Wrapper:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch Notepad whenever the trigger fires
         td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }
}

Alternatively you can use native API or go for Quartz.NET. See this for details.

Django DateField default options

Your mistake is using the datetime module instead of the date module. You meant to do this:

from datetime import date
date = models.DateField(_("Date"), default=date.today)

If you only want to capture the current date the proper way to handle this is to use the auto_now_add parameter:

date = models.DateField(_("Date"), auto_now_add=True)

However, the modelfield docs clearly state that auto_now_add and auto_now will always use the current date and are not a default value that you can override.

Email & Phone Validation in Swift

Using Swift 3

 func validate(value: String) -> Bool {
    let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
    let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
    let result =  phoneTest.evaluate(with: value)
    return result
}

how to prevent "directory already exists error" in a makefile when using mkdir

Inside your makefile:

target:
    if test -d dir; then echo "hello world!"; else mkdir dir; fi

Difference between hamiltonian path and euler path

They are related but are neither dependent nor mutually exclusive. If a graph has an Eurler cycle, it may or may not also have a Hamiltonian cyle and vice versa.


Euler cycles visit every edge in the graph exactly once. If there are vertices in the graph with more than two edges, then by definition, the cycle will pass through those vertices more than once. As a result, vertices can be repeated but edges cannot.

Hamiltonian cycles visit every vertex in the graph exactly once (similar to the travelling salesman problem). As a result, neither edges nor vertices can be repeated.

Error: The 'brew link' step did not complete successfully

I have tried all of the methods and none of them works. The easiest way is to reinstall node from https://nodejs.org/en/download/

Simply download the pkg and install it. Now I have a working npm and node again.

ld cannot find -l<library>

I had a similar problem with another library and the reason why it didn't found it, was that I didn't run the make install (after running ./configure and make) for that library. The make install may require root privileges (in this case use: sudo make install). After running the make install you should have the so files in the correct folder, i.e. here /usr/local/lib and not in the folder mentioned by you.

Matplotlib/pyplot: How to enforce axis range?

To answer my own question, the trick is to turn auto scaling off...

p.axis([0.0,600.0, 10000.0,20000.0])
ax = p.gca()
ax.set_autoscale_on(False)

Is it possible to set an object to null?

"an object" of what type?

You can certainly assign NULL (and nullptr) to objects of pointer types, and it is implementation defined if you can assign NULL to objects of arithmetic types.

If you mean objects of some class type, the answer is NO (excepting classes that have operator= accepting pointer or arithmetic types)

"empty" is more plausible, as many types have both copy assignment and default construction (often implicitly). To see if an existing object is like a default constructed one, you will also need an appropriate bool operator==

How to find a value in an excel column by vba code Cells.Find

I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

Set cell = ActiveSheet.Columns("B:B").Find( _
    What:=celda, _
    After:=ActiveCell _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False _
)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

Dim rng as Range
Dim cell as Range
Dim search as String

Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

Using JavaScript to display a Blob

In the fiddle your blob isn't a blob, it's a string representation of hexadecimal data. Try this on a blob and your done

var image = document.createElement('img');
let reader=new FileReader()
reader.addEventListener('loadend',()=>{
  let contents=reader.result
  image.src = contents
  document.body.appendChild(image);
})
if(blob instanceof Blob) reader.readAsDataURL(blob)

readAsDataURL give you a base64 encoded image ready for you image element () source (src)

Docker is installed but Docker Compose is not ? why?

just use brew:

brew install docker-compose

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

There are two ways to do it.

  1. In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true:

    export class AppComponent {
      constructor(private dialog: MatDialog){}
      openDialog() {
        this.dialog.open(DialogComponent, { disableClose: true });
      }
    }
    
  2. Alternatively, do it in the dialog component itself.

    export class DialogComponent {
      constructor(private dialogRef: MatDialogRef<DialogComponent>){
        dialogRef.disableClose = true;
      }
    }
    

Here's what you're looking for:

<code>disableClose</code> property in material.angular.io

And here's a Stackblitz demo


Other use cases

Here's some other use cases and code snippets of how to implement them.

Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
  selector: 'app-third-dialog',
  templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
  constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {      
}
  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close();
  }

}

Prevent esc from closing the dialog but allow clicking on the backdrop to close

P.S. This is an answer which originated from this answer, where the demo was based on this answer.

To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick to listen for click events to the backdrop.

Initially, the dialog will have the configuration option disableClose set as true. This ensures that the esc keypress, as well as clicking on the backdrop will not cause the dialog to close.

Afterwards, subscribe to the MatDialogRef#backdropClick method (which emits when the backdrop gets clicked and returns as a MouseEvent).

Anyways, enough technical talk. Here's the code:

openDialog() {
  let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
  /*
     Subscribe to events emitted when the backdrop is clicked
     NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
     See https://stackoverflow.com/a/41086381 for more info
  */
  dialogRef.backdropClick().subscribe(() => {
    // Close the dialog
    dialogRef.close();
  })

  // ...
}

Alternatively, this can be done in the dialog component:

export class DialogComponent {
  constructor(private dialogRef: MatDialogRef<DialogComponent>) {
    dialogRef.disableClose = true;
    /*
      Subscribe to events emitted when the backdrop is clicked
      NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
      See https://stackoverflow.com/a/41086381 for more info
    */
    dialogRef.backdropClick().subscribe(() => {
      // Close the dialog
      dialogRef.close();
    })
  }
}

Python Anaconda - How to Safely Uninstall

rm -rf ~/anaconda3

nano ~/.bashrc
  • Ctrl+W to search for "Anaconda"
  • Delete or comment out the following lines:

    /home/sammuel/.bashrc
    # added by Anaconda3 4.2.0 installer
    export PATH="/home/sammuel/anaconda3/bin:$PATH"
    

When you’re done editing the file, type Ctrl+X to exit and y to save changes.

Anaconda is now removed from your server.

Why am I getting AttributeError: Object has no attribute

I have encountered the same error as well. I am sure my indentation did not have any problem. Only restarting the python sell solved the problem.

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

I use XAMPP and had the same error. I used Paul Gobée solution above and it worked for me. I navigated to C:\xampp\mysql\bin\mysqld-debug.exe and upon starting the .exe my Windows Firewall popped up asking for permission. Once I allowed it, it worked fine. I would have commented under his post but I do not have that much rep yet... sry! Just wanted to let everyone know this worked for me as well.

Is there a Java equivalent or methodology for the typedef keyword in C++?

If this is what you mean, you can simply extend the class you would like to typedef, e.g.:

public class MyMap extends HashMap<String, String> {}

Making LaTeX tables smaller?

You could add \singlespacing near the beginning of your table. See the setspace instructions for more options.

C multi-line macro: do/while(0) vs scope block

Andrey Tarasevich provides the following explanation:

  1. On Google Groups
  2. On bytes.com

[Minor changes to formatting made. Parenthetical annotations added in square brackets []].

The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.

Consider the following code sketch:

if (<condition>)
  foo(a);
else
  bar(a);

where foo and bar are ordinary functions. Now imagine that you'd like to replace function foo with a macro of the above nature [named CALL_FUNCS]:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

Now, if your macro is defined in accordance with the second approach (just { and }) the code will no longer compile, because the 'true' branch of if is now represented by a compound statement. And when you put a ; after this compound statement, you finished the whole if statement, thus orphaning the else branch (hence the compilation error).

One way to correct this problem is to remember not to put ; after macro "invocations":

if (<condition>)
  CALL_FUNCS(a)
else
  bar(a);

This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:

#define CALL_FUNCS(x) \
do { \
  func1(x); \
  func2(x); \
  func3(x); \
} while (0)

Now this code:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

will compile without any problems.

However, note the small but important difference between my definition of CALL_FUNCS and the first version in your message. I didn't put a ; after } while (0). Putting a ; at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.

I don't know why the author of the code you quoted in your original message put this ; after while (0). In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final ; into the macro (for the reasons that I explained above).

SignalR Console app example

First of all, you should install SignalR.Host.Self on the server application and SignalR.Client on your client application by nuget :

PM> Install-Package SignalR.Hosting.Self -Version 0.5.2

PM> Install-Package Microsoft.AspNet.SignalR.Client

Then add the following code to your projects ;)

(run the projects as administrator)

Server console app:

using System;
using SignalR.Hubs;

namespace SignalR.Hosting.Self.Samples {
    class Program {
        static void Main(string[] args) {
            string url = "http://127.0.0.1:8088/";
            var server = new Server(url);

            // Map the default hub url (/signalr)
            server.MapHubs();

            // Start the server
            server.Start();

            Console.WriteLine("Server running on {0}", url);

            // Keep going until somebody hits 'x'
            while (true) {
                ConsoleKeyInfo ki = Console.ReadKey(true);
                if (ki.Key == ConsoleKey.X) {
                    break;
                }
            }
        }

        [HubName("CustomHub")]
        public class MyHub : Hub {
            public string Send(string message) {
                return message;
            }

            public void DoSomething(string param) {
                Clients.addMessage(param);
            }
        }
    }
}

Client console app:

using System;
using SignalR.Client.Hubs;

namespace SignalRConsoleApp {
    internal class Program {
        private static void Main(string[] args) {
            //Set connection
            var connection = new HubConnection("http://127.0.0.1:8088/");
            //Make proxy to hub based on hub name on server
            var myHub = connection.CreateHubProxy("CustomHub");
            //Start connection

            connection.Start().ContinueWith(task => {
                if (task.IsFaulted) {
                    Console.WriteLine("There was an error opening the connection:{0}",
                                      task.Exception.GetBaseException());
                } else {
                    Console.WriteLine("Connected");
                }

            }).Wait();

            myHub.Invoke<string>("Send", "HELLO World ").ContinueWith(task => {
                if (task.IsFaulted) {
                    Console.WriteLine("There was an error calling send: {0}",
                                      task.Exception.GetBaseException());
                } else {
                    Console.WriteLine(task.Result);
                }
            });

            myHub.On<string>("addMessage", param => {
                Console.WriteLine(param);
            });

            myHub.Invoke<string>("DoSomething", "I'm doing something!!!").Wait();


            Console.Read();
            connection.Stop();
        }
    }
}

Fastest way to extract frames using ffmpeg?

If you know exactly which frames to extract, eg 1, 200, 400, 600, 800, 1000, try using:

select='eq(n\,1)+eq(n\,200)+eq(n\,400)+eq(n\,600)+eq(n\,800)+eq(n\,1000)' \
       -vsync vfr -q:v 2

I'm using this with a pipe to Imagemagick's montage to get 10 frames preview from any videos. Obviously the frame numbers you'll need to figure out using ffprobe

ffmpeg -i myVideo.mov -vf \
    select='eq(n\,1)+eq(n\,200)+eq(n\,400)+eq(n\,600)+eq(n\,800)+eq(n\,1000)',scale=320:-1 \
    -vsync vfr -q:v 2 -f image2pipe -vcodec ppm - \
  | montage -tile x1 -geometry "1x1+0+0<" -quality 100 -frame 1 - output.png

.

Little explanation:

  1. In ffmpeg expressions + stands for OR and * for AND
  2. \, is simply escaping the , character
  3. Without -vsync vfr -q:v 2 it doesn't seem to work but I don't know why - anyone?

JQuery - Set Attribute value

Seriously, just don't use jQuery for this. disabled is a boolean property of form elements that works perfectly in every major browser since 1997, and there is no possible way it could be simpler or more intuitive to change whether or not a form element is disabled.

The simplest way of getting a reference to the checkbox would be to give it an id. Here's my suggested HTML:

<input type="hidden" name="chk0" value="">
<input type="checkbox" name="chk0" id="chk0_checkbox" value="true" disabled>

And the line of JavaScript to make the check box enabled:

document.getElementById("chk0_checkbox").disabled = false;

If you prefer, you can instead use jQuery to get hold of the checkbox:

$("#chk0_checkbox")[0].disabled = false;

What do numbers using 0x notation mean?

It's a hexadecimal number.

0x6400 translates to 4*16^2 + 6*16^3 = 25600

Closure in Java 7

A closure implementation for Java 5, 6, and 7

http://mseifed.blogspot.se/2012/09/bringing-closures-to-java-5-6-and-7.html

It contains all one could ask for...

How to find out what the date was 5 days ago?

General algorithms for date manipulation convert dates to and from Julian Day Numbers. Here is a link to a description of such algorithms, a description of the best algorithms currently known, and the mathematical proofs of each of them: http://web.archive.org/web/20140910060704/http://mysite.verizon.net/aesir_research/date/date0.htm

How to format numbers by prepending 0 to single-digit numbers?

("0" + (date.getMonth() + 1)).slice(-2);
("0" + (date.getDay())).slice(-2);

Difference between declaring variables before or in loop?

this is the better form

double intermediateResult;
int i = byte.MinValue;

for(; i < 1000; i++)
{
intermediateResult = i;
System.out.println(intermediateResult);
}

1) in this way declared once time both variable, and not each for cycle. 2) the assignment it's fatser thean all other option. 3) So the bestpractice rule is any declaration outside the iteration for.

Get the current date in java.sql.Date format

Simply in one line:

java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());

How to determine the number of days in a month in SQL Server?

simple query in SQLServer2012 :

select day(('20-05-1951 22:00:00'))

i tested for many dates and it return always a correct result

how does Array.prototype.slice.call() work?

Maybe a bit late, but the answer to all of this mess is that call() is used in JS for inheritance. If we compare this to Python or PHP, for example, call is used respectively as super().init() or parent::_construct().

This is an example of its usage that clarifies all:

function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

Reference: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance

Open a URL in a new tab (and not a new window)

Do not use target="_blank"

Always use specific name for that window in my case meaningfulName, in this case you save processor resource:

button.addEventListener('click', () => {
    window.open('https://google.com', 'meaningfulName')
})

On this way when you click for example 10 times on button, browser will always re-render it in one new tab, instead of opening it in 10 different tabs which will consume much more resources.

You can read more about this on MDN.

Getting the length of two-dimensional array

Remember, 2D array is not a 2D array in real sense.Every element of an array in itself is an array, not necessarily of the same size. so, nir[0].length may or may not be equal to nir[1].length or nir[2]length.

Hope that helps..:)

How to compare Boolean?

As long as checker is not null, you may use !checker as posted. This is possible since Java 5, because this Boolean variable will be autoboxed to the primivite boolean value.

how to add css class to html generic control div?

I think the answer of Curt is correct, however, what if you want to add a class to a div that already has a class declared in the ASP.NET code.

Here is my solution for that, it is a generic method so you can call it directly as this:

Asp Net Div declaration:

<div id="divButtonWrapper" runat="server" class="text-center smallbutton fixPad">

Code to add class:

divButtonWrapper.AddClassToHtmlControl("nameOfYourCssClass")

Generic class:

public static class HtmlGenericControlExtensions
{
    public static void AddClassToHtmlControl(this HtmlGenericControl htmlGenericControl, string className)
    {
        if (string.IsNullOrWhiteSpace(className))
            return;

        htmlGenericControl
            .Attributes.Add("class", string.Join(" ", htmlGenericControl
            .Attributes["class"]
            .Split(' ')
            .Except(new[] { "", className })
            .Concat(new[] { className })
            .ToArray()));
    }
}

Creating a Custom Event

Yes, provided you have access to the object definition and can modify it to declare the custom event

public event EventHandler<EventArgs> ModelChanged;

And normally you'd back this up with a private method used internally to invoke the event:

private void OnModelChanged(EventArgs e)
{
    if (ModelChanged != null)
        ModelChanged(this, e);
}

Your code simply declares a handler for the declared myMethod event (you can also remove the constructor), which would get invoked every time the object triggers the event.

myObject.myMethod += myNameEvent;

Similarly, you can detach a handler using

myObject.myMethod -= myNameEvent;

Also, you can write your own subclass of EventArgs to provide specific data when your event fires.

Ruby, remove last N characters from a string?

I would suggest chop. I think it has been mentioned in one of the comments but without links or explanations so here's why I think it's better:

It simply removes the last character from a string and you don't have to specify any values for that to happen.

If you need to remove more than one character then chomp is your best bet. This is what the ruby docs have to say about chop:

Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator.

Although this is used mostly to remove separators such as \r\n I've used it to remove the last character from a simple string, for example the s to make the word singular.

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

After an hour ,i found best approach. we should save result of dialog in variable, after that call close method of variable.

Like this:

var dd= $("#divDialog")
.dialog({
   height: 600,
   width: 600,
   modal: true,
   draggable: false,
   resizable: false
});

// . . .

dd.dialog('close');

Close iOS Keyboard by touching anywhere using Swift

Another possibility is to simply add a big button with no content that lies underneath all views you might need to touch. Give it an action named:

@IBAction func dismissKeyboardButton(sender: AnyObject) {
    view.endEditing(true)
}

The problem with a gesture recognizer was for me, that it also caught all touches I wanted to receive by the tableViewCells.

Does Internet Explorer 8 support HTML 5?

According to http://msdn.microsoft.com/en-us/library/cc288472(VS.85).aspx#html, IE8 will have "strong" HTML 5 support. I haven't seen anything discussing exactly what "strong support" entails, but I can say that yes, some HTML5 stuff is going to make it into IE8.

Set JavaScript variable = null, or leave undefined?

The only time you need to set it (or not) is if you need to explicitly check that a variable a is set exactly to null or undefined.

if(a === null) {

}

...is not the same as:

if(a === undefined) {

}

That said, a == null && a == undefined will return true.

Fiddle

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Referring to SimpleDataFormat JavaDoc:

Letter | Date or Time Component | Presentation | Examples
---------------------------------------------------------
   H   |  Hour in day (0-23)    |    Number    |    0
   h   |  Hour in am/pm (1-12)  |    Number    |    12

JSP : JSTL's <c:out> tag

c:out also has an attribute for assigning a default value if the value of person.name happens to be null.

Source: out (TLDDoc Generated Documentation)

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

Note

If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

python pandas remove duplicate columns

An update on @kalu's answer, which uses the latest pandas:

def find_duplicated_columns(df):
    dupes = []

    columns = df.columns

    for i in range(len(columns)):
        col1 = df.iloc[:, i]
        for j in range(i + 1, len(columns)):
            col2 = df.iloc[:, j]
            # break early if dtypes aren't the same (helps deal with
            # categorical dtypes)
            if col1.dtype is not col2.dtype:
                break
            # otherwise compare values
            if col1.equals(col2):
                dupes.append(columns[i])
                break

    return dupes

How to retrieve the current value of an oracle sequence without increment it?

If your use case is that some backend code inserts a record, then the same code wants to retrieve the last insert id, without counting on any underlying data access library preset function to do this, then, as mentioned by others, you should just craft your SQL query using SEQ_MY_NAME.NEXTVAL for the column you want (usually the primary key), then just run statement SELECT SEQ_MY_NAME.CURRVAL FROM dual from the backend.

Remember, CURRVAL is only callable if NEXTVAL has been priorly invoked, which is all naturally done in the strategy above...

How to format column to number format in Excel sheet?

If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe

Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value

But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version

Sub CommandClick()

    Dim rCell As Range
    Dim rNext As Range

    For Each rCell In Sheet2.Range("C1:C30000").Cells
        If rCell.Value >= 100 And rCell.Value < 1000 Then
            Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
            rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
        End If
    Next rCell

End Sub

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

How to remove application from app listings on Android Developer Console

Actually it is now partially possible: https://support.google.com/googleplay/android-developer/answer/9023647

Updates to reports

In late May 2018, you may begin to see changes in your app's metrics based on your users' deletion of data. Some metrics are calculated based on data from users who have agreed to share their data with developers in aggregate.

The metrics that we provide in the Play Console are adjusted to more closely reflect data from all of your users. However, Google will not display data that falls under certain minimum thresholds.

Delete an app or game

You can permanently remove draft apps or games from your Play Console. You can also delete:

  1. Published apps or games that haven't been installed on any devices
  2. Published apps or games that no users are entitled to re-install

In these cases, contact our support team to request that your app's or game's data be permanently deleted.

How to check 'undefined' value in jQuery

You can use two way 1) if ( val == null ) 2) if ( val === undefine )

How to convert empty spaces into null values, using SQL Server?

I solved a similar problem using NULLIF function:

UPDATE table 
SET col1 = NULLIF(col1, '')

From the T-SQL reference:

NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.

Split string into array of characters?

Here's another way to do it in VBA.

Function ConvertToArray(ByVal value As String)
    value = StrConv(value, vbUnicode)
    ConvertToArray = Split(Left(value, Len(value) - 1), vbNullChar)
End Function
Sub example()
    Dim originalString As String
    originalString = "hi there"
    Dim myArray() As String
    myArray = ConvertToArray(originalString)
End Sub

What exactly does Perl's "bless" do?

This function tells the entity referenced by REF that it is now an object in the CLASSNAME package, or the current package if CLASSNAME is omitted. Use of the two-argument form of bless is recommended.

Example:

bless REF, CLASSNAME
bless REF

Return Value

This function returns the reference to an object blessed into CLASSNAME.

Example:

Following is the example code showing its basic usage, the object reference is created by blessing a reference to the package's class -

#!/usr/bin/perl

package Person;
sub new
{
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    # Print all the values just for clarification.
    print "First Name is $self->{_firstName}\n";
    print "Last Name is $self->{_lastName}\n";
    print "SSN is $self->{_ssn}\n";
    bless $self, $class;
    return $self;
}

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

Set LIMIT with doctrine 2?

I use Doctrine\ORM\Tools\Pagination\Paginator for this, and it works perfectly (doctrine 2.2).

$dql = "SELECT p, c FROM BlogPost p JOIN p.comments c";
$query = $entityManager->createQuery($dql)
                       ->setFirstResult(0)
                       ->setMaxResults(10);

$paginator = new Paginator($query, $fetchJoinCollection = true);

Clearing my form inputs after submission

I used the following with jQuery $("#submitForm").val("");

where submitForm is the id for the input element in the html. I ran it AFTER my function to extract the value from the input field. That extractValue function below:

function extractValue() { var value = $("#submitForm").val().trim(); console.log(value); };

Also don't forget to include preventDefault(); method to stop the submit type form from refreshing your page!

How to run function in AngularJS controller on document ready?

See this post How to execute angular controller function on page load?
For fast lookup:

// register controller in html
<div data-ng-controller="myCtrl" data-ng-init="init()"></div>

// in controller
$scope.init = function () {
    // check if there is query in url
    // and fire search in case its value is not empty
};

This way, You don't have to wait till document is ready.

Secure random token in Node.js

Random URL and filename string safe (1 liner)

Crypto.randomBytes(48).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');

Visual studio equivalent of java System.out

Or, if you want to see output in the Output window of Visual Studio, System.Diagnostics.Debug.WriteLine(stuff)

Rails DateTime.now without Time

If you want today's date without the time, just use Date.today

Chrome - ERR_CACHE_MISS

Yes, this is a current issue in Chrome. There is an issue report here.

The fix will appear in 40.x.y.z versions.

Until then? I don't think you can resolve the issue yourself. But you can ignore it. The shown error is only related to the dev tools and does not influence the behavior of your website. If you have any other problems they are not related to this error.

What's the best way to convert a number to a string in JavaScript?

In my opinion n.toString() takes the prize for its clarity, and I don't think it carries any extra overhead.

How to fix the error "Windows SDK version 8.1" was not found?

I realize this post is a few years old, but I just wanted to extend this to anyone still struggling through this issue.

The company I work for still uses VS2015 so in turn I still use VS2015. I recently started working on a RPC application using C++ and found the need to download the Win32 Templates. Like many others I was having this "SDK 8.1 was not found" issue. i took the following corrective actions with no luck.

  • I found the SDK through Micrsoft at the following link https://developer.microsoft.com/en-us/windows/downloads/sdk-archive/ as referenced above and downloaded it.
  • I located my VS2015 install in Apps & Features and ran the repair.
  • I completely uninstalled my VS2015 and reinstalled it.
  • I attempted to manually point my console app "Executable" and "Include" directories to the C:\Program Files (x86)\Microsoft SDKs\Windows Kits\8.1 and C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools.

None of the attempts above corrected the issue for me...

I then found this article on social MSDN https://social.msdn.microsoft.com/Forums/office/en-US/5287c51b-46d0-4a79-baad-ddde36af4885/visual-studio-cant-find-windows-81-sdk-when-trying-to-build-vs2015?forum=visualstudiogeneral

Finally what resolved the issue for me was:

  • Uninstalling and reinstalling VS2015.
  • Locating my installed "Windows Software Development Kit for Windows 8.1" and running the repair.
  • Checked my "C:\Program Files (x86)\Microsoft SDKs\Windows Kits\8.1" to verify the "DesignTime" folder was in fact there.
  • Opened VS created a Win32 Console application and comiled with no errors or issues

I hope this saves anyone else from almost 3 full days of frustration and loss of productivity.

Temporarily switch working copy to a specific Git commit

If you are at a certain branch mybranch, just go ahead and git checkout commit_hash. Then you can return to your branch by git checkout mybranch. I had the same game bisecting a bug today :) Also, you should know about git bisect.

How to rollback everything to previous commit

I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.

I generally use this to reset the git to the specific commit in source tree.

  1. select commit to reset on sourcetree.

  2. In dropdowns select the active branch , first Parent Only

  3. And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)

  4. and then go to terminal git push -f

You should be all set!

How to round up the result of integer division?

The following should do rounding better than the above solutions, but at the expense of performance (due to floating point calculation of 0.5*rctDenominator):

uint64_t integerDivide( const uint64_t& rctNumerator, const uint64_t& rctDenominator )
{
  // Ensure .5 upwards is rounded up (otherwise integer division just truncates - ie gives no remainder)
  return (rctDenominator == 0) ? 0 : (rctNumerator + (int)(0.5*rctDenominator)) / rctDenominator;
}

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

The object 'DF__*' is dependent on column '*' - Changing int to double

MS SQL Studio take care of when you delete the column but if you need to Delete Constraint Programmatically here is simple solution

Here’s a code snippet that’ll drop a column with a default constraint:

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__') AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = N'__ColumnName__' AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
IF EXISTS (SELECT * FROM syscolumns WHERE id=object_id('__TableName__') AND name='__ColumnName__')
EXEC('ALTER TABLE __TableName__ DROP COLUMN __ColumnName__')

Just replace TableName and ColumnName with the appropriate values. You can safely run this even if the column has already been dropped.

Bonus: Here’s the code to drop foreign keys and other types of constraints.

IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '__TableName__' AND COLUMN_NAME = '__ColumnName__')
BEGIN
SELECT @ConstraintName = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '__TableName__' AND COLUMN_NAME = '__ColumnName__'
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
END

Blog

How to make <a href=""> link look like a button?

Check Bootstrap's docs. A class .btn exists and works with the a tag, but you need to add a specific .btn-* class with the .btn class.

eg: <a class="btn btn-info"></a>

How can I represent a range in Java?

You could create a class to represent this

public class Range
{
    private int low;
    private int high;

    public Range(int low, int high){
        this.low = low;
        this.high = high;
    }

    public boolean contains(int number){
        return (number >= low && number <= high);
    }
}

Sample usage:

Range range = new Range(0, 2147483647);

if (range.contains(foo)) {
    //do something
}

CAST DECIMAL to INT

Try cast (columnName as unsigned)

unsigned is positive value only

If you want to include negative value, then cast (columnName as signed),
The difference between sign (negative include) and unsigned (twice the size of sign, but non-negative)

How to execute VBA Access module?

Well it depends on how you want to call this code.

Are you calling it from a button click on a form, if so then on the properties for the button on form, go to the Event tab, then On Click item, select [Event Procedure]. This will open the VBA code window for that button. You would then call your Module.Routine and then this would trigger when you click the button.

Similar to this:

Private Sub Command1426_Click()
    mdl_ExportMorning.ExportMorning
End Sub

This button click event calls the Module mdl_ExportMorning and the Public Sub ExportMorning.

How can I rotate an HTML <div> 90 degrees?

We can add the following to a particular tag in CSS:

-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);

In case of half rotation change 90 to 45.

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

Capturing mobile phone traffic on Wireshark

For iOS Devices:

? Open Terminal and simply write:

rvictl -s udid

it'll open an interface on Wireshark with a name, In my case its rvi0.

enter image description here

udid is iPhone's unique device id.

(How to find my iOS Device UDID)

Java - Abstract class to contain variables?

Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.

How to create JSON Object using String?

In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).

https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)

(Android API 19-27. Kotlin 1.2.50)

How do I size a UITextView to its content?

It's quite easy with Key Value Observing (KVO), just create a subclass of UITextView and do:

private func setup() { // Called from init or somewhere

    fitToContentObservations = [
        textView.observe(\.contentSize) { _, _ in
            self.invalidateIntrinsicContentSize()
        },
        // For some reason the content offset sometimes is non zero even though the frame is the same size as the content size.
        textView.observe(\.contentOffset) { _, _ in
            if self.contentOffset != .zero { // Need to check this to stop infinite loop
                self.contentOffset = .zero
            }
        }
    ]
}
public override var intrinsicContentSize: CGSize {
    return contentSize
}

If you don't want to subclass you could try doing textView.bounds = textView.contentSize in the contentSize observer.

How might I force a floating DIV to match the height of another floating DIV?

I recommend you wrap them both in an outer div with the desired background color.

Table column sizing

Using d-flex class works well but some other attributes don't work anymore like vertical-align: middle property.

The best way I found to size columns very easily is to use the width attribute with percentage only in thead cells.

<table class="table">
    <thead>
        <tr>
            <th width="25%">25%</th>
            <th width="25%">25%</th>
            <th width="50%">50%</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>25%</td>
            <td>25%</td>
            <td>50%</td>
        </tr>
    </tbody>
</table>

substring of an entire column in pandas dataframe

Use the str accessor with square brackets:

df['col'] = df['col'].str[:9]

Or str.slice:

df['col'] = df['col'].str.slice(0, 9)

The EntityManager is closed

Same problem, solved with a simple code refactoring. The problem is sometime present when a required field is null, before do anithing, try to refactor your code. A better workflow can solve the problem.

How to deserialize a list using GSON or another JSON library in Java?

Another way is to use an array as a type, e.g.:

Video[] videoArray = gson.fromJson(json, Video[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list, e.g.:

List<Video> videoList = Arrays.asList(videoArray);

IMHO this is much more readable.


In Kotlin this looks like this:

Gson().fromJson(jsonString, Array<Video>::class.java)

To convert this array into List, just use .toList() method

Java reflection: how to get field value from an object, not knowing its class

There is one more way, i got the same situation in my project. i solved this way

List<Object[]> list = HQL.list();

In above hibernate query language i know at which place what are my objects so what i did is :

for(Object[] obj : list){
String val = String.valueOf(obj[1]);
int code =Integer.parseint(String.valueof(obj[0]));
}

this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help

How to create an infinite loop in Windows batch file?

How about using good(?) old goto?

:loop

echo Ooops

goto loop

See also this for a more useful example.

Centering image and text in R Markdown for a PDF report

None of the answers work for all output types the same way and others focus on figures plottet within the code chunk and not external images.

The include_graphics() function provides an easy solution. The only argument is the name of the file (with the relative path if it's in a subfolder). By setting echo to FALSE and fig.align=center you get the wished result.

```{r, echo=FALSE, fig.align='center'}
include_graphics("image.jpg")
```

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

SQL Server: converting UniqueIdentifier to string in a case statement

Instead of Str(RequestID), try convert(varchar(38), RequestID)

I want to align the text in a <td> to the top

https://developer.mozilla.org/en/CSS/vertical-align

<table style="height: 275px; width: 188px">
    <tr>
        <td style="width: 259px; vertical-align:top">
            main page
        </td>
    </tr>
</table>

?

How to flip background image using CSS?

You can flip both vertical and horizontal at the same time

    -moz-transform: scaleX(-1) scaleY(-1);
    -o-transform: scaleX(-1) scaleY(-1);
    -webkit-transform: scaleX(-1) scaleY(-1);
    transform: scaleX(-1) scaleY(-1);

And with the transition property you can get a cool flip

    -webkit-transition: transform .4s ease-out 0ms;
    -moz-transition: transform .4s ease-out 0ms;
    -o-transition: transform .4s ease-out 0ms;
    transition: transform .4s ease-out 0ms;
    transition-property: transform;
    transition-duration: .4s;
    transition-timing-function: ease-out;
    transition-delay: 0ms;

Actually it flips the whole element, not just the background-image

SNIPPET

_x000D_
_x000D_
function flip(){_x000D_
 var myDiv = document.getElementById('myDiv');_x000D_
 if (myDiv.className == 'myFlipedDiv'){_x000D_
  myDiv.className = '';_x000D_
 }else{_x000D_
  myDiv.className = 'myFlipedDiv';_x000D_
 }_x000D_
}
_x000D_
#myDiv{_x000D_
  display:inline-block;_x000D_
  width:200px;_x000D_
  height:20px;_x000D_
  padding:90px;_x000D_
  background-color:red;_x000D_
  text-align:center;_x000D_
  -webkit-transition:transform .4s ease-out 0ms;_x000D_
  -moz-transition:transform .4s ease-out 0ms;_x000D_
  -o-transition:transform .4s ease-out 0ms;_x000D_
  transition:transform .4s ease-out 0ms;_x000D_
  transition-property:transform;_x000D_
  transition-duration:.4s;_x000D_
  transition-timing-function:ease-out;_x000D_
  transition-delay:0ms;_x000D_
}_x000D_
.myFlipedDiv{_x000D_
  -moz-transform:scaleX(-1) scaleY(-1);_x000D_
  -o-transform:scaleX(-1) scaleY(-1);_x000D_
  -webkit-transform:scaleX(-1) scaleY(-1);_x000D_
  transform:scaleX(-1) scaleY(-1);_x000D_
}
_x000D_
<div id="myDiv">Some content here</div>_x000D_
_x000D_
<button onclick="flip()">Click to flip</button>
_x000D_
_x000D_
_x000D_

How to add a Browse To File dialog to a VB.NET application

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

How can I iterate over the elements in Hashmap?

Need Key & Value in Iteration

Use entrySet() to iterate through Map and need to access value and key:

Map<String, Person> hm = new HashMap<String, Person>();

hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));

Set<Map.Entry<String, Person>> set = hm.entrySet();

for (Map.Entry<String, Person> me : set) {
  System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());

}

Need Key in Iteration

If you want just to iterate over keys of map you can use keySet()

for(String key: map.keySet()) {
     Person value = map.get(key); 
}

Need Value in Iteration

If you just want to iterate over values of map you can use values()

for(Person person: map.values()) {

}

Service Temporarily Unavailable Magento?

You can do this thing:

Go to http://localhost/magento/downloader url. Here I am running the magento store on my localhost. Now you can login to magento connect manager and uninstall the extension which you installed previously.

Hope this works !!!!!

Thanks.

$.focus() not working

Had this issue again just now, and believe it or not, all I had to do was close the developer tools. Apparently the Console tab has the focus priority over the page content.

How do I remove trailing whitespace using a regular expression?

To remove trailing whitespace while also preserving whitespace-only lines, you want the regex to only remove trailing whitespace after non-whitespace characters. So you need to first check for a non-whitespace character. This means that the non-whitespace character will be included in the match, so you need to include it in the replacement.

Regex: ([^ \t\r\n])[ \t]+$

Replacement: \1 or $1, depending on the IDE

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

  1. Check if compatible Mysql for your PHP version is correctly installed. (eg. mysql-installer-community-5.5.40.1.msi for PHP 5.2.10, apache 2.2 and phpMyAdmin 3.5.2)
  2. In your php\php.ini set your loadable php extensions path (eg. extension_dir = "C:\php\ext") (https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)
  3. (In your php\php.ini) check if extension=php_mysqli.dll is uncommented (https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)
  4. Set your php folder (eg."C:\php") and php\ext folder (eg."C:\php\ext") as your runtime environment variable path (https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)
  5. Restart apache service (https://drive.google.com/open?id=1kJF5kxPSrj3LdKWJcJTos9ecKFx0ORAW)

JavaScriptSerializer - JSON serialization of enum as string

        Person p = new Person();
        p.Age = 35;
        p.Gender = Gender.Male;
        //1.  male="Male";
        string male = Gender.Male.ToString();

        p.Gender = Gender.Female;

        //2.  female="Female";
        string female = Enum.GetName(typeof(Gender), p.Gender);

        JObject jobj = new JObject();
        jobj["Age"] = p.Age;
        jobj["Gender"] = male;
        jobj["Gender2"] = female;

        //you result:  josn= {"Age": 35,"Gender": "Male","Gender2": "Female"}
        string json = jobj.ToString();

Import/Index a JSON file into Elasticsearch

You are using

$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests

If 'requests' is a json file then you have to change this to

$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests.json

Now before this, if your json file is not indexed, you have to insert an index line before each line inside the json file. You can do this with JQ. Refer below link: http://kevinmarsh.com/2014/10/23/using-jq-to-import-json-into-elasticsearch.html

Go to elasticsearch tutorials (example the shakespeare tutorial) and download the json file sample used and have a look at it. In front of each json object (each individual line) there is an index line. This is what you are looking for after using the jq command. This format is mandatory to use the bulk API, plain json files wont work.

How to make Bootstrap carousel slider use mobile left/right swipe

If anyone is looking for the angular version of this answer then I would suggest creating a directive would be a great idea.

NOTE: ngx-bootstrap is used.

import { Directive, Host, Self, Optional, Input, Renderer2, OnInit, ElementRef } from '@angular/core';
import { CarouselComponent } from 'ngx-bootstrap/carousel';

@Directive({
  selector: '[appCarouselSwipe]'
})
export class AppCarouselSwipeDirective implements OnInit {
  @Input() swipeThreshold = 50;
  private start: number;
  private stillMoving: boolean;
  private moveListener: Function;

  constructor(
    @Host() @Self() @Optional() private carousel: CarouselComponent,
    private renderer: Renderer2,
    private element: ElementRef
  ) {
  }

  ngOnInit(): void {
    if ('ontouchstart' in document.documentElement) {
      this.renderer.listen(this.element.nativeElement, 'touchstart', this.onTouchStart.bind(this));
      this.renderer.listen(this.element.nativeElement, 'touchend', this.onTouchEnd.bind(this));
    }
  }

  private onTouchStart(e: TouchEvent): void {
    if (e.touches.length === 1) {
      this.start = e.touches[0].pageX;
      this.stillMoving = true;
      this.moveListener = this.renderer.listen(this.element.nativeElement, 'touchmove', this.onTouchMove.bind(this));
    }
  }

  private onTouchMove(e: TouchEvent): void {
    if (this.stillMoving) {
      const x = e.touches[0].pageX;
      const difference = this.start - x;
      if (Math.abs(difference) >= this.swipeThreshold) {
        this.cancelTouch();
        if (difference > 0) {
          if (this.carousel.activeSlide < this.carousel.slides.length - 1) {
            this.carousel.activeSlide = this.carousel.activeSlide + 1;
          }
        } else {
          if (this.carousel.activeSlide > 0) {
            this.carousel.activeSlide = this.carousel.activeSlide - 1;
          }
        }
      }
    }
  }

  private onTouchEnd(e: TouchEvent): void {
    this.cancelTouch();
  }

  private cancelTouch() {
    if (this.moveListener) {
      this.moveListener();
      this.moveListener = undefined;
    }
    this.start = null;
    this.stillMoving = false;
  }
}

in html:

<carousel appCarouselSwipe>

    ...

</carousel>

Reference

Detecting real time window size changes in Angular 4

This is an example of service which I use.

You can get the screen width by subscribing to screenWidth$, or via screenWidth$.value.

The same is for mediaBreakpoint$ ( or mediaBreakpoint$.value)

import {
  Injectable,
  OnDestroy,
} from '@angular/core';
import {
  Subject,
  BehaviorSubject,
  fromEvent,
} from 'rxjs';
import {
  takeUntil,
  debounceTime,
} from 'rxjs/operators';

@Injectable()
export class ResponsiveService implements OnDestroy {
  private _unsubscriber$: Subject<any> = new Subject();
  public screenWidth$: BehaviorSubject<number> = new BehaviorSubject(null);
  public mediaBreakpoint$: BehaviorSubject<string> = new BehaviorSubject(null);

  constructor() {
    this.init();
  }

  init() {
    this._setScreenWidth(window.innerWidth);
    this._setMediaBreakpoint(window.innerWidth);
    fromEvent(window, 'resize')
      .pipe(
        debounceTime(1000),
        takeUntil(this._unsubscriber$)
      ).subscribe((evt: any) => {
        this._setScreenWidth(evt.target.innerWidth);
        this._setMediaBreakpoint(evt.target.innerWidth);
      });
  }

  ngOnDestroy() {
    this._unsubscriber$.next();
    this._unsubscriber$.complete();
  }

  private _setScreenWidth(width: number): void {
    this.screenWidth$.next(width);
  }

  private _setMediaBreakpoint(width: number): void {
    if (width < 576) {
      this.mediaBreakpoint$.next('xs');
    } else if (width >= 576 && width < 768) {
      this.mediaBreakpoint$.next('sm');
    } else if (width >= 768 && width < 992) {
      this.mediaBreakpoint$.next('md');
    } else if (width >= 992 && width < 1200) {
      this.mediaBreakpoint$.next('lg');
    } else if (width >= 1200 && width < 1600) {
      this.mediaBreakpoint$.next('xl');
    } else {
      this.mediaBreakpoint$.next('xxl');
    }
  }

}

Hope this helps someone

Base64: java.lang.IllegalArgumentException: Illegal character

I encountered this error since my encoded image started with data:image/png;base64,iVBORw0....

This answer led me to the solution:

String partSeparator = ",";
if (data.contains(partSeparator)) {
  String encodedImg = data.split(partSeparator)[1];
  byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
  Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
  Files.write(destinationFile, decodedImg);
}

declaring a priority_queue in c++ with a custom comparator

You have to define the compare first. There are 3 ways to do that:

  1. use class
  2. use struct (which is same as class)
  3. use lambda function.

It's easy to use class/struct because easy to declare just write this line of code above your executing code

struct compare{
  public:
  bool operator()(Node& a,Node& b) // overloading both operators 
  {
      return a.w < b.w: // if you want increasing order;(i.e increasing for minPQ)
      return a.w > b.w // if you want reverse of default order;(i.e decreasing for minPQ)
   }
};

Calling code:

priority_queue<Node,vector<Node>,compare> pq;

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

How to programmatically send SMS on the iPhone?

One of the systems of inter-process communication in MacOS is XPC. This system layer has been developed for inter-process communication based on the transfer of plist structures using libSystem and launchd. In fact, it is an interface that allows managing processes via the exchange of such structures as dictionaries. Due to heredity, iOS 5 possesses this mechanism as well.

You might already understand what I mean by this introduction. Yep, there are system services in iOS that include tools for XPC communication. And I want to exemplify the work with a daemon for SMS sending. However, it should be mentioned that this ability is fixed in iOS 6, but is relevant for iOS 5.0—5.1.1. Jailbreak, Private Framework, and other illegal tools are not required for its exploitation. Only the set of header files from the directory /usr/include/xpc/* are needed.

One of the elements for SMS sending in iOS is the system service com.apple.chatkit, the tasks of which include generation, management, and sending of short text messages. For the ease of control, it has the publicly available communication port com.apple.chatkit.clientcomposeserver.xpc. Using the XPC subsystem, you can generate and send messages without user's approval.

Well, let's try to create a connection.

xpc_connection_t myConnection;

dispatch_queue_t queue = dispatch_queue_create("com.apple.chatkit.clientcomposeserver.xpc", DISPATCH_QUEUE_CONCURRENT);

myConnection = xpc_connection_create_mach_service("com.apple.chatkit.clientcomposeserver.xpc", queue, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);

Now we have the XPC connection myConnection set to the service of SMS sending. However, XPC configuration provides for creation of suspended connections —we need to take one more step for the activation.

xpc_connection_set_event_handler(myConnection, ^(xpc_object_t event){
xpc_type_t xtype = xpc_get_type(event);
if(XPC_TYPE_ERROR == xtype)
{
NSLog(@"XPC sandbox connection error: %s\n", xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
}
// Always set an event handler. More on this later.

NSLog(@"Received a message event!");

});

xpc_connection_resume(myConnection);

The connection is activated. Right at this moment iOS 6 will display a message in the telephone log that this type of communication is forbidden. Now we need to generate a dictionary similar to xpc_dictionary with the data required for the message sending.

NSArray *recipient = [NSArray arrayWithObjects:@"+7 (90*) 000-00-00", nil];

NSData *ser_rec = [NSPropertyListSerialization dataWithPropertyList:recipient format:200 options:0 error:NULL];

xpc_object_t mydict = xpc_dictionary_create(0, 0, 0);
xpc_dictionary_set_int64(mydict, "message-type", 0);
xpc_dictionary_set_data(mydict, "recipients", [ser_rec bytes], [ser_rec length]);
xpc_dictionary_set_string(mydict, "text", "hello from your application!");

Little is left: send the message to the XPC port and make sure it is delivered.

xpc_connection_send_message(myConnection, mydict);
xpc_connection_send_barrier(myConnection, ^{
NSLog(@"The message has been successfully delivered");
});

That's all. SMS sent.

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

I will give you a better idea

for(decltype(things.size()) i = 0; i < things.size(); i++){
                   //...
}

decltype is

Inspects the declared type of an entity or the type and value category of an expression.

So, It deduces type of things.size() and i will be a type as same as things.size(). So, i < things.size() will be executed without any warning

Tools for making latex tables in R

The stargazer package is another good option. It supports objects from many commonly used functions and packages (lm, glm, svyreg, survival, pscl, AER), as well as from zelig. In addition to regression tables, it can also output summary statistics for data frames, or directly output the content of data frames.

How to search by key=>value in a multidimensional array in PHP

$result = array_filter($arr, function ($var) {   
  $found = false;
  array_walk_recursive($var, function ($item, $key) use (&$found) {  
    $found = $found || $key == "name" && $item == "cat 1";
  });
  return $found;
});

package android.support.v4.app does not exist ; in Android studio 0.8

For me the problem was caused by a gradle.properties file in the list of Gradle scripts. It showed as gradle.properties (global) and refered to a file in C:\users\.gradle\gradle.properties. I right-clicked on it and selected delete from the menu to delete it. It deleted the file from the hard disk and my project now builds and runs. I guess that the global file was overwriting something that was used to locate the package android.support

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

As ams said above, don't take a pointer to a member of a struct that's packed. This is simply playing with fire. When you say __attribute__((__packed__)) or #pragma pack(1), what you're really saying is "Hey gcc, I really know what I'm doing." When it turns out that you do not, you can't rightly blame the compiler.

Perhaps we can blame the compiler for it's complacency though. While gcc does have a -Wcast-align option, it isn't enabled by default nor with -Wall or -Wextra. This is apparently due to gcc developers considering this type of code to be a brain-dead "abomination" unworthy of addressing -- understandable disdain, but it doesn't help when an inexperienced programmer bumbles into it.

Consider the following:

struct  __attribute__((__packed__)) my_struct {
    char c;
    int i;
};

struct my_struct a = {'a', 123};
struct my_struct *b = &a;
int c = a.i;
int d = b->i;
int *e __attribute__((aligned(1))) = &a.i;
int *f = &a.i;

Here, the type of a is a packed struct (as defined above). Similarly, b is a pointer to a packed struct. The type of of the expression a.i is (basically) an int l-value with 1 byte alignment. c and d are both normal ints. When reading a.i, the compiler generates code for unaligned access. When you read b->i, b's type still knows it's packed, so no problem their either. e is a pointer to a one-byte-aligned int, so the compiler knows how to dereference that correctly as well. But when you make the assignment f = &a.i, you are storing the value of an unaligned int pointer in an aligned int pointer variable -- that's where you went wrong. And I agree, gcc should have this warning enabled by default (not even in -Wall or -Wextra).

Time complexity of nested for-loop

First we'll consider loops where the number of iterations of the inner loop is independent of the value of the outer loop's index. For example:

 for (i = 0; i < N; i++) {
     for (j = 0; j < M; j++) {
         sequence of statements
      }
  }

The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times. Thus, the total complexity for the two loops is O(N2).

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Implicit and Explicit Waits

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit Wait + Expected Conditions

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

Change event on select with knockout binding, how can I know if it is a real change?

Create js component

define([
    'Magento_Ui/js/form/element/select',
    'mage/translate'
], function (AbstractField, $t) {
    'use strict';

    return AbstractField.extend({
        defaults: {
            imports: {
                update: 'checkout.steps.shipping-step.shippingAddress.shipping-address-fieldset.country_id:value'
            },
            modules: {
                vat_id: '${ $.parentName }.vat_id'


            }
        },

        /**
         * Initializes UISelect component.
         *
         * @returns {UISelect} Chainable.
         */
        initialize: function () {
            this._super();
            this.vat_id().visible(false);
            return this;
        },
        update: function (value) {
            if(value == 'GB'){
                this.vat_id().visible(true);
            }else{
                this.vat_id().visible(false);

            }
        }
        
        
            
         
      
    });
});

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

Finding an elements XPath using IE Developer tool

Are you trying to find some work around getting xpath in IE?

There are many add-ons for other browsers like xpather for Chrome or xpather, xpath-checker and firebug for FireFox that will give you the xpath of an element in a second. But sadly there is no add-on or tool available that will do this for IE. For most cases you can get the xpath of the elements that fall in your script using the above tools in Firefox and tweak them a little (if required) to make them work in IE.

But if you are testing an application that will work only in IE or the specific scenario or page that has this element will open-up/play-out only in IE then you cannot use any of the above mention tools to find the XPATH. Well the only thing that works in this case is the Bookmarklets that were coded just for this purpose. Bookmarklets are JavaScript code that you will add in IE as bookmarks and later use to get the XPATH of the element you desire. Using these you can get the XPATH as easily as you get using xpather or any other firefox addon.

STEPS TO INSTALL BOOKMARKLETS

1)Open IE

2)Type about:blank in the address bar and hit enter

3)From Favorites main menu select ---> Add favorites

4) In the Add a favorite popup window enter name GetXPATH1.

5)Click add button in the add a favorite popup window.

6)Open the Favorites menu and right click the newly added favorite and select properties option.

7)GetXPATH1 Properties will open up. Select the web Document Tab.

8)Enter the following in the URL field.

javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}

9)Click Ok. Click YES on the popup alert.

10)Add another favorite by following steps 3 to 5, Name this favorite GetXPATH2 (step4)

11)Repeat steps 6 and 7 for GetXPATH2 that you just created.

12)Enter the following in the URL field for GetXPATH2

javascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o__o();

13)Repeat Step 9.

You are all done!!

Now to get the XPATH of elements just select the element with your mouse. This would involve clicking the left mouse button just before the element (link, button, image, checkbox, text etc) begins and dragging it till the element ends. Once you do this first select the favorite GetXPATH1 from the favorites menu and then select the second favorite GetXPATH2. At this point you will get a confirmation, hit allow access button. Now open up a notepad file, right click and select paste option. This will give you the XPATH of the element you seek.

PHP Configuration: It is not safe to rely on the system's timezone settings

Open your .htaccess file , add this line to the file, save, and try again :

php_value date.timezone "America/Sao_Paulo"

This works for me.

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

Why not forget the hacks and just do it with CSS?

One I use frequently:

.boxsizingBorder {
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

See browser support here.

How do I separate an integer into separate digits in an array in JavaScript?

This will work for a number greater than 0. You don't need to convert the number into string:

function convertNumberToDigitArray(number) {
    const arr = [];
    while (number > 0) {
        let lastDigit = number % 10;
        arr.push(lastDigit);
        number = Math.floor(number / 10);
    }
    return arr;
}

iPhone 5 CSS media query

Just a very quick addition as I have been testing a few options and missed this along the way. Make sure your page has:

<meta name="viewport" content="initial-scale=1.0">

jQuery: Check if button is clicked

$('#submit1, #submit2').click(function () {
   if (this.id == 'submit1') {
      alert('Submit 1 clicked');
   }
   else if (this.id == 'submit2') {
      alert('Submit 2 clicked');
   }
});

Make div fill remaining space along the main axis in flexbox

Use the flex-grow property to make a flex item consume free space on the main axis.

This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

Hence, instead of width: 96% on your div, use flex: 1.


You wrote:

So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

The squashing of the fixed-width div is related to another flex property: flex-shrink

By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

To disable this feature use flex-shrink: 0.

For more details see The flex-shrink factor section in the answer here:


Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

How to generate a random integer number from within a range

unsigned int
randr(unsigned int min, unsigned int max)
{
       double scaled = (double)rand()/RAND_MAX;

       return (max - min +1)*scaled + min;
}

See here for other options.

What are the best PHP input sanitizing functions?

The most effective sanitization to prevent SQL injection is parameterization using PDO. Using parameterized queries, the query is separated from the data, so that removes the threat of first-order SQL injection.

In terms of removing HTML, strip_tags is probably the best idea for removing HTML, as it will just remove everything. htmlentities does what it sounds like, so that works, too. If you need to parse which HTML to permit (that is, you want to allow some tags), you should use an mature existing parser such as HTML Purifier

Git push existing repo to a new and different remote repo server?

There is a deleted answer on this question that had a useful link: https://help.github.com/articles/duplicating-a-repository

The gist is

0. create the new empty repository (say, on github)
1. make a bare clone of the repository in some temporary location
2. change to the temporary location
3. perform a mirror-push to the new repository
4. change to another location and delete the temporary location

OP's example:

On your local machine

$ cd $HOME
$ git clone --bare https://git.fedorahosted.org/the/path/to/my_repo.git
$ cd my_repo.git
$ git push --mirror https://github.com/my_username/my_repo.git
$ cd ..
$ rm -rf my_repo.git

onKeyPress Vs. onKeyUp and onKeyDown

Just wanted to share a curiosity:

when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!

For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !

Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!

Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK

and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.

Save Javascript objects in sessionStorage

Session storage cannot support an arbitrary object because it may contain function literals (read closures) which cannot be reconstructed after a page reload.

Using Caps Lock as Esc in Mac OS X

Karabiner-Elements A powerful and stable keyboard customizer for macOS. (freeware)

https://pqrs.org/osx/karabiner/index.html

Worked for me for Mojave to change caps-lock to backspace

Why use a READ UNCOMMITTED isolation level?

It can be used for a simple table, for example in an insert-only audit table, where there is no update to existing row, and no fk to other table. The insert is a simple insert, which has no or little chance of rollback.

Download TS files from video stream

Copy and paste one of the .ts video files into a new tab in Chrome. Remove the identifying number of the .ts file (0,1,2,3 etc. or whatever number it is) and change the extension from ".ts" to ".mp4". That should bring up the video file in your browser as usual.

Sticky and NON-Sticky sessions

When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.

However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.

Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.

If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.

To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.

As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html

No provider for HttpClient

Go to app.module.ts

import import { HttpClientModule } from '@angular/common/http';

AND

Add HttpClientModule under imports

should look like this

imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule]

c# open file with default application and parameters

I converted the VB code in the blog post linked by xsl to C# and modified it a bit:

public static bool TryGetRegisteredApplication(
                     string extension, out string registeredApp)
{
    string extensionId = GetClassesRootKeyDefaultValue(extension);
    if (extensionId == null)
    {
        registeredApp = null;
        return false;
    }

    string openCommand = GetClassesRootKeyDefaultValue(
            Path.Combine(new[] {extensionId, "shell", "open", "command"}));

    if (openCommand == null)
    {
        registeredApp = null;
        return false;
    }

    registeredApp = openCommand
                     .Replace("%1", string.Empty)
                     .Replace("\"", string.Empty)
                     .Trim();
    return true;
}

private static string GetClassesRootKeyDefaultValue(string keyPath)
{
    using (var key = Registry.ClassesRoot.OpenSubKey(keyPath))
    {
        if (key == null)
        {
            return null;
        }

        var defaultValue = key.GetValue(null);
        if (defaultValue == null)
        {
            return null;
        }

        return defaultValue.ToString();
    }
}

EDIT - this is unreliable. See Finding the default application for opening a particular file type on Windows.

How to get value of Radio Buttons?

An alterntive is to use an enum and a component class that extends the standard RadioButton.

public enum Genders
{
    Male,
    Female
}

[ToolboxBitmap(typeof(RadioButton))]
public partial class GenderRadioButton : RadioButton
{
    public GenderRadioButton()
    {
        InitializeComponent();
    }

    public GenderRadioButton (IContainer container)
    {
        container.Add(this);

        InitializeComponent();
    }

    public Genders gender{ get; set; }
}

Use a common event handler for the GenderRadioButtons

private void Gender_CheckedChanged(Object sender, EventArgs e)
{
    if (((RadioButton)sender).Checked)
    {
        //get selected value
        Genders myGender = ((GenderRadioButton)sender).Gender;
        //get the name of the enum value
        string GenderName = Enum.GetName(typeof(Genders ), myGender);
        //do any work required when you change gender
        switch (myGender)
        {
            case Genders.Male:
                break;
            case Genders.Female:
                break;
            default:
                break;
        }
    }
}

What is the difference between declarative and imperative paradigm in programming?

In computer science, declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.

From http://en.wikipedia.org/wiki/Declarative_programming

in a nutshell the declarative language is simpler because it lacks the complexity of control flow ( loops, if statements, etc. )

A good comparison is the ASP.Net 'code-behind' model. You have declarative '.ASPX' files and then the imperative 'ASPX.CS' code files. I often find that if I can do all I need in the declarative half of the script a lot more people can follow what's being done.

Javascript format date / time

For the date part:(month is 0-indexed while days are 1-indexed)

var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' +  date.getFullYear());

for the time you'll want to create a function to test different situations and convert.

Difference between using gradlew and gradle

gradlew is a wrapper(w - character) that uses gradle.

Under the hood gradlew performs three main things:

  • Download and install the correct gradle version
  • Parse the arguments
  • Call a gradle task

Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.

To create a wrapper run:

gradle wrapper

This command generate:

gradle-wrapper.properties will contain the information about the Gradle distribution

*./ Is used on Unix to specify the current directory

jQuery .val() vs .attr("value")

There is a big difference between an objects properties and an objects attributes

See this questions (and its answers) for some of the differences: .prop() vs .attr()

The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.

jQuery when element becomes visible

I just Improved ProllyGeek`s answer

Someone may find it useful. you can access displayChanged(event, state) event when .show(), .hide() or .toggle() is called on element

(function() {
  var eventDisplay = new $.Event('displayChanged'),
    origShow = $.fn.show,
    origHide = $.fn.hide;
  //
  $.fn.show = function() {
    origShow.apply(this, arguments);
    $(this).trigger(eventDisplay,['show']);
  };
  //
  $.fn.hide = function() {
    origHide.apply(this, arguments);
    $(this).trigger(eventDisplay,['hide']);
  };
  //
})();

$('#header').on('displayChanged', function(e,state) {
      console.log(state);
});

$('#header').toggle(); // .show() .hide() supported

Difference between web reference and service reference?

The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.

You can access web references via the advanced options in add service reference (if I recall correctly).

I'd use service reference because as I understand it, it's the newer mechanism of the two.

Horizontal ListView in Android?

I had used horizontal listview link in my project & I got good results. I had been used devsmart library initially but it gave me some issues. So best way to use horizontal listview link as it recovered my issues & also I recently launched my app on Google PlayStore using this library & got nice response from users. So I recommend you to use the same library which I mentioned above to show listview horizontally. Enjoy :)

Use tnsnames.ora in Oracle SQL Developer

On the newer versions of macOS, one also has to set java.library.path. The easiest/safest way to do that [1] is by creating ~/.sqldeveloper/<version>/sqldeveloper.conf file and populating it as such:

AddVMOption -Djava.library.path=<instant client directory>

[1] https://community.oracle.com/message/14132189#14132189

download file using an ajax request

To make the browser downloads a file you need to make the request like that:

 function downloadFile(urlToSend) {
     var req = new XMLHttpRequest();
     req.open("GET", urlToSend, true);
     req.responseType = "blob";
     req.onload = function (event) {
         var blob = req.response;
         var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
         var link=document.createElement('a');
         link.href=window.URL.createObjectURL(blob);
         link.download=fileName;
         link.click();
     };

     req.send();
 }

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

Force Internet Explorer to use a specific Java Runtime Environment install?

Use the deployment Toolkit's deployJava.js (though this ensures a minimum version, rather than a specific version)

How to use Class<T> in Java?

In java <T> means Generic class. A Generic Class is a class which can work on any type of data type or in other words we can say it is data type independent.

public class Shape<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

Where T means type. Now when you create instance of this Shape class you will need to tell the compiler for what data type this will be working on.

Example:

Shape<Integer> s1 = new Shape();
Shape<String> s2 = new Shape();

Integer is a type and String is also a type.

<T> specifically stands for generic type. According to Java Docs - A generic type is a generic class or interface that is parameterized over types.

Gradients in Internet Explorer 9

I understand that IE9 still won't be supporting CSS gradients. Which is a shame, because it's supporting loads of other great new stuff.

You might want to look into CSS3Pie as a way of getting all versions of IE to support various CSS3 features (including gradients, but also border-radius and box-shadow) with the minimum of fuss.

I believe CSS3Pie works with IE9 (I've tried it on the pre-release versions, but not yet on the current beta).

Spin or rotate an image on hover

It's very simple.

  1. You add an image.
  2. You create a css property to this image.

    img { transition: all 0.3s ease-in-out 0s; }
    
  3. You add an animation like that:

    img:hover
    {
        cursor: default;
        transform: rotate(360deg);
        transition: all 0.3s ease-in-out 0s;
    }
    

Call one constructor from another

Like this:

public Sample(string str) : this(int.Parse(str)) { }

How to give a pandas/matplotlib bar graph custom colors

You can specify the color option as a list directly to the plot function.

from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np  # I find np.random.randint to be better

# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)

# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))

# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)

To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.

my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.

The last example yields the follow simple gradient of colors for me:

enter image description here

I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.

In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.

Best way to get child nodes

Sounds like you're overthinking it. You've observed the difference between childNodes and children, which is that childNodes contains all nodes, including text nodes consisting entirely of whitespace, while children is a collection of just the child nodes that are elements. That's really all there is to it.

There is nothing unpredictable about either collection, although there are a couple of issues to be aware of:

  • IE <= 8 do not include white space-only text nodes in childNodes while other browsers do
  • IE <= 8 includes comment nodes within children while other browsers only have elements

children, firstElementChild and friends are just conveniences, presenting a filtered view of the DOM restricted to just elements.