Programs & Examples On #Arcmap

ArcMap is a piece of software within the ArcGIS suite. It is utilized for cartographic production as well as geospatial analysis.

Create an Oracle function that returns a table

To return the whole table at once you could change the SELECT to:

SELECT  ...
BULK COLLECT INTO T
FROM    ...

This is only advisable for results that aren't excessively large, since they all have to be accumulated in memory before being returned; otherwise consider the pipelined function as suggested by Charles, or returning a REF CURSOR.

How do I use this JavaScript variable in HTML?

You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.

If you want to display a variable on the screen, this is done with JavaScript.

First, you need somewhere for it to write to:

<body>
    <p id="output"></p>
</body>

Then you need to update your JavaScript code to write to that <p> tag. Make sure you do so after the page is ready.

<script>
window.onload = function(){
    var name = prompt("What's your name?");
    var lengthOfName = name.length

    document.getElementById('output').innerHTML = lengthOfName;
};
</script>

_x000D_
_x000D_
window.onload = function() {_x000D_
  var name = prompt("What's your name?");_x000D_
  var lengthOfName = name.length_x000D_
_x000D_
  document.getElementById('output').innerHTML = lengthOfName;_x000D_
};
_x000D_
<p id="output"></p>
_x000D_
_x000D_
_x000D_

encrypt and decrypt md5

Hashes can not be decrypted check this out.

If you want to encrypt-decrypt, use a two way encryption function of your database like - AES_ENCRYPT (in MySQL).

But I'll suggest CRYPT_BLOWFISH algorithm for storing password. Read this- http://php.net/manual/en/function.crypt.php and http://us2.php.net/manual/en/function.password-hash.php

For Blowfish by crypt() function -

crypt('String', '$2a$07$twentytwocharactersalt$');

password_hash will be introduced in PHP 5.5.

$options = [
    'cost' => 7,
    'salt' => 'BCryptRequires22Chrcts',
];
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);

Once you have stored the password, you can then check if the user has entered correct password by hashing it again and comparing it with the stored value.

Looping through a Scripting.Dictionary using index/item number

Using d.Keys()(i) method is a very bad idea, because on each call it will re-create a new array (you will have significant speed reduction).

Here is an analogue of Scripting.Dictionary called "Hash Table" class from @TheTrick, that support such enumerator: http://www.cyberforum.ru/blogs/354370/blog2905.html

Dim oDict As clsTrickHashTable

Sub aaa()
    Set oDict = New clsTrickHashTable

    oDict.Add "a", "aaa"
    oDict.Add "b", "bbb"

    For i = 0 To oDict.Count - 1
        Debug.Print oDict.Keys(i) & " - " & oDict.Items(i)
    Next
End Sub

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

How do I install PHP cURL on Linux Debian?

Whatever approach you take, make sure in the end that you have an updated version of curl and libcurl. You can do curl --version and see the versions.

Here's what I did to get the latest curl version installed in Ubuntu:

  1. sudo add-apt-repository "deb http://mirrors.kernel.org/ubuntu wily main"
  2. sudo apt-get update
  3. sudo apt-get install curl

What are the differences between the urllib, urllib2, urllib3 and requests module?

A key point that I find missing in the above answers is that urllib returns an object of type <class http.client.HTTPResponse> whereas requests returns <class 'requests.models.Response'>.

Due to this, read() method can be used with urllib but not with requests.

P.S. : requests is already rich with so many methods that it hardly needs one more as read() ;>

Call Activity method from adapter

In Kotlin there is now a cleaner way by using lambda functions, no need for interfaces:

class MyAdapter(val adapterOnClick: (Any) -> Unit) {
    fun setItem(item: Any) {
        myButton.setOnClickListener { adapterOnClick(item) }
    }
}

class MyActivity {
    override fun onCreate(savedInstanceState: Bundle?) {
        var myAdapter = MyAdapter { item -> doOnClick(item) }
    }


    fun doOnClick(item: Any) {

    }
}

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

How do I find an array item with TypeScript? (a modern, easier way)

Part One - Polyfill

For browsers that haven't implemented it, a polyfill for array.find. Courtesy of MDN.

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

Part Two - Interface

You need to extend the open Array interface to include the find method.

interface Array<T> {
    find(predicate: (search: T) => boolean) : T;
}

When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.

Part Three - Use it

The variable x will have the expected type... { id: number }

var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);

How to print Two-Dimensional Array like table

A part from @djechlin answer, you should change the rows and columns. Since you are taken as 7 rows and 5 columns, but actually you want is 7 columns and 5 rows.

Do this way:-

int twoDm[][]= new int[5][7];

for(i=0;i<5;i++){
    for(j=0;j<7;j++) {
        System.out.print(twoDm[i][j]+" ");
    }
    System.out.println("");
}

Multiple conditions in a C 'for' loop

The comma expression takes on the value of the last (eg. right-most) expression.

So in your first loop, the only controlling expression is i<=5; and j>=0 is ignored.

In the second loop, j>=0 controls the loop, and i<=5 is ignored.


As for a reason... there is no reason. This code is just wrong. The first part of the comma-expressions does nothing except confuse programmers. If a serious programmer wrote this, they should be ashamed of themselves and have their keyboard revoked.

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

Upgrade python in a virtualenv

I wasn't able to create a new virtualenv on top of the old one. But there are tools in pip which make it much faster to re-install requirements into a brand new venv. Pip can build each of the items in your requirements.txt into a wheel package, and store that in a local cache. When you create a new venv and run pip install in it, pip will automatically use the prebuilt wheels if it finds them. Wheels install much faster than running setup.py for each module.

My ~/.pip/pip.conf looks like this:

[global]
download-cache = /Users/me/.pip/download-cache
find-links =
/Users/me/.pip/wheels/

[wheel]
wheel-dir = /Users/me/.pip/wheels

I install wheel (pip install wheel), then run pip wheel -r requirements.txt. This stores the built wheels in the wheel-dir in my pip.conf.

From then on, any time I pip install any of these requirements, it installs them from the wheels, which is pretty quick.

Ruby value of a hash key?

I didn't understand your problem clearly but I think this is what you're looking for(Based on my understanding)

  person =   {"name"=>"BillGates", "company_name"=>"Microsoft", "position"=>"Chairman"}

  person.delete_if {|key, value| key == "name"} #doing something if the key == "something"

  Output: {"company_name"=>"Microsoft", "position"=>"Chairman"}

MVC 4 Data Annotations "Display" Attribute

If two different views are sharing the same model (for instance, maybe one is for mobile output and one is regular), it could be nice to have the string reside in a single place: as metadata on the ViewModel.

Additionally, if you had an inherited version of the model that necessitated a different display, it could be useful. For instance:

public class BaseViewModel
{
    [Display(Name = "Basic Name")]
    public virtual string Name { get; set; }
}

public class OtherViewModel : BaseViewModel
{
    [Display(Name = "Customized Inherited Name")]
    public override string Name { get; set; }
}

I'll admit that that example is pretty contrived...

Those are the best arguments in favor of using the attribute that I can come up with. My personal opinion is that, for the most part, that sort of thing is best left to the markup.

How to tell if a file is git tracked (by shell exit code)?

I suggest a custom alias on you .gitconfig.

You have to way to do:

1) With git command:

git config --global alias.check-file <command>

2) Editing ~/.gitconfig and add this line on alias section:

[alias]
    check-file = "!f() { if [ $# -eq 0 ]; then echo 'Filename missing!'; else tracked=$(git ls-files ${1}); if [[ -z ${tracked} ]]; then echo 'File not tracked'; else echo 'File tracked'; fi; fi;  };  f"

Once launched command (1) or saved file (2), on your workspace you can test it:

$ git check-file
$ Filename missing 

$ git check-file README.md
$ File tracked 

$ git check-file foo
$ File not tracked

How to get a path to a resource in a Java JAR file

I spent a while messing around with this problem, because no solution I found actually worked, strangely enough! The working directory is frequently not the directory of the JAR, especially if a JAR (or any program, for that matter) is run from the Start Menu under Windows. So here is what I did, and it works for .class files run from outside a JAR just as well as it works for a JAR. (I only tested it under Windows 7.)

try {
    //Attempt to get the path of the actual JAR file, because the working directory is frequently not where the file is.
    //Example: file:/D:/all/Java/TitanWaterworks/TitanWaterworks-en.jar!/TitanWaterworks.class
    //Another example: /D:/all/Java/TitanWaterworks/TitanWaterworks.class
    PROGRAM_DIRECTORY = getClass().getClassLoader().getResource("TitanWaterworks.class").getPath(); // Gets the path of the class or jar.

    //Find the last ! and cut it off at that location. If this isn't being run from a jar, there is no !, so it'll cause an exception, which is fine.
    try {
        PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(0, PROGRAM_DIRECTORY.lastIndexOf('!'));
    } catch (Exception e) { }

    //Find the last / and cut it off at that location.
    PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(0, PROGRAM_DIRECTORY.lastIndexOf('/') + 1);
    //If it starts with /, cut it off.
    if (PROGRAM_DIRECTORY.startsWith("/")) PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(1, PROGRAM_DIRECTORY.length());
    //If it starts with file:/, cut that off, too.
    if (PROGRAM_DIRECTORY.startsWith("file:/")) PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(6, PROGRAM_DIRECTORY.length());
} catch (Exception e) {
    PROGRAM_DIRECTORY = ""; //Current working directory instead.
}

Deep copy in ES6 using the spread syntax

From MDN

Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).

Personally, I suggest using Lodash's cloneDeep function for multi-level object/array cloning.

Here is a working example:

_x000D_
_x000D_
const arr1 = [{ 'a': 1 }];_x000D_
_x000D_
const arr2 = [...arr1];_x000D_
_x000D_
const arr3 = _.clone(arr1);_x000D_
_x000D_
const arr4 = arr1.slice();_x000D_
_x000D_
const arr5 = _.cloneDeep(arr1);_x000D_
_x000D_
const arr6 = [...{...arr1}]; // a bit ugly syntax but it is working!_x000D_
_x000D_
_x000D_
// first level_x000D_
console.log(arr1 === arr2); // false_x000D_
console.log(arr1 === arr3); // false_x000D_
console.log(arr1 === arr4); // false_x000D_
console.log(arr1 === arr5); // false_x000D_
console.log(arr1 === arr6); // false_x000D_
_x000D_
// second level_x000D_
console.log(arr1[0] === arr2[0]); // true_x000D_
console.log(arr1[0] === arr3[0]); // true_x000D_
console.log(arr1[0] === arr4[0]); // true_x000D_
console.log(arr1[0] === arr5[0]); // false_x000D_
console.log(arr1[0] === arr6[0]); // false
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
_x000D_
_x000D_

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

Make an exception handler like this,

private int ConvertIntoNumeric(String xVal)
{
 try
  { 
     return Integer.parseInt(xVal);
  }
 catch(Exception ex) 
  {
     return 0; 
  }
}

.
.
.
.

int xTest = ConvertIntoNumeric("N/A");  //Will return 0

Difference between signed / unsigned char

This because a char is stored at all effects as a 8-bit number. Speaking about a negative or positive char doesn't make sense if you consider it an ASCII code (which can be just signed*) but makes sense if you use that char to store a number, which could be in range 0-255 or in -128..127 according to the 2-complement representation.

*: it can be also unsigned, it actually depends on the implementation I think, in that case you will have access to extended ASCII charset provided by the encoding used

How to perform grep operation on all files in a directory?

If you want to do multiple commands, you could use:

for I in `ls *.sql`
do
    grep "foo" $I >> foo.log
    grep "bar" $I >> bar.log
done

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

Rising to @Ankan-Zerob's challenge, this is my estimate of the maximum length which can be stored in each text type measured in words:

      Type |         Bytes | English words | Multi-byte words
-----------+---------------+---------------+-----------------
  TINYTEXT |           255 |           ±44 |              ±23
      TEXT |        65,535 |       ±11,000 |           ±5,900
MEDIUMTEXT |    16,777,215 |    ±2,800,000 |       ±1,500,000
  LONGTEXT | 4,294,967,295 |  ±740,000,000 |     ±380,000,000

In English, 4.8 letters per word is probably a good average (eg norvig.com/mayzner.html), though word lengths will vary according to domain (e.g. spoken language vs. academic papers), so there's no point being too precise. English is mostly single-byte ASCII characters, with very occasional multi-byte characters, so close to one-byte-per-letter. An extra character has to be allowed for inter-word spaces, so I've rounded down from 5.8 bytes per word. Languages with lots of accents such as say Polish would store slightly fewer words, as would e.g. German with longer words.

Languages requiring multi-byte characters such as Greek, Arabic, Hebrew, Hindi, Thai, etc, etc typically require two bytes per character in UTF-8. Guessing wildly at 5 letters per word, I've rounded down from 11 bytes per word.

CJK scripts (Hanzi, Kanji, Hiragana, Katakana, etc) I know nothing of; I believe characters mostly require 3 bytes in UTF-8, and (with massive simplification) they might be considered to use around 2 characters per word, so they would be somewhere between the other two. (CJK scripts are likely to require less storage using UTF-16, depending).

This is of course ignoring storage overheads etc.

ImportError: No module named site on Windows

If somebody will find that it's still not working under non-admin users:

Example error:

ImportError: No module named iso8601

you need to set '--always-unzip' option for easy_install:

easy_install --always-unzip python-keystoneclient

It will unzip your egg files and will allow import to find em.

MySQL: How to add one day to datetime field in query

Have a go with this, as this is how I would do it :)

SELECT * 
FROM fab_scheduler
WHERE custid = '123456'
AND CURDATE() = DATE(DATE_ADD(eventdate, INTERVAL 1 DAY))

Adding data attribute to DOM

 $(document.createElement("img")).attr({
                src: 'https://graph.facebook.com/'+friend.id+'/picture',
                title: friend.name ,
                'data-friend-id':friend.id,
                'data-friend-name':friend.name
            }).appendTo(divContainer);

Count all duplicates of each value

This is quite simple.

Assuming the data is stored in a column called A in a table called T, you can use

select A, count(A) from T group by A

js window.open then print()

function printCrossword(printContainer) {
    var DocumentContainer = getElement(printContainer);
    var WindowObject = window.open('', "PrintWindow", "width=5,height=5,top=200,left=200,toolbars=no,scrollbars=no,status=no,resizable=no");
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
}

How to escape a JSON string to have it in a URL?

Using encodeURIComponent():

var url = 'index.php?data='+encodeURIComponent(JSON.stringify({"json":[{"j":"son"}]})),

Access key value from Web.config in Razor View-MVC3 ASP.NET

@System.Configuration.ConfigurationManager.AppSettings["myKey"]

How to declare a constant map in Golang?

Your syntax is incorrect. To make a literal map (as a pseudo-constant), you can do:

var romanNumeralDict = map[int]string{
  1000: "M",
  900 : "CM",
  500 : "D",
  400 : "CD",
  100 : "C",
  90  : "XC",
  50  : "L",
  40  : "XL",
  10  : "X",
  9   : "IX",
  5   : "V",
  4   : "IV",
  1   : "I",
}

Inside a func you can declare it like:

romanNumeralDict := map[int]string{
...

And in Go there is no such thing as a constant map. More information can be found here.

Try it out on the Go playground.

Which to use <div class="name"> or <div id="name">?

ID is suitable for the elements which appears only once Like Logo sidebar container

And Class is suitable for the elements which has same UI but they can be appear more than once. Like

.feed in the #feeds Container

No provider for Http StaticInjectorError

Add these two file in your app.module.ts

import { FileTransfer } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';

after that declare these to in provider..

providers: [
    Api,
    Items,
    User,
    Camera,
    File,
    FileTransfer];

This is work for me.

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Use preventDefault() to stop the event of submit button and in ajax call success submit the form using submit():

$('#btnSave').click(function (e) {
    e.preventDefault(); // <------------------ stop default behaviour of button
    var element = this;    
    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.status == "Success") {
                alert("Done");
                $(element).closest("form").submit(); //<------------ submit form
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

Github: error cloning my private repository

I found a good solution for adding/updating the CA certificates on RHEL/CentOS 6 which is the root cause reported issue.

Since they become outdated distros, the cacert authorities in that system has not been updated until executing the command sudo yum update.

Didn't realize the issue until the GIT_CURL_VERBOSE mode shows the cacert path issue.

Getting first value from map in C++

A map will not keep insertion order. Use *(myMap.begin()) to get the value of the first pair (the one with the smallest key when ordered).

You could also do myMap.begin()->first to get the key and myMap.begin()->second to get the value.

How to open a specific port such as 9090 in Google Compute Engine

Creating firewall rules

Please review the firewall rule components [1] if you are unfamiliar with firewall rules in GCP. Firewall rules are defined at the network level, and only apply to the network where they are created; however, the name you choose for each of them must be unique to the project.

For Cloud Console:

  1. Go to the Firewall rules page in the Google Cloud Platform Console.
  2. Click Create firewall rule.
  3. Enter a Name for the firewall rule. This name must be unique for the project.
  4. Specify the Network where the firewall rule will be implemented.
  5. Specify the Priority of the rule. The lower the number, the higher the priority.
  6. For the Direction of traffic, choose ingress or egress.
  7. For the Action on match, choose allow or deny.
  8. Specify the Targets of the rule.

    • If you want the rule to apply to all instances in the network, choose All instances in the network.
    • If you want the rule to apply to select instances by network (target) tags, choose Specified target tags, then type the tags to which the rule should apply into the Target tags field.
    • If you want the rule to apply to select instances by associated service account, choose Specified service account, indicate whether the service account is in the current project or another one under Service account scope, and choose or type the service account name in the Target service account field.
  9. For an ingress rule, specify the Source filter:

    • Choose IP ranges and type the CIDR blocks into the Source IP ranges field to define the source for incoming traffic by IP address ranges. Use 0.0.0.0/0 for a source from any network.
    • Choose Subnets then mark the ones you need from the Subnets pop-up button to define the source for incoming traffic by subnet name.
    • To limit source by network tag, choose Source tags, then type the network tags in to the Source tags field. For the limit on the number of source tags, see VPC Quotas and Limits. Filtering by source tag is only available if the target is not specified by service account. For more information, see filtering by service account vs.network tag.
    • To limit source by service account, choose Service account, indicate whether the service account is in the current project or another one under Service account scope, and choose or type the service account name in the Source service account field. Filtering by source service account is only available if the target is not specified by network tag. For more information, see filtering by service account vs. network tag.
    • Specify a Second source filter if desired. Secondary source filters cannot use the same filter criteria as the primary one.
  10. For an egress rule, specify the Destination filter:

    • Choose IP ranges and type the CIDR blocks into the Destination IP ranges field to define the destination for outgoing traffic by IP address ranges. Use 0.0.0.0/0 to mean everywhere.
    • Choose Subnets then mark the ones you need from the Subnets pop-up button to define the destination for outgoing traffic by subnet name.
  11. Define the Protocols and ports to which the rule will apply:

    • Select Allow all or Deny all, depending on the action, to have the rule apply to all protocols and ports.

    • Define specific protocols and ports:

      • Select tcp to include the TCP protocol and ports. Enter all or a comma delimited list of ports, such as 20-22, 80, 8080.
      • Select udp to include the UDP protocol and ports. Enter all or a comma delimited list of ports, such as 67-69, 123.
      • Select Other protocols to include protocols such as icmp or sctp.
  12. (Optional) You can create the firewall rule but not enforce it by setting its enforcement state to disabled. Click Disable rule, then select Disabled.

  13. (Optional) You can enable firewall rules logging:

    • Click Logs > On.
    • Click Turn on.
  14. Click Create.

Link: [1] https://cloud.google.com/vpc/docs/firewalls#firewall_rule_components

How to store a byte array in Javascript

I wanted a more exact and useful answer to this question. Here's the real answer (adjust accordingly if you want a byte array specifically; obviously the math will be off by a factor of 8 bits : 1 byte):

class BitArray {
  constructor(bits = 0) {
    this.uints = new Uint32Array(~~(bits / 32));
  }

  getBit(bit) {
    return (this.uints[~~(bit / 32)] & (1 << (bit % 32))) != 0 ? 1 : 0;
  }

  assignBit(bit, value) {
    if (value) {
      this.uints[~~(bit / 32)] |= (1 << (bit % 32));
    } else {
      this.uints[~~(bit / 32)] &= ~(1 << (bit % 32));
    }
  }

  get size() {
    return this.uints.length * 32;
  }

  static bitsToUints(bits) {
    return ~~(bits / 32);
  }
}

Usage:

let bits = new BitArray(500);
for (let uint = 0; uint < bits.uints.length; ++uint) {
  bits.uints[uint] = 457345834;
}
for (let bit = 0; bit < 50; ++bit) {
  bits.assignBit(bit, 1);
}
str = '';
for (let bit = bits.size - 1; bit >= 0; --bit) {
  str += bits.getBit(bit);
}
str;

Output:

"00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000111111111111111111
 11111111111111111111111111111111"

Note: This class is really slow to e.g. assign bits (i.e. ~2s per 10 million assignments) if it's created as a global variable, at least in the Firefox 76.0 Console on Linux... If, on the other hand, it's created as a variable (i.e. let bits = new BitArray(1e7);), then it's blazingly fast (i.e. ~300ms per 10 million assignments)!


For more info, see here:

Note that I used Uint32Array because there's no way to directly have a bit/byte array (that you can interact with directly) and because even though there's a BigUint64Array, JS only supports 32 bits:

Bitwise operators treat their operands as a sequence of 32 bits

...

The operands of all bitwise operators are converted to...32-bit integers

What's the proper way to "go get" a private repository?

For people using private GitLabs, here's a snippet that may help: https://gist.github.com/MicahParks/1ba2b19c39d1e5fccc3e892837b10e21

Also pasted below:

Problem

The go command line tool needs to be able to fetch dependencies from your private GitLab, but authenticaiton is required.

This assumes your private GitLab is hosted at privategitlab.company.com.

Environment variables

The following environment variables are recommended:

export GO111MODULE=on
export GOPRIVATE=privategitlab.company.com

The above lines might fit best in your shell startup, like a ~/.bashrc.

Explanation

GO111MODULE=on tells Golang command line tools you are using modules. I have not tested this with projects not using Golang modules on a private GitLab.

GOPRIVATE=privategitlab.company.com tells Golang command line tools to not use public internet resources for the hostnames listed (like the public module proxy).

Get a personal access token from your private GitLab

To future proof these instructions, please follow this guide from the GitLab docs. I know that the read_api scope is required for Golang command line tools to work, and I may suspect read_repository as well, but have not confirmed this.

Set up the ~/.netrc

In order for the Golang command line tools to authenticate to GitLab, a ~/.netrc file is best to use.

To create the file if it does not exist, run the following commands:

touch ~/.netrc
chmod 600 ~/.netrc

Now edit the contents of the file to match the following:

machine privategitlab.company.com login USERNAME_HERE password TOKEN_HERE

Where USERNAME_HERE is replaced with your GitLab username and TOKEN_HERE is replaced with the access token aquired in the previous section.

Common mistakes

Do not set up a global git configuration with something along the lines of this:

git config --global url."[email protected]:".insteadOf "https://privategitlab.company.com"

I beleive at the time of writing this, the SSH git is not fully supported by Golang command line tools and this may cause conflicts with the ~/.netrc.

Bonus: SSH config file

For regular use of the git tool, not the Golang command line tools, it's convient to have a ~/.ssh/config file set up. In order to do this, run the following commands:

mkdir ~/.ssh
chmod 700 ~/.ssh
touch ~/.ssh/config
chmod 600 ~/.ssh/config

Please note the permissions on the files and directory above are essentail for SSH to work in it's default configuration on most Linux systems.

Then, edit the ~/.ssh/config file to match the following:

Host privategitlab.company.com
  Hostname privategitlab.company.com
  User USERNAME_HERE
  IdentityFile ~/.ssh/id_rsa

Please note the spacing in the above file matters and will invalidate the file if it is incorrect.

Where USERNAME_HERE is your GitLab username and ~/.ssh/id_rsa is the path to your SSH private key in your file system. You've already uploaded its public key to GitLab. Here are some instructions.

UIView bottom border?

You can add a separate UIView with 1 point height and gray background color to self.view and position it right below toScrollView.

EDIT: Unless you have a good reason (want to use some services of UIView which are not offered by CALayer), you should use CALayer as @MattDiPasquale suggests. UIView has a greater overhead, which might not be a problem in most cases, but still, the other solution is more elegant.

Reason to Pass a Pointer by Reference in C++?

You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to.

This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.

In Python, is there an elegant way to print a list in a custom format without explicit looping?

from time import clock
from random import sample

n = 500
myList = sample(xrange(10000),n)
#print myList

A,B,C,D = [],[],[],[]

for i in xrange(100):
    t0 = clock()
    ecr =( '\n'.join('{}: {}'.format(*k) for k in enumerate(myList)) )
    A.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join(str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList))
    B.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join(map(lambda x: '%s: %s' % x, enumerate(myList)))
    C.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join('%s: %s' % x for x in enumerate(myList))
    D.append(clock()-t0)

print '\n'.join(('t1 = '+str(min(A))+'   '+'{:.1%}.'.format(min(A)/min(D)),
                 't2 = '+str(min(B))+'   '+'{:.1%}.'.format(min(B)/min(D)),
                 't3 = '+str(min(C))+'   '+'{:.1%}.'.format(min(C)/min(D)),
                 't4 = '+str(min(D))+'   '+'{:.1%}.'.format(min(D)/min(D))))

For n=500:

150.8%.
142.7%.
110.8%.
100.0%.

For n=5000:

153.5%.
176.2%.
109.7%.
100.0%.

Oh, I see now: only the solution 3 with map() fits with the title of the question.

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

If you have changed your assembly version or copied a different version of the managed library stated in the error you may also have previously compiled files referencing the wrong version. A 'Rebuild All' (or deleting you 'bin and 'obj' folders as mentioned in an earlier comment) should fix this case.

Cannot read property 'getContext' of null, using canvas

This might seem like overkill, but if in another case you were trying to load a canvas from js (like I am doing), you could use a setInterval function and an if statement to constantly check if the canvas has loaded.

//set up the interval
var thisInterval = setInterval(function{
  //this if statment checks if the id "thisCanvas" is linked to something
  if(document.getElementById("thisCanvas") != null){
    //do what you want


    //clearInterval() will remove the interval if you have given your interval a name.
    clearInterval(thisInterval)
  }
//the 500 means that you will loop through this every 500 milliseconds (1/2 a second)
},500)

(In this example the canvas I am trying to load has an id of "thisCanvas")

Tick symbol in HTML/XHTML

Coming very late to the party, I found that &check; (✓) worked in Opera. I haven't tested it on any other browsers, but it might be useful for some people.

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

You could use jQuery to add an event listener on the document DOM.

_x000D_
_x000D_
    $(document).on("click", function () {_x000D_
        console.log('clicked');_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Getting an element from a Set

Default Set in Java is, unfortunately, not designed to provide a "get" operation, as jschreiner accurately explained.

The solutions of using an iterator to find the element of interest (suggested by dacwe) or to remove the element and re-add it with its values updated (suggested by KyleM), could work, but can be very inefficient.

Overriding the implementation of equals so that non-equal objects are "equal", as stated correctly by David Ogren, can easily cause maintenance problems.

And using a Map as an explicit replacement (as suggested by many), imho, makes the code less elegant.

If the goal is to get access to the original instance of the element contained in the set (hope I understood correctly your use case), here is another possible solution.


I personally had your same need while developing a client-server videogame with Java. In my case, each client had copies of the components stored in the server and the problem was whenever a client needed to modify an object of the server.

Passing an object through the internet meant that the client had different instances of that object anyway. In order to match this "copied" instance with the original one, I decided to use Java UUIDs.

So I created an abstract class UniqueItem, which automatically gives a random unique id to each instance of its subclasses.

This UUID is shared between the client and the server instance, so this way it could be easy to match them by simply using a Map.

However directly using a Map in a similar usecase was still inelegant. Someone might argue that using an Map might be more complicated to mantain and handle.

For these reasons I implemented a library called MagicSet, that makes the usage of an Map "transparent" to the developer.

https://github.com/ricpacca/magicset


Like the original Java HashSet, a MagicHashSet (which is one of the implementations of MagicSet provided in the library) uses a backing HashMap, but instead of having elements as keys and a dummy value as values, it uses the UUID of the element as key and the element itself as value. This does not cause overhead in the memory use compared to a normal HashSet.

Moreover, a MagicSet can be used exactly as a Set, but with some more methods providing additional functionalities, like getFromId(), popFromId(), removeFromId(), etc.

The only requirement to use it is that any element that you want to store in a MagicSet needs to extend the abstract class UniqueItem.


Here is a code example, imagining to retrieve the original instance of a city from a MagicSet, given another instance of that city with the same UUID (or even just its UUID).

class City extends UniqueItem {

    // Somewhere in this class

    public void doSomething() {
        // Whatever
    }
}

public class GameMap {
    private MagicSet<City> cities;

    public GameMap(Collection<City> cities) {
        cities = new MagicHashSet<>(cities);
    }

    /*
     * cityId is the UUID of the city you want to retrieve.
     * If you have a copied instance of that city, you can simply 
     * call copiedCity.getId() and pass the return value to this method.
     */
    public void doSomethingInCity(UUID cityId) {
        City city = cities.getFromId(cityId);
        city.doSomething();
    }

    // Other methods can be called on a MagicSet too
}

Read and overwrite a file in Python

Try writing it in a new file..

f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()

Find length (size) of an array in jquery

If length is undefined you can use:

function count(array){

    var c = 0;
    for(i in array) // in returns key, not object
        if(array[i] != undefined)
            c++;

    return c;
}

var total = count(array);

How to initialize a list with constructor?

Are you looking for this?

ContactNumbers = new List<ContactNumber>(){ new ContactNumber("555-5555"),
                                            new ContactNumber("555-1234"),
                                            new ContactNumber("555-5678") };

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

As mentioned in the above answer, by updating the bashrc file you can run the pycharm.sh from anywhere on the linux terminal.

But if you love the icon and wants the Desktop shortcuts for the Pycharm on Ubuntu OS then follow the Below steps,

 Quick way to create Pycharm launcher. 
     1. Start Pycharm using the pycharm.sh cmd from anywhere on the terminal or start the pycharm.sh located under bin folder of the pycharm artifact.
     2. Once the Pycharm application loads, navigate to tools menu and select “Create Desktop Entry..”
     3. Check the box if you want the launcher for all users.
     4. If you Check the box i.e “Create entry for all users”, you will be asked for your password.
     5. A message should appear informing you that it was successful.
     6. Now Restart Pycharm application and you will find Pycharm in Unity dash and Application launcher.."

How to append to the end of an empty list?

append returns None, so at the second iteration you are calling method append of NoneType. Just remove the assignment:

for i in range(0, n):
    list1.append([i])

Unsetting array values in a foreach loop


foreach($images as $key=>$image)                                
{               
   if($image == 'http://i27.tinypic.com/29ykt1f.gif' ||    
   $image == 'http://img3.abload.de/img/10nxjl0fhco.gif' ||    
   $image == 'http://i42.tinypic.com/9pp2tx.gif')     
   { unset($images[$key]); }                               
}

!!foreach($images as $key=>$image

cause $image is the value, so $images[$image] make no sense.

Tomcat base URL redirection

Name your webapp WAR “ROOT.war” or containing folder “ROOT”

How to change position of Toast in Android?

From the documentation,

Positioning your Toast

A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.

wkhtmltopdf: cannot connect to X server

It is recommended to use at least 0.12.2.1.

Starting from wkhtmltopdf >= 0.12.2 it doesn't require X server or emulation anymore. You can download new version from http://wkhtmltopdf.org/downloads.html

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

function checkCharType (charToCheck) {
    // body... 
    var returnValue = "O";
    var charCode = charToCheck.charCodeAt(0);

    if(charCode >= "A".charCodeAt(0) && charCode <= "Z".charCodeAt(0)){

        returnValue = "U";

    }else if (charCode >= "a".charCodeAt(0) &&
                charCode <= "z".charCodeAt(0) ){
        returnValue = "L";
    }else if (charCode >= "0".charCodeAt(0) &&
            charCode <= "9".charCodeAt(0)  ) {
        returnValue = "N";
    }
    return returnValue;
}

var myString = prompt("Enter Some text: ", "Hello world !");

switch (checkCharType(myString)) {
    case "U":
        // statements_1
        document.write("First character was upper case");
        break;

    case "L":
        document.write("First character was a lower case");
        break;
    case "N":
        document.write("First character was a number");
        break
    default:
        // statements_def
        document.write("First character was not a character or a number");
        break;
}
  1. Define a Function checkCharType().By declaring the variable returnValue and initialising it to the Character "O" to indicate it's Some other value.

  2. U for uppercase; L for Lowercase ; N for number

  3. Use the charCodeAt() method to get the character code of the first character.

  4. Using if Statement , which check within what range of values the character code falls.

  5. If it falls between the character codes for A and Z, Its Uppercase, character code between a and z ,Its Lowercase. and so on.

  6. "A".charCode(0)

    var myChar = new String("A"); myChar.charCodeAt(0); "A" : number code "65“

  7. Check the String

How to enable PHP's openssl extension to install Composer?

You need to enable "extension=php_openssl.dll" in both files (php and apache). my pc files path are these :

  1. C:\wamp\bin\php\php5.3.13\php.ini
  2. C:\wamp\bin\apache\apache2.2.22\bin\php.ini

How can I set NODE_ENV=production on Windows?

It seems that

{
   "start_windows": "set NODE_ENV=test"
}

is not working for me. I'm currently trying this on my Windows machine. When I hit:

npm run start_windows

it would execute on the console without errors but when I try to echo

echo %NODE_ENV%

nothing comes out of it, meaning it does not exist and it wasn't set at all...

fatal: bad default revision 'HEAD'

Your repo is yours, what goes on in it is entirely your business until you push or (allow a) fetch or clone. When you deleted your windows repo -- that folder didn't represent your local repo, it was your actual local repo, you deleted everything done in it that was never pushed, fetched or cloned.

edit: Ah, okay, I think I see what's going on here: you pushed to your linux repo but it's not bare and you never worked in it.

Instead of git log, do git log --all. Or git checkoutsome-branch-name.

Then try cloning the repo locally, on your linux box; I bet it works. What are you using to serve your repo on linux? Try cd'ing into its .git directory and git daemon --base-path=. --export-all, if that just sits there then go to your windows box and try git clone git://your.linux.box.ip, if the daemon complains it can't bind add --port=54345 to the daemon invoke and :54345 to the clone url.

How do I turn a String into a InputStreamReader in java?

Does it have to be specifically an InputStreamReader? How about using StringReader?

Otherwise, you could use StringBufferInputStream, but it's deprecated because of character conversion issues (which is why you should prefer StringReader).

How to normalize an array in NumPy to a unit vector?

You can specify ord to get the L1 norm. To avoid zero division I use eps, but that's maybe not great.

def normalize(v):
    norm=np.linalg.norm(v, ord=1)
    if norm==0:
        norm=np.finfo(v.dtype).eps
    return v/norm

Mongoose.js: Find user by username LIKE value

The following query will find the documents with required string case insensitively and with global occurrence also

var name = 'Peter';
    db.User.find({name:{
                         $regex: new RegExp(name, "ig")
                     }
                },function(err, doc) {
                                     //Your code here...
              });

Operand type clash: uniqueidentifier is incompatible with int

Sounds to me like at least one of those tables has defined UserID as a uniqueidentifier, not an int. Did you check the data in each table? What does SELECT TOP 1 UserID FROM each table yield? An int or a GUID?

EDIT

I think you have built a procedure based on all tables that contain a column named UserID. I think you should not have included the aspnet_Membership table in your script, since it's not really one of "your" tables.

If you meant to design your tables around the aspnet_Membership database, then why are the rest of the columns int when that table clearly uses a uniqueidentifier for the UserID column?

Search for an item in a Lua list

This is a swiss-armyknife function you can use:

function table.find(t, val, recursive, metatables, keys, returnBool)
    if (type(t) ~= "table") then
        return nil
    end

    local checked = {}
    local _findInTable
    local _checkValue
    _checkValue = function(v)
        if (not checked[v]) then
            if (v == val) then
                return v
            end
            if (recursive and type(v) == "table") then
                local r = _findInTable(v)
                if (r ~= nil) then
                    return r
                end
            end
            if (metatables) then
                local r = _checkValue(getmetatable(v))
                if (r ~= nil) then
                    return r
                end
            end
            checked[v] = true
        end
        return nil
    end
    _findInTable = function(t)
        for k,v in pairs(t) do
            local r = _checkValue(t, v)
            if (r ~= nil) then
                return r
            end
            if (keys) then
                r = _checkValue(t, k)
                if (r ~= nil) then
                    return r
                end
            end
        end
        return nil
    end

    local r = _findInTable(t)
    if (returnBool) then
        return r ~= nil
    end
    return r
end

You can use it to check if a value exists:

local myFruit = "apple"
if (table.find({"apple", "pear", "berry"}, myFruit)) then
    print(table.find({"apple", "pear", "berry"}, myFruit)) -- 1

You can use it to find the key:

local fruits = {
    apple = {color="red"},
    pear = {color="green"},
}
local myFruit = fruits.apple
local fruitName = table.find(fruits, myFruit)
print(fruitName) -- "apple"

I hope the recursive parameter speaks for itself.

The metatables parameter allows you to search metatables as well.

The keys parameter makes the function look for keys in the list. Of course that would be useless in Lua (you can just do fruits[key]) but together with recursive and metatables, it becomes handy.

The returnBool parameter is a safe-guard for when you have tables that have false as a key in a table (Yes that's possible: fruits = {false="apple"})

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

Actually you can set custom text to that little blue button. In the xml file just use

android:imeActionLabel="whatever"

on your EditText.

Or in the java file use

etEditText.setImeActionLabel("whatever", EditorInfo.IME_ACTION_DONE);

I arbitrarily choose IME_ACTION_DONE as an example of what should go in the second parameter for this function. A full list of these actions can be found here.

It should be noted that this will not cause text to appear on all keyboards on all devices. Some keyboards do not support text on that button (e.g. swiftkey). And some devices don't support it either. A good rule is, if you see text already on the button, this will change it to whatever you'd want.

Enum String Name from Value

you can just cast it

int dbValue = 2;
EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;
string stringName = enumValue.ToString(); //Visible

ah.. kent beat me to it :)

Open text file and program shortcut in a Windows batch file

I was able to figure out the solution:

start notepad "myfile.txt"
"myshortcut.lnk"
exit

Invoking a jQuery function after .each() has completed

I'm using something like this:

$.when(
           $.each(yourArray, function (key, value) {
                // Do Something in loop here
            })
          ).then(function () {
               // After loop ends.
          });

OpenCV & Python - Image too big to display

Try this:

image = cv2.imread("img/Demo.jpg")
image = cv2.resize(image,(240,240))

The image is now resized. Displaying it will render in 240x240.

overlay a smaller image on a larger image python OpenCv

A simple function that blits an image front onto an image back and returns the result. It works with both 3 and 4-channel images and deals with the alpha channel. Overlaps are handled as well.

The output image has the same size as back, but always 4 channels.
The output alpha channel is given by (u+v)/(1+uv) where u,v are the alpha channels of the front and back image and -1 <= u,v <= 1. Where there is no overlap with front, the alpha value from back is taken.

import cv2

def merge_image(back, front, x,y):
    # convert to rgba
    if back.shape[2] == 3:
        back = cv2.cvtColor(back, cv2.COLOR_BGR2BGRA)
    if front.shape[2] == 3:
        front = cv2.cvtColor(front, cv2.COLOR_BGR2BGRA)

    # crop the overlay from both images
    bh,bw = back.shape[:2]
    fh,fw = front.shape[:2]
    x1, x2 = max(x, 0), min(x+fw, bw)
    y1, y2 = max(y, 0), min(y+fh, bh)
    front_cropped = front[y1-y:y2-y, x1-x:x2-x]
    back_cropped = back[y1:y2, x1:x2]

    alpha_front = front_cropped[:,:,3:4] / 255
    alpha_back = back_cropped[:,:,3:4] / 255
    
    # replace an area in result with overlay
    result = back.copy()
    print(f'af: {alpha_front.shape}\nab: {alpha_back.shape}\nfront_cropped: {front_cropped.shape}\nback_cropped: {back_cropped.shape}')
    result[y1:y2, x1:x2, :3] = alpha_front * front_cropped[:,:,:3] + alpha_back * back_cropped[:,:,:3]
    result[y1:y2, x1:x2, 3:4] = (alpha_front + alpha_back) / (1 + alpha_front*alpha_back) * 255

    return result

How to lock orientation of one view controller to portrait mode only in Swift

Swift 4

enter image description here AppDelegate

var orientationLock = UIInterfaceOrientationMask.all

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return self.orientationLock
}
struct AppUtility {
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
        self.lockOrientation(orientation)
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }
}

Your ViewController Add Following line if you need only portrait orientation. you have to apply this to all ViewController need to display portrait mode.

override func viewWillAppear(_ animated: Bool) {
AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.portrait, andRotateTo: UIInterfaceOrientation.portrait)
    }

and that will make screen orientation for others Viewcontroller according to device physical orientation.

override func viewWillDisappear(_ animated: Bool) {
        AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.all)

    }

@class vs. #import

Three simple rules:

  • Only #import the super class, and adopted protocols, in header files (.h files).
  • #import all classes, and protocols, you send messages to in implementation (.m files).
  • Forward declarations for everything else.

If you do forward declaration in the implementation files, then you probably do something wrong.

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

I'd use onMouseOver & onMouseOut. Cause in React

The onMouseEnter and onMouseLeave events propagate from the element being left to the one being entered instead of ordinary bubbling and do not have a capture phase.

Here it is in the React documentation for mouse events.

What is the difference between syntax and semantics in programming languages?

Syntax is the structure or form of expressions, statements, and program units but Semantics is the meaning of those expressions, statements, and program units. Semantics follow directly from syntax. Syntax refers to the structure/form of the code that a specific programming language specifies but Semantics deal with the meaning assigned to the symbols, characters and words.

how to make a countdown timer in java

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class Stopwatch {
static int interval;
static Timer timer;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Input seconds => : ");
    String secs = sc.nextLine();
    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval = Integer.parseInt(secs);
    System.out.println(secs);
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            System.out.println(setInterval());

        }
    }, delay, period);
}

private static final int setInterval() {
    if (interval == 1)
        timer.cancel();
    return --interval;
}
}

Try this.

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

How to mock static methods in c# using MOQ framework?

As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.

Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.

A possible solution is to wrap the static in a proxy with an interface which can be mocked

    public interface IFileProxy {
        void Delete(string path);
    }

    public class FileProxy : IFileProxy {
        public void Delete(string path) {
            System.IO.File.Delete(path);
        }
    }

    public class MyClass {

        private IFileProxy _fileProxy;

        public MyClass(IFileProxy fileProxy) {
            _fileProxy = fileProxy;
        }

        public void DoSomethingAndDeleteFile(string path) {
            // Do Something with file
            // ...
            // Delete
            System.IO.File.Delete(path);
        }

        public void DoSomethingAndDeleteFileUsingProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            _fileProxy.Delete(path);

        }
    }

The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)

Another possibility is to have a 'static proxy' with different implementations of the interface behind it

   public static class FileServices {

        static FileServices() {
            Reset();
        }

        internal static IFileProxy FileProxy { private get; set; }

        public static void Reset(){
           FileProxy = new FileProxy();
        }

        public static void Delete(string path) {
            FileProxy.Delete(path);
        }

    }

Our method now becomes

    public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            FileServices.Delete(path);

    }

For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).

Is there a JSON equivalent of XQuery/XPath?

ObjectPath is a query language similar to XPath or JSONPath, but much more powerful thanks to embedded arithmetic calculations, comparison mechanisms and built-in functions. See the syntax:

Find in the shop all shoes of red color and price less than 50

$..shoes.*[color is "red" and price < 50]

How to change the pop-up position of the jQuery DatePicker control

First I think there should be a afterShowing method in the datepicker object, where you could change the position after jquery has done all its voodoo in the _showDatepicker method. Additionally, a parameter called preferedPosition would be also desirable, so you could set it and jquery modify it in case the dialog is rendered outside the viewport.

There's a "trick" to do this last thing. If you study the _showDatepicker method, you will see the use of a private variable $.datepikcer._pos. That variable will be setup if nobody has set it up before. If you modify that variable before showing the dialog, Jquery will take it and will try to allocate the dialog in that position, and if it renders out of the screen, it will adjust it to make sure it is visible. Sounds good, eh?

Problem is; _pos is private, but if you don't mind that. You can:

$('input.date').datepicker({
    beforeShow: function(input, inst)
    {
        $.datepicker._pos = $.datepicker._findPos(input); //this is the default position
        $.datepicker._pos[0] = whatever; //left
        $.datepicker._pos[1] = whatever; //top
    }
});

But be careful of Jquery-ui updates, because a change in the internal implementation of the _showDatepicker might break your code.

Access 2010 VBA query a table and iterate through results

I know some things have changed in AC 2010. However, the old-fashioned ADODB is, as far as I know, the best way to go in VBA. An Example:

Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Dim SQL As String
SQL = _
    "SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
    "c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
    "FROM tblClient AS c " & _
    "WHERE c.ClientID = @ClientID"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
    Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
    .Parameters.Append prm
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
        Do Until .EOF
            mstrLastName = Nz(!LastName, "")
            mstrFirstName = Nz(!FirstName, "")
            mstrMI = Nz(!MI, "")
            mdDOB = !DOB
            mstrSSN = Nz(!SSN, "")
            mlngRaceID = Nz(!RaceID, -1)
            mlngEthnicityID = Nz(!EthnicityID, -1)
            mlngGenderID = Nz(!GenderID, -1)
            mbooDeleted = Deleted
            mdRecordDate = Nz(!RecordDate, "")

            .MoveNext
        Loop
    End If
    .Close
End With

cn.Close

Set rs = Nothing
Set cn = Nothing

how to open a jar file in Eclipse

A project is not exactly the same thing as an executable jar file.

For starters, a project generally contains source code, while an executable jar file generally doesn't. Again, generally speaking, you need to export an Eclipse project to obtain a file suitable for importing.

Maximum length of the textual representation of an IPv6 address?

Answered my own question:

IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).

So that's 39 characters max.

Correctly determine if date string is a valid date in that format

This option is not only simple but also accepts almost any format, although with non-standard formats it can be buggy.

$timestamp = strtotime($date);
return $timestamp ? $date : null;

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

How to specify the bottom border of a <tr>?

What I want to say here is like some kind of add-on on @Suciu Lucian's answer.

The weird situation I ran into is that when I apply the solution of @Suciu Lucian in my file, it works in Chrome but not in Safari (and did not try in Firefox). After I studied the guide of styling table border published by w3.org, I found something alternative:

table.myTable{
  border-spacing: 0;
}

table.myTable td{
  border-bottom:1px solid red;
}

Yes you have to style the td instead of the tr.

How to enable Auto Logon User Authentication for Google Chrome

While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.

Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:

  • Launching Chrome with the auth-server-whitelist command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz". Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.
  • Installing, enabling, and configuring the AuthServerWhitelist/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.

Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:

  1. Download and unzip the latest Chrome policy templates
  2. Start > Run > gpedit.msc
  3. Navigate to Local Computer Policy > Computer Configuration > Administrative Templates
  4. Right-click Administrative Templates, and select Add/Remove Templates
  5. Add the windows\adm\en-US\chrome.adm template via the dialog
  6. In Computer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication enable and configure Authentication server whitelist
  7. Restart Chrome and navigate to chrome://policy to view active policies

XPath to select multiple tags

You can avoid the repetition with an attribute test instead:

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

Contrary to Dimitre's antagonistic opinion, the above is not incorrect in a vacuum where the OP has not specified the interaction with namespaces. The self:: axis is namespace restrictive, local-name() is not. If the OP's intention is to capture c|d|e regardless of namespace (which I'd suggest is even a likely scenario given the OR nature of the problem) then it is "another answer that still has some positive votes" which is incorrect.

You can't be definitive without definition, though I'm quite happy to delete my answer as genuinely incorrect if the OP clarifies his question such that I am incorrect.

How to change title of Activity in Android?

If you're using onCreateOptionsMenu, you can also add setTitle code in onCreateOptionsMenu.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);

    setTitle("Neue Aktivität");
    return true;
}

What should a JSON service return on failure / error

Rails scaffolds use 422 Unprocessable Entity for these kinds of errors. See RFC 4918 for more information.

A failure occurred while executing com.android.build.gradle.internal.tasks

search your code you must be referring to color in color.xml in an xml drawable. go and give hex code instead of referencing....

Example: in drawable.xml you must have called

android:fillColor="@color/blue"

change it to android:fillColor="#ffaacc" hope it solve your problem...

How to prevent Browser cache on Angular 2 site?

Found a way to do this, simply add a querystring to load your components, like so:

@Component({
  selector: 'some-component',
  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})

This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:

new Date().toISOString() //2016-09-24T00:43:21.584Z

And substring some characters so that it will only change after an hour for example:

new Date().toISOString().substr(0,13) //2016-09-24T00

Hope this helps

How to set background color of a button in Java GUI?

Changing the background property might not be enough as the component won't look like a button anymore. You might need to re-implement the paint method as in here to get a better result:

enter image description here

iOS: Modal ViewController with transparent background

In iOS 8.0 and above it can be done by setting the property modalPresentationStyle to UIModalPresentationOverCurrentContext

//Set property **definesPresentationContext** YES to avoid presenting over presenting-viewController's navigation bar

self.definesPresentationContext = YES; //self is presenting view controller
presentedController.view.backgroundColor = [YOUR_COLOR with alpha OR clearColor]
presentedController.modalPresentationStyle = UIModalPresentationOverCurrentContext;

[self presentViewController:presentedController animated:YES completion:nil];

See Image Attached

Create code first, many to many, with additional fields in association table

I'll just post the code to do this using the fluent API mapping.

public class User {
    public int UserID { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }

    public ICollection<UserEmail> UserEmails { get; set; }
}

public class Email {
    public int EmailID { get; set; }
    public string Address { get; set; }

    public ICollection<UserEmail> UserEmails { get; set; }
}

public class UserEmail {
    public int UserID { get; set; }
    public int EmailID { get; set; }
    public bool IsPrimary { get; set; }
}

On your DbContext derived class you could do this:

public class MyContext : DbContext {
    protected override void OnModelCreating(DbModelBuilder builder) {
        // Primary keys
        builder.Entity<User>().HasKey(q => q.UserID);
        builder.Entity<Email>().HasKey(q => q.EmailID);
        builder.Entity<UserEmail>().HasKey(q => 
            new { 
                q.UserID, q.EmailID
            });

        // Relationships
        builder.Entity<UserEmail>()
            .HasRequired(t => t.Email)
            .WithMany(t => t.UserEmails)
            .HasForeignKey(t => t.EmailID)

        builder.Entity<UserEmail>()
            .HasRequired(t => t.User)
            .WithMany(t => t.UserEmails)
            .HasForeignKey(t => t.UserID)
    }
}

It has the same effect as the accepted answer, with a different approach, which is no better nor worse.

Setting log level of message at runtime in slf4j

no, it has a number of methods, info(), debug(), warn(), etc (this replaces the priority field)

have a look at http://www.slf4j.org/api/org/slf4j/Logger.html for the full Logger api.

How to elegantly check if a number is within a range?

There are a lot of options:

int x = 30;
if (Enumerable.Range(1,100).Contains(x))
    //true

if (x >= 1 && x <= 100)
    //true

Also, check out this SO post for regex options.

how to implement login auth in node.js

Why not disecting a bare minimum authentication module?

SweetAuth

A lightweight, zero-configuration user authentication module which doesn't depend on a database.

https://www.npmjs.com/package/sweet-auth

It's simple as:

app.get('/private-page', (req, res) => {

    if (req.user.isAuthorized) {
        // user is logged in! send the requested page
        // you can access req.user.email
    }
    else {
        // user not logged in. redirect to login page
    }
})

How to download dependencies in gradle

This version builds on Robert Elliot's, but I'm not 100% sure of its efficacy.

// There are a few dependencies added by one of the Scala plugins that this cannot reach.
task downloadDependencies {
  description "Pre-downloads *most* dependencies"
  doLast {
    configurations.getAsMap().each { name, config ->
      println "Retrieving dependencies for $name"
      try {
        config.files
      } catch (e) {
        project.logger.info e.message // some cannot be resolved, silentlyish skip them
      }
    }
  }
}

I tried putting it into configuration instead of action (by removing doLast) and it broke zinc. I worked around it, but the end result was the same with or without. So, I left it as an explicit state. It seems to work enough to reduce the dependencies that have to be downloaded later, but not eliminate them in my case. I think one of the Scala plugins adds dependencies later.

Pretty printing XML with javascript

All of the javascript functions given here won't work for an xml document having unspecified white spaces between the end tag '>' and the start tag '<'. To fix them, you just need to replace the first line in the functions

var reg = /(>)(<)(\/*)/g;

by

var reg = /(>)\s*(<)(\/*)/g;

Index inside map() function

You will be able to get the current iteration's index for the map method through its 2nd parameter.

Example:

const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return currElement; //equivalent to list[index]
});

Output:

The current iteration is: 0 <br>The current element is: h

The current iteration is: 1 <br>The current element is: e

The current iteration is: 2 <br>The current element is: l

The current iteration is: 3 <br>The current element is: l 

The current iteration is: 4 <br>The current element is: o

See also: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Parameters

callback - Function that produces an element of the new Array, taking three arguments:

1) currentValue
The current element being processed in the array.

2) index
The index of the current element being processed in the array.

3) array
The array map was called upon.

Using FileSystemWatcher to monitor a directory

The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

How can I initialize an ArrayList with all zeroes in Java?

Java 8 implementation (List initialized with 60 zeroes):

List<Integer> list = IntStream.of(new int[60])
                    .boxed()
                    .collect(Collectors.toList());
  • new int[N] - creates an array filled with zeroes & length N
  • boxed() - each element boxed to an Integer
  • collect(Collectors.toList()) - collects elements of stream

How to append new data onto a new line

The answer is not to add a newline after writing your string. That may solve a different problem. What you are asking is how to add a newline before you start appending your string. If you want to add a newline, but only if one does not already exist, you need to find out first, by reading the file.

For example,

with open('hst.txt') as fobj:
    text = fobj.read()

name = 'Bob'

with open('hst.txt', 'a') as fobj:
    if not text.endswith('\n'):
        fobj.write('\n')
    fobj.write(name)

You might want to add the newline after name, or you may not, but in any case, it isn't the answer to your question.

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

How to add composite primary key to table

If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.

enter image description here

How to embed a Google Drive folder in a website

At the time of writing this answer, there was no method to embed which let the user navigate inside folders and view the files without her leaving the website (the method in other answers, makes everything open in a new tab on google drive website), so I made my own tool for it. To embed a drive, paste the iframe code below in your HTML:

<iframe src="https://googledriveembedder.collegefam.com/?key=YOUR_API_KEY&folderid=FOLDER_ID_WHIHCH_IS_PUBLICLY_VIEWABLE" style="border:none;" width="100%"></iframe>

In the above code, you need to have your own API key and the folder ID. You can set the height as per your wish.

To get the API key:

1.) Go to https://console.developers.google.com/ Create a new project.

2.) From the menu button, go to 'APIs and Services' --> 'Dashboard' --> Click on 'Enable APIs and Services'.

3.) Search for 'Google Drive API', enable it. Then go to "credentials' tab, and create credentials. Keep your API key unrestricted.

4.) Copy the newly generated API key.

To get the folder ID:

1.)Go to the google drive folder you want to embed (for example, drive.google.com/drive/u/0/folders/1v7cGug_e3lNT0YjhvtYrwKV7dGY-Nyh5u [this is not a real folder]) Ensure that the folder is publicly shared and visible to anyone.

2.) Copy the part after 'folders/', this is your folder ID.

Now put both the API key and folder id in the above code and embed.

Note: To hide the download button for files, add '&allowdl=no' at the end of the iframe's src URL.

I made the widget keeping mobile users in mind, however it suits both mobile and desktop. If you run into issues, leave a comment here. I have attached some screenshots of the content of the iframe here.

The file preview looks like this The content of the iframe looks like this

Create list of object from another using Java 8 Streams

What you are possibly looking for is map(). You can "convert" the objects in a stream to another by mapping this way:

...
 .map(userMeal -> new UserMealExceed(...))
...

Creating a folder if it does not exists - "Item already exists"

Alternative syntax using the -Not operator and depending on your preference for readability:

if( -Not (Test-Path -Path $TARGETDIR ) )
{
    New-Item -ItemType directory -Path $TARGETDIR
}

Get current language in CultureInfo

This is what i used:

var culture = System.Globalization.CultureInfo.CurrentCulture;

and it's working :)

What is the use of the JavaScript 'bind' method?

As mentioned, Function.bind() lets you specify the context that the function will execute in (that is, it lets you pass in what object the this keyword will resolve to in the body of the function.

A couple of analogous toolkit API methods that perform a similar service:

jQuery.proxy()

Dojo.hitch()

How can I make a horizontal ListView in Android?

Have you looked into using a HorizontalScrollView to wrap your list items? That will allow each of your list items to be horizontally scrollable (what you put in there is up to you, and can make them dynamic items similar to ListView). This will work well if you are only after a single row of items.

How to add "on delete cascade" constraints?

Based off of @Mike Sherrill Cat Recall's answer, this is what worked for me:

ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
  FOREIGN KEY ("parentId")
  REFERENCES "Parent"(id)
  ON DELETE CASCADE;

Converting JavaScript object with numeric keys into array

You simply do it like

var data = {
    "0": "1",
    "1": "2",
    "2": "3",
    "3": "4"
};
var arr = [];
for (var prop in data) {
    arr.push(data[prop]);
}
console.log(arr);

DEMO

Entity Framework : How do you refresh the model when the db changes?

I have found the designer "update from database" can only handle small changes. If you have deleted tables, changed foreign keys or (gasp) changed the signature of a stored procedure with a function mapping, you will eventually get to such a messed up state you will have to either delete all the entities and "add from database" or simply delete the edmx resource and start over.

How to set css style to asp.net button?

If you have a button in asp.net design page like "Default.asp" and you want to create CSS file and specified attributes for a button,labels or other controller. Then first of all create a css page

  1. Right click on Project
  2. Add new item
  3. Select StyleSheet

now you have a css page now write these code in your css page(StyleSheet.css)

StyleSheet.css

.mybtnstyle
{
 border:1px solid Red;
 background-color:Red;
 border-style:groove;
 border-top:5px;
 outline-style:dotted;
}

Default.asp

{

  <head> 
  <title> testing.com </title>
 </head>
<body>
 <b>Using Razer<b/>
<form id="form1" runat="server">
 <link id="Link1" rel="stylesheet" runat="server" media="screen" href="Stylesheet1.css" />
 <asp:Button ID="mybtn" class="mybtn" runat="server" Width="339px"/>
 </form>
 </body>
</html>

}

How to use range-based for() loop with std::map?

If you only want to see the keys/values from your map and like using boost, you can use the boost adaptors with the range based loops:

for (const auto& value : myMap | boost::adaptors::map_values)
{
    std::cout << value << std::endl;
}

there is an equivalent boost::adaptors::key_values

http://www.boost.org/doc/libs/1_51_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html

Rename package in Android Studio

The accepted answer didn't work for me. Here's a python script to change the package name directly on the source files.

"""
Notes:
1 - This script it for python3
2 - Create a backup first
3 - Place on the root folder of the android project you want to change
4 - run `python change_android_studio_pkg_name.py`
5 - Type the old package name
6 - Type the new package name
7 - Clean and Rebuild on Android Studio
8 - SRC folder names won't be changed but app will work
"""

import os, glob, traceback
from pathlib import Path

def rwf(fp, mode="r", data="" ):
    if mode == "r":
        with open(fp, "r", encoding='utf8') as f:
            return(f.read())
    elif mode == "w":
        with open(fp, "w", encoding='utf8') as f:
            f.write(data)

old_pkg = input("Old PKG\n").strip()
new_pkg = input("New PKG\n").strip()

if not old_pkg or not new_pkg:
    exit("Args Missing")

dirname, filename = os.path.split(os.path.abspath(__file__))
file_types = ['xml', 'txt', 'json', 'gradle', 'java']
_fs =  glob.iglob(f"{dirname}/**", recursive=True)
for file_path in _fs:
    ext = Path(file_path).suffix.replace(".", "").lower()
    if os.path.isfile(file_path) and ext in file_types:
        try:
            content = rwf(file_path)
            new_content = content.replace(old_pkg, new_pkg)
            rwf(file_path, "w", new_content)
        except:
            print(traceback.format_exc())
            pass

python3 gist

Prevent form redirect OR refresh on submit?

In the opening tag of your form, set an action attribute like so:

<form id="contactForm" action="#">

What exactly is Spring Framework for?

Basically Spring is a framework for which is a pattern that allows building very decoupled systems.

The problem

For example, suppose you need to list the users of the system and thus declare an interface called UserLister:

public interface UserLister {
    List<User> getUsers();
}

And maybe an implementation accessing a database to get all the users:

public class UserListerDB implements UserLister {
    public List<User> getUsers() {
        // DB access code here
    }
}

In your view you'll need to access an instance (just an example, remember):

public class SomeView {
    private UserLister userLister;

    public void render() {
        List<User> users = userLister.getUsers();
        view.render(users);
    }
}

Note that the code above hasn't initialized the variable userLister. What should we do? If I explicitly instantiate the object like this:

UserLister userLister = new UserListerDB();

...I'd couple the view with my implementation of the class that access the DB. What if I want to switch from the DB implementation to another that gets the user list from a comma-separated file (remember, it's an example)? In that case, I would go to my code again and change the above line to:

UserLister userLister = new UserListerCommaSeparatedFile();

This has no problem with a small program like this but... What happens in a program that has hundreds of views and a similar number of business classes? The maintenance becomes a nightmare!

Spring (Dependency Injection) approach

What Spring does is to wire the classes up by using an XML file or annotations, this way all the objects are instantiated and initialized by Spring and injected in the right places (Servlets, Web Frameworks, Business classes, DAOs, etc, etc, etc...).

Going back to the example in Spring we just need to have a setter for the userLister field and have either an XML file like this:

<bean id="userLister" class="UserListerDB" />

<bean class="SomeView">
    <property name="userLister" ref="userLister" />
</bean>

or more simply annotate the filed in our view class with @Inject:

@Inject
private UserLister userLister;

This way when the view is created it magically will have a UserLister ready to work.

List<User> users = userLister.getUsers();  // This will actually work
                                           // without adding any line of code

It is great! Isn't it?

  • What if you want to use another implementation of your UserLister interface? Just change the XML.
  • What if don't have a UserLister implementation ready? Program a temporal mock implementation of UserLister and ease the development of the view.
  • What if I don't want to use Spring anymore? Just don't use it! Your application isn't coupled to it. Inversion of Control states: "The application controls the framework, not the framework controls the application".

There are some other options for Dependency Injection around there, what in my opinion has made Spring so famous besides its simplicity, elegance and stability is that the guys of SpringSource have programmed many many POJOs that help to integrate Spring with many other common frameworks without being intrusive in your application. Also, Spring has several good subprojects like Spring MVC, Spring WebFlow, Spring Security and again a loooong list of etceteras.

Hope this helps. Anyway, I encourage you to read Martin Fowler's article about Dependency Injection and Inversion of Control because he does it better than me. After understanding the basics take a look at Spring Documentation, in my opinion, it is used to be the best Spring book ever.

What is the best way to create and populate a numbers table?

Here is a short and fast in-memory solution that I came up with utilizing the Table Valued Constructors introduced in SQL Server 2008:

It will return 1,000,000 rows, however you can either add/remove CROSS JOINs, or use TOP clause to modify this.

;WITH v AS (SELECT * FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) v(z))

SELECT N FROM (SELECT ROW_NUMBER() OVER (ORDER BY v1.z)-1 N FROM v v1 
    CROSS JOIN v v2 CROSS JOIN v v3 CROSS JOIN v v4 CROSS JOIN v v5 CROSS JOIN v v6) Nums

Note that this could be quickly calculated on the fly, or (even better) stored in a permanent table (just add an INTO clause after the SELECT N segment) with a primary key on the N field for improved efficiency.

use a javascript array to fill up a drop down select box

Use a for loop to iterate through your array. For each string, create a new option element, assign the string as its innerHTML and value, and then append it to the select element.

var cuisines = ["Chinese","Indian"];     
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
    var opt = document.createElement('option');
    opt.innerHTML = cuisines[i];
    opt.value = cuisines[i];
    sel.appendChild(opt);
}

DEMO

UPDATE: Using createDocumentFragment and forEach

If you have a very large list of elements that you want to append to a document, it can be non-performant to append each new element individually. The DocumentFragment acts as a light weight document object that can be used to collect elements. Once all your elements are ready, you can execute a single appendChild operation so that the DOM only updates once, instead of n times.

var cuisines = ["Chinese","Indian"];     

var sel = document.getElementById('CuisineList');
var fragment = document.createDocumentFragment();

cuisines.forEach(function(cuisine, index) {
    var opt = document.createElement('option');
    opt.innerHTML = cuisine;
    opt.value = cuisine;
    fragment.appendChild(opt);
});

sel.appendChild(fragment);

DEMO

Save file/open file dialog box, using Swing & Netbeans GUI editor

I have created a sample UI which shows the save and open file dialog. Click on save button to open save dialog and click on open button to open file dialog.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class FileChooserEx {
    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new FileChooserEx().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());

        JButton saveBtn = new JButton("Save");
        JButton openBtn = new JButton("Open");

        saveBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser saveFile = new JFileChooser();
                saveFile.showSaveDialog(null);
            }
        });

        openBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser openFile = new JFileChooser();
                openFile.showOpenDialog(null);
            }
        });

        frame.add(new JLabel("File Chooser"), BorderLayout.NORTH);
        frame.add(saveBtn, BorderLayout.CENTER);
        frame.add(openBtn, BorderLayout.SOUTH);
        frame.setTitle("File Chooser");
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

How do I create a self-signed certificate for code signing on Windows?

It's fairly easy using the New-SelfSignedCertificate command in Powershell. Open powershell and run these 3 commands.

1) Create certificate:
$cert = New-SelfSignedCertificate -DnsName www.yourwebsite.com -Type CodeSigning -CertStoreLocation Cert:\CurrentUser\My

2) set the password for it:
$CertPassword = ConvertTo-SecureString -String "my_passowrd" -Force –AsPlainText

3) Export it:
Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath "d:\selfsigncert.pfx" -Password $CertPassword

Your certificate selfsigncert.pfx will be located @ D:/


Optional step: You would also require to add certificate password to system environment variables. do so by entering below in cmd: setx CSC_KEY_PASSWORD "my_password"

git - pulling from specific branch

See the git-pull man page:

git pull [options] [<repository> [<refspec>...]]

and in the examples section:

Merge into the current branch the remote branch next:

$ git pull origin next

So I imagine you want to do something like:

git pull origin dev

To set it up so that it does this by default while you're on the dev branch:

git branch --set-upstream-to dev origin/dev

How to get the date 7 days earlier date from current date in Java

Or use JodaTime:

DateTime lastWeek = new DateTime().minusDays(7);

no target device found android studio 2.1.1

On the phone

  1. Have you enabled Developer Mode?

  2. Have you enabled USB debugging within the Developer Tools menu in settings (this menu doesn't appear unless you've enabled Developer Mode)

  3. Do you have a good and securely connected USB cable?

In Android Studio

  1. In Edit Run/Debug Configurations, do you have "Target: USB Device"?

  2. It may help to download the latest version of the USB driver for that particular phone.

It's also helpful to know whether your phone appears as a recognised device at the operating system level. And when in doubt, reboot everything you can think of.

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

You have forgotten to mark the getProducts return type as an array. In your getProducts it says that it will return a single product. So change it to this:

public getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(`api/products/v1/`);
  }

Converting DateTime format using razor

Try this in MVC 4.0

@Html.TextBoxFor(m => m.YourDate, "{0:dd/MM/yyyy}", new { @class = "datefield form-control", @placeholder = "Enter start date..." })

jQuery - find table row containing table cell containing specific text

You can use filter() to do that:

var tableRow = $("td").filter(function() {
    return $(this).text() == "foo";
}).closest("tr");

Exiting from python Command Line

This works for me, best way to come out of python prompt.

exit()

How can I get (query string) parameters from the URL in Next.js?

Using Next.js 9 or above you can get query parameters:

With router:

import { useRouter } from 'next/router'

const Index = () => {
  const router = useRouter()
  const {id} = router.query

  return(<div>{id}</div>)
}

With getInitialProps:

const Index = ({id}) => {
  return(<div>{id}</div>)
}

Index.getInitialProps = async ({ query }) => {
  const {id} = query

  return {id}
}

What's the pythonic way to use getters and setters?

In [1]: class test(object):
    def __init__(self):
        self.pants = 'pants'
    @property
    def p(self):
        return self.pants
    @p.setter
    def p(self, value):
        self.pants = value * 2
   ....: 
In [2]: t = test()
In [3]: t.p
Out[3]: 'pants'
In [4]: t.p = 10
In [5]: t.p
Out[5]: 20

Broadcast receiver for checking internet connection in android app

Warning: Declaring a broadcastreceiver for android.net.conn.CONNECTIVITY_CHANGE is deprecated for apps targeting N and higher. In general, apps should not rely on this broadcast and instead use JobScheduler or GCMNetworkManager.

As CONNECTIVITY_CHANGE is deprecated then we should use another way of doing the same stuff

Following NetworkConnectionLiveData will handle all the OS Version till now and also if target SDK is less than Build.VERSION_CODES.LOLLIPOP then only we can use broadcastReceiver

Best Part is this class uses LiveData so no need to register any receiver use LiveData and it will handle all the things

class NetworkConnectionLiveData(val context: Context) : LiveData<Boolean>() {

    private var connectivityManager: ConnectivityManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager

    private lateinit var connectivityManagerCallback: ConnectivityManager.NetworkCallback

    override fun onActive() {
        super.onActive()
        updateConnection()
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> connectivityManager.registerDefaultNetworkCallback(getConnectivityManagerCallback())
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> lollipopNetworkAvailableRequest()
            else -> {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    context.registerReceiver(networkReceiver, IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"))
                }
            }
        }
    }

    override fun onInactive() {
        super.onInactive()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            connectivityManager.unregisterNetworkCallback(connectivityManagerCallback)
        } else {
            context.unregisterReceiver(networkReceiver)
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun lollipopNetworkAvailableRequest() {
        val builder = NetworkRequest.Builder()
                .addTransportType(android.net.NetworkCapabilities.TRANSPORT_CELLULAR)
                .addTransportType(android.net.NetworkCapabilities.TRANSPORT_WIFI)
        connectivityManager.registerNetworkCallback(builder.build(), getConnectivityManagerCallback())
    }

    private fun getConnectivityManagerCallback(): ConnectivityManager.NetworkCallback {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            connectivityManagerCallback = object : ConnectivityManager.NetworkCallback() {
                override fun onAvailable(network: Network?) {
                    postValue(true)
                }

                override fun onLost(network: Network?) {
                    postValue(false)
                }
            }
            return connectivityManagerCallback
        } else {
            throw IllegalAccessError("Should not happened")
        }
    }

    private val networkReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            updateConnection()
        }
    }

    private fun updateConnection() {
        val activeNetwork: NetworkInfo? = connectivityManager.activeNetworkInfo
        postValue(activeNetwork?.isConnected == true)
    }
} 

Use of the LiveData into any class:

NetworkConnectionLiveData(context ?: return)
    .observe(viewLifecycleOwner, Observer { isConnected ->
        if (!isConnected) {
            // Internet Not Available
            return@Observer
        }
        // Internet Available
})

Checking if a number is a prime number in Python

If a is a prime then the while x: in your code will run forever, since x will remain True.

So why is that while there?

I think you wanted to end the for loop when you found a factor, but didn't know how, so you added that while since it has a condition. So here is how you do it:

def is_prime(a):
    x = True 
    for i in range(2, a):
       if a%i == 0:
           x = False
           break # ends the for loop
       # no else block because it does nothing ...


    if x:
        print "prime"
    else:
        print "not prime"

installing apache: no VCRUNTIME140.dll

Problem: Wamp Won't Turn Green & VCRUNTIME140.dll error

Solved:)

You need C++ Redistributable for Visual Studio 2015 RC. Try to download the file, vc_redist.x64.exe from here, https://www.microsoft.com/en-us/download/details.aspx?id=48145

if you already installed then uninstalled it first

  1. I installed the vc_redist.x64.exe (if you OS is 32 bit then you should download vc_redist.x86.exe)
  2. then installed the wampserver (if you already installed then unsintalled it first)

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

Observe if the view has the model required:

View

@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....

Controller

[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}

In my case I Use a partial view but runs in normal views

Python Key Error=0 - Can't find Dict error in code

It only comes when your list or dictionary not available in the local function.

SQL query to find record with ID not in another table

Try this

SELECT ID, Name 
FROM   Table1 
WHERE  ID NOT IN (SELECT ID FROM Table2)

pip install access denied on Windows

Change your Python installation folder's security permissions by:

  1. Open a Python shell
  2. Go to task manager
  3. Find the python process
  4. Right-click and open location
  5. The folder will open in explorer, go up a directory
  6. Right-click the folder and select properties
  7. Click the security tab and hit 'edit'
  8. Add everyone and give them permission to Read and Write.
  9. Save your changes

If you open cmd as admin; then you can do the following:

If Python is set in your PATH, then:

python -m pip install mitmproxy

How to install mechanize for Python 2.7?

You need to follow the installation instructions and not just download the files into your Python27 directory. It has to be installed in the site-packages directory properly, which the directions tell you how to do.

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Perfect Tree:

       x
     /   \
    /     \
   x       x
  / \     / \
 x   x   x   x
/ \ / \ / \ / \
x x x x x x x x

Complete Tree:

       x
     /   \
    /     \
   x       x
  / \     / \
 x   x   x   x
/ \ /
x x x

Strict/Full Tree:

       x
     /   \
    /     \
   x       x
  / \ 
 x   x 
    / \
    x x 

Regex: ignore case sensitivity

[gG][aAbB].* probably simples solution if the pattern is not too complicated or long.

How to insert a large block of HTML in JavaScript?

If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:

var x =
    "<div> \
    <span> \
    <p> \
    some text \
    </p> \
    </div>";

Could pandas use column as index?

You can change the index as explained already using set_index. You don't need to manually swap rows with columns, there is a transpose (data.T) method in pandas that does it for you:

> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                    ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> newdf = df.set_index('Locality').T
> newdf

Locality    ABBOTSFORD  ABERFELDIE
2005        427000      534000
2006        448000      600000

then you can fetch the dataframe column values and transform them to a list:

> newdf['ABBOTSFORD'].values.tolist()

[427000, 448000]

Running bash script from within python

Actually, you just have to add the shell=True argument:

subprocess.call("sleep.sh", shell=True)

But beware -

Warning Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.

source

How to convert HTML file to word?

Other Alternatives from just renaming the file to .doc.....

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(office.11).aspx

Here is a good place to start. You can also try using this Office Open XML.

http://www.ecma-international.org/publications/standards/Ecma-376.htm

Grant execute permission for a user on all stored procedures in database?

Create a role add this role to users, and then you can grant execute to all the routines in one shot to this role.

CREATE ROLE <abc>
GRANT EXECUTE TO <abc>

EDIT
This works in SQL Server 2005, I'm not sure about backward compatibility of this feature, I'm sure anything later than 2005 should be fine.

Hiding an Excel worksheet with VBA

I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.

So, for hiding the sheet:

Sub try()
    Worksheets("Sheet1").Visible = xlSheetHidden
End Sub

There are other methods also if you want to learn all Methods Click here

How can I generate a 6 digit unique number?

<?php
$file = 'count.txt';

//get the number from the file
$uniq = file_get_contents($file);

//add +1
$id = $uniq + 1 ;

// add that new value to text file again for next use
file_put_contents($file, $id);

// your unique id ready
echo $id;
?>

i hope this will work fine. i use the same technique in my website.

How to close activity and go back to previous activity in android

When you click your button you can have it call:

super.onBackPressed();

How to 'insert if not exists' in MySQL?

Update or insert without known primary key

If you already have a unique or primary key, the other answers with either INSERT INTO ... ON DUPLICATE KEY UPDATE ... or REPLACE INTO ... should work fine (note that replace into deletes if exists and then inserts - thus does not partially update existing values).

But if you have the values for some_column_id and some_type, the combination of which are known to be unique. And you want to update some_value if exists, or insert if not exists. And you want to do it in just one query (to avoid using a transaction). This might be a solution:

INSERT INTO my_table (id, some_column_id, some_type, some_value)
SELECT t.id, t.some_column_id, t.some_type, t.some_value
FROM (
    SELECT id, some_column_id, some_type, some_value
    FROM my_table
    WHERE some_column_id = ? AND some_type = ?
    UNION ALL
    SELECT s.id, s.some_column_id, s.some_type, s.some_value
    FROM (SELECT NULL AS id, ? AS some_column_id, ? AS some_type, ? AS some_value) AS s
) AS t
LIMIT 1
ON DUPLICATE KEY UPDATE
some_value = ?

Basically, the query executes this way (less complicated than it may look):

  • Select an existing row via the WHERE clause match.
  • Union that result with a potential new row (table s), where the column values are explicitly given (s.id is NULL, so it will generate a new auto-increment identifier).
  • If an existing row is found, then the potential new row from table s is discarded (due to LIMIT 1 on table t), and it will always trigger an ON DUPLICATE KEY which will UPDATE the some_value column.
  • If an existing row is not found, then the potential new row is inserted (as given by table s).

Note: Every table in a relational database should have at least a primary auto-increment id column. If you don't have this, add it, even when you don't need it at first sight. It is definitely needed for this "trick".

How to create a custom-shaped bitmap marker with Android map API v2

I hope it still not too late to share my solution. Before that, you can follow the tutorial as stated in Android Developer documentation. To achieve this, you need to use Cluster Manager with defaultRenderer.

  1. Create an object that implements ClusterItem

    public class SampleJob implements ClusterItem {
    
    private double latitude;
    private double longitude;
    
    //Create constructor, getter and setter here
    
    @Override
    public LatLng getPosition() {
        return new LatLng(latitude, longitude);
    }
    
  2. Create a default renderer class. This is the class that do all the job (inflating custom marker/cluster with your own style). I am using Universal image loader to do the downloading and caching the image.

    public class JobRenderer extends DefaultClusterRenderer< SampleJob > {
    
    private final IconGenerator iconGenerator;
    private final IconGenerator clusterIconGenerator;
    private final ImageView imageView;
    private final ImageView clusterImageView;
    private final int markerWidth;
    private final int markerHeight;
    private final String TAG = "ClusterRenderer";
    private DisplayImageOptions options;
    
    
    public JobRenderer(Context context, GoogleMap map, ClusterManager<SampleJob> clusterManager) {
        super(context, map, clusterManager);
    
        // initialize cluster icon generator
        clusterIconGenerator = new IconGenerator(context.getApplicationContext());
        View clusterView = LayoutInflater.from(context).inflate(R.layout.multi_profile, null);
        clusterIconGenerator.setContentView(clusterView);
        clusterImageView = (ImageView) clusterView.findViewById(R.id.image);
    
        // initialize cluster item icon generator
        iconGenerator = new IconGenerator(context.getApplicationContext());
        imageView = new ImageView(context.getApplicationContext());
        markerWidth = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
        markerHeight = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
        imageView.setLayoutParams(new ViewGroup.LayoutParams(markerWidth, markerHeight));
        int padding = (int) context.getResources().getDimension(R.dimen.custom_profile_padding);
        imageView.setPadding(padding, padding, padding, padding);
        iconGenerator.setContentView(imageView);
    
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.circle_icon_logo)
                .showImageForEmptyUri(R.drawable.circle_icon_logo)
                .showImageOnFail(R.drawable.circle_icon_logo)
                .cacheInMemory(false)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }
    
    @Override
    protected void onBeforeClusterItemRendered(SampleJob job, MarkerOptions markerOptions) {
    
    
        ImageLoader.getInstance().displayImage(job.getJobImageURL(), imageView, options);
        Bitmap icon = iconGenerator.makeIcon(job.getName());
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(job.getName());
    
    
    }
    
    @Override
    protected void onBeforeClusterRendered(Cluster<SampleJob> cluster, MarkerOptions markerOptions) {
    
        Iterator<Job> iterator = cluster.getItems().iterator();
        ImageLoader.getInstance().displayImage(iterator.next().getJobImageURL(), clusterImageView, options);
        Bitmap icon = clusterIconGenerator.makeIcon(iterator.next().getName());
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
    }
    
    @Override
    protected boolean shouldRenderAsCluster(Cluster cluster) {
        return cluster.getSize() > 1;
    }
    
  3. Apply cluster manager in your activity/fragment class.

    public class SampleActivity extends AppCompatActivity implements OnMapReadyCallback {
    
    private ClusterManager<SampleJob> mClusterManager;
    private GoogleMap mMap;
    private ArrayList<SampleJob> jobs = new ArrayList<SampleJob>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landing);
    
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.getUiSettings().setMapToolbarEnabled(true);
        mClusterManager = new ClusterManager<SampleJob>(this, mMap);
        mClusterManager.setRenderer(new JobRenderer(this, mMap, mClusterManager));
        mMap.setOnCameraChangeListener(mClusterManager);
        mMap.setOnMarkerClickListener(mClusterManager);
    
        //Assume that we already have arraylist of jobs
    
    
        for(final SampleJob job: jobs){
            mClusterManager.addItem(job);
        }
        mClusterManager.cluster();
    }
    
  4. Result

Result

Redirecting to a certain route based on condition

    $routeProvider
 .when('/main' , {templateUrl: 'partials/main.html',  controller: MainController})
 .when('/login', {templateUrl: 'partials/login.html', controller: LoginController}).
 .when('/login', {templateUrl: 'partials/index.html', controller: IndexController})
 .otherwise({redirectTo: '/index'});

What does request.getParameter return?

Per the Javadoc:

Returns the value of a request parameter as a String, or null if the parameter does not exist.

Do note that it is possible to submit an empty parameter - such that the parameter exists, but has no value. For example, I could include &log=&somethingElse into the URL to enable logging, without needing to specify &log=true. In this case, the value will be an empty String ("").

Search File And Find Exact Match And Print Line?

It's very easy:

numb = raw_input('Input Line: ')
fiIn = open('file.txt').readlines()
for lines in fiIn:
   if numb == lines[0]:
      print lines

Jackson serialization: ignore empty values (or null)

For jackson 2.x

@JsonInclude(JsonInclude.Include.NON_NULL)

just before the field.

How to use Apple's new .p8 certificate for APNs in firebase console

Follow these steps:

1. Generate an APNs Auth Key
Open the APNs Auth Key page in your Developer Center and click the + button to create a new APNs Auth Key.

enter image description here

In the next page, select Apple Push Notification Authentication Key (Sandbox & Production) and click Continue at the bottom of the page.

enter image description here

Apple will then generate a .p8 key file containing your APNs Auth Key.

enter image description here

Download the .p8 key file to your computer and save it for later. Also, be sure to write down the Key ID somewhere, as you'll need it later when connecting to APNs.

2. Send Push Notifications

Ref: APNS (Configure push notifications)

Important: Save a back up of your key in a secure place. It will not be presented again and cannot be retrieved later.

How to position two elements side by side using CSS

Just use the float style. Put your google map iframe in a div class, and the paragraph in another div class, then apply the following CSS styles to those div classes(don't forget to clear the blocks after float effect, to not make the blocks trouble below them):

css

.google_map{
    width:55%;
    margin-right:2%;
    float: left;
}
.google_map iframe{
   width:100%;
}
.paragraph {
    width:42%;
    float: left;
}
.clearfix{
    clear:both
}

html

<div class="google_map">
      <iframe></iframe>
</div>
<div class="paragraph">
      <p></p>
</div>
<div class="clearfix"></div>

How to Enable ActiveX in Chrome?

anyone who says activex is less secure then NPAPI is crazy. They both allow the exact same access. Yes I've written both. The only reason people think activeX is insecure is because 10+ years ago IE had default settings that allowed a remote site to auto download the plugin.

How to replace four spaces with a tab in Sublime Text 2?

Do a regex "Search" for \t (backslash-t, a tab), and replace with four spaces.

Either the main menu, or lower-right status-bar spacing menu does the same thing, with less work.

Jquery Ajax Posting json to webservice

You mentioned using json2.js to stringify your data, but the POSTed data appears to be URLEncoded JSON You may have already seen it, but this post about the invalid JSON primitive covers why the JSON is being URLEncoded.

I'd advise against passing a raw, manually-serialized JSON string into your method. ASP.NET is going to automatically JSON deserialize the request's POST data, so if you're manually serializing and sending a JSON string to ASP.NET, you'll actually end up having to JSON serialize your JSON serialized string.

I'd suggest something more along these lines:

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
               { "position": "235.1944023323615", "markerPosition": "19" },
               { "position": "42.5978231292517", "markerPosition": "-3" }];

$.ajax({
    type: "POST",
    url: "/webservices/PodcastService.asmx/CreateMarkers",
    // The key needs to match your method's input parameter (case-sensitive).
    data: JSON.stringify({ Markers: markers }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    error: function(errMsg) {
        alert(errMsg);
    }
});

The key to avoiding the invalid JSON primitive issue is to pass jQuery a JSON string for the data parameter, not a JavaScript object, so that jQuery doesn't attempt to URLEncode your data.

On the server-side, match your method's input parameters to the shape of the data you're passing in:

public class Marker
{
  public decimal position { get; set; }
  public int markerPosition { get; set; }
}

[WebMethod]
public string CreateMarkers(List<Marker> Markers)
{
  return "Received " + Markers.Count + " markers.";
}

You can also accept an array, like Marker[] Markers, if you prefer. The deserializer that ASMX ScriptServices uses (JavaScriptSerializer) is pretty flexible, and will do what it can to convert your input data into the server-side type you specify.

Limit results in jQuery UI Autocomplete

Here is the proper documentation for the jQueryUI widget. There isn't a built-in parameter for limiting max results, but you can accomplish it easily:

$("#auto").autocomplete({
    source: function(request, response) {
        var results = $.ui.autocomplete.filter(myarray, request.term);

        response(results.slice(0, 10));
    }
});

You can supply a function to the source parameter and then call slice on the filtered array.

Here's a working example: http://jsfiddle.net/andrewwhitaker/vqwBP/

Magento - Retrieve products with a specific attribute value

This is a follow up to my original question to help out others with the same problem. If you need to filter by an attribute, rather than manually looking up the id you can use the following code to retrieve all the id, value pairs for an attribute. The data is returned as an array with the attribute name as the key.

function getAttributeOptions($attributeName) {
    $product = Mage::getModel('catalog/product');
    $collection = Mage::getResourceModel('eav/entity_attribute_collection')
              ->setEntityTypeFilter($product->getResource()->getTypeId())
              ->addFieldToFilter('attribute_code', $attributeName);

    $_attribute = $collection->getFirstItem()->setEntity($product->getResource());
    $attribute_options  = $_attribute->getSource()->getAllOptions(false);
    foreach($attribute_options as $val) {
        $attrList[$val['label']] = $val['value'];
    }   

    return $attrList;
}

Here is a function you can use to get products by their attribute set id. Retrieved using the previous function.

function getProductsByAttributeSetId($attributeSetId) {
   $products = Mage::getModel('catalog/product')->getCollection();
   $products->addAttributeToFilter('attribute_set_id',$attributeSetId);

   $products->addAttributeToSelect('*');

   $products->load();
   foreach($products as $val) {
     $productsArray[] = $val->getData();
  }

  return $productsArray;
}

Corrupt jar file

As I just came across this topic I wanted to share the reason and solution why I got the message "invalid or corrupt jarfile":

I had updated the version of the "maven-jar-plugin" in my pom.xml from 2.1 to 3.1.2. Everything still went fine and a jar file was built. But somehow it obviously wouldn't run anymore.

As soon as i set the "maven-jar-plugin" version back to 2.1 again, the problem was gone.

What is a pre-revprop-change hook in SVN, and how do I create it?

For Windows, here's a link to an example batch file that only allows changes to the log message (not other properties):

http://ayria.livejournal.com/33438.html

Basically copy the code below into a text file and name it pre-revprop-change.bat and save it in the \hooks subdirectory for your repository.

@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5

:: Only allow the log message to be changed, but not author, etc.
if /I not "%propertyName%" == "svn:log" goto ERROR_PROPNAME

:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION

:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY

goto :eof

:ERROR_EMPTY
echo Empty svn:log messages are not allowed. >&2
goto ERROR_EXIT

:ERROR_PROPNAME
echo Only changes to svn:log messages are allowed. >&2
goto ERROR_EXIT

:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT

:ERROR_EXIT
exit /b 1

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

Addition to @BalusC 's answer. You also need to set width of headers. In my case, below css can only apply to my table's column width.

.myTable td:nth-child(1),.myTable th:nth-child(1) {
   width: 20px;
}

Adding item to Dictionary within loop

# Let's add key:value to a dictionary, the functional way 
# Create your dictionary class 
class my_dictionary(dict): 
    # __init__ function 
    def __init__(self): 
        self = dict()   
    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value 
# Main Function 
dict_obj = my_dictionary() 
limit = int(input("Enter the no of key value pair in a dictionary"))
c=0
while c < limit :   
    dict_obj.key = input("Enter the key: ") 
    dict_obj.value = input("Enter the value: ") 
    dict_obj.add(dict_obj.key, dict_obj.value) 
    c += 1
print(dict_obj) 

Inheritance and Overriding __init__ in python

If the FileInfo class has more than one ancestor class then you should definitely call all of their __init__() functions. You should also do the same for the __del__() function, which is a destructor.

CSS Styling for a Button: Using <input type="button> instead of <button>

Do you really want to style the <div>? Or do you want to style the <input type="button">? You should use the correct selector if you want the latter:

input[type=button] {
    color:#08233e;
    font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
    font-size:70%;
    /* ... other rules ... */
    cursor:pointer;
}

input[type=button]:hover {
    background-color:rgba(255,204,0,0.8);
}

See also:

PHP + curl, HTTP POST sample code?

Examples of sending form and raw data:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify array of form fields
     */
    CURLOPT_POSTFIELDS => [
        'foo' => 'bar',
        'baz' => 'biz',
    ],
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Convert array of indices to 1-hot encoded numpy array

Use the following code. It works best.

def one_hot_encode(x):
"""
    argument
        - x: a list of labels
    return
        - one hot encoding matrix (number of labels, number of class)
"""
encoded = np.zeros((len(x), 10))

for idx, val in enumerate(x):
    encoded[idx][val] = 1

return encoded

Found it here P.S You don't need to go into the link.

What does the Visual Studio "Any CPU" target mean?

Here's a quick overview that explains the different build targets.

From my own experience, if you're looking to build a project that will run on both x86 and x64 platforms, and you don't have any specific x64 optimizations, I'd change the build to specifically say "x86."

The reason for this is sometimes you can get some DLL files that collide or some code that winds up crashing WoW in the x64 environment. By specifically specifying x86, the x64 OS will treat the application as a pure x86 application and make sure everything runs smoothly.

How to loop over a Class attributes in Java?

Here is a solution which sorts the properties alphabetically and prints them all together with their values:

public void logProperties() throws IllegalArgumentException, IllegalAccessException {
  Class<?> aClass = this.getClass();
  Field[] declaredFields = aClass.getDeclaredFields();
  Map<String, String> logEntries = new HashMap<>();

  for (Field field : declaredFields) {
    field.setAccessible(true);

    Object[] arguments = new Object[]{
      field.getName(),
      field.getType().getSimpleName(),
      String.valueOf(field.get(this))
    };

    String template = "- Property: {0} (Type: {1}, Value: {2})";
    String logMessage = System.getProperty("line.separator")
            + MessageFormat.format(template, arguments);

    logEntries.put(field.getName(), logMessage);
  }

  SortedSet<String> sortedLog = new TreeSet<>(logEntries.keySet());

  StringBuilder sb = new StringBuilder("Class properties:");

  Iterator<String> it = sortedLog.iterator();
  while (it.hasNext()) {
    String key = it.next();
    sb.append(logEntries.get(key));
  }

  System.out.println(sb.toString());
}

Tell Ruby Program to Wait some amount of time

I find until very useful with sleep. example:

> time = Time.now
> sleep 2.seconds until Time.now > time + 10.seconds # breaks when true
# or something like
> sleep 1.seconds until !req.loading # suggested by ohsully

How to set a default entity property value with Hibernate

If you want to set default value in terms of database, just set @Column( columnDefinition = "int default 1")

But if what you intend is to set a default value in your java app you can set it on your class attribute like this: private Integer attribute = 1;

What is the correct way to check for string equality in JavaScript?

always Until you fully understand the differences and implications of using the == and === operators, use the === operator since it will save you from obscure (non-obvious) bugs and WTFs. The "regular" == operator can have very unexpected results due to the type-coercion internally, so using === is always the recommended approach.

For insight into this, and other "good vs. bad" parts of Javascript read up on Mr. Douglas Crockford and his work. There's a great Google Tech Talk where he summarizes lots of good info: http://www.youtube.com/watch?v=hQVTIJBZook


Update:

The You Don't Know JS series by Kyle Simpson is excellent (and free to read online). The series goes into the commonly misunderstood areas of the language and explains the "bad parts" that Crockford suggests you avoid. By understanding them you can make proper use of them and avoid the pitfalls.

The "Up & Going" book includes a section on Equality, with this specific summary of when to use the loose (==) vs strict (===) operators:

To boil down a whole lot of details to a few simple takeaways, and help you know whether to use == or === in various situations, here are my simple rules:

  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===.
  • In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

I still recommend Crockford's talk for developers who don't want to invest the time to really understand Javascript—it's good advice for a developer who only occasionally works in Javascript.

How to retrieve form values from HTTPPOST, dictionary or?

If you want to get the form data directly from Http request, without any model bindings or FormCollection you can use this:

[HttpPost] 
public ActionResult SubmitAction() {

    // This will return an string array of all keys in the form.
    // NOTE: you specify the keys in form by the name attributes e.g:
    // <input name="this is the key" value="some value" type="test" />
    var keys = Request.Form.AllKeys;

    // This will return the value for the keys.
    var value1 = Request.Form.Get(keys[0]);
    var value2 = Request.Form.Get(keys[1]);
}

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

For Jackson versions < 2.0 use this annotation on the class being serialized:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

You can fix this issue by deleting browser cookie from the begining of time. I have tried this and it is working fine for me.

To delete only cookies:

  1. hold down ctrl+shift+delete
  2. remove all check boxes except for cookies of course
  3. use the drop down on top to select "from the beginning of time
  4. click clear browsing data

How do I change the font size and color in an Excel Drop Down List?

I work on 60-70% zoom vue and my dropdown are unreadable so I made this simple code to overcome the issue

Note that I selected first all my dropdown lsts (CTRL+mouse click), went on formula tab, clicked "define name" and called them "ProduktSelection"

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim KeyCells As Range
Set KeyCells = Range("ProduktSelection")
    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

ActiveWindow.Zoom = 100

End If

End Sub

I then have another sub

Private Sub Worksheet_Change(ByVal Target As Range) 

where I come back to 65% when value is changed.

How to implement infinity in Java?

double supports Infinity

double inf = Double.POSITIVE_INFINITY;
System.out.println(inf + 5);
System.out.println(inf - inf); // same as Double.NaN
System.out.println(inf * -1); // same as Double.NEGATIVE_INFINITY

prints

Infinity
NaN
-Infinity

note: Infinity - Infinity is Not A Number.

Insert ellipsis (...) into HTML tag if content too wide

Here's another JavaScript solution. Works very good and very fast.

https://github.com/dobiatowski/jQuery.FastEllipsis

Tested on Chrome, FF, IE on Windows and Mac.

How to create a session using JavaScript?

I think you misunderstood the concept of session, session is a server side per-user-data-store which allows you to save user data on the server side.

thus, you have 2 options, resort to use cookies, which will give the illusion of session(but not quite the same), you can access cookies very simply by document.cookie .

but, if you want your server be aware of the session, you need to use some sort of server request probably the best way is to use AJAX to do this.

I would recommend you to re-read the definition of sessions.

Does Eclipse have line-wrap

In Eclipse v4.7 (Oxygen):

Window menu ? Editor ? Toggle Word Wrap (Shift+Alt+Y)

What is the difference between the | and || or operators?

For bitwise | and Logicall ||

OR

bitwise & and logicall &&

it means if( a>b | a==0) in this first left a>b will be evaluated and then a==0 will be evaluated then | operation will be done

but in|| if a>b then if wont check for next RHS

Similarly for & and &&

if(A>0 & B>0)

it will evalue LHS and then RHS then do bitwise & but

in(A>0 && B>0)

if(A>0) is false(LHS) it will directly return false;

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

brew switch to python3 by default, so if you want to still set python2 as default bin python, running:

brew unlink python && brew link python2 --force

Zero an array in C code

int arr[20];
memset(arr, 0, sizeof arr);

See the reference for memset

How to align an input tag to the center without specifying the width?

You can also use the tag, this works in divs and everything else:

<center><form></form></center>

This link will help you with the tag:

Why is the <center> tag deprecated in HTML?

How to hide column of DataGridView when using custom DataSource?

Just set DataGridView.AutoGenerateColumns = false;

You need click on the arrow on top right corner (in datagridview) to add columns, and in DataPropertyName you need to put a name of your property in your class.

Then, after you defined your columns in datagridview, you can set datagridview.datasource = myClassViewModel.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Copy text from nano editor to shell

Relatively straightforward solution:

  1. From the first character you want to copy, hold Shift down and go all the way to the end.

  2. Press Ctrl+K, which cuts the text from the file.

  3. Press Ctrl+X, and then N to not save any changes.

  4. Paste the cut text anywhere you want.

Alternatively, if your text fits into the screen, you can simply use mouse to select and it automatically copies it to clipboard.

Mock a constructor with parameter

Starting with version 3.5.0 of Mockito and using the InlineMockMaker, you can now mock object constructions:

 try (MockedConstruction mocked = mockConstruction(A.class)) {
   A a = new A();
   when(a.check()).thenReturn("bar");
 }

Inside the try-with-resources construct all object constructions are returning a mock.

TypeError: can only concatenate list (not "str") to list

I think what you want to do is add a new item to your list, so you have change the line newinv=inventory+str(add) with this one:

newinv = inventory.append(add)

What you are doing now is trying to concatenate a list with a string which is an invalid operation in Python.

However I think what you want is to add and delete items from a list, in that case your if/else block should be:

if selection=="use":
    print(inventory)
    remove=input("What do you want to use? ")
    inventory.remove(remove)
    print(inventory)

elif selection=="pickup":
    print(inventory)
    add=input("What do you want to pickup? ")
    inventory.append(add)
    print(inventory)

You don't need to build a new inventory list every time you add a new item.

Error: Cannot pull with rebase: You have unstaged changes

Do git status, this will show you what files have changed. Since you stated that you don't want to keep the changes you can do git checkout -- <file name> or git reset --hard to get rid of the changes.

For the most part, git will tell you what to do about changes. For example, your error message said to git stash your changes. This would be if you wanted to keep them. After pulling, you would then do git stash pop and your changes would be reapplied.

git status also has how to get rid of changes depending on if the file is staged for commit or not.

How to Update Date and Time of Raspberry Pi With out Internet

Thanks for the replies.
What I did was,
1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
2. change raspberry pi ntp.conf file (for auto update date and time)

server xxx.xxx.xxx.xxx iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst

3. If you want to make sure that date and time update at startup run this python script in rpi,

import os

try:
    client = ntplib.NTPClient()
    response = client.request('xxx.xxx.xxx.xxx', version=4)
    print "===================================="
    print "Offset : "+str(response.offset)
    print "Version : "+str(response.version)
    print "Date Time : "+str(ctime(response.tx_time))
    print "Leap : "+str(ntplib.leap_to_text(response.leap))
    print "Root Delay : "+str(response.root_delay)
    print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
    os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
    print "===================================="
except:
    os.system("sudo date")
    print "NTP Server Down Date Time NOT Set At The Startup"
    pass

I found more info in raspberry pi forum.