Programs & Examples On #Bduf

Big Design Up Front (BDUF) Is a software methodology of ensuring a design is complete before any implementation is done. BUDF is traditionally associated with the waterfall model.

Can a relative sitemap url be used in a robots.txt?

According to the official documentation on sitemaps.org it needs to be a full URL:

You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:

Sitemap: http://www.example.com/sitemap.xml

Updates were rejected because the tip of your current branch is behind its remote counterpart

It must be because of commit is ahead of your current push.

  1. git pull origin "name of branch you want to push"
  2. git rebase

If git rebase is successful, then good. Otherwise, you have resolve all merge conflicts locally and keep it continuing until rebase with remote is successful.

  1. git rebase --continue

create table in postgreSQL

-- Table: "user"

-- DROP TABLE "user";

CREATE TABLE "user"
(
  id bigserial NOT NULL,
  name text NOT NULL,
  email character varying(20) NOT NULL,
  password text NOT NULL,
  CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "user"
  OWNER TO postgres;

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

Set your PRIMARY KEY as AUTO_INCREMENT.

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Your code was compiled with Java 8.

Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.

Hope this helps...

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

LINQ Group By into a Dictionary Object

I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.

Use it like:

var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]

Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

Best way to disable button in Twitter's Bootstrap

What ever attribute is added to the button/anchor/link to disable it, bootstrap is just adding style to it and user will still be able to click it while there is still onclick event. So my simple solution is to check if it is disabled and remove/add onclick event:

if (!('#button').hasAttr('disabled'))
 $('#button').attr('onclick', 'someFunction();');
else
 $('#button').removeattr('onclick');

Using logging in multiple modules

The best practice would be to create a module separately which has only one method whose task we be to give a logger handler to the the calling method. Save this file as m_logger.py

import logger, logging

def getlogger():
    # logger
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    # create console handler and set level to debug
    #ch = logging.StreamHandler()
    ch = logging.FileHandler(r'log.txt')
    ch.setLevel(logging.DEBUG)
    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    # add formatter to ch
    ch.setFormatter(formatter)
    # add ch to logger
    logger.addHandler(ch)
    return logger

Now call the getlogger() method whenever logger handler is needed.

from m_logger import getlogger
logger = getlogger()
logger.info('My mssg')

RegEx to parse or validate Base64 data

Here's an alternative regular expression:

^(?=(.{4})*$)[A-Za-z0-9+/]*={0,2}$

It satisfies the following conditions:

  • The string length must be a multiple of four - (?=^(.{4})*$)
  • The content must be alphanumeric characters or + or / - [A-Za-z0-9+/]*
  • It can have up to two padding (=) characters on the end - ={0,2}
  • It accepts empty strings

How do you remove an invalid remote branch reference from Git?

In my case I was trying to delete entries that were saved in .git/packed-refs. You can edit this plain text file and delete entries from it that git br -D doesn't know how to touch (At least in ver 1.7.9.5).

I found this solution here: https://stackoverflow.com/a/11050880/1695680

How to write and read java serialized objects into a file

I think you have to write each object to an own File or you have to split the one when reading it. You may also try to serialize your list and retrieve that when deserializing.

How to clone all remote branches in Git?

Using the --mirror option seems to copy the remote tracking branches properly. However, it sets up the repository as a bare repository, so you have to turn it back into a normal repository afterwards.

git clone --mirror path/to/original path/to/dest/.git
cd path/to/dest
git config --bool core.bare false
git checkout anybranch

Reference: Git FAQ: How do I clone a repository with all remotely tracked branches?

How to use a class object in C++ as a function parameter

At its simplest:

#include <iostream>
using namespace std;

class A {
   public:
     A( int x ) : n( x ){}
     void print() { cout << n << endl; }
   private:
     int n;
};

void func( A p ) {
   p.print();
}

int main () {
   A a;
   func ( a );
}

Of course, you should probably be using references to pass the object, but I suspect you haven't got to them yet.

What's the reason I can't create generic array types in Java?

If the class uses as a parameterized type, it can declare an array of type T[], but it cannot directly instantiate such an array. Instead, a common approach is to instantiate an array of type Object[], and then make a narrowing cast to type T[], as shown in the following:

  public class Portfolio<T> {
  T[] data;
 public Portfolio(int capacity) {
   data = new T[capacity];                 // illegal; compiler error
   data = (T[]) new Object[capacity];      // legal, but compiler warning
 }
 public T get(int index) { return data[index]; }
 public void set(int index, T element) { data[index] = element; }
}

How to delete columns in a CSV file?

I would use Pandas with col number

f = pd.read_csv("test.csv", usecols=[0,1,3,4])

f.to_csv("test.csv", index=False)

IIS Express Windows Authentication

If none of the answers helps, you might need to adjust the project properties. Check this other StackOverflow answer on how to do that:

https://stackoverflow.com/a/20857049/56621

How to close a Tkinter window by pressing a Button?

You can associate directly the function object window.destroy to the command attribute of your button:

button = Button (frame, text="Good-bye.", command=window.destroy)

This way you will not need the function close_window to close the window for you.

What is causing "Unable to allocate memory for pool" in PHP?

To resolve this problem set value for apc.shm_size as integer Locate your apc.ini file (In my system apc.ini file location /etc/php5/conf.d/apc.ini) and set: apc.shm_size = 1000

Is there a difference between PhoneGap and Cordova commands?

I have also noticed that cordova has a "serve" command that Phonegap doesn't. This command launches a local server on port 8000. This is handy for running your app in Chrome and using the Ripple emulator.

Table overflowing outside of div

I tried almost all of above but did not work for me ... The following did

word-break: break-all;

This to be added on the parent div (container of the table .)

HTML table headers always visible at top of window when viewing a large table

I've made a proof-of-concept solution using jQuery.

View sample here.

I've now got this code in a Mercurial bitbucket repository. The main file is tables.html.

I'm aware of one issue with this: if the table contains anchors, and if you open the URL with the specified anchor in a browser, when the page loads, the row with the anchor will probably be obscured by the floating header.

Update 2017-12-11: I see this doesn't work with current Firefox (57) and Chrome (63). Not sure when and why this stopped working, or how to fix it. But now, I think the accepted answer by Hendy Irawan is superior.

How to use JavaScript with Selenium WebDriver Java

JavaScript With Selenium WebDriver

Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.

    public static WebDriver driver;
    public static void main(String[] args) {
        driver = new FirefoxDriver(); // This opens a window    
        String url = "----";


        /*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
        driver.findElement(By.name("j_password")).sendKeys("yashwanth@123");*/

        JavascriptExecutor jse = (JavascriptExecutor) driver;       
        if (jse instanceof WebDriver) {
            //Launching the browser application
            jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[@name='j_password']")).sendKeys("admin");


//Opend Site and click on some links. then you can apply go(-1)--> back  forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();            
jse.executeScript("window.history.go(0)");
            jse.executeScript("window.history.go(-2)");
            jse.executeScript("window.history.forward(-2)");

            String title = (String)jse.executeScript("return document.title");
            System.out.println(" Title Of site : "+title);

            String domain = (String)jse.executeScript("return document.domain");
            System.out.println("Web Site Domain-Name : "+domain);

            // To get all NodeList[1052] document.querySelectorAll('*');  or document.all
            jse.executeAsyncScript("document.getElementsByTagName('*')");

            String error=(String) jse.executeScript("return window.jsErrors");
            System.out.println("Windowerrors  :   "+error);



            System.out.println("To Find the input tag position from top"); 
            ArrayList<?> al =  (ArrayList<?>) jse.executeScript(
                    "var source = [];"+
                    "var inputs = document.getElementsByTagName('input');"+
                    "for(var i = 0; i < inputs.length; i++) { " +
                       "   source[i] = inputs[i].offsetParent.offsetTop" +      //"    inputs[i].type = 'radio';"
                    "}"+
                    "return source"                 
                    );//inputs[i].offsetParent.offsetTop     inputs[i].type

            System.out.println("next");
            System.out.println("array : "+al);

            // (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys 
            Keys k = null;
            String selectAll = Keys.chord(Keys.CONTROL, "a");
            WebElement body = driver.findElement(By.tagName("body"));
            body.sendKeys(selectAll);

            // Search for text in Site. Gets all ViewSource content and checks their.
            if (driver.getPageSource().contains("login")) {
                System.out.println("Text present in Web Site");
            }

        Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
        System.out.println("Client Body Height : "+clent_height);

        // using selenium we con only execute script but not JS-functions.

    }
    driver.quit(); // to close browser
}

To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.

Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
        String js_TxtFile = ""; 
            while (sc.hasNext()) {          
                String[] s = sc.next().split("\r\n");   
                for (int i = 0; i < s.length; i++) {
                    js_TxtFile += s[i];
                    js_TxtFile += " ";
                }           
            }
        String title =  (String) jse.executeScript(js_TxtFile);
        System.out.println("Title  : "+title);

document.title & document.getElementById() is a property/method available in Browsers.

JsFile.txt

var title = getTitle();
return title;

function getTitle() {
    return document.title;
}

Running sites on "localhost" is extremely slow

I had the same problem with PHP. I solved it by changing "localhost" to "127.0.0.1" in database connection parameters like someone suggested here: https://serverfault.com/a/444338/62739 . I think it may work for you too, give it a try.

Password encryption at client side

This won't be secure, and it's simple to explain why:

If you hash the password on the client side and use that token instead of the password, then an attacker will be unlikely to find out what the password is.

But, the attacker doesn't need to find out what the password is, because your server isn't expecting the password any more - it's expecting the token. And the attacker does know the token because it's being sent over unencrypted HTTP!

Now, it might be possible to hack together some kind of challenge/response form of encryption which means that the same password will produce a different token each request. However, this will require that the password is stored in a decryptable format on the server, something which isn't ideal, but might be a suitable compromise.

And finally, do you really want to require users to have javascript turned on before they can log into your website?

In any case, SSL is neither an expensive or especially difficult to set up solution any more

How do I use Assert.Throws to assert the type of the exception?

Since I'm disturbed by the verbosity of some of the new NUnit patterns, I use something like this to create code that is cleaner for me personally:

public void AssertBusinessRuleException(TestDelegate code, string expectedMessage)
{
    var ex = Assert.Throws<BusinessRuleException>(code);
    Assert.AreEqual(ex.Message, expectedMessage);
}

public void AssertException<T>(TestDelegate code, string expectedMessage) where T:Exception
{
    var ex = Assert.Throws<T>(code);
    Assert.AreEqual(ex.Message, expectedMessage);
}

The usage is then:

AssertBusinessRuleException(() => user.MakeUserActive(), "Actual exception message");

How to change facet labels?

The EASIEST way to change WITHOUT modifying the underlying data is:

  1. Create an object using the as_labeller function adding the back tick mark for each of the default values:
# Necessary to put RH% into the facet labels
hum.names <- as_labeller(
     c(`50` = "RH% 50", `60` = "RH% 60",`70` = "RH% 70", 
       `80` = "RH% 80",`90` = "RH% 90", `100` = "RH% 100"))
  1. We add into the GGplot:
    ggplot(dataframe, aes(x = Temperature.C, y = fit)) + 
        geom_line() + 
        facet_wrap(~Humidity.RH., nrow = 2, labeller = hum.names)

Is there a way to use SVG as content in a pseudo element :before or :after

#mydiv:before {
    content: url("data:image/svg+xml; utf8, <svg.. code here</svg>");
    display:block;
    width:22px;
    height:10px;
    margin:10px 5px 0 10px;
}

make sure your svg doesn't contain double quotes, and uriencode any # symbols.

What is the meaning of single and double underscore before an object name?

Accroding to https://dbader.org/blog/meaning-of-underscores-in-python

  • Single Leading Underscore(_var): Naming convention indicating a name is meant for internal use. Generally not enforced by the Python interpreter (except in wildcard imports) and meant as a hint to the programmer only.
  • Single Trailing Underscore(var_): Used by convention to avoid naming conflicts with Python keywords.
  • Double Leading Underscore(__var): Triggers name mangling when used in a class context. Enforced by the Python interpreter.
  • Double Leading and Trailing Underscore(__var__): Indicates special methods defined by the Python language. Avoid this naming scheme for your own attributes.
  • Single Underscore(_): Sometimes used as a name for temporary or insignificant variables (“don’t care”). Also: The result of the last expression in a Python REPL.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Look at the exception:

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency

This means that there's no bean available to fulfill that dependency. Yes, you have an implementation of the interface, but you haven't created a bean for that implementation. You have two options:

  • Annotate UserDaoImpl with @Component or @Repository, and let the component scan do the work for you, exactly as you have done with UserService.
  • Add the bean manually to your xml file, the same you have done with UserBoImpl.

Remember that if you create the bean explicitly you need to put the definition before the component scan. In this case the order is important.

how to use the Box-Cox power transformation in R

Applying the BoxCox transformation to data, without the need of any underlying model, can be done currently using the package geoR. Specifically, you can use the function boxcoxfit() for finding the best parameter and then predict the transformed variables using the function BCtransform().

C++ Matrix Class

In C++ you can use like this:

matrix *p = new matrix;

After that,

delete p; 

Build a simple HTTP server in C

I have written my own that you can use. This one works has sqlite, is thread safe and is in C++ for UNIX.

You should be able to pick it apart and use the C compatible code.

http://code.google.com/p/mountain-cms/

How to fast get Hardware-ID in C#?

For more details refer to this link

The following code will give you CPU ID:

namespace required System.Management

var mbs = new ManagementObjectSearcher("Select ProcessorId From Win32_processor");
ManagementObjectCollection mbsList = mbs.Get();
string id = "";
foreach (ManagementObject mo in mbsList)
{
    id = mo["ProcessorId"].ToString();
    break;
}

For Hard disk ID and motherboard id details refer this-link

To speed up this procedure, make sure you don't use SELECT *, but only select what you really need. Use SELECT * only during development when you try to find out what you need to use, because then the query will take much longer to complete.

How to install Python MySQLdb module using pip?

Go to pycharm then go to default setting --> pip (double click) -- pymsqldb..-- > install --after installing use in a program like this

import pymysql as MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","root","test" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("show tables")

# Fetch a single row using fetchone() method.
data = cursor.fetchall()
print (data)

# disconnect from server
db.close()

CSS content property: is it possible to insert HTML instead of Text?

In CSS3 paged media this is possible using position: running() and content: element().

Example from the CSS Generated Content for Paged Media Module draft:

@top-center {
  content: element(heading); 
}

.runner { 
  position: running(heading);
}

.runner can be any element and heading is an arbitrary name for the slot.

EDIT: to clarify, there is basically no browser support so this was mostly meant to be for future reference/in addition to the 'practical answers' given already.

Where does the iPhone Simulator store its data?

There is another (faster?) way to find where your app data is without Terminal:

  1. Launch the app in the simulator
  2. Open Activity Monitor
  3. Find the name of your app in the CPU tab
  4. Double-click it and open the "Open Files and Ports"

enter image description here

How to use "/" (directory separator) in both Linux and Windows in Python?

If you are fortunate enough to be running Python 3.4+, you can use pathlib:

from pathlib import Path

path = Path(dir, subdir, filename)  # returns a path of the system's path flavour

or, equivalently,

path = Path(dir) / subdir / filename

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

Difference of two date time in sql server

Sol-1:

select 
  StartTime
  , EndTime
  , CONVERT(NVARCHAR,(EndTime-StartTime), 108) as TimeDiff 
from 
  [YourTable]

Sol-2:

select 
  StartTime
  , EndTime
  , DATEDIFF(hh, StartTime, EndTime)
  , DATEDIFF(mi, StartTime, EndTime) % 60 
from 
  [YourTable]

Sol-3:

select 
  DATEPART(hour,[EndTime]-[StartTime])
  , DATEPART(minute,[EndTime]-[StartTime]) 
from 
  [YourTable]

Datepart works the best

To switch from vertical split to horizontal split fast in Vim

Ctrl-w followed by H, J, K or L (capital) will move the current window to the far left, bottom, top or right respectively like normal cursor navigation.

The lower case equivalents move focus instead of moving the window.

Find by key deep in a nested array

Some time ago I have made a small lib find-and, which is available on npm, for working with nested objects in a lodash manner. There's the returnFound function which returns the found object, or an object array if there's more than one object found.

E.g.,

const findAnd = require('find-and');

const a = [
  {
    'title': "some title",
    'channel_id':'123we',
    'options': [
      {
        'channel_id':'abc',
        'image':'http://asdasd.com/all-inclusive-block-img.jpg',
        'title':'All-Inclusive',
        'options':[
          {
            'channel_id':'dsa2',
            'title':'Some Recommends',
            'options':[
              {
                'image':'http://www.asdasd.com',
                'title':'Sandals',
                'id':'1',
                'content':{},
              },
            ],
          },
        ],
      },
    ],
  },
];

findAnd.returnFound(a, {id: '1'});

returns

{
  'image':'http://www.asdasd.com',
  'title':'Sandals',
  'id':'1',
  'content':{},
}

Set background color in PHP?

You can use php in the style sheet. Just remember to set header("Content-type: text/css") in the style.php (or whatever then name is) file

Best way to test exceptions with Assert to ensure they will be thrown

With most .net unit testing frameworks you can put an [ExpectedException] attribute on the test method. However this can't tell you that the exception happened at the point you expected it to. That's where xunit.net can help.

With xunit you have Assert.Throws, so you can do things like this:

    [Fact]
    public void CantDecrementBasketLineQuantityBelowZero()
    {
        var o = new Basket();
        var p = new Product {Id = 1, NetPrice = 23.45m};
        o.AddProduct(p, 1);
        Assert.Throws<BusinessException>(() => o.SetProductQuantity(p, -3));
    }

[Fact] is the xunit equivalent of [TestMethod]

Most efficient way to concatenate strings in JavaScript?

Seems based on benchmarks at JSPerf that using += is the fastest method, though not necessarily in every browser.

For building strings in the DOM, it seems to be better to concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.

(Thanks @zAlbee for correction)

Find duplicate entries in a column

Try this query.. It uses the Analytic function SUM:

SELECT * FROM
(  
 SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
 FROM table1 a 
 WHERE s_ind ='Y'   
)
WHERE cnt > 2

Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1

Ant: How to execute a command for each file in directory?

ant-contrib is evil; write a custom ant task.

ant-contrib is evil because it tries to convert ant from a declarative style to an imperative style. But xml makes a crap programming language.

By contrast a custom ant task allows you to write in a real language (Java), with a real IDE, where you can write unit tests to make sure you have the behavior you want, and then make a clean declaration in your build script about the behavior you want.

This rant only matters if you care about writing maintainable ant scripts. If you don't care about maintainability by all means do whatever works. :)

Jtf

Deploy a project using Git push

After many false starts and dead ends, I'm finally able to deploy website code with just "git push remote" thanks to this article.

The author's post-update script is only one line long and his solution doesn't require .htaccess configuration to hide the Git repo as some others do.

A couple of stumbling blocks if you're deploying this on an Amazon EC2 instance;

1) If you use sudo to create the bare destination repository, you have to change the owner of the repo to ec2-user or the push will fail. (Try "chown ec2-user:ec2-user repo.")

2) The push will fail if you don't pre-configure the location of your amazon-private-key.pem, either in /etc/ssh/ssh_config as an IdentityFile parameter or in ~/.ssh/config using the "[Host] - HostName - IdentityFile - User" layout described here...

...HOWEVER if Host is configured in ~/.ssh/config and different than HostName the Git push will fail. (That's probably a Git bug)

Target Unreachable, identifier resolved to null in JSF 2.2

  1. You need

    @ManagedBean(name="userBean")

  2. Make sure you have getUser() method.

  3. Type of setUser() method should be void.

  4. Make sure that User class has proper setters and getters as well.

How to Batch Rename Files in a macOS Terminal?

You could use sed:

ls * | sed -e 'p;s@_.*_@_@g' | xargs -n2 mv

result:

prefix_567.png prefix_efg.png

*to do a dry-run first, replace mv at the end with echo

Explanation:

  • e: optional for only 1 sed command.
  • p: to print the input to sed, in this case it will be the original file name before any renaming
  • @: is a replacement of / character to make sed more readable. That is, instead of using sed s/search/replace/g, use s@search@replace@g
  • _.* : the underscore is an escape character to refer to the actual '.' character zero or more times (as opposed to ANY character in regex)
  • -n2: indicates that there are 2 outputs that need to be passed on to mv as parameters. for each input from ls, this sed command will generate 2 output, which will then supplied to mv.

HTML favicon won't show on google chrome

I've found that (at Chrome 56, OSX) the favicon state appears to be cached for the browser lifetime, so if a favicon isn't being loaded, it won't be until after restarting Chrome. It appears that it doesn't show up in the "application" tab in dev tools and isn't cleared by a hard reload or 'Clear site data'.

How to open a web page from my application?

The old school way ;)

public static void openit(string x) {
   System.Diagnostics.Process.Start("cmd", "/C start" + " " + x); 
}

Use: openit("www.google.com");

How to read a file into a variable in shell?

Two important pitfalls

which were ignored by other answers so far:

  1. Trailing newline removal from command expansion
  2. NUL character removal

Trailing newline removal from command expansion

This is a problem for the:

value="$(cat config.txt)"

type solutions, but not for read based solutions.

Command expansion removes trailing newlines:

S="$(printf "a\n")"
printf "$S" | od -tx1

Outputs:

0000000 61
0000001

This breaks the naive method of reading from files:

FILE="$(mktemp)"
printf "a\n\n" > "$FILE"
S="$(<"$FILE")"
printf "$S" | od -tx1
rm "$FILE"

POSIX workaround: append an extra char to the command expansion and remove it later:

S="$(cat $FILE; printf a)"
S="${S%a}"
printf "$S" | od -tx1

Outputs:

0000000 61 0a 0a
0000003

Almost POSIX workaround: ASCII encode. See below.

NUL character removal

There is no sane Bash way to store NUL characters in variables.

This affects both expansion and read solutions, and I don't know any good workaround for it.

Example:

printf "a\0b" | od -tx1
S="$(printf "a\0b")"
printf "$S" | od -tx1

Outputs:

0000000 61 00 62
0000003

0000000 61 62
0000002

Ha, our NUL is gone!

Workarounds:

  • ASCII encode. See below.

  • use bash extension $"" literals:

    S=$"a\0b"
    printf "$S" | od -tx1
    

    Only works for literals, so not useful for reading from files.

Workaround for the pitfalls

Store an uuencode base64 encoded version of the file in the variable, and decode before every usage:

FILE="$(mktemp)"
printf "a\0\n" > "$FILE"
S="$(uuencode -m "$FILE" /dev/stdout)"
uudecode -o /dev/stdout <(printf "$S") | od -tx1
rm "$FILE"

Output:

0000000 61 00 0a
0000003

uuencode and udecode are POSIX 7 but not in Ubuntu 12.04 by default (sharutils package)... I don't see a POSIX 7 alternative for the bash process <() substitution extension except writing to another file...

Of course, this is slow and inconvenient, so I guess the real answer is: don't use Bash if the input file may contain NUL characters.

Styles.Render in MVC4

I did all things necessary to add bundling to an MVC 3 web (I'm new to the existing solution). Styles.Render didn't work for me. I finally discovered I was simply missing a colon. In a master page: <%: Styles.Render("~/Content/Css") %> I'm still confused about why (on the same page) <% Html.RenderPartial("LogOnUserControl"); %> works without the colon.

A non-blocking read on a subprocess.PIPE in Python

Here is a simple solution based on threads which:

  • works on both Linux and Windows (not relying on select).
  • reads both stdout and stderr asynchronouly.
  • doesn't rely on active polling with arbitrary waiting time (CPU friendly).
  • doesn't use asyncio (which may conflict with other libraries).
  • runs until the child process terminates.

printer.py

import time
import sys

sys.stdout.write("Hello\n")
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("World!\n")
sys.stdout.flush()
time.sleep(1)
sys.stderr.write("That's an error\n")
sys.stderr.flush()
time.sleep(2)
sys.stdout.write("Actually, I'm fine\n")
sys.stdout.flush()
time.sleep(1)

reader.py

import queue
import subprocess
import sys
import threading


def enqueue_stream(stream, queue, type):
    for line in iter(stream.readline, b''):
        queue.put(str(type) + line.decode('utf-8'))
    stream.close()


def enqueue_process(process, queue):
    process.wait()
    queue.put('x')


p = subprocess.Popen('python printer.py', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
q = queue.Queue()
to = threading.Thread(target=enqueue_stream, args=(p.stdout, q, 1))
te = threading.Thread(target=enqueue_stream, args=(p.stderr, q, 2))
tp = threading.Thread(target=enqueue_process, args=(p, q))
te.start()
to.start()
tp.start()

while True:
    line = q.get()
    if line[0] == 'x':
        break
    if line[0] == '2':  # stderr
        sys.stdout.write("\033[0;31m")  # ANSI red color
    sys.stdout.write(line[1:])
    if line[0] == '2':
        sys.stdout.write("\033[0m")  # reset ANSI code
    sys.stdout.flush()

tp.join()
to.join()
te.join()

How to hide the title bar for an Activity in XML with existing custom theme

There are mentions of it in this post but no one explicitly addresses it, so maybe this will save people some time. If you are like me and have multiple classes extending one root class which extends ActionBarActivity, it may not be immediately obvious that trying to set that activity to a NoTitleBar/NoActionBar will throw an error, specifically:

"You need to use a Theme.AppCompat theme (or descendant) with this activity"

You can fix this changing the extends to Activity.

Drawing an image from a data URL to a canvas

Just to add to the other answers: In case you don't like the onload callback approach, you can "promisify" it like so:

let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img

pull out p-values and r-squared from a linear regression

Another option is to use the cor.test function, instead of lm:

> x <- c(44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1)
> y <- c( 2.6,  3.1,  2.5,  5.0,  3.6,  4.0,  5.2,  2.8,  3.8)

> mycor = cor.test(x,y)
> mylm = lm(x~y)

# r and rsquared:
> cor.test(x,y)$estimate ** 2
      cor 
0.3262484 
> summary(lm(x~y))$r.squared
[1] 0.3262484

# P.value 

> lmp(lm(x~y))  # Using the lmp function defined in Chase's answer
[1] 0.1081731
> cor.test(x,y)$p.value
[1] 0.1081731

Save and load MemoryStream to/from a file

For anyone looking for the short versions:

var memoryStream = new MemoryStream(File.ReadAllBytes("1.dat"));

File.WriteAllBytes("1.dat", memoryStream.ToArray()); 

MySQL Select Date Equal to Today

This query will use index if you have it for signup_date field

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
    FROM users 
    WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)

Get Table and Index storage size in sql server

This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:

SELECT 
    s.Name AS SchemaName,
    t.NAME AS TableName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM 
    sys.tables t
INNER JOIN 
    sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE 'dt%'    -- filter out system tables for diagramming
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    s.Name, t.Name

If you want to separate table space from index space, you need to use AND i.index_id IN (0,1) for the table space (index_id = 0 is the heap space, index_id = 1 is the size of the clustered index = data pages) and AND i.index_id > 1 for the index-only space

iPhone App Icons - Exact Radius?

Important: iOS 7 icon equation

With the upcoming release of iOS 7 you will notice that the "standard" icon radius has been increased. So try to do what Apple and I suggested with this answer.

It appears that for a 120px icon the formula that best represents its shape on iOS 7 is the following superellipse:

|x/120|^5 + |y/120|^5 = 1

Obviously you can change the 120 number with the desired icon size to get the corresponding function.

Original

You should provide an image that has 90° corners (it’s important to avoid cropping the corners of your icon—iOS does that for you when it applies the corner-rounding mask) (Apple Documentation)

The best approach is not rounding the corners of your icons at all. If you set your icon as a square icon, iOS will automatically overlay the icon with a predefined mask that will set the appropriate rounded corners.

If you manually set rounded corners for your icons, they will probably look broken in this or that device, because the rounding mask happens to slightly change from an iOS version to another. Sometimes your icons will be slightly larger, sometimes (sigh) slightly smaller. Using a square icon will free you from this burden, and you will be sure to have an always up-to-date and good looking icon for your app.

This approach is valid for each icon size (iPhone/iPod/iPad/retina), and also for the iTunes artwork. I followed this approach a couple of times, and if you want I can post you a link to an app that uses native square icons.

Edit

To better understand this answer, please refer to the official Apple documentation about iOS icons. In this page it is clearly stated that a square icon will automatically get these things when displayed on an iOS device:

  1. Rounded corners
  2. Drop shadow
  3. Reflective shine (unless you prevent the shine effect)

So, you can achieve whatever effect you want just drawing a plain square icon and filling content in it. The final corner radius will be something similar to what the other answers here are saying, but this will never be guaranteed, since those numbers are not part of the official Apple documentation on iOS. They ask you to draw square icons, so ... why not?

Writing .csv files from C++

As explained above by @kris, depending on the region configurations of MS Excel it won't interpret the comma as the separator character. In my case I had to change it to semi-colon

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

The window.navigator.platform property is not spoofed when the userAgent string is changed. I tested on my Mac if I change the userAgent to iPhone or Chrome Windows, navigator.platform remains MacIntel.

navigator.platform is not spoofed when the userAgent string is changed

The property is also read-only

navigator.platform is read-only


I could came up with the following table

Mac Computers

Mac68K Macintosh 68K system.
MacPPC Macintosh PowerPC system.
MacIntel Macintosh Intel system.

iOS Devices

iPhone iPhone.
iPod iPod Touch.
iPad iPad.


Modern macs returns navigator.platform == "MacIntel" but to give some "future proof" don't use exact matching, hopefully they will change to something like MacARM or MacQuantum in future.

var isMac = navigator.platform.toUpperCase().indexOf('MAC')>=0;

To include iOS that also use the "left side"

var isMacLike = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
var isIOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);

_x000D_
_x000D_
var is_OSX = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
var is_iOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
_x000D_
var is_Mac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;_x000D_
var is_iPhone = navigator.platform == "iPhone";_x000D_
var is_iPod = navigator.platform == "iPod";_x000D_
var is_iPad = navigator.platform == "iPad";_x000D_
_x000D_
/* Output */_x000D_
var out = document.getElementById('out');_x000D_
if (!is_OSX) out.innerHTML += "This NOT a Mac or an iOS Device!";_x000D_
if (is_Mac) out.innerHTML += "This is a Mac Computer!\n";_x000D_
if (is_iOS) out.innerHTML += "You're using an iOS Device!\n";_x000D_
if (is_iPhone) out.innerHTML += "This is an iPhone!";_x000D_
if (is_iPod) out.innerHTML += "This is an iPod Touch!";_x000D_
if (is_iPad) out.innerHTML += "This is an iPad!";_x000D_
out.innerHTML += "\nPlatform: " + navigator.platform;
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_


Since most O.S. use the close button on the right, you can just move the close button to the left when the user is on a MacLike O.S., otherwise isn't a problem if you put it on the most common side, the right.

_x000D_
_x000D_
setTimeout(test, 1000); //delay for demonstration_x000D_
_x000D_
function test() {_x000D_
_x000D_
  var mac = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
_x000D_
  if (mac) {_x000D_
    document.getElementById('close').classList.add("left");_x000D_
  }_x000D_
}
_x000D_
#window {_x000D_
  position: absolute;_x000D_
  margin: 1em;_x000D_
  width: 300px;_x000D_
  padding: 10px;_x000D_
  border: 1px solid gray;_x000D_
  background-color: #DDD;_x000D_
  text-align: center;_x000D_
  box-shadow: 0px 1px 3px #000;_x000D_
}_x000D_
#close {_x000D_
  position: absolute;_x000D_
  top: 0px;_x000D_
  right: 0px;_x000D_
  width: 22px;_x000D_
  height: 22px;_x000D_
  margin: -12px;_x000D_
  box-shadow: 0px 1px 3px #000;_x000D_
  background-color: #000;_x000D_
  border: 2px solid #FFF;_x000D_
  border-radius: 22px;_x000D_
  color: #FFF;_x000D_
  text-align: center;_x000D_
  font: 14px"Comic Sans MS", Monaco;_x000D_
}_x000D_
#close.left{_x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="window">_x000D_
  <div id="close">x</div>_x000D_
  <p>Hello!</p>_x000D_
  <p>If the "close button" change to the left side</p>_x000D_
  <p>you're on a Mac like system!</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://www.nczonline.net/blog/2007/12/17/don-t-forget-navigator-platform/

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

Look here for the answer by TheMattster. I implemented it and it worked like a charm. In a nutshell, his solution suggests to add the COM dll as a resource to the project (so now it compiles into the project's dll), and upon the first run write it to a file (i.e. the dll file I wanted there in the first place).

The following is taken from his answer.

Step 1) Add the DLL as a resource (below as "Resources.DllFile"). To do this open project properties, select the resources tab, select "add existing file" and add the DLL as a resource.

Step 2) Add the name of the DLL as a string resource (below as "Resources.DllName").

Step 3) Add this code to your main form-load:

if (!File.Exists(Properties.Resources.DllName))
{
    var outStream = new StreamWriter(Properties.Resources.DllName, false);
    var binStream = new BinaryWriter(outStream.BaseStream);
    binStream.Write(Properties.Resources.DllFile);
    binStream.Close();
}

My problem was that not only I had to use the COM dll in my project, I also had to deploy it with my app using ClickOnce, and without being able to add reference to it in my project the above solution is practically the only one that worked.

Exporting PDF with jspdf not rendering CSS

As I know jsPDF is not working with CSS and the same issue I was facing.

To solve this issue, I used Html2Canvas. Just Add HTML2Canvas JS and then use pdf.addHTML() instead of pdf.fromHTML().

Here's my code (no other code):

 var pdf = new jsPDF('p', 'pt', 'letter');
 pdf.addHTML($('#ElementYouWantToConvertToPdf')[0], function () {
     pdf.save('Test.pdf');
 });

Best of Luck!

Edit: Refer to this line in case you didn't find .addHTML()

How to generate a random alpha-numeric string

Best Random String Generator Method

public class RandomStringGenerator{

    private static int randomStringLength = 25 ;
    private static boolean allowSpecialCharacters = true ;
    private static String specialCharacters = "!@$%*-_+:";
    private static boolean allowDuplicates = false ;

    private static boolean isAlphanum = false;
    private static boolean isNumeric = false;
    private static boolean isAlpha = false;
    private static final String alphabet = "abcdefghijklmnopqrstuvwxyz";
    private static boolean mixCase = false;
    private static final String capAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String num = "0123456789";

    public static String getRandomString() {
        String returnVal = "";
        int specialCharactersCount = 0;
        int maxspecialCharacters = randomStringLength/4;

        try {
            StringBuffer values = buildList();
            for (int inx = 0; inx < randomStringLength; inx++) {
                int selChar = (int) (Math.random() * (values.length() - 1));
                if (allowSpecialCharacters)
                {
                    if (specialCharacters.indexOf("" + values.charAt(selChar)) > -1)
                    {
                        specialCharactersCount ++;
                        if (specialCharactersCount > maxspecialCharacters)
                        {
                            while (specialCharacters.indexOf("" + values.charAt(selChar)) != -1)
                            {
                                selChar = (int) (Math.random() * (values.length() - 1));
                            }
                        }
                    }
                }
                returnVal += values.charAt(selChar);
                if (!allowDuplicates) {
                    values.deleteCharAt(selChar);
                }
            }
        } catch (Exception e) {
            returnVal = "Error While Processing Values";
        }
        return returnVal;
    }

    private static StringBuffer buildList() {
        StringBuffer list = new StringBuffer(0);
        if (isNumeric || isAlphanum) {
            list.append(num);
        }
        if (isAlpha || isAlphanum) {
            list.append(alphabet);
            if (mixCase) {
                list.append(capAlpha);
            }
        }
        if (allowSpecialCharacters)
        {
            list.append(specialCharacters);
        }
        int currLen = list.length();
        String returnVal = "";
        for (int inx = 0; inx < currLen; inx++) {
            int selChar = (int) (Math.random() * (list.length() - 1));
            returnVal += list.charAt(selChar);
            list.deleteCharAt(selChar);
        }
        list = new StringBuffer(returnVal);
        return list;
    }   

}

convert date string to mysql datetime field

SELECT *
FROM table_name
WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) ,  '-', SUBSTRING( json_date, 7, 2 ) ,  '-', SUBSTRING( json_date, 3, 2 ) ) >= NOW();

json_date ["05/11/2011"]

Hide text using css

Jeffrey Zeldman suggests the following solution:

.hide-text {
  text-indent: 100%;
  white-space: nowrap;
  overflow: hidden;
}

It should be less resource intensive than -9999px;

Please read all about it here:

http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/

"No cached version... available for offline mode."

Just happened to me after upgrading to Android Studio 3.1. The Offline Work checkbox was unchecked, so no luck there.

I went to Settings > Build, Execution, Deployment > Compiler and the Command-line Options textfield contained --offline, so I just deleted that and everything worked.

setting screenshot

Can I use jQuery to check whether at least one checkbox is checked?

if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }

How do I display a text file content in CMD?

If you want it to display the content of the file live, and update when the file is altered, just use this script:

@echo off
:start
cls
type myfile.txt
goto start

That will repeat forever until you close the cmd window.

React Native: Possible unhandled promise rejection

In My case, I am running a local Django backend in IP 127.0.0.1:8000 with Expo start. Just make sure you have the server in public domain not hosted lcoally on your machine

Differences between "java -cp" and "java -jar"?

I prefer the first version to start a java application just because it has less pitfalls ("welcome to classpath hell"). The second one requires an executable jar file and the classpath for that application has to be defined inside the jar's manifest (all other classpath declaration will be silently ignored...). So with the second version you'd have to look into the jar, read the manifest and try to find out if the classpath entries are valid from where the jar is stored... That's avoidable.

I don't expect any performance advantages or disadvantages for either version. It's just telling the jvm which class to use for the main thread and where it can find the libraries.

What's the difference between fill_parent and wrap_content?

Either attribute can be applied to View's (visual control) horizontal or vertical size. It's used to set a View or Layouts size based on either it's contents or the size of it's parent layout rather than explicitly specifying a dimension.

fill_parent (deprecated and renamed MATCH_PARENT in API Level 8 and higher)

Setting the layout of a widget to fill_parent will force it to expand to take up as much space as is available within the layout element it's been placed in. It's roughly equivalent of setting the dockstyle of a Windows Form Control to Fill.

Setting a top level layout or control to fill_parent will force it to take up the whole screen.

wrap_content

Setting a View's size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains. For controls -- like text boxes (TextView) or images (ImageView) -- this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.

It's roughly the equivalent of setting a Windows Form Control's Autosize property to True.

Online Documentation

There's some details in the Android code documentation here.

Convert hex string to int in Python

If you are using the python interpreter, you can just type 0x(your hex value) and the interpreter will convert it automatically for you.

>>> 0xffff

65535

How to pass a function as a parameter in Java?

I know this is a rather old post but I have another slightly simpler solution. You could create another class within and make it abstract. Next make an Abstract method name it whatever you like. In the original class make a method that takes the new class as a parameter, in this method call the abstract method. It will look something like this.

public class Demo {

    public Demo(/.../){

    }

    public void view(Action a){
        a.preform();
    }

    /**
     * The Action Class is for making the Demo
     * View Custom Code
     */
    public abstract class Action {

        public Action(/.../){

        }

        abstract void preform();
    }
}

Now you can do something like this to call a method from within the class.

/...
Demo d = new Demo;
Action a = new Action() {

    @Override
    void preform() {
        //Custom Method Code Goes Here
    }
};

/.../
d.view(a)

Like I said I know its old but this way I think is a little easier. Hope it helps.

How to use ternary operator in razor (specifically on HTML attributes)?

in my problem I want the text of anchor <a>text</a> inside my view to be based on some value and that text is retrieved form App string Resources

so, this @() is the solution

<a href='#'>
      @(Model.ID == 0 ? Resource_en.Back : Resource_en.Department_View_DescartChanges)
</a>

if the text is not from App string Resources use this

@(Model.ID == 0 ? "Back" :"Descart Changes")

Substring in excel

In Excel, the substring function is called MID function, and indexOf is called FIND for case-sensitive location and SEARCH function for non-case-sensitive location. For the first portion of your text parsing the LEFT function may also be useful.

See all the text functions here: Text Functions (reference).

Full worksheet function reference lists available at:

    Excel functions (by category)
    Excel functions (alphabetical)

jquery's append not working with svg element?

Based on @chris-dolphin 's answer but using helper function:

// Creates svg element, returned as jQuery object
function $s(elem) {
  return $(document.createElementNS('http://www.w3.org/2000/svg', elem));
}

var $svg = $s("svg");
var $circle = $s("circle").attr({...});
$svg.append($circle);

How do I create dynamic variable names inside a loop?

Use an array for this.

var markers = [];
for (var i = 0; i < coords.length; ++i) {
    markers[i] = "some stuff";
}

What's the main difference between int.Parse() and Convert.ToInt32

Int32.parse(string)--->

Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent. When s is a null reference, it will throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException. For example:

string s1 = "1234"; 
string s2 = "1234.65"; 
string s3 = null; 
string s4 = "123456789123456789123456789123456789123456789"; 

result = Int32.Parse(s1);    //1234
result = Int32.Parse(s2);    //FormatException
result = Int32.Parse(s3);    //ArgumentNullException 
result = Int32.Parse(s4);    //OverflowException

Convert.ToInt32(string) --> Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

For example:

 result = Convert.ToInt32(s1);    // 1234 
 result = Convert.ToInt32(s2);    // FormatException
 result = Convert.ToInt32(s3);    // 0
 result = Convert.ToInt32(s4);    // OverflowException 

Specifying content of an iframe instead of the src attribute to a page

iframe now supports srcdoc which can be used to specify the HTML content of the page to show in the inline frame.

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

Python 3 handles strings a bit different. Originally there was just one type for strings: str. When unicode gained traction in the '90s the new unicode type was added to handle Unicode without breaking pre-existing code1. This is effectively the same as str but with multibyte support.

In Python 3 there are two different types:

  • The bytes type. This is just a sequence of bytes, Python doesn't know anything about how to interpret this as characters.
  • The str type. This is also a sequence of bytes, but Python knows how to interpret those bytes as characters.
  • The separate unicode type was dropped. str now supports unicode.

In Python 2 implicitly assuming an encoding could cause a lot of problems; you could end up using the wrong encoding, or the data may not have an encoding at all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to guess) is often a lot better and much more in line with the "Python philosophy" of "explicit is better than implicit".

This change is incompatible with Python 2 as many return values have changed, leading to subtle problems like this one; it's probably the main reason why Python 3 adoption has been so slow. Since Python doesn't have static typing2 it's impossible to change this automatically with a script (such as the bundled 2to3).

  • You can convert str to bytes with bytes('h€llo', 'utf-8'); this should produce b'H\xe2\x82\xacllo'. Note how one character was converted to three bytes.
  • You can convert bytes to str with b'H\xe2\x82\xacllo'.decode('utf-8').

Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.

In your specific piece of code, nextline is of type bytes, not str, reading stdout and stdin from subprocess changed in Python 3 from str to bytes. This is because Python can't be sure which encoding this uses. It probably uses the same as sys.stdin.encoding (the encoding of your system), but it can't be sure.

You need to replace:

sys.stdout.write(nextline)

with:

sys.stdout.write(nextline.decode('utf-8'))

or maybe:

sys.stdout.write(nextline.decode(sys.stdout.encoding))

You will also need to modify if nextline == '' to if nextline == b'' since:

>>> '' == b''
False

Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.


1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A') and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.

2 Yes, you can use function annotations, but it's a comparatively new feature and little used.

#include errors detected in vscode

After closing and reopening VS, this should resolve.

Substring in VBA

Shorter:

   Split(stringval,":")(0)

How to run a cron job on every Monday, Wednesday and Friday?

This is how I configure it on my server:

0  19  *  *  1,3,5 root bash /home/divo/data/support_files/support_files_inc_backup.sh

The above command will run my script at 19:00 on Monday, Wednesday, and Friday.

NB: For cron entries for day of the week (dow)

0 = Sunday
1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers

The server (that the POST request is sent to) needs to include the Content-Type header in its response.

Here's a list of typical headers to include, including one custom "X_ACCESS_TOKEN" header:

"X-ACCESS_TOKEN", "Access-Control-Allow-Origin", "Authorization", "Origin", "x-requested-with", "Content-Type", "Content-Range", "Content-Disposition", "Content-Description"

That's what your http server guy needs to configure for the web server that you're sending your requests to.

You may also want to ask your server guy to expose the "Content-Length" header.

He'll recognize this as a Cross-Origin Resource Sharing (CORS) request and should understand the implications of making those server configurations.

For details see:

Checking if element exists with Python Selenium

Solution without try&catch and without new imports:

if len(driver.find_elements_by_id('blah')) > 0: #pay attention: find_element*s*
    driver.find_element_by_id('blah').click #pay attention: find_element

How to replicate vector in c?

They would start by hiding the defining a structure that would hold members necessary for the implementation. Then providing a group of functions that would manipulate the contents of the structure.

Something like this:

typedef struct vec
{
    unsigned char* _mem;
    unsigned long _elems;
    unsigned long _elemsize;
    unsigned long _capelems;
    unsigned long _reserve;
};

vec* vec_new(unsigned long elemsize)
{
    vec* pvec = (vec*)malloc(sizeof(vec));
    pvec->_reserve = 10;
    pvec->_capelems = pvec->_reserve;
    pvec->_elemsize = elemsize;
    pvec->_elems = 0;
    pvec->_mem = (unsigned char*)malloc(pvec->_capelems * pvec->_elemsize);
    return pvec;
}

void vec_delete(vec* pvec)
{
    free(pvec->_mem);
    free(pvec);
}

void vec_grow(vec* pvec)
{
    unsigned char* mem = (unsigned char*)malloc((pvec->_capelems + pvec->_reserve) * pvec->_elemsize);
    memcpy(mem, pvec->_mem, pvec->_elems * pvec->_elemsize);
    free(pvec->_mem);
    pvec->_mem = mem;
    pvec->_capelems += pvec->_reserve;
}

void vec_push_back(vec* pvec, void* data, unsigned long elemsize)
{
    assert(elemsize == pvec->_elemsize);
    if (pvec->_elems == pvec->_capelems) {
        vec_grow(pvec);
    }
    memcpy(pvec->_mem + (pvec->_elems * pvec->_elemsize), (unsigned char*)data, pvec->_elemsize);
    pvec->_elems++;    
}

unsigned long vec_length(vec* pvec)
{
    return pvec->_elems;
}

void* vec_get(vec* pvec, unsigned long index)
{
    assert(index < pvec->_elems);
    return (void*)(pvec->_mem + (index * pvec->_elemsize));
}

void vec_copy_item(vec* pvec, void* dest, unsigned long index)
{
    memcpy(dest, vec_get(pvec, index), pvec->_elemsize);
}

void playwithvec()
{
    vec* pvec = vec_new(sizeof(int));

    for (int val = 0; val < 1000; val += 10) {
        vec_push_back(pvec, &val, sizeof(val));
    }

    for (unsigned long index = (int)vec_length(pvec) - 1; (int)index >= 0; index--) {
        int val;
        vec_copy_item(pvec, &val, index);
        printf("vec(%d) = %d\n", index, val);
    }

    vec_delete(pvec);
}

Further to this they would achieve encapsulation by using void* in the place of vec* for the function group, and actually hide the structure definition from the user by defining it within the C module containing the group of functions rather than the header. Also they would hide the functions that you would consider to be private, by leaving them out from the header and simply prototyping them only in the C module.

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

How can I "disable" zoom on a mobile web page?

<script type="text/javascript">
document.addEventListener('touchmove', function (event) {
  if (event.scale !== 1) { event.preventDefault(); }
}, { passive: false });
</script>

Please Add the Script to Disable pinch, tap, focus Zoom

Batch file for PuTTY/PSFTP file transfer automation

You need to store the psftp script (lines from open to bye) into a separate file and pass that to psftp using -b switch:

cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b


EDIT: For username+password: As you cannot use psftp commands in a batch file, for the same reason, you cannot specify the username and the password as psftp commands. These are inputs to the open command. While you can specify the username with the open command (open <user>@<IP>), you cannot specify the password this way. This can be done on a psftp command line only. Then it's probably cleaner to do all on the command-line:

cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>

And remove the open, <user> and <PW> lines from your script.txt.

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw


What you are doing atm is that you run psftp without any parameter or commands. Once you exit it (like by typing bye), your batch file continues trying to run open command (and others), what Windows shell obviously does not understand.


If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:

(
    echo cd ...
    echo lcd ...
    echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>

How to write MySQL query where A contains ( "a" or "b" )

I user for searching the size of motorcycle :

For example : Data = "Tire cycle size 70 / 90 - 16"

i can search with "70 90 16"

$searchTerms = preg_split("/[\s,-\/?!]+/", $itemName);

foreach ($searchTerms as $term) {
        $term = trim($term);
            if (!empty($term)) {
            $searchTermBits[] = "name LIKE '%$term%'";
            }
        }

$query = "SELECT * FROM item WHERE " .implode(' AND ', $searchTermBits);

What's a quick way to comment/uncomment lines in Vim?

This solution maps / to commenting and ? to uncommenting (comment toggling using the single mapping is too complex to implement properly). It takes comment strings from VIM's builtin commentstring option which is populated from files like /usr/share/vim/vim*/ftplugin/*.vim if filetype plugin on is declared.

filetype plugin on
autocmd FileType * let b:comment = split(&commentstring, '%s', 1)
autocmd FileType * execute "map <silent> <Leader>/ :normal 0i" . b:comment[0] . "<C-O>$" . b:comment[1] . "<C-O>0<CR>"
autocmd FileType * execute "map <silent> <Leader>? :normal $" . repeat('x', strlen(b:comment[1])) . "0" . strlen(b:comment[0]) . "x<CR>"

Passing Arrays to Function in C++

firstarray and secondarray are converted to a pointer to int, when passed to printarray().

printarray(int arg[], ...) is equivalent to printarray(int *arg, ...)

However, this is not specific to C++. C has the same rules for passing array names to a function.

How do I fire an event when a iframe has finished loading in jQuery?

@Alex aw that's a bummer. What if in your iframe you had an html document that looked like:

<html>
  <head>
    <meta http-equiv="refresh" content="0;url=/pdfs/somepdf.pdf" />
  </head>
  <body>
  </body>
</html>

Definitely a hack, but it might work for Firefox. Although I wonder if the load event would fire too soon in that case.

Download a single folder or directory from a GitHub repo

Just 5 steps to go

  • Download SVN from here.
  • Open CMD and go to SVN bin directory like: cd %ProgramFiles%\SlikSvn\bin
  • Let's suppose I wan to download this directory URL
    https://github.com/ZeBobo5/Vlc.DotNet/tree/develop/src/Samples
  • Replace tree/develop or tree/master with trunk
  • Now fire this last command to download folder in same directory.
svn export https://github.com/ZeBobo5/Vlc.DotNet/trunk/src/Samples

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

There's also a shorthand ternary operator and it looks like this:

(expression1) ?: expression2 will return expression1 if it evaluates to true or expression2 otherwise.

Example:

$a = 'Apples';
echo ($a ?: 'Oranges') . ' are great!';

will return

Apples are great!

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

From the PHP Manual

how to access downloads folder in android?

You should add next permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

And then here is usages in code:

val externalFilesDir = context.getExternalFilesDir(DIRECTORY_DOWNLOADS)

Can't connect to MySQL server on 'localhost' (10061)

Nothing to do just "Reset to Default" your firewall setting it will start working.

I read many solutions but nothing worked properly, so at last I reset firewall settings which worked.

forward declaration of a struct in C?

Try this

#include <stdio.h>

struct context;

struct funcptrs{
  void (*func0)(struct context *ctx);
  void (*func1)(void);
};

struct context{
    struct funcptrs fps;
}; 

void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }

void getContext(struct context *con){
    con->fps.func0 = func0;  
    con->fps.func1 = func1;  
}

int main(int argc, char *argv[]){
 struct context c;
   c.fps.func0 = func0;
   c.fps.func1 = func1;
   getContext(&c);
   c.fps.func0(&c);
   getchar();
   return 0;
}

A Simple AJAX with JSP example

I have used jQuery AJAX to make AJAX requests.

Check the following code:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#call').click(function ()
            {
                $.ajax({
                    type: "post",
                    url: "testme", //this is my servlet
                    data: "input=" +$('#ip').val()+"&output="+$('#op').val(),
                    success: function(msg){      
                            $('#output').append(msg);
                    }
                });
            });

        });
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    input:<input id="ip" type="text" name="" value="" /><br></br>
    output:<input id="op" type="text" name="" value="" /><br></br>
    <input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
    <div id="output"></div>
</body>

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

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

Disabling right click on images using jquery

A very simple way is to add the image as a background to a DIV then load an empty transparent gif set to the same size as the DIV in the foreground. that keeps the less determined out. They cant get the background without viewing the code and copying the URL and right clicking just downloads the transparent gif.

How do I apply the for-each loop to every character in a String?

The easiest way to for-each every char in a String is to use toCharArray():

for (char ch: "xyz".toCharArray()) {
}

This gives you the conciseness of for-each construct, but unfortunately String (which is immutable) must perform a defensive copy to generate the char[] (which is mutable), so there is some cost penalty.

From the documentation:

[toCharArray() returns] a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.

There are more verbose ways of iterating over characters in an array (regular for loop, CharacterIterator, etc) but if you're willing to pay the cost toCharArray() for-each is the most concise.

Debug JavaScript in Eclipse

I don't believe Eclipse has a JavaScript debugger - those breakpoints are for Java code (I'm guessing you are editing a JSP file?)

Use Firebug to debug Javascript code, it's an excellent add-on that all web developers should have in their toolbox.

What are the correct version numbers for C#?

C# language version history:

These are the versions of C# known about at the time of this writing:

In response to the OP's question:

What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5?

There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (this MSDN page used to refer to it that way, for example), but the Environment.Version property still reports 4.0.xxx.

As of May 3, 2017, the C# Language Team created a history of C# versions and features on their GitHub repository: Features Added in C# Language Versions. There is also a page that tracks upcoming and recently implemented language features.

Search for all occurrences of a string in a mysql database

In phpMyAdmin a 'Search' feature is available:

  1. Select particular database not table.
  2. Click 'Search' tab
  3. Enter the search term you want
  4. Select the tables you want to search in

phpMyAdmin screen shot:

phpMyAdmin Database Search tab

The 'Search' feature is also available in MySQL Workbench:

  1. Database Menu > Search Table Data
  2. Select database and tables you want to search (it will search in selected tables only)
  3. In search you can use wildChars.

MySQL Workbench screen shot:

MySQL Workbench Database Search

iPad/iPhone hover problem causes the user to double click a link

I ran into a similar situation where I had events binded to the mouseenter/mouseleave/click states of an element, yet on an iPhone, the user had to double click the element to first trigger the mouseenter event, then again to fire the click event.

I resolved this using a similar method as above, but I made use of the jQuery $.browser plugin (for jQuery 1.9>) and added a .trigger event to the mouseenter binding event, as follows:

// mouseenter event
$('.element').on( "mouseenter", function() {
    // insert mouseenter events below

    // double click fix for iOS and mouseenter events
    if ($.browser.iphone || $.browser.ipad) $(this).trigger('click');
});
// mouseleave event
$('.element').on( "mouseleave", function() { 
    // insert mouseout events below
});
// onclick event
$('.element').on( "click", function() {
    // insert click events below
});

The .trigger prevents the need to double click the element by firing the .click event handler upon mouseenter (or initial click) of the element when viewed on iPhones or iPads. Might not be the most elegant solution, but it works great in my case and utilizes a plugin that I already had in place, and required me to add a single line of code to get my existing events working under these devices.

You can get the jQuery $.browser plugin here: https://github.com/gabceb/jquery-browser-plugin

How to resolve compiler warning 'implicit declaration of function memset'

memset requires you to import the header string.h file. So just add the following header

#include <string.h>
...

Array copy values to keys in PHP

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}

iterating and filtering two lists using java 8

@DSchmdit answer worked for me. I would like to add on that. So my requirement was to filter a file based on some configurations stored in the table. The file is first retrieved and collected as list of dtos. I receive the configurations from the db and store it as another list. This is how I made the filtering work with streams

    List<FPRSDeferralModel> modelList = Files
            .lines(Paths.get("src/main/resources/rootFiles/XXXXX.txt")).parallel().parallel()
            .map(line -> {
                FileModel fileModel= new FileModel();
                line = line.trim();
                if (line != null && !line.isEmpty()) {
                    System.out.println("line" + line);
                    fileModel.setPlanId(Long.parseLong(line.substring(0, 5)));
                    fileModel.setDivisionList(line.substring(15, 30));
                    fileModel.setRegionList(line.substring(31, 50));
                    Map<String, String> newMap = new HashedMap<>();
                    newMap.put("other", line.substring(51, 80));
                    fileModel.setOtherDetailsMap(newMap);

                }
                return fileModel;
            }).collect(Collectors.toList());

    for (FileModel model : modelList) {
        System.out.println("model:" + model);
    }

    DbConfigModelList respList = populate();
    System.out.println("after populate");
    List<DbConfig> respModelList = respList.getFeedbackResponseList();


    Predicate<FileModel> somePre = s -> respModelList.stream().anyMatch(respitem -> {

        System.out.println("sinde respitem:"+respitem.getPrimaryConfig().getPlanId());
        System.out.println("s.getPlanid()"+s.getPlanId());
        System.out.println("s.getPlanId() == respitem.getPrimaryConfig().getPlanId():"+
        (s.getPlanId().compareTo(respitem.getPrimaryConfig().getPlanId())));
        return s.getPlanId().compareTo(respitem.getPrimaryConfig().getPlanId()) == 0
                && (s.getSsnId() != null);
    });



 final List<FileModel> finalList =  modelList.stream().parallel().filter(somePre).collect(Collectors.toList());

 finalList.stream().forEach(item -> {
     System.out.println("filtered item is:"+item);
 });

The details are in the implementation of filter predicates. This proves much more perfomant over iterating over loops and filtering out

How to insert a blob into a database using sql server management studio

You can insert into a varbinary(max) field using T-SQL within SQL Server Management Studio and in particular using the OPENROWSET commmand.

For example:

INSERT Production.ProductPhoto 
(
    ThumbnailPhoto, 
    ThumbnailPhotoFilePath, 
    LargePhoto, 
    LargePhotoFilePath
)
SELECT ThumbnailPhoto.*, null, null, N'tricycle_pink.gif'
FROM OPENROWSET 
    (BULK 'c:\images\tricycle.jpg', SINGLE_BLOB) ThumbnailPhoto

Take a look at the following documentation for a good example/walkthrough

Working With Large Value Types

Note that the file path in this case is relative to the targeted SQL server and not your client running this command.

What does functools.wraps do?

I very often use classes, rather than functions, for my decorators. I was having some trouble with this because an object won't have all the same attributes that are expected of a function. For example, an object won't have the attribute __name__. I had a specific issue with this that was pretty hard to trace where Django was reporting the error "object has no attribute '__name__'". Unfortunately, for class-style decorators, I don't believe that @wrap will do the job. I have instead created a base decorator class like so:

class DecBase(object):
    func = None

    def __init__(self, func):
        self.__func = func

    def __getattribute__(self, name):
        if name == "func":
            return super(DecBase, self).__getattribute__(name)

        return self.func.__getattribute__(name)

    def __setattr__(self, name, value):
        if name == "func":
            return super(DecBase, self).__setattr__(name, value)

        return self.func.__setattr__(name, value)

This class proxies all the attribute calls over to the function that is being decorated. So, you can now create a simple decorator that checks that 2 arguments are specified like so:

class process_login(DecBase):
    def __call__(self, *args):
        if len(args) != 2:
            raise Exception("You can only specify two arguments")

        return self.func(*args)

Fatal error: Namespace declaration statement has to be the very first statement in the script in

I had the same error message after running out of drive space. When I realized somehow the php file was corrupted, I copied the content and created a new file (I´m using Sublime Text for editing), and it solved my problem

Can I do Model->where('id', ARRAY) multiple where conditions?

WHERE AND SELECT Condition In Array Format Laravel

use DB;

$conditions = array(
    array('email', '=', '[email protected]')
);
$selected = array('id','name','email','mobile','created');
$result = DB::table('users')->select($selected)->where($conditions)->get();

How to reverse a 'rails generate'

You can destroy all things that was created same way except little thing change. For controller,

rails d controller_name (d stands for destroy)

For Model

rails d model_name

you just put d(destroy) instead of g(generate) in your migration.

Pandas Merge - How to avoid duplicating columns

You can work out the columns that are only in one DataFrame and use this to select a subset of columns in the merge.

cols_to_use = df2.columns.difference(df.columns)

Then perform the merge (note this is an index object but it has a handy tolist() method).

dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer')

This will avoid any columns clashing in the merge.

How to parse JSON in Java

In addition to other answers, I recomend this online opensource service jsonschema2pojo.org for quick generating Java classes from json or json schema for GSON, Jackson 1.x or Jackson 2.x. For example, if you have:

{
   "pageInfo": {
         "pageName": "abc",
         "pagePic": "http://example.com/content.jpg"
    }
    "posts": [
         {
              "post_id": "123456789012_123456789012",
              "actor_id": 1234567890,
              "picOfPersonWhoPosted": "http://example.com/photo.jpg",
              "nameOfPersonWhoPosted": "Jane Doe",
              "message": "Sounds cool. Can't wait to see it!",
              "likesCount": 2,
              "comments": [],
              "timeOfPost": 1234567890
         }
    ]
}

The jsonschema2pojo.org for GSON generated:

@Generated("org.jsonschema2pojo")
public class Container {
    @SerializedName("pageInfo")
    @Expose
    public PageInfo pageInfo;
    @SerializedName("posts")
    @Expose
    public List<Post> posts = new ArrayList<Post>();
}

@Generated("org.jsonschema2pojo")
public class PageInfo {
    @SerializedName("pageName")
    @Expose
    public String pageName;
    @SerializedName("pagePic")
    @Expose
    public String pagePic;
}

@Generated("org.jsonschema2pojo")
public class Post {
    @SerializedName("post_id")
    @Expose
    public String postId;
    @SerializedName("actor_id")
    @Expose
    public long actorId;
    @SerializedName("picOfPersonWhoPosted")
    @Expose
    public String picOfPersonWhoPosted;
    @SerializedName("nameOfPersonWhoPosted")
    @Expose
    public String nameOfPersonWhoPosted;
    @SerializedName("message")
    @Expose
    public String message;
    @SerializedName("likesCount")
    @Expose
    public long likesCount;
    @SerializedName("comments")
    @Expose
    public List<Object> comments = new ArrayList<Object>();
    @SerializedName("timeOfPost")
    @Expose
    public long timeOfPost;
}

How to export a CSV to Excel using Powershell

Why would you bother? Load your CSV into Excel like this:

$csv = Join-Path $env:TEMP "process.csv"
$xls = Join-Path $env:TEMP "process.xlsx"

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.OpenText($csv)

$wb.SaveAs($xls, 51)

You just need to make sure that the CSV export uses the delimiter defined in your regional settings. Override with -Delimiter if need be.


Edit: A more general solution that should preserve the values from the CSV as plain text. Code for iterating over the CSV columns taken from here.

$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.Add()
$ws = $wb.Sheets.Item(1)

$ws.Cells.NumberFormat = "@"

$i = 1
Import-Csv $csv | ForEach-Object {
  $j = 1
  foreach ($prop in $_.PSObject.Properties) {
    if ($i -eq 1) {
      $ws.Cells.Item($i, $j++).Value = $prop.Name
    } else {
      $ws.Cells.Item($i, $j++).Value = $prop.Value
    }
  }
  $i++
}

$wb.SaveAs($xls, 51)
$wb.Close()

$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)

Obviously this second approach won't perform too well, because it's processing each cell individually.

How to check if a value exists in a dictionary (python)

>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> 'one' in d.values()
True

Out of curiosity, some comparative timing:

>>> T(lambda : 'one' in d.itervalues()).repeat()
[0.28107285499572754, 0.29107213020324707, 0.27941107749938965]
>>> T(lambda : 'one' in d.values()).repeat()
[0.38303399085998535, 0.37257885932922363, 0.37096405029296875]
>>> T(lambda : 'one' in d.viewvalues()).repeat()
[0.32004380226135254, 0.31716084480285645, 0.3171098232269287]

EDIT: And in case you wonder why... the reason is that each of the above returns a different type of object, which may or may not be well suited for lookup operations:

>>> type(d.viewvalues())
<type 'dict_values'>
>>> type(d.values())
<type 'list'>
>>> type(d.itervalues())
<type 'dictionary-valueiterator'>

EDIT2: As per request in comments...

>>> T(lambda : 'four' in d.itervalues()).repeat()
[0.41178202629089355, 0.3959040641784668, 0.3970959186553955]
>>> T(lambda : 'four' in d.values()).repeat()
[0.4631338119506836, 0.43541407585144043, 0.4359898567199707]
>>> T(lambda : 'four' in d.viewvalues()).repeat()
[0.43414998054504395, 0.4213531017303467, 0.41684913635253906]

Read Content from Files which are inside Zip file

Because of the condition in while, the loop might never break:

while (entry != null) {
  // If entry never becomes null here, loop will never break.
}

Instead of the null check there, you can try this:

ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
  // Rest of your code
}

Convert String to Type in C#

You can only use just the name of the type (with its namespace, of course) if the type is in mscorlib or the calling assembly. Otherwise, you've got to include the assembly name as well:

Type type = Type.GetType("Namespace.MyClass, MyAssembly");

If the assembly is strongly named, you've got to include all that information too. See the documentation for Type.GetType(string) for more information.

Alternatively, if you have a reference to the assembly already (e.g. through a well-known type) you can use Assembly.GetType:

Assembly asm = typeof(SomeKnownType).Assembly;
Type type = asm.GetType(namespaceQualifiedTypeName);

How to query all the GraphQL type fields without writing a long query?

GraphQL query format was designed in order to allow:

  1. Both query and result shape be exactly the same.
  2. The server knows exactly the requested fields, thus the client downloads only essential data.

However, according to GraphQL documentation, you may create fragments in order to make selection sets more reusable:

# Only most used selection properties

fragment UserDetails on User {
    id,
    username
} 

Then you could query all user details by:

FetchUsers {
    users() {
        ...UserDetails
    }
}

You can also add additional fields alongside your fragment:

FetchUserById($id: ID!) {
    users(id: $id) {
        ...UserDetails
        count
    }
}

how to make log4j to write to the console as well

Your log4j File should look something like below read comments.

# Define the types of logger and level of logging    
log4j.rootLogger = DEBUG,console, FILE

# Define the File appender    
log4j.appender.FILE=org.apache.log4j.FileAppender    

# Define Console Appender    
log4j.appender.console=org.apache.log4j.ConsoleAppender    

# Define the layout for console appender. If you do not 
# define it, you will get an error    
log4j.appender.console.layout=org.apache.log4j.PatternLayout

# Set the name of the file    
log4j.appender.FILE.File=log.out

# Set the immediate flush to true (default)    
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode    
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite    
log4j.appender.FILE.Append=false

# Define the layout for file appender    
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout    
log4j.appender.FILE.layout.conversionPattern=%m%n

Encode html entities in javascript

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<style>_x000D_
button {_x000D_
backround: #ccc;_x000D_
padding: 14px;_x000D_
width: 400px;_x000D_
font-size: 32px;_x000D_
}_x000D_
#demo {_x000D_
font-size: 20px;_x000D_
font-family: Arial;_x000D_
font-weight: bold;_x000D_
}_x000D_
</style>_x000D_
<body>_x000D_
_x000D_
<p>Click the button to decode.</p>_x000D_
_x000D_
<button onclick="entitycode()">Html Code</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
_x000D_
<script>_x000D_
function entitycode() {_x000D_
  var uri = "quotation  = ark __ &apos; = apostrophe  __ &amp; = ampersand __ &lt; = less-than __ &gt; = greater-than __  non- = reaking space __ &iexcl; = inverted exclamation mark __ &cent; = cent __ &pound; = pound __ &curren; = currency __ &yen; = yen __ &brvbar; = broken vertical bar __ &sect; = section __ &uml; = spacing diaeresis __ &copy; = copyright __ &ordf; = feminine ordinal indicator __ &laquo; = angle quotation mark (left) __ &not; = negation __ &shy; = soft hyphen __ &reg; = registered trademark __ &macr; = spacing macron __ &deg; = degree __ &plusmn; = plus-or-minus  __ &sup2; = superscript 2 __ &sup3; = superscript 3 __ &acute; = spacing acute __ &micro; = micro __ &para; = paragraph __ &middot; = middle dot __ &cedil; = spacing cedilla __ &sup1; = superscript 1 __ &ordm; = masculine ordinal indicator __ &raquo; = angle quotation mark (right) __ &frac14; = fraction 1/4 __ &frac12; = fraction 1/2 __ &frac34; = fraction 3/4 __ &iquest; = inverted question mark __ &times; = multiplication __ &divide; = division __ &Agrave; = capital a, grave accent __ &Aacute; = capital a, acute accent __ &Acirc; = capital a, circumflex accent __ &Atilde; = capital a, tilde __ &Auml; = capital a, umlaut mark __ &Aring; = capital a, ring __ &AElig; = capital ae __ &Ccedil; = capital c, cedilla __ &Egrave; = capital e, grave accent __ &Eacute; = capital e, acute accent __ &Ecirc; = capital e, circumflex accent __ &Euml; = capital e, umlaut mark __ &Igrave; = capital i, grave accent __ &Iacute; = capital i, acute accent __ &Icirc; = capital i, circumflex accent __ &Iuml; = capital i, umlaut mark __ &ETH; = capital eth, Icelandic __ &Ntilde; = capital n, tilde __ &Ograve; = capital o, grave accent __ &Oacute; = capital o, acute accent __ &Ocirc; = capital o, circumflex accent __ &Otilde; = capital o, tilde __ &Ouml; = capital o, umlaut mark __ &Oslash; = capital o, slash __ &Ugrave; = capital u, grave accent __ &Uacute; = capital u, acute accent __ &Ucirc; = capital u, circumflex accent __ &Uuml; = capital u, umlaut mark __ &Yacute; = capital y, acute accent __ &THORN; = capital THORN, Icelandic __ &szlig; = small sharp s, German __ &agrave; = small a, grave accent __ &aacute; = small a, acute accent __ &acirc; = small a, circumflex accent __ &atilde; = small a, tilde __ &auml; = small a, umlaut mark __ &aring; = small a, ring __ &aelig; = small ae __ &ccedil; = small c, cedilla __ &egrave; = small e, grave accent __ &eacute; = small e, acute accent __ &ecirc; = small e, circumflex accent __ &euml; = small e, umlaut mark __ &igrave; = small i, grave accent __ &iacute; = small i, acute accent __ &icirc; = small i, circumflex accent __ &iuml; = small i, umlaut mark __ &eth; = small eth, Icelandic __ &ntilde; = small n, tilde __ &ograve; = small o, grave accent __ &oacute; = small o, acute accent __ &ocirc; = small o, circumflex accent __ &otilde; = small o, tilde __ &ouml; = small o, umlaut mark __ &oslash; = small o, slash __ &ugrave; = small u, grave accent __ &uacute; = small u, acute accent __ &ucirc; = small u, circumflex accent __ &uuml; = small u, umlaut mark __ &yacute; = small y, acute accent __ &thorn; = small thorn, Icelandic __ &yuml; = small y, umlaut mark";_x000D_
  var enc = encodeURI(uri);_x000D_
  var dec = decodeURI(enc);_x000D_
  var res = dec;_x000D_
  document.getElementById("demo").innerHTML = res;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to plot a function curve in R

plot has a plot.function method

plot(eq, 1, 1000)

Or

curve(eq, 1, 1000)

How can I keep my branch up to date with master with git?

If your branch is local only and hasn't been pushed to the server, use

git rebase master

Otherwise, use

git merge master

Best way to store a key=>value array in JavaScript?

In javascript a key value array is stored as an object. There are such things as arrays in javascript, but they are also somewhat considered objects still, check this guys answer - Why can I add named properties to an array as if it were an object?

Arrays are typically seen using square bracket syntax, and objects ("key=>value" arrays) using curly bracket syntax, though you can access and set object properties using square bracket syntax as Alexey Romanov has shown.

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.

Simple Array eg.

$(document).ready(function(){

    var countries = ['Canada','Us','France','Italy'];
    console.log('I am from '+countries[0]);
    $.each(countries, function(key, value) {
        console.log(key, value);
    });

});

Output -

0 "Canada"

1 "Us"

2 "France"

3 "Italy"

We see above that we can loop a numerical array using the jQuery.each function and access info outside of the loop using square brackets with numerical keys.

Simple Object (json)

$(document).ready(function(){

    var person = {
        name: "James",
        occupation: "programmer",
        height: {
            feet: 6,
            inches: 1
        },
    }

    console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation);

    $.each(person, function(key, value) {
        console.log(key, value);
    });

});

Output -

My name is James and I am a 6 ft 1 programmer

name James

occupation programmer

height Object {feet: 6, inches: 1}

In a language like php this would be considered a multidimensional array with key value pairs, or an array within an array. I'm assuming because you asked about how to loop through a key value array you would want to know how to get an object (key=>value array) like the person object above to have, let's say, more than one person.

Well, now that we know javascript arrays are used typically for numeric indexing and objects more flexibly for associative indexing, we will use them together to create an array of objects that we can loop through, like so -

JSON array (array of objects) -

$(document).ready(function(){

    var people = [
        {
            name: "James",
            occupation: "programmer",
            height: {
                feet: 6,
                inches: 1
            }
        }, {
            name: "Peter",
            occupation: "designer",
            height: {
                feet: 4,
                inches: 10
            }
        }, {
            name: "Joshua",
            occupation: "CEO",
            height: {
                feet: 5,
                inches: 11
            }
        }
    ];

    console.log("My name is "+people[2].name+" and I am a "+people[2].height.feet+" ft "+people[2].height.inches+" "+people[2].occupation+"\n");

    $.each(people, function(key, person) {
        console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation+"\n");
    });

});

Output -

My name is Joshua and I am a 5 ft 11 CEO

My name is James and I am a 6 ft 1 programmer

My name is Peter and I am a 4 ft 10 designer

My name is Joshua and I am a 5 ft 11 CEO

Note that outside the loop I have to use the square bracket syntax with a numeric key because this is now an numerically indexed array of objects, and of course inside the loop the numeric key is implied.

Looping from 1 to infinity in Python

Simplest and best:

i = 0
while not there_is_reason_to_break(i):
    # some code here
    i += 1

It may be tempting to choose the closest analogy to the C code possible in Python:

from itertools import count

for i in count():
    if thereIsAReasonToBreak(i):
        break

But beware, modifying i will not affect the flow of the loop as it would in C. Therefore, using a while loop is actually a more appropriate choice for porting that C code to Python.

Expression must be a modifiable lvalue

You test k = M instead of k == M.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))

GCC -fPIC option

A minor addition to the answers already posted: object files not compiled to be position independent are relocatable; they contain relocation table entries.

These entries allow the loader (that bit of code that loads a program into memory) to rewrite the absolute addresses to adjust for the actual load address in the virtual address space.

An operating system will try to share a single copy of a "shared object library" loaded into memory with all the programs that are linked to that same shared object library.

Since the code address space (unlike sections of the data space) need not be contiguous, and because most programs that link to a specific library have a fairly fixed library dependency tree, this succeeds most of the time. In those rare cases where there is a discrepancy, yes, it may be necessary to have two or more copies of a shared object library in memory.

Obviously, any attempt to randomize the load address of a library between programs and/or program instances (so as to reduce the possibility of creating an exploitable pattern) will make such cases common, not rare, so where a system has enabled this capability, one should make every attempt to compile all shared object libraries to be position independent.

Since calls into these libraries from the body of the main program will also be made relocatable, this makes it much less likely that a shared library will have to be copied.

What is an Endpoint?

It's one end of a communication channel, so often this would be represented as the URL of a server or service.

Making heatmap from pandas DataFrame

Surprised to see no one mentioned more capable, interactive and easier to use alternatives.

A) You can use plotly:

  1. Just two lines and you get:

  2. interactivity,

  3. smooth scale,

  4. colors based on whole dataframe instead of individual columns,

  5. column names & row indices on axes,

  6. zooming in,

  7. panning,

  8. built-in one-click ability to save it as a PNG format,

  9. auto-scaling,

  10. comparison on hovering,

  11. bubbles showing values so heatmap still looks good and you can see values wherever you want:

import plotly.express as px
fig = px.imshow(df.corr())
fig.show()

enter image description here

B) You can also use Bokeh:

All the same functionality with a tad much hassle. But still worth it if you do not want to opt-in for plotly and still want all these things:

from bokeh.plotting import figure, show, output_notebook
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.transform import transform
output_notebook()
colors = ['#d7191c', '#fdae61', '#ffffbf', '#a6d96a', '#1a9641']
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
data = df.corr().stack().rename("value").reset_index()
p = figure(x_range=list(df.columns), y_range=list(df.index), tools=TOOLS, toolbar_location='below',
           tooltips=[('Row, Column', '@level_0 x @level_1'), ('value', '@value')], height = 500, width = 500)

p.rect(x="level_1", y="level_0", width=1, height=1,
       source=data,
       fill_color={'field': 'value', 'transform': LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max())},
       line_color=None)
color_bar = ColorBar(color_mapper=LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max()), major_label_text_font_size="7px",
                     ticker=BasicTicker(desired_num_ticks=len(colors)),
                     formatter=PrintfTickFormatter(format="%f"),
                     label_standoff=6, border_line_color=None, location=(0, 0))
p.add_layout(color_bar, 'right')

show(p)

enter image description here

What is the difference between C# and .NET?

C# is a language, .NET is an application framework. The .NET libraries can run on the CLR and thus any language which can run on the CLR can also use the .NET libraries.

If you are familiar with Java, this is similar... Java is a language built on top of the JVM... though any of the pre-assembled Java libraries can be used by another language built on top of the JVM.

CSS smooth bounce animation

In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:

.ball {
  animation: bounce 1s infinite alternate;
  -webkit-animation: bounce 1s infinite alternate;
}

@keyframes bounce {
  from {
    margin-top: 0;
  }
  to {
    margin-top: -15px;
  }
}

What is the purpose of nameof?

It's really useful for ArgumentException and its derivatives:

public string DoSomething(string input) 
{
    if(input == null) 
    {
        throw new ArgumentNullException(nameof(input));
    }
    ...

Now if someone refactors the name of the input parameter the exception will be kept up to date too.

It is also useful in some places where previously reflection had to be used to get the names of properties or parameters.

In your example nameof(T) gets the name of the type parameter - this can be useful too:

throw new ArgumentException(nameof(T), $"Type {typeof(T)} does not support this method.");

Another use of nameof is for enums - usually if you want the string name of an enum you use .ToString():

enum MyEnum { ... FooBar = 7 ... }

Console.WriteLine(MyEnum.FooBar.ToString());

> "FooBar"

This is actually relatively slow as .Net holds the enum value (i.e. 7) and finds the name at run time.

Instead use nameof:

Console.WriteLine(nameof(MyEnum.FooBar))

> "FooBar"

Now .Net replaces the enum name with a string at compile time.


Yet another use is for things like INotifyPropertyChanged and logging - in both cases you want the name of the member that you're calling to be passed to another method:

// Property with notify of change
public int Foo
{
    get { return this.foo; }
    set
    {
        this.foo = value;
        PropertyChanged(this, new PropertyChangedEventArgs(nameof(this.Foo));
    }
}

Or...

// Write a log, audit or trace for the method called
void DoSomething(... params ...)
{
    Log(nameof(DoSomething), "Message....");
}

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The error tells you that there is an error but you don´t catch it. This is how you can catch it:

getAllPosts().then(response => {
    console.log(response);
}).catch(e => {
    console.log(e);
});

You can also just put a console.log(reponse) at the beginning of your API callback function, there is definitely an error message from the Graph API in it.

More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

Or with async/await:

//some async function
try {
    let response = await getAllPosts();
} catch(e) {
    console.log(e);
}

Kill python interpeter in linux from the terminal

There's a rather crude way of doing this, but be careful because first, this relies on python interpreter process identifying themselves as python, and second, it has the concomitant effect of also killing any other processes identified by that name.

In short, you can kill all python interpreters by typing this into your shell (make sure you read the caveats above!):

ps aux | grep python | grep -v "grep python" | awk '{print $2}' | xargs kill -9

To break this down, this is how it works. The first bit, ps aux | grep python | grep -v "grep python", gets the list of all processes calling themselves python, with the grep -v making sure that the grep command you just ran isn't also included in the output. Next, we use awk to get the second column of the output, which has the process ID's. Finally, these processes are all (rather unceremoniously) killed by supplying each of them with kill -9.

How to enumerate an enum

I made some extensions for easy enum usage. Maybe someone can use it...

public static class EnumExtensions
{
    /// <summary>
    /// Gets all items for an enum value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static IEnumerable<T> GetAllItems<T>(this Enum value)
    {
        foreach (object item in Enum.GetValues(typeof(T)))
        {
            yield return (T)item;
        }
    }

    /// <summary>
    /// Gets all items for an enum type.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static IEnumerable<T> GetAllItems<T>() where T : struct
    {
        foreach (object item in Enum.GetValues(typeof(T)))
        {
            yield return (T)item;
        }
    }

    /// <summary>
    /// Gets all combined items from an enum value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    /// <example>
    /// Displays ValueA and ValueB.
    /// <code>
    /// EnumExample dummy = EnumExample.Combi;
    /// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())
    /// {
    ///    Console.WriteLine(item);
    /// }
    /// </code>
    /// </example>
    public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)
    {
        int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);

        foreach (object item in Enum.GetValues(typeof(T)))
        {
            int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);

            if (itemAsInt == (valueAsInt & itemAsInt))
            {
                yield return (T)item;
            }
        }
    }

    /// <summary>
    /// Determines whether the enum value contains a specific value.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <param name="request">The request.</param>
    /// <returns>
    ///     <c>true</c> if value contains the specified value; otherwise, <c>false</c>.
    /// </returns>
    /// <example>
    /// <code>
    /// EnumExample dummy = EnumExample.Combi;
    /// if (dummy.Contains<EnumExample>(EnumExample.ValueA))
    /// {
    ///     Console.WriteLine("dummy contains EnumExample.ValueA");
    /// }
    /// </code>
    /// </example>
    public static bool Contains<T>(this Enum value, T request)
    {
        int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
        int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);

        if (requestAsInt == (valueAsInt & requestAsInt))
        {
            return true;
        }

        return false;
    }
}

The enum itself must be decorated with the FlagsAttribute:

[Flags]
public enum EnumExample
{
    ValueA = 1,
    ValueB = 2,
    ValueC = 4,
    ValueD = 8,
    Combi = ValueA | ValueB
}

How to set the initial zoom/width for a webview

The following code loads the desktop version of the Google homepage fully zoomed out to fit within the webview for me in Android 2.2 on an 854x480 pixel screen. When I reorient the device and it reloads in portrait or landscape, the page width fits entirely within the view each time.

BrowserLayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

     <WebView android:id="@+id/webview"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent" />
</LinearLayout>

Browser.java:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class Browser extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.BrowserLayout);

        String loadUrl = "http://www.google.com/webhp?hl=en&output=html";

        // initialize the browser object
        WebView browser = (WebView) findViewById(R.id.webview);

        browser.getSettings().setLoadWithOverviewMode(true);
        browser.getSettings().setUseWideViewPort(true);

        try {
            // load the url
            browser.loadUrl(loadUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How to "grep" for a filename instead of the contents of a file?

Example

find <path> -name *FileName*

From manual:

find -name pattern

Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories are removed, the file names considered for a match with -name will never include a slash, so "-name a/b" will never match anything (you probably need to use -path instead). The metacharacters ("*", "?", and "[]") match a "." at the start of the base name (this is a change in find- utils-4.2.2; see section STANDARDS CONFORMANCE below). To ignore a directory and the files under it, use -prune; see an example in the description of -path. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell.

Project vs Repository in GitHub

Fact 1: Projects and Repositories were always synonyms on GitHub.

Fact 2: This is no longer the case.

There is a lot of confusion about Repositories and Projects. In the past both terms were used pretty much interchangeably by the users and the GitHub's very own documentation. This is reflected by some of the answers and comments here that explain the subtle differences between those terms and when the one was preferred over the other. The difference were always subtle, e.g. like the issue tracker being part of the project but not part of the repository which might be thought of as a strictly git thing etc.

Not any more.

Currently repos and projects refer to a different kinds of entities that have separate APIs:

Since then it is no longer correct to call the repo a project or vice versa. Note that it is often confused in the official documentation and it is unfortunate that a term that was already widely used has been chosen as the name of the new entity but this is the case and we have to live with that.

The consequence is that repos and projects are usually confused and every time you read about GitHub projects you have to wonder if it's really about the projects or about repos. Had they chosen some other name or an abbreviation like "proj" then we could know that what is discussed is the new type of entity, a precise object with concrete properties, or a general speaking repo-like projectish kind of thingy.

The term that is usually unambiguous is "project board".

What can we learn from the API

The first endpoint in the documentation of the Projects API:

is described as: List repository projects. It means that a repository can have many projects. So those two cannot mean the same thing. It includes Response if projects are disabled:

{
  "message": "Projects are disabled for this repo",
  "documentation_url": "https://developer.github.com/v3"
}

which means that some repos can have projects disabled. Again, those cannot be the same thing when a repo can have projects disabled.

There are some other interesting endpoints:

  • Create a repository project - POST /repos/:owner/:repo/projects
  • Create an organization project - POST /orgs/:org/projects

but there is no:

  • Create a user's project - POST /users/:user/projects

Which leads us to another difference:

1. Repositories can belong to users or organizations
2. Projects can belong to repositories or organizations

or, more importantly:

1. Projects can belong to repositories but not the other way around
2. Projects can belong to organizations but not to users
3. Repositories can belong to organizations and to users

See also:

I know it's confusing. I tried to explain it as precisely as I could.

HTML5 Canvas: Zooming

One option is to use css zoom feature:

$("#canvas_id").css("zoom","x%"); 

How to set default font family in React Native?

The recommended way is to create your own component, such as MyAppText. MyAppText would be a simple component that renders a Text component using your universal style and can pass through other props, etc.

https://facebook.github.io/react-native/docs/text.html#limited-style-inheritance

npm install hangs

For anyone on MacOS (I'm on Mojave 10.14), the following helped me out: https://github.com/reactioncommerce/reaction/issues/1938#issuecomment-284207213

You'd run these commands

echo kern.maxfiles=65536 | sudo tee -a /etc/sysctl.conf
echo kern.maxfilesperproc=65536 | sudo tee -a /etc/sysctl.conf
sudo sysctl -w kern.maxfiles=65536
sudo sysctl -w kern.maxfilesperproc=65536
ulimit -n 65536

Then try npm install once more.

scp with port number specified

Hope this will help someone looking for a perfect answer

Copying a folder or file from a server with a port defined to another server or local machine

  1. Go to a directory where you have admin rights preferably your home directory on the machine where you want to copy files to
  2. Write the command below

scp -r -P port user@IP_address:/home/file/pathDirectory .

**Note:** The last . on the command directs it to copy everything in that folder to your directory of preference

Apache POI Excel - how to configure columns to be expanded?

For Excel POI:

sheetName.autoSizeColumn(cellnum); 

Best Way to do Columns in HTML/CSS

You also have CSS Grid and CSS Flex, both can give you columns that keep their position and size ratios depending on screen size, and flex can also easily rearrange the columns if screen size is too small so they can maintain a minimum width nicely.

See these guides for full details:

Grid:

.container {
  display: grid | inline-grid;
}

Flex:

.container {
  display: flex | inline-flex;
}

Could not open ServletContext resource

try with this code...

 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="ignoreUnresolvablePlaceholders" value="true"/>
             <property name="locations">
              <list>                        
                    <value>/social.properties</value>               
              </list>
         </property>         
        </bean>

How to make a cross-module variable?

You can already do this with module-level variables. Modules are the same no matter what module they're being imported from. So you can make the variable a module-level variable in whatever module it makes sense to put it in, and access it or assign to it from other modules. It would be better to call a function to set the variable's value, or to make it a property of some singleton object. That way if you end up needing to run some code when the variable's changed, you can do so without breaking your module's external interface.

It's not usually a great way to do things — using globals seldom is — but I think this is the cleanest way to do it.

How to fix broken paste clipboard in VNC on Windows

You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.

Is there "\n" equivalent in VBscript?

This page has a table of string constants including vbCrLf

vbCrLf | Chr(13) & Chr(10) | Carriage return–linefeed combination

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., UTF-8).

How to create a density plot in matplotlib?

Maybe try something like:

import matplotlib.pyplot as plt
import numpy
from scipy import stats
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
density = stats.kde.gaussian_kde(data)
x = numpy.arange(0., 8, .1)
plt.plot(x, density(x))
plt.show()

You can easily replace gaussian_kde() by a different kernel density estimate.

Check if all values in list are greater than a certain number

There is a builtin function all:

all (x > limit for x in my_list)

Being limit the value greater than which all numbers must be.

Reading a column from CSV file using JAVA

You are not changing the value of line. It should be something like this.

import java.io.BufferedReader;
import java.io.FileReader;

public class InsertValuesIntoTestDb {

  @SuppressWarnings("rawtypes")
  public static void main(String[] args) throws Exception {
      String splitBy = ",";
      BufferedReader br = new BufferedReader(new FileReader("test.csv"));
      while((line = br.readLine()) != null){
           String[] b = line.split(splitBy);
           System.out.println(b[0]);
      }
      br.close();

  }
}

readLine returns each line and only returns null when there is nothing left. The above code sets line and then checks if it is null.

Windows Forms ProgressBar: Easiest way to start/stop marquee?

There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).

How to round each item in a list of floats to 2 decimal places?

mylist = [0.30000000000000004, 0.5, 0.20000000000000001]
myRoundedList =  [round(x,2) for x in mylist] 
# [0.3, 0.5, 0.2]

How do I solve this error, "error while trying to deserialize parameter"

In my case; my WCF service function was using List<byte> Types parameter and i was getting this exception in the client side. Then i changed it to byte[] Types, updated service reference and problem is solved.

AngularJS $http-post - convert binary to excel file and download

Answer No 5 worked for me ,Suggestion to developer who are facing similar issue.

//////////////////////////////////////////////////////////
//Server side 
//////////////////////////////////////////////////////////
imports ***
public class AgentExcelBuilder extends AbstractExcelView {

protected void buildExcelDocument(Map<String, Object> model,
            HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        //poi code goes here ....

        response.setHeader("Cache-Control","must-revalidate");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-Transfer-Encoding","binary");
        response.setHeader("Content-disposition", "attachment; filename=test.xls");

        OutputStream output = response.getOutputStream();

        workbook.write(output);
        System.out.println(workbook.getActiveSheetIndex());
        System.out.println(workbook.getNumberOfSheets());
        System.out.println(workbook.getNumberOfNames());
        output.flush();
        output.close(); 
}//method buildExcelDocument ENDS

//service.js at angular JS code
function getAgentInfoExcel(workgroup,callback){
        $http({
            url: CONTEXT_PATH+'/rest/getADInfoExcel',
            method: "POST",
            data: workgroup, //this is your json data string
            headers: {
               'Content-type': 'application/json'
            },
            responseType: 'arraybuffer'
        }).success(function (data, status, headers, config) {
            var blob = new Blob([data], {type: "application/vnd.ms-excel"});
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        }).error(function (data, status, headers, config) {
            console.log('Failed to download Excel')
        });
    }
////////////////////////////////in .html 

<div class="form-group">`enter code here`
                                <a href="javascript:void(0)" class="fa fa-file-excel-o"
                                    ng-click="exportToExcel();"> Agent Export</a>
                            </div>

How do I get the key at a specific index from a Dictionary in Swift?

SWIFT 3. Example for the first element

let wordByLanguage = ["English": 5, "Spanish": 4, "Polish": 3, "Arabic": 2]

if let firstLang = wordByLanguage.first?.key {
    print(firstLang)  // English
}

How to add not null constraint to existing column in MySQL

Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

How does JavaScript .prototype work?

It's just that you already have an object with Object.new but you still don't have an object when using the constructor syntax.

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

Create a function that addresses all the whitespace possibilites and enable only those that seem appropriate:

SELECT dbo.ShowWhiteSpace(myfield) from mytable

Uncomment only those whitespace cases you want to test for:


CREATE FUNCTION dbo.ShowWhiteSpace (@str varchar(8000))
RETURNS varchar(8000)
AS
BEGIN
     DECLARE @ShowWhiteSpace varchar(8000);
     SET @ShowWhiteSpace = @str
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(32), '[?]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(13), '[CR]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(10), '[LF]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(9),  '[TAB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(1),  '[SOH]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(2),  '[STX]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(3),  '[ETX]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(4),  '[EOT]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(5),  '[ENQ]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(6),  '[ACK]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(7),  '[BEL]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(8),  '[BS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(11), '[VT]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(12), '[FF]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(14), '[SO]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(15), '[SI]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(16), '[DLE]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(17), '[DC1]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(18), '[DC2]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(19), '[DC3]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(20), '[DC4]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(21), '[NAK]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(22), '[SYN]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(23), '[ETB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(24), '[CAN]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(25), '[EM]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(26), '[SUB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(27), '[ESC]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(28), '[FS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(29), '[GS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(30), '[RS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(31), '[US]')
     RETURN(@ShowWhiteSpace)
END

Colspan all columns

As a partial answer, here's a few points about colspan="0", which was mentioned in the question.

tl;dr version:

colspan="0" doesn't work in any browser whatsoever. W3Schools is wrong (as usual). HTML 4 said that colspan="0" should cause a column to span the whole table, but nobody implemented this and it was removed from the spec after HTML 4.

Some more detail and evidence:

  • All major browsers treat it as equivalent to colspan="1".

    Here's a demo showing this; try it on any browser you like.

    _x000D_
    _x000D_
    td {_x000D_
      border: 1px solid black;_x000D_
    }
    _x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>ay</td>_x000D_
        <td>bee</td>_x000D_
        <td>see</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="0">colspan="0"</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="1">colspan="1"</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="3">colspan="3"</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td colspan="1000">colspan="1000"</td>_x000D_
      </tr>_x000D_
    </table>
    _x000D_
    _x000D_
    _x000D_

  • The HTML 4 spec (now old and outdated, but current back when this question was asked) did indeed say that colspan="0" should be treated as spanning all columns:

    The value zero ("0") means that the cell spans all columns from the current column to the last column of the column group (COLGROUP) in which the cell is defined.

    However, most browsers never implemented this.

  • HTML 5.0 (made a candidate recommendation back in 2012), the WhatWG HTML living standard (the dominant standard today), and the latest W3 HTML 5 spec all do not contain the wording quoted from HTML 4 above, and unanimously agree that a colspan of 0 is not allowed, with this wording which appears in all three specs:

    The td and th elements may have a colspan content attribute specified, whose value must be a valid non-negative integer greater than zero ...

    Sources:

  • The following claims from the W3Schools page linked to in the question are - at least nowadays - completely false:

    Only Firefox supports colspan="0", which has a special meaning ... [It] tells the browser to span the cell to the last column of the column group (colgroup)

    and

    Differences Between HTML 4.01 and HTML5

    NONE.

    If you're not already aware that W3Schools is generally held in contempt by web developers for its frequent inaccuracies, consider this a lesson in why.

Create a file if it doesn't exist

'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in (over)write mode
    [it overwrites the file if it already exists]
r+  open an existing file in read+write mode
a+  create file if it doesn't exist and open it in append mode
'''

example:

file_name = 'my_file.txt'
f = open(file_name, 'a+')  # open file in append mode
f.write('python rules')
f.close()

I hope this helps. [FYI am using python version 3.6.2]

Cannot find Microsoft.Office.Interop Visual Studio

I think you need to run that .msi to install the dlls. After I ran that .msi I can go to (VS 2012) Add References > Assemblies > Extensions and all of the Microsoft.Office.Interop dlls are there.

On my computer the dlls are found in "c:\Program Files(x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA" so you could check in a similar/equivalent directory on yours just to make sure they're not there?

Remove elements from collection while iterating

Old Timer Favorite (it still works):

List<String> list;

for(int i = list.size() - 1; i >= 0; --i) 
{
        if(list.get(i).contains("bad"))
        {
                list.remove(i);
        }
}

Benefits:

  1. It only iterates over the list once
  2. No extra objects created, or other unneeded complexity
  3. No problems with trying to use the index of a removed item, because... well, think about it!

How to get all elements inside "div" that starts with a known text

var $list = $('#divname input[id^="q17_"]');   // get all input controls with id q17_

// once you have $list you can do whatever you want

var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {

    var id = $(this).prop("id");      // get id
    var cbx = '';
    if ($(this).is(':checkbox') || $(this).is(':radio')) {
        // Need to see if this control is checked
    }
    else { 
        // Nope, not a checked control - so do something else
    }

});

Python re.sub replace with matched content

For the replacement portion, Python uses \1 the way sed and vi do, not $1 the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1 interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

How to determine whether an object has a given property in JavaScript

If you want to know if the object physically contains the property @gnarf's answer using hasOwnProperty will do the work.

If you're want to know if the property exists anywhere, either on the object itself or up in the prototype chain, you can use the in operator.

if ('prop' in obj) {
  // ...
}

Eg.:

var obj = {};

'toString' in obj == true; // inherited from Object.prototype
obj.hasOwnProperty('toString') == false; // doesn't contains it physically

How to hide Bootstrap modal with javascript?

(Referring to Bootstrap 3), To hide the modal use: $('#modal').modal('hide'). But the reason the backdrop hung around (for me) was because I was destroying the DOM for the modal before 'hide' finished.

To resolve this, I chained the hidden event with the DOM removal. In my case: this.render()

var $modal = $('#modal');

//when hidden
$modal.on('hidden.bs.modal', function(e) { 
  return this.render(); //DOM destroyer
});

$modal.modal('hide'); //start hiding

Is there any method to get the URL without query string?

Here are two methods:

<script type="text/javascript">
    var s="http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu
                                =true&pcode=1235";

    var st=s.substring(0, s.indexOf("?"));

    alert(st);

    alert(s.replace(/\?.*/,''));
</script>

ASP.NET MVC - passing parameters to the controller

Or, you could try changing the parameter type to string, then convert the string to an integer in the method. I am new to MVC, but I believe you need nullable objects in your parameter list, how else will the controller indicate that no such parameter was provided? So...

public ActionResult ViewNextItem(string id)...

How should I copy Strings in Java?

Your second version is less efficient because it creates an extra string object when there is simply no need to do so.

Immutability means that your first version behaves the way you expect and is thus the approach to be preferred.

HTML character codes for this ? or this ?

I usually use the excellent Gucharmap to look up Unicode characters. It's installed on all recent Linux installations with Gnome under the name "Character Map". I don't know of any equivalent tools for Windows or Mac OS X, but its homepage lists a few.

Creating a class object in c++

First of all, both cases calls a constructor. If you write

Example *example = new Example();

then you are creating an object, call the constructor and retrieve a pointer to it.

If you write

Example example;

The only difference is that you are getting the object and not a pointer to it. The constructor called in this case is the same as above, the default (no argument) constructor.

As for the singleton question, you must simple invoke your static method by writing:

Example *e = Singleton::getExample();

Difference between \w and \b regular expression meta characters

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

Simply put: \b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".

In all flavors, the characters [a-zA-Z0-9_] are word characters. These are also matched by the short-hand character class \w. Flavors showing "ascii" for word boundaries in the flavor comparison recognize only these as word characters.

\w stands for "word character", usually [A-Za-z0-9_]. Notice the inclusion of the underscore and digits.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

\W is short for [^\w], the negated version of \w.

Getting Serial Port Information

I tried so many solutions on here that didn't work for me, only displaying some of the ports. But the following displayed All of them and their information.

        using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'"))
        {
            var portnames = SerialPort.GetPortNames();
            var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());

            var portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();

            foreach(string s in portList)
            {
                Console.WriteLine(s);
            }
        }
    }

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

This worked for me after i tryed many solutions:
For some reason the adb process didn't restart itself after installing new packages. Manualy killing adb.exe and attempt to import the project another time solved this problem for me.

Bitbucket git credentials if signed up with Google

It's March 2019, and I just did it this way:

  1. Access https://id.atlassian.com/login/resetpassword
  2. Fill your email and click "Send recovery link"
  3. You will receive an email, and this is where people mess it up. Don't click the Log in to my account button, instead, you want to click the small link bellow that says Alternatively, you can reset your password for your Atlassian account.
  4. Set a password as you normally would

Now try to run git commands on terminal.

It might ask you to do a two-step verification the first time, just follow the steps and you're done!

Oracle Sql get only month and year in date datatype

Easiest solution is to create the column using the correct data type: DATE

For example:

  1. Create table:

    create table test_date (mydate date);

  2. Insert row:

    insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));

To get the month and year, do as follows:

select to_char(mydate, 'MM-YYYY') from test_date;

Your result will be as follows: 01-2011

Another cool function to use is "EXTRACT"

select extract(year from mydate) from test_date;

This will return: 2011

'nuget' is not recognized but other nuget commands working

  • Right-click on your project in solution explorer.
  • Select Manage NuGet Packages for Solution.
  • Search NuGet.CommandLine by Microsoft and Install it. Search Nuget.CommandLine
  • On complete installation, you will find a folder named packages in your project. Go to solution explorer and look for it. packages
  • Inside packages look for a folder named NuGet.CommandLine.3.5.0, here 3.5.0 is just version name your folder name will change accordingly. nuGet COmmand Line
  • Inside NuGet.CommandLine.3.5.0 look for a folder named tools. tools
  • Inside tools you will get your nuget.exe nuget.exe

Custom CSS for <audio> tag?

Besides the box-shadow, transform and border options mentioned in other answers, WebKit browsers currently also obey -webkit-text-fill-color to set the colour of the "time elapsed" numbers, but since there is no way to set their background (which might vary with platform, e.g. inverted high-contrast modes on some operating systems), you would be advised to set -webkit-text-fill-color to the value "initial" if you've used it elsewhere and the audio element is inheriting this, otherwise some users might find those numbers unreadable.

Is it possible to force Excel recognize UTF-8 CSV files automatically?

Simple vba macro for opening utf-8 text and csv files

Sub OpenTextFile()

   filetoopen = Application.GetOpenFilename("Text Files (*.txt;*.csv), *.txt;*.csv")
   If filetoopen = Null Or filetoopen = Empty Then Exit Sub

   Workbooks.OpenText Filename:=filetoopen, _
   Origin:=65001, DataType:=xlDelimited, Comma:=True

End Sub

Origin:=65001 is UTF-8. Comma:True for .csv files distributed in colums

Save it in Personal.xlsb to have it always available. Personalise excel toolbar adding a macro call button and open files from there. You can add more formating to the macro, like column autofit , alignment,etc.

How do I check if an object has a key in JavaScript?

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

Side-by-side list items as icons within a div (css)

add this line in your css file:

.classname ul li {
    float: left;
}

Ajax - 500 Internal Server Error

I think your return string data is very long. so the JSON format has been corrupted. You should change the max size for JSON data in this way :

Open the Web.Config file and paste these lines into the configuration section

<system.web.extensions>
  <scripting>
    <webServices>
      <jsonSerialization maxJsonLength="50000000"/>
    </webServices>
  </scripting>
</system.web.extensions>

How do I detect whether a Python variable is a function?

In Python3 I came up with type (f) == type (lambda x:x) which yields True if f is a function and False if it is not. But I think I prefer isinstance (f, types.FunctionType), which feels less ad hoc. I wanted to do type (f) is function, but that doesn't work.

How to resolve 'npm should be run outside of the node repl, in your normal shell'

enter image description here

Just open Node.js commmand promt as run as administrator

How do I check two or more conditions in one <c:if>?

Recommendation:

when you have more than one condition with and and or is better separate with () to avoid verification problems

<c:if test="${(not validID) and (addressIso == 'US' or addressIso == 'BR')}">

Sorting hashmap based on keys

Use sorted TreeMap:

Map<String, Float> map = new TreeMap<>(yourMap);

It will automatically put entries sorted by keys. I think natural String ordering will be fine in your case.

Note that HashMap due to lookup optimizations does not preserve order.