Programs & Examples On #Freopen

freopen reopens a stream with a different file or mode.

Create a file if one doesn't exist - C

If fptr is NULL, then you don't have an open file. Therefore, you can't freopen it, you should just fopen it.

FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
    fptr = fopen("scores.dat", "wb");
}

note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.

A complete example

int main()
{
    FILE *fptr;
    char there_was_error = 0;
    char opened_in_read  = 1;
    fptr = fopen("scores.dat", "rb+");
    if(fptr == NULL) //if file does not exist, create it
    {
        opened_in_read = 0;
        fptr = fopen("scores.dat", "wb");
        if (fptr == NULL)
            there_was_error = 1;
    }
    if (there_was_error)
    {
        printf("Disc full or no permission\n");
        return EXIT_FAILURE;
    }
    if (opened_in_read)
        printf("The file is opened in read mode."
               " Let's read some cached data\n");
    else
        printf("The file is opened in write mode."
               " Let's do some processing and cache the results\n");
    return EXIT_SUCCESS;
}

Why does ASP.NET webforms need the Runat="Server" attribute?

Any tag with runat=server is added as server control in Page and any html content between is handled as LiteralControls which are also added to Page controls collection.

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Use the method provided in the Date object as follows:

var ts_hms = new Date();

console.log(
    ts_hms.getFullYear() + '-' + 
    ("0" + (ts_hms.getMonth() + 1)).slice(-2) + '-' + 
    ("0" + (ts_hms.getDate())).slice(-2) + ' ' +
    ("0" + ts_hms.getHours()).slice(-2) + ':' +
    ("0" + ts_hms.getMinutes()).slice(-2) + ':' +
    ("0" + ts_hms.getSeconds()).slice(-2));

It looks really dirty, but it should work fine with JavaScript core methods

QED symbol in latex

You can use \blacksquare ¦:

When creating TeX, Knuth provided the symbol ¦ (solid black square), also called by mathematicians tombstone or Halmos symbol (after Paul Halmos, who pioneered its use as an equivalent of Q.E.D.). The tombstone is sometimes open: ? (hollow black square).

What is the opposite of evt.preventDefault();

None of the solutions helped me here and I did this to solve my situation.

<a onclick="return clickEvent(event);" href="/contact-us">

And the function clickEvent(),

function clickEvent(event) {
    event.preventDefault();
    // do your thing here

    // remove the onclick event trigger and continue with the event
    event.target.parentElement.onclick = null;
    event.target.parentElement.click();
}

Convert Go map to json

If you had caught the error, you would have seen this:

jsonString, err := json.Marshal(datas)
fmt.Println(err)

// [] json: unsupported type: map[int]main.Foo

The thing is you cannot use integers as keys in JSON; it is forbidden. Instead, you can convert these values to strings beforehand, for instance using strconv.Itoa.

See this post for more details: https://stackoverflow.com/a/24284721/2679935

How to send multiple data fields via Ajax?

The correct syntax is:

data: {status: status, name: name},

As specified here: http://api.jquery.com/jQuery.ajax/

So if that doesn't work, I would alert those variables to make sure they have values.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

That’s right, Executors.newCachedThreadPool() isn't a great choice for server code that's servicing multiple clients and concurrent requests.

Why? There are basically two (related) problems with it:

  1. It's unbounded, which means that you're opening the door for anyone to cripple your JVM by simply injecting more work into the service (DoS attack). Threads consume a non-negligible amount of memory and also increase memory consumption based on their work-in-progress, so it's quite easy to topple a server this way (unless you have other circuit-breakers in place).

  2. The unbounded problem is exacerbated by the fact that the Executor is fronted by a SynchronousQueue which means there's a direct handoff between the task-giver and the thread pool. Each new task will create a new thread if all existing threads are busy. This is generally a bad strategy for server code. When the CPU gets saturated, existing tasks take longer to finish. Yet more tasks are being submitted and more threads created, so tasks take longer and longer to complete. When the CPU is saturated, more threads is definitely not what the server needs.

Here are my recommendations:

Use a fixed-size thread pool Executors.newFixedThreadPool or a ThreadPoolExecutor. with a set maximum number of threads;

Set selected item of spinner programmatically

Use the following: spinnerObject.setSelection(INDEX_OF_CATEGORY2).

What is a difference between unsigned int and signed int in C?

The C standard specifies that unsigned numbers will be stored in binary. (With optional padding bits). Signed numbers can be stored in one of three formats: Magnitude and sign; two's complement or one's complement. Interestingly that rules out certain other representations like Excess-n or Base -2.

However on most machines and compilers store signed numbers in 2's complement.

int is normally 16 or 32 bits. The standard says that int should be whatever is most efficient for the underlying processor, as long as it is >= short and <= long then it is allowed by the standard.

On some machines and OSs history has causes int not to be the best size for the current iteration of hardware however.

Set the location in iPhone Simulator

As of Xcode 11.6 and Swift 5.3, facility to simulate custom location has been moved from "Debug" to "Features" in iOS Simulator menu.

Error occurred during initialization of boot layer FindException: Module not found

I just encountered the same issue after adding the bin folder to .gitignore, not sure if that caused the issue.

I solved it by going to Project/Properties/Build Path and I removed the scr folder and added it again.

Double free or corruption after queue::push

You need to define a copy constructor, assignment, operator.

class Test {
   Test(const Test &that); //Copy constructor
   Test& operator= (const Test &rhs); //assignment operator
}

Your copy that is pushed on the queue is pointing to the same memory your original is. When the first is destructed, it deletes the memory. The second destructs and tries to delete the same memory.

Soft Edges using CSS?

Another option is to use one of my personal favorite CSS tools: box-shadow.

A box shadow is really a drop-shadow on the node. It looks like this:

-moz-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
-webkit-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
box-shadow: 1px 2px 3px rgba(0,0,0,.5);

The arguments are:

1px: Horizontal offset of the effect. Positive numbers shift it right, negative left.
2px: Vertical offset of the effect. Positive numbers shift it down, negative up.
3px: The blur effect.  0 means no blur.
color: The color of the shadow.

So, you could leave your current design, and add a box-shadow like:

box-shadow: 0px -2px 2px rgba(34,34,34,0.6);

This should give you a 'blurry' top-edge.

This website will help with more information: http://css-tricks.com/snippets/css/css-box-shadow/

Convert seconds value to hours minutes seconds?

Something really helpful in Java 8

import java.time.LocalTime;

private String ConvertSecondToHHMMSSString(int nSecondTime) {
    return LocalTime.MIN.plusSeconds(nSecondTime).toString();
}

proper way to logout from a session in PHP

From the session_destroy() page in the PHP manual:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

Quick way to list all files in Amazon S3 bucket?

Alternatively you can use Minio Client aka mc. Its Open Source and compatible with AWS S3. It is available for Linux, Windows, Mac, FreeBSD.

All you have do do is to run mc ls command for listing the contents.

$ mc ls s3/kline/
[2016-04-30 13:20:47 IST] 1.1MiB 1.jpg
[2016-04-30 16:03:55 IST] 7.5KiB docker.png
[2016-04-30 15:16:17 IST]  50KiB pi.png
[2016-05-10 14:34:39 IST] 365KiB upton.pdf

Note:

  • s3: Alias for Amazon S3
  • kline: AWS S3 bucket name

Installing Minio Client Linux Download mc for:

$ chmod 755 mc
$ ./mc --help

Setting up AWS credentials with Minio Client

$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12

Note: Please replace mys3 with alias you would like for this account and ,BKIKJAA5BMMU2RHO6IBB, V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 with your AWS ACCESS-KEY and SECRET-KEY

Hope it helps.

Disclaimer: I work for Minio

Resetting MySQL Root Password with XAMPP on Localhost

On Dashboard, Go to User Accounts, Select user, Click Change Password, Fill the New Password, Go.

How are environment variables used in Jenkins with Windows Batch Command?

I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.

If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE

echo %WORKSPACE%

If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &, &&, or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.

setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
  set WORKSPACE=AFTER
  echo Normal Expansion = %WORKSPACE%
  echo Delayed Expansion = !WORKSPACE!
)

The output of the above is

Normal Expansion = BEFORE
Delayed Expansion = AFTER

Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.

How do you tell if caps lock is on using JavaScript?

You can give it a try.. Added a working example. When focus is on input, turning on caps lock makes the led go red otherwise green. (Haven't tested on mac/linux)

NOTE: Both versions are working for me. Thanks for constructive inputs in the comments.

OLD VERSION: https://jsbin.com/mahenes/edit?js,output

Also, here is a modified version (can someone test on mac and confirm)

NEW VERSION: https://jsbin.com/xiconuv/edit?js,output

NEW VERSION:

function isCapslock(e) {
  const IS_MAC = /Mac/.test(navigator.platform);

  const charCode = e.charCode;
  const shiftKey = e.shiftKey;

  if (charCode >= 97 && charCode <= 122) {
    capsLock = shiftKey;
  } else if (charCode >= 65 && charCode <= 90
    && !(shiftKey && IS_MAC)) {
    capsLock = !shiftKey;
  }

  return capsLock;
}

OLD VERSION:

function isCapslock(e) {
  e = (e) ? e : window.event;

  var charCode = false;
  if (e.which) {
    charCode = e.which;
  } else if (e.keyCode) {
    charCode = e.keyCode;
  }

  var shifton = false;
  if (e.shiftKey) {
    shifton = e.shiftKey;
  } else if (e.modifiers) {
    shifton = !!(e.modifiers & 4);
  }

  if (charCode >= 97 && charCode <= 122 && shifton) {
    return true;
  }

  if (charCode >= 65 && charCode <= 90 && !shifton) {
    return true;
  }

  return false;
}

For international characters, additional check can be added for the following keys as needed. You have to get the keycode range for characters you are interested in, may be by using a keymapping array which will hold all the valid use case keys you are addressing...

uppercase A-Z or 'Ä', 'Ö', 'Ü', lowercase a-Z or 0-9 or 'ä', 'ö', 'ü'

The above keys are just sample representation.

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

Can I redirect the stdout in python into some sort of string buffer?

There is contextlib.redirect_stdout() function in Python 3.4:

import io
from contextlib import redirect_stdout

with io.StringIO() as buf, redirect_stdout(buf):
    print('redirected')
    output = buf.getvalue()

Here's code example that shows how to implement it on older Python versions.

Bootstrap 4 Dropdown Menu not working?

Edit: In case anyone else is having this problem, I believe the solution for OP was that he had not imported popper.js.

Check that jQuery and all the relevant Bootstrap components are there. Also check the console and make sure there are no errors.

_x000D_
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
      <ul class="navbar-nav">
        <li class="nav-item active">
          <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Features</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Pricing</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Dropdown link
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
        </li>
      </ul>
    </div>
  </nav>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<-- Always remember to call the above files first before calling the bootstrap.min.js file -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_

How to find the size of an int[]?

Besides Carl's answer, the "standard" C++ way is not to use a C int array, but rather something like a C++ STL std::vector<int> list which you can query for list.size().

Java Date - Insert into database

Before I answer your question, I'd like to mention that you should probably look into using some sort of ORM solution (e.g., Hibernate), wrapped behind a data access tier. What you are doing appear to be very anti-OO. I admittedly do not know what the rest of your code looks like, but generally, if you start seeing yourself using a lot of Utility classes, you're probably taking too structural of an approach.

To answer your question, as others have mentioned, look into java.sql.PreparedStatement, and use java.sql.Date or java.sql.Timestamp. Something like (to use your original code as much as possible, you probably want to change it even more):

java.util.Date myDate = new java.util.Date("10/10/2009");
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());

sb.append("INSERT INTO USERS");
sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) ");
sb.append("VALUES ( ");
sb.append("?, ?, ?, ?, ?");
sb.append(")");

Connection conn = ...;// you'll have to get this connection somehow
PreparedStatement stmt = conn.prepareStatement(sb.toString());
stmt.setString(1, userId);
stmt.setString(2, myUser.GetFirstName());
stmt.setString(3, myUser.GetLastName());
stmt.setString(4, myUser.GetSex());
stmt.setDate(5, sqlDate);

stmt.executeUpdate(); // optionally check the return value of this call

One additional benefit of this approach is that it automatically escapes your strings for you (e.g., if were to insert someone with the last name "O'Brien", you'd have problems with your original implementation).

How can I create a unique constraint on my column (SQL Server 2008 R2)?

To create these constraints through the GUI you need the "indexes and keys" dialogue not the check constraints one.

But in your case you just need to run the piece of code you already have. It doesn't need to be entered into the expression dialogue at all.

Windows batch script to unhide files hidden by virus

this will unhide all files and folders on your computer

attrib -r -s -h /S /D

How to stop C++ console application from exiting immediately?

If you are running Windows, then you can do system("pause >nul"); or system("pause");. It executes a console command to pause the program until you press a key. >nul prevents it from saying Press any key to continue....

grep a file, but show several surrounding lines?

$ grep thestring thefile -5

-5 gets you 5 lines above and below the match 'thestring' is equivalent to -C 5 or -A 5 -B 5.

How to get instance variables in Python?

Suggest

>>> print vars.__doc__
vars([object]) -> dictionary

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.

In otherwords, it essentially just wraps __dict__

AngularJS: How to make angular load script inside ng-include?

Unfortunately all the answers in this post didn't work for me. I kept getting following error.

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

I found out that this happens if you use some 3rd party widgets (demandforce in my case) that also call additional external JavaScript files and try to insert HTML. Looking at the console and the JavaScript code, I noticed multiple lines like this:

document.write("<script type='text/javascript' "..."'></script>");

I used 3rd party JavaScript files (htmlParser.js and postscribe.js) from: https://github.com/krux/postscribe. That solved the problem in this post and fixed the above error at the same time.

(This was a quick and dirty way around under the tight deadline I have now. I am not comfortable with using 3rd party JavaScript library however. I hope someone can come up with a cleaner and better way.)

How could I create a function with a completion handler in Swift?

I had trouble understanding the answers so I'm assuming any other beginner like myself might have the same problem as me.

My solution does the same as the top answer but hopefully a little more clear and easy to understand for beginners or people just having trouble understanding in general.

To create a function with a completion handler

func yourFunctionName(finished: () -> Void) {

     print("Doing something!")

     finished()

}

to use the function

     override func viewDidLoad() {

          yourFunctionName {

          //do something here after running your function
           print("Tada!!!!")
          }

    }

Your output will be

Doing something

Tada!!!

Hope this helps!

Assert equals between 2 Lists in Junit

I know there are already many options to solve this issue, but I would rather do the following to assert two lists in any oder:

assertTrue(result.containsAll(expected) && expected.containsAll(result))

MySQL compare DATE string with string from DATETIME field

SELECT * FROM `calendar` WHERE DATE_FORMAT(startTime, "%Y-%m-%d") = '2010-04-29'"

OR

SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29'

How do you specify a debugger program in Code::Blocks 12.11?

Here is the tutorial to install GBD.

Usually GNU Debugger might not be in your computer, so you would install it first. The installation steps are basic "configure", "make", and "make install".

Once installed, try which gdb in terminal, to find the executable path of GDB.

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

If the jdk.tools is present in the .m2 repository. Still you get the error something like this:

missing artifact: jdk.tools.....c:.../jre/..

In the buildpath->configure build path-->Libraries.Just change JRE system library from JRE to JDK.

Karma: Running a single test file from command line

Even though --files is no longer supported, you can use an env variable to provide a list of files:

// karma.conf.js
function getSpecs(specList) {
  if (specList) {
    return specList.split(',')
  } else {
    return ['**/*_spec.js'] // whatever your default glob is
  }
}

module.exports = function(config) {
  config.set({
    //...
    files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))
  });
});

Then in CLI:

$ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run

How do I perform query filtering in django templates

This can be solved with an assignment tag:

from django import template

register = template.Library()

@register.assignment_tag
def query(qs, **kwargs):
    """ template tag which allows queryset filtering. Usage:
          {% query books author=author as mybooks %}
          {% for book in mybooks %}
            ...
          {% endfor %}
    """
    return qs.filter(**kwargs)

Conditional Formatting (IF not empty)

This worked for me:

=NOT(ISBLANK(A1))

I wanted a box around NOT Blank cells in an entire worksheet. Use the $A1 if you want the WHOLE ROW formatted based on the A1, B1, etc result.

Thanks!

How to store a dataframe using Pandas

If I understand correctly, you're already using pandas.read_csv() but would like to speed up the development process so that you don't have to load the file in every time you edit your script, is that right? I have a few recommendations:

  1. you could load in only part of the CSV file using pandas.read_csv(..., nrows=1000) to only load the top bit of the table, while you're doing the development

  2. use ipython for an interactive session, such that you keep the pandas table in memory as you edit and reload your script.

  3. convert the csv to an HDF5 table

  4. updated use DataFrame.to_feather() and pd.read_feather() to store data in the R-compatible feather binary format that is super fast (in my hands, slightly faster than pandas.to_pickle() on numeric data and much faster on string data).

You might also be interested in this answer on stackoverflow.

How to download and save a file from Internet using Java?

If you are behind a proxy, you can set the proxies in java program as below:

        Properties systemSettings = System.getProperties();
        systemSettings.put("proxySet", "true");
        systemSettings.put("https.proxyHost", "https proxy of your org");
        systemSettings.put("https.proxyPort", "8080");

If you are not behind a proxy, don't include the lines above in your code. Full working code to download a file when you are behind a proxy.

public static void main(String[] args) throws IOException {
        String url="https://raw.githubusercontent.com/bpjoshi/fxservice/master/src/test/java/com/bpjoshi/fxservice/api/TradeControllerTest.java";
        OutputStream outStream=null;
        URLConnection connection=null;
        InputStream is=null;
        File targetFile=null;
        URL server=null;
        //Setting up proxies
        Properties systemSettings = System.getProperties();
            systemSettings.put("proxySet", "true");
            systemSettings.put("https.proxyHost", "https proxy of my organisation");
            systemSettings.put("https.proxyPort", "8080");
            //The same way we could also set proxy for http
            System.setProperty("java.net.useSystemProxies", "true");
            //code to fetch file
        try {
            server=new URL(url);
            connection = server.openConnection();
            is = connection.getInputStream();
            byte[] buffer = new byte[is.available()];
            is.read(buffer);

                targetFile = new File("src/main/resources/targetFile.java");
                outStream = new FileOutputStream(targetFile);
                outStream.write(buffer);
        } catch (MalformedURLException e) {
            System.out.println("THE URL IS NOT CORRECT ");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Io exception");
            e.printStackTrace();
        }
        finally{
            if(outStream!=null) outStream.close();
        }
    }

The performance impact of using instanceof in Java

Demian and Paul mention a good point; however, the placement of the code to execute really depends on how you want to use the data...

I'm a big fan of small data objects that can be used in many ways. If you follow the override (polymorphic) approach, your objects can only be used "one way".

This is where patterns come in...

You can use double-dispatch (as in the visitor pattern) to ask each object to "call you" passing itself -- this will resolve the type of the object. However (again) you'll need a class that can "do stuff" with all of the possible subtypes.

I prefer to use a strategy pattern, where you can register strategies for each subtype you want to handle. Something like the following. Note that this only helps for exact type matches, but has the advantage that it's extensible - third-party contributors can add their own types and handlers. (This is good for dynamic frameworks like OSGi, where new bundles can be added)

Hopefully this will inspire some other ideas...

package com.javadude.sample;

import java.util.HashMap;
import java.util.Map;

public class StrategyExample {
    static class SomeCommonSuperType {}
    static class SubType1 extends SomeCommonSuperType {}
    static class SubType2 extends SomeCommonSuperType {}
    static class SubType3 extends SomeCommonSuperType {}

    static interface Handler<T extends SomeCommonSuperType> {
        Object handle(T object);
    }

    static class HandlerMap {
        private Map<Class<? extends SomeCommonSuperType>, Handler<? extends SomeCommonSuperType>> handlers_ =
            new HashMap<Class<? extends SomeCommonSuperType>, Handler<? extends SomeCommonSuperType>>();
        public <T extends SomeCommonSuperType> void add(Class<T> c, Handler<T> handler) {
            handlers_.put(c, handler);
        }
        @SuppressWarnings("unchecked")
        public <T extends SomeCommonSuperType> Object handle(T o) {
            return ((Handler<T>) handlers_.get(o.getClass())).handle(o);
        }
    }

    public static void main(String[] args) {
        HandlerMap handlerMap = new HandlerMap();

        handlerMap.add(SubType1.class, new Handler<SubType1>() {
            @Override public Object handle(SubType1 object) {
                System.out.println("Handling SubType1");
                return null;
            } });
        handlerMap.add(SubType2.class, new Handler<SubType2>() {
            @Override public Object handle(SubType2 object) {
                System.out.println("Handling SubType2");
                return null;
            } });
        handlerMap.add(SubType3.class, new Handler<SubType3>() {
            @Override public Object handle(SubType3 object) {
                System.out.println("Handling SubType3");
                return null;
            } });

        SubType1 subType1 = new SubType1();
        handlerMap.handle(subType1);
        SubType2 subType2 = new SubType2();
        handlerMap.handle(subType2);
        SubType3 subType3 = new SubType3();
        handlerMap.handle(subType3);
    }
}

What is the difference between 'my' and 'our' in Perl?

Great question: How does our differ from my and what does our do?

In Summary:

Available since Perl 5, my is a way to declare non-package variables, that are:

  • private
  • new
  • non-global
  • separate from any package, so that the variable cannot be accessed in the form of $package_name::variable.


On the other hand, our variables are package variables, and thus automatically:

  • global variables
  • definitely not private
  • not necessarily new
  • can be accessed outside the package (or lexical scope) with the qualified namespace, as $package_name::variable.


Declaring a variable with our allows you to predeclare variables in order to use them under use strict without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete use vars, which was only file-scoped, and not lexically scoped as is our.

For example, the formal, qualified name for variable $x inside package main is $main::x. Declaring our $x allows you to use the bare $x variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses use strict or use strict "vars". The scope might be one, or two, or more packages, or one small block.

R: invalid multibyte string

If you want an R solution, here's a small convenience function I sometimes use to find where the offending (multiByte) character is lurking. Note that it is the next character to what gets printed. This works because print will work fine, but substr throws an error when multibyte characters are present.

find_offending_character <- function(x, maxStringLength=256){  
  print(x)
  for (c in 1:maxStringLength){
    offendingChar <- substr(x,c,c)
    #print(offendingChar) #uncomment if you want the indiv characters printed
    #the next character is the offending multibyte Character
  }    
}

string_vector <- c("test", "Se\x96ora", "works fine")

lapply(string_vector, find_offending_character)

I fix that character and run this again. Hope that helps someone who encounters the invalid multibyte string error.

Convert int to char in java

int a = 1;
char b = (char) (a + 48);

In ASCII, every char have their own number. And char '0' is 48 for decimal, '1' is 49, and so on. So if

char b = '2';
int a = b = 50;

Getting started with OpenCV 2.4 and MinGW on Windows 7

As pointed out by @Nenad Bulatovic one has to be careful while adding libraries(19th step). one should not add any trailing spaces while adding each library line by line. otherwise mingw goes haywire.

jQuery get input value after keypress

This is because keypress events are fired before the new character is added to the value of the element (so the first keypress event is fired before the first character is added, while the value is still empty). You should use keyup instead, which is fired after the character has been added.

Note that, if your element #dSuggest is the same as input:text[name=dSuggest] you can simplify this code considerably (and if it isn't, having an element with a name that is the same as the id of another element is not a good idea).

$('#dSuggest').keypress(function() {
    var dInput = this.value;
    console.log(dInput);
    $(".dDimension:contains('" + dInput + "')").css("display","block");
});

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

In the head section of your html document:

<link rel="stylesheet" type="text/css" href="/path/to/ABCD.css">

Your css file should be css only and not contain any markup.

How do I get the full path to a Perl script that is executing?

perlfaq8 answers a very similar question with using the rel2abs() function on $0. That function can be found in File::Spec.

Cannot install Aptana Studio 3.6 on Windows

I have some issue, the fix is:

  1. Uninstall any nodejs version.
  2. Install https://nodejs.org/dist/v0.10.36/x64/node-v0.10.36-x64.msi.
  3. Install Aptana.
  4. Code...

greetings!

Getting current directory in .NET web application

Use this code:

 HttpContext.Current.Server.MapPath("~")

Detailed Reference:

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward (/) or backward slash (), the MapPath method returns a path as if Path were a full, virtual path.

If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

Server.MapPath(null) and Server.MapPath("") will produce this effect too.

PHP Warning: PHP Startup: ????????: Unable to initialize module

Looks like you haven't upgraded PHP modules, they are not compatible.

Check extension_dir directive in your php.ini. It should point to folder with 5.2 modules.

Create and open a phpinfo file and search for extension_dir to find the path.

Since you did upgrade, there is a chance that you are using old php.ini that is pointing to 5.1 modules

Filtering Pandas Dataframe using OR statement

You can do like below to achieve your result:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()


#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()

<input type="file"> limit selectable files by extensions

 function uploadFile() {
     var fileElement = document.getElementById("fileToUpload");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension == "odx-d"||fileExtension == "odx"||fileExtension == "pdx"||fileExtension == "cmo"||fileExtension == "xml") {
         var fd = new FormData();
        fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
        xhr.addEventListener("error", uploadFailed, false);
        xhr.addEventListener("abort", uploadCanceled, false);
        xhr.open("POST", "/post_uploadReq");
        xhr.send(fd);
        }
        else {
            alert("You must select a valid odx,pdx,xml or cmo file for upload");
            return false;
        }
       
      }

tried this , works very well

Routing with Multiple Parameters using ASP.NET MVC

Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.

A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Summary:

First you enable attribute routing

 public class RouteConfig 
 {
     public static void RegisterRoutes(RouteCollection routes)
     {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapMvcAttributeRoutes();
     } 
 }

Then you can use attributes to define parameters and optionally data types

public class BooksController : Controller
{
    // eg: /books
    // eg: /books/1430210079
    [Route("books/{isbn?}")]
    public ActionResult View(string isbn)

How is OAuth 2 different from OAuth 1?

OAuth 2.0 promises to simplify things in following ways:

  1. SSL is required for all the communications required to generate the token. This is a huge decrease in complexity because those complex signatures are no longer required.
  2. Signatures are not required for the actual API calls once the token has been generated -- SSL is also strongly recommended here.
  3. Once the token was generated, OAuth 1.0 required that the client send two security tokens on every API call, and use both to generate the signature. OAuth 2.0 has only one security token, and no signature is required.
  4. It is clearly specified which parts of the protocol are implemented by the "resource owner," which is the actual server that implements the API, and which parts may be implemented by a separate "authorization server." That will make it easier for products like Apigee to offer OAuth 2.0 support to existing APIs.

Source:http://blog.apigee.com/detail/oauth_differences

Using msbuild to execute a File System Publish Profile

FYI: Same problem with running on a build server (Jenkins with msbuild 15 installed, driven from VS 2017 on a .NET Core 2.1 web project).

In my case it was the use of the "publish" target with msbuild that ignored the profile.

So my msbuild command started with:

msbuild /t:restore;build;publish

This correctly triggerred the publish process, but no combination or variation of "/p:PublishProfile=FolderProfile" ever worked to select the profile I wanted to use ("FolderProfile").

When I stopped using the publish target:

msbuild /t:restore;build /p:DeployOnBuild=true /p:PublishProfile=FolderProfile

I (foolishly) thought that it would make no difference, but as soon as I used the DeployOnBuild switch it correctly picked up the profile.

How to run ssh-add on windows?

Original answer using git's start-ssh-agent

Make sure you have Git installed and have git's cmd folder in your PATH. For example, on my computer the path to git's cmd folder is C:\Program Files\Git\cmd

Make sure your id_rsa file is in the folder c:\users\yourusername\.ssh

Restart your command prompt if you haven't already, and then run start-ssh-agent. It will find your id_rsa and prompt you for the passphrase

Update 2019 - A better solution if you're using Windows 10: OpenSSH is available as part of Windows 10 which makes using SSH from cmd/powershell much easier in my opinion. It also doesn't rely on having git installed, unlike my previous solution.

  1. Open Manage optional features from the start menu and make sure you have Open SSH Client in the list. If not, you should be able to add it.

  2. Open Services from the start Menu

  3. Scroll down to OpenSSH Authentication Agent > right click > properties

  4. Change the Startup type from Disabled to any of the other 3 options. I have mine set to Automatic (Delayed Start)

  5. Open cmd and type where ssh to confirm that the top listed path is in System32. Mine is installed at C:\Windows\System32\OpenSSH\ssh.exe. If it's not in the list you may need to close and reopen cmd.

Once you've followed these steps, ssh-agent, ssh-add and all other ssh commands should now work from cmd. To start the agent you can simply type ssh-agent.

  1. Optional step/troubleshooting: If you use git, you should set the GIT_SSH environment variable to the output of where ssh which you ran before (e.g C:\Windows\System32\OpenSSH\ssh.exe). This is to stop inconsistencies between the version of ssh you're using (and your keys are added/generated with) and the version that git uses internally. This should prevent issues that are similar to this

Some nice things about this solution:

  • You won't need to start the ssh-agent every time you restart your computer
  • Identities that you've added (using ssh-add) will get automatically added after restarts. (It works for me, but you might possibly need a config file in your c:\Users\User\.ssh folder)
  • You don't need git!
  • You can register any rsa private key to the agent. The other solution will only pick up a key named id_rsa

Hope this helps

How can I debug a .BAT script?

I don't know of anyway to step through the execution of a .bat file but you can use echo and pause to help with debugging.

ECHO
Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line.

PAUSE
Prompt the user to press any key to continue.

Source: Batch File Help

@workmad3: answer has more good tips for working with the echo command.

Another helpful resource... DDB: DOS Batch File Tips

Commands out of sync; you can't run this command now

Another cause: store_result() cannot be called twice.

For instance, in the following code, Error 5 is printed.

<?php

$db = new mysqli("localhost", "something", "something", "something");

$stmt = $db->stmt_init();
if ($stmt->error) printf("Error 1 : %s\n", $stmt->error);

$stmt->prepare("select 1");
if ($stmt->error) printf("Error 2 : %s\n", $stmt->error);

$stmt->execute();
if ($stmt->error) printf("Error 3 : %s\n", $stmt->error);

$stmt->store_result();
if ($stmt->error) printf("Error 4 : %s\n", $stmt->error);

$stmt->store_result();
if ($stmt->error) printf("Error 5 : %s\n", $stmt->error);

(This may not be relevant to the original sample code, but it can be relevant to people seeking answers to this error.)

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Try sorting index after concatenating them

result=pd.concat([df1,df2]).sort_index()

Getting content/message from HttpResponseMessage

I think the easiest approach is just to change the last line to

txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!

This way you don't need to introduce any stream readers and you don't need any extension methods.

Git and nasty "error: cannot lock existing info/refs fatal"

This is what I did to get rid of all the lock ref issues:

git gc --prune=now
git remote prune origin

This is probably what you only need to do too.

Connect to mysql in a docker container from the host

I recommend checking out docker-compose. Here's how that would work:

Create a file named, docker-compose.yml that looks like this:

version: '2'

services:

  mysql:
    image: mariadb:10.1.19
    ports:
      - 8083:3306
    volumes:
      - ./mysql:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: wp

Next, run:

$ docker-compose up

Notes:

Now, you can access the mysql console thusly:

$ mysql -P 8083 --protocol=tcp -u root -p

Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.5.5-10.1.19-MariaDB-1~jessie mariadb.org binary distribution

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Notes:

  • You can pass the -d flag to run the mysql/mariadb container in detached/background mode.

  • The password is "wp" which is defined in the docker-compose.yml file.

  • Same advice as maniekq but full example with docker-compose.

How can I get the file name from request.FILES?

request.FILES['filename'].name

From the request documentation.

If you don't know the key, you can iterate over the files:

for filename, file in request.FILES.iteritems():
    name = request.FILES[filename].name

What causes "Unable to access jarfile" error?

Just came across the same problem trying to make a bad USB...

I tried to run this command in admin cmd

java -jar c:\fw\ducky\duckencode.jar -I c:\fw\ducky\HelloWorld.txt  -o c:\fw\ducky\inject.bin

But got this error:

Error: unable to access jarfile c:\fw\ducky\duckencode.jar

Solution

1st step

Right click the jarfile in question. Click properties. Click the unblock tab in bottom right corner. The file was blocked, because it was downloaded and not created on my PC.

2nd step

In the cmd I changed the directory to where the jar file is located.

cd C:\fw\ducky\

Then I typed dir and saw the file was named duckencode.jar.jar

So in cmd I changed the original command to reference the file with .jar.jar

java -jar c:\fw\ducky\duckencode.jar.jar -I c:\fw\ducky\HelloWorld.txt  -o c:\fw\ducky\inject.bin

That command executed without error messages and the inject.bin I was trying to create was now located in the directory.

Hope this helps.

How to use http.client in Node.js if there is basic authorization

for what it's worth I'm using node.js 0.6.7 on OSX and I couldn't get 'Authorization':auth to work with our proxy, it needed to be set to 'Proxy-Authorization':auth my test code is:

var http = require("http");
var auth = 'Basic ' + new Buffer("username:password").toString('base64');
var options = {
    host: 'proxyserver',
    port: 80,
    method:"GET",
    path: 'http://www.google.com',
    headers:{
        "Proxy-Authorization": auth,
        Host: "www.google.com"
    } 
};
http.get(options, function(res) {
    console.log(res);
    res.pipe(process.stdout);
});

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

I have changed in my activity but effected. Here is my code:

View layout = getLayoutInflater().inflate(R.layout.list_group,null);
        try {
            LinearLayout linearLayout = (LinearLayout) layout.findViewById(R.id.ldrawernav);
            linearLayout.setBackgroundColor(Color.parseColor("#ffffff"));
        }
        catch (Exception e) {

        }

    }

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

SELECT * FROM TABLE
WHERE DATE BETWEEN '09/16/2010 05:00:00' and '09/21/2010 09:00:00'

Count lines in large files

As per my test, I can verify that the Spark-Shell (based on Scala) is way faster than the other tools (GREP, SED, AWK, PERL, WC). Here is the result of the test that I ran on a file which had 23782409 lines

time grep -c $ my_file.txt;

real 0m44.96s user 0m41.59s sys 0m3.09s

time wc -l my_file.txt;

real 0m37.57s user 0m33.48s sys 0m3.97s

time sed -n '$=' my_file.txt;

real 0m38.22s user 0m28.05s sys 0m10.14s

time perl -ne 'END { $_=$.;if(!/^[0-9]+$/){$_=0;};print "$_" }' my_file.txt;

real 0m23.38s user 0m20.19s sys 0m3.11s

time awk 'END { print NR }' my_file.txt;

real 0m19.90s user 0m16.76s sys 0m3.12s

spark-shell
import org.joda.time._
val t_start = DateTime.now()
sc.textFile("file://my_file.txt").count()
val t_end = DateTime.now()
new Period(t_start, t_end).toStandardSeconds()

res1: org.joda.time.Seconds = PT15S

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

<!DOCTYPE html>

<html>
 <head>
   <link rel="stylesheet" type="text/css" href="main.css" />
 </head>

<body>
 <div id="page-container">
   <div id="content-wrap">
     <!-- all other page content -->
   </div>
   <footer id="footer"></footer>
 </div>
</body>

</html>


#page-container {
  position: relative;
  min-height: 100vh;
}

#content-wrap {
  padding-bottom: 2.5rem;    /* Footer height */
}

#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 2.5rem;            /* Footer height */
}

Name does not exist in the current context

I came across a similar problem with a meta tag. In the designer.cs, the control was defined as:

protected global::System.Web.UI.HtmlControl.HtmlGenericControl metatag;

I had to move the definition to the .aspx.cs file and define as:

protected global::System.Web.UI.HtmlControl.HtmlMeta metatag;

Dynamic type languages versus static type languages

It is all about the right tool for the job. Neither is better 100% of the time. Both systems were created by man and have flaws. Sorry, but we suck and making perfect stuff.

I like dynamic typing because it gets out of my way, but yes runtime errors can creep up that I didn't plan for. Where as static typing may fix the aforementioned errors, but drive a novice(in typed languages) programmer crazy trying to cast between a constant char and a string.

AngularJS Folder Structure

I'm on my third angularjs app and the folder structure has improved every time so far. I keep mine simple right now.

index.html (or .php)
/resources
  /css
  /fonts
  /images
  /js
    /controllers
    /directives
    /filters
    /services
  /partials (views)

I find that good for single apps. I haven't really had a project yet where I'd need multiple.

TypeScript typed array usage

You have an error in your syntax here:

this._possessions = new Thing[100]();

This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:

this._possessions = [];

Of the array constructor if you want to set the length:

this._possessions = new Array(100);

I have created a brief working example you can try in the playground.

module Entities {  

    class Thing {

    }        

    export class Person {
        private _name: string;
        private _possessions: Thing[];
        private _mostPrecious: Thing;

        constructor (name: string) {
            this._name = name;
            this._possessions = [];
            this._possessions.push(new Thing())
            this._possessions[100] = new Thing();
        }
    }
}

Is there a JavaScript strcmp()?

What about

str1.localeCompare(str2)

How to determine if a list of polygon points are in clockwise order?

As also explained in this Wikipedia article Curve orientation, given 3 points p, q and r on the plane (i.e. with x and y coordinates), you can calculate the sign of the following determinant

enter image description here

If the determinant is negative (i.e. Orient(p, q, r) < 0), then the polygon is oriented clockwise (CW). If the determinant is positive (i.e. Orient(p, q, r) > 0), the polygon is oriented counterclockwise (CCW). The determinant is zero (i.e. Orient(p, q, r) == 0) if points p, q and r are collinear.

In the formula above, we prepend the ones in front of the coordinates of p, q and r because we are using homogeneous coordinates.

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

How to open remote files in sublime text 3

On server

Install rsub:

wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate
chmod a+x /usr/local/bin/rsub

On local

  1. Install rsub Sublime3 package:

On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub and install it

  1. Open command line and connect to remote server:

ssh -R 52698:localhost:52698 server_user@server_address

  1. after connect to server run this command on server:

rsub path_to_file/file.txt

  1. File opening auto in Sublime 3

As of today (2018/09/05) you should use : https://github.com/randy3k/RemoteSubl because you can find it in packagecontrol.io while "rsub" is not present.

XPath to select multiple tags

Why not a/b/(c|d|e)? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work. abc.xml is the doc described by OP.

(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
    #<XdmNode <d>D1</d>>
    #<XdmNode <e>E1</e>>
    #<XdmNode <c>C2</c>>
    #<XdmNode <d>D2</d>>
    #<XdmNode <e>E1</e>>)

How is TeamViewer so fast?

would take time to route through TeamViewer's servers (TeamViewer bypasses corporate Symmetric NATs by simply proxying traffic through their servers)

You'll find that TeamViewer rarely needs to relay traffic through their own servers. TeamViewer penetrates NAT and networks complicated by NAT using NAT traversal (I think it is UDP hole-punching, like Google's libjingle).

They do use their own servers to middle-man in order to do the handshake and connection set-up, but most of the time the relationship between client and server will be P2P (best case, when the hand-shake is successful). If NAT traversal fails, then TeamViewer will indeed relay traffic through its own servers.

I've only ever seen it do this when a client has been behind double-NAT, though.

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

Merge replication. You can create the subscriber (2008) from the distributor (2008). After the database has fully synchronized, drop the subscription and the publication.

How to read Data from Excel sheet in selenium webdriver

Don't know about what the error you are facing exactly. But log4j:WARN No appenders could be found for logger error, is due to the log4j jar file that you have included in your project.

Initializing log4j is needed but actually Log4j is not necessary for your project. So Right click on your Project → Properties → Java Build Path → Libraries.. Search for log4j jar file and remove it.

Hope it will work fine now.

How can I get a specific parameter from location.search?

This is what I like to do:

window.location.search
    .substr(1)
    .split('&')
    .reduce(
        function(accumulator, currentValue) {
            var pair = currentValue
                .split('=')
                .map(function(value) {
                    return decodeURIComponent(value);
                });

            accumulator[pair[0]] = pair[1];

            return accumulator;
        },
        {}
    );

Of course you can make it more compact using modern syntax or writing everything into one line...

I leave that up to you.

How to create a simple proxy in C#?

Socks4 is a very simple protocol to implement. You listen for the initial connection, connect to the host/port that was requested by the client, send the success code to the client then forward the outgoing and incoming streams across sockets.

If you go with HTTP you'll have to read and possibly set/remove some HTTP headers so that's a little more work.

If I remember correctly, SSL will work across HTTP and Socks proxies. For a HTTP proxy you implement the CONNECT verb, which works much like the socks4 as described above, then the client opens the SSL connection across the proxied tcp stream.

Auto-expanding layout with Qt-Designer

According to the documentation, there needs to be a top level layout set.

A top level layout is necessary to ensure that your widgets will resize correctly when its window is resized. To check if you have set a top level layout, preview your widget and attempt to resize the window by dragging the size grip.

You can set one by clearing the selection and right clicking on the form itself and choosing one of the layouts available in the context menu.

Qt layouts

Set value of textbox using JQuery

You're targeting the wrong item with that jQuery selector. The name of your search bar is searchBar, not the id. What you want to use is $('#main_search').val('hi').

How to use a DataAdapter with stored procedure and parameter

SqlConnection con = new SqlConnection(@"Some Connection String");//connection object
SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);//SqlDataAdapter class object
da.SelectCommand.CommandType = CommandType.StoredProcedure; //command sype
da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123; //pass perametter
DataTable dt = new DataTable();  //dataset class object
da.Fill(dt); //call the stored producer

Java SimpleDateFormat for time zone with a colon separator?

Try setLenient(false).

Addendum: It looks like you're recognizing variously formatted Date strings. If you have to do entry, you might like looking at this example that extends InputVerifier.

Make a dictionary in Python from input values

n=int(input())
pair = dict()

for i in range(0,n):
        word = input().split()
        key = word[0]
        value = word[1]
        pair[key]=value

print(pair)

Can I install the "app store" in an IOS simulator?

No, according to Apple here:

Note: You cannot install apps from the App Store in simulation environments.

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Html attributes for EditorFor() in ASP.NET MVC

If you don't want to use Metadata you can use a [UIHint("PeriodType")] attribute to decorate the property or if its a complex type you don't have to decorate anything. EditorFor will then look for a PeriodType.aspx or ascx file in the EditorTemplates folder and use that instead.

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)

To quote the most relevant bits:

[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.

The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”

Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.

The full post explains this in more detail. At RTM, the MSDN docs on this should be better.

Show ImageView programmatically

int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp = 
    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                    LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);        
imageView.setImageResource(id);        
someLinearLayout.addView(imageView); 

Convert and format a Date in JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
 <!DOCTYPE html>
 <html dir="ltr" lang="en-US">
 <head>
 <meta charset="UTF-8" />
  <title>JSP with the current date</title>
  </head>
 <body>
 <%java.text.DateFormat df = new java.text.SimpleDateFormat("dd/MM/yyyy"); %>
<h1>Current Date: <%= df.format(new java.util.Date()) %> </h1>
</body>
</html>

Output: Current Date: 10/03/2010

Is there a way to disable initial sorting for jquery DataTables?

Well I found the answer set "aaSorting" to an empty array:

$(document).ready( function() {
    $('#example').dataTable({
        /* Disable initial sort */
        "aaSorting": []
    });
})

For newer versions of Datatables (>= 1.10) use order option:

$(document).ready( function() {
    $('#example').dataTable({
        /* No ordering applied by DataTables during initialisation */
        "order": []
    });
})

"unrecognized selector sent to instance" error in Objective-C

..And now mine

I had the button linked to a method which accessed another button's parameter and that worked great BUT as soon I tried to do something with the button itself, I got a crash. While compiling, no error has been displayed.. Solution?

I failed to link the button to the file's owner. So if anyone here is as stupid as me, try this :)

How to set default values in Go structs

One possible idea is to write separate constructor function

//Something is the structure we work with
type Something struct {
     Text string 
     DefaultText string 
} 
// NewSomething create new instance of Something
func NewSomething(text string) Something {
   something := Something{}
   something.Text = text
   something.DefaultText = "default text"
   return something
}

HTML input - name vs. id

Adding some actual references to W3 docs that authoritatively explain the role of the 'name' attribute on form elements. (For what it's worth, I arrived here while exploring exactly how Stripe.js works to implement safe interaction with payment gateway Stripe. In particular, what causes a form input element to get submitted back to the server, or prevents it from being submitted?)

The following W3 docs are relevent:

HTML 4: https://www.w3.org/TR/html401/interact/forms.html#control-name Section 17.2 Controls

HTML 5: https://www.w3.org/TR/html5/forms.html#form-submission-0 and https://www.w3.org/TR/html5/forms.html#constructing-the-form-data-set Section 4.10.22.4 Constructing the form data set.

As explained therein, an input element will be submitted by the browser if and only if it has a valid 'name' attribute.

As others have noted, the 'id' attribute uniquely identifies DOM elements, but is not involved in normal form submission. (Though 'id' or other attributes can of course be used by javascript to obtain form values, which javascript could then use for AJAX submissions and so on.)

One oddity regarding previous answers/commenters concern about id's values and name's values being in the same namespace. So far as I can tell from the specs, this applied to some deprecated uses of the name attribute (not on form elements). For example https://www.w3.org/TR/html5/obsolete.html:

"Authors should not specify the name attribute on a elements. If the attribute is present, its value must not be the empty string and must neither be equal to the value of any of the IDs in the element's home subtree other than the element's own ID, if any, nor be equal to the value of any of the other name attributes on a elements in the element's home subtree. If this attribute is present and the element has an ID, then the attribute's value must be equal to the element's ID. In earlier versions of the language, this attribute was intended as a way to specify possible targets for fragment identifiers in URLs. The id attribute should be used instead."

Clearly in this special case there's some overlap between id and name values for 'a' tags. But this seems to be a peculiarity of processing for fragment ids, not due to general sharing of namespace of ids and names.

How do I set up CLion to compile and run?

I met some problems in Clion and finally, I solved them. Here is some experience.

  1. Download and install MinGW
  2. g++ and gcc package should be installed by default. Use the MinGW installation manager to install mingw32-libz and mingw32-make. You can open MinGW installation manager through C:\MinGW\libexec\mingw-get.exe This step is the most important step. If Clion cannot find make, C compiler and C++ compiler, recheck the MinGW installation manager to make every necessary package is installed.
  3. In Clion, open File->Settings->Build,Execution,Deployment->Toolchains. Set MinGW home as your local MinGW file.
  4. Start your "Hello World"!

How Do I Upload Eclipse Projects to GitHub?

Jokab's answer helped me a lot but in my case I could not push to github until I logged in my github account to my git bash so i ran the following commands

git config credential.helper store

then

git push http://github.com/[user name]/[repo name].git

After the second command a GUI window appeared, I provided my login credentials and it worked for me.

Visual Studio Code - Convert spaces to tabs

Ctrl+Shift+P, then "Convert Indentation to Tabs"

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I had the same problem. Just after enabling Internet Virtualization from BIOS. After that let the system boot and install HAXM once again. Now emulator will run faster than before and HAXM will work. Enjoy!!

How to get elements with multiple classes

html

<h2 class="example example2">A heading with class="example"</h2>

javascritp code

var element = document.querySelectorAll(".example.example2");
element.style.backgroundColor = "green";

The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

also learn more about https://www.w3schools.com/jsref/met_document_queryselectorall.asp

== Thank You ==

UIImage: Resize, then Crop

Xamarin.iOS version for accepted answer on how to resize and then crop UIImage (Aspect Fill) is below

    public static UIImage ScaleAndCropImage(UIImage sourceImage, SizeF targetSize)
    {
        var imageSize = sourceImage.Size;
        UIImage newImage = null;
        var width = imageSize.Width;
        var height = imageSize.Height;
        var targetWidth = targetSize.Width;
        var targetHeight = targetSize.Height;
        var scaleFactor = 0.0f;
        var scaledWidth = targetWidth;
        var scaledHeight = targetHeight;
        var thumbnailPoint = PointF.Empty;
        if (imageSize != targetSize)
        {
            var widthFactor = targetWidth / width;
            var heightFactor = targetHeight / height;
            if (widthFactor > heightFactor)
            {
                scaleFactor = widthFactor;// scale to fit height
            }
            else
            {
                scaleFactor = heightFactor;// scale to fit width
            }
            scaledWidth = width * scaleFactor;
            scaledHeight = height * scaleFactor;
            // center the image
            if (widthFactor > heightFactor)
            {
                thumbnailPoint.Y = (targetHeight - scaledHeight) * 0.5f;
            }
            else
            {
                if (widthFactor < heightFactor)
                {
                    thumbnailPoint.X = (targetWidth - scaledWidth) * 0.5f;
                }
            }
        }
        UIGraphics.BeginImageContextWithOptions(targetSize, false, 0.0f);
        var thumbnailRect = new RectangleF(thumbnailPoint, new SizeF(scaledWidth, scaledHeight));
        sourceImage.Draw(thumbnailRect);
        newImage = UIGraphics.GetImageFromCurrentImageContext();
        if (newImage == null)
        {
            Console.WriteLine("could not scale image");
        }
        //pop the context to get back to the default
        UIGraphics.EndImageContext();

        return newImage;
    }

Android: Center an image

You can also use this,

android:layout_centerHorizontal="true"

The image will be placed at the center of the screen

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

Perhaps the easiest way to see which extensions are (compiled and) loaded (not in cli) is to have a server run the following:

<?php
$ext = get_loaded_extensions();
asort($ext);
foreach ($ext as $ref) {
    echo $ref . "\n";
}

PHP cli does not necessarily have the same extensions loaded.

Invalid self signed SSL cert - "Subject Alternative Name Missing"

  • Make a copy of your OpenSSL config in your home directory:

    cp /System/Library/OpenSSL/openssl.cnf ~/openssl-temp.cnf
    

    or on Linux:

    cp /etc/ssl/openssl.cnf ~/openssl-temp.cnf
    
  • Add Subject Alternative Name to openssl-temp.cnf, under [v3_ca]:

    [ v3_ca ]
    subjectAltName = DNS:localhost
    

    Replace localhost by the domain for which you want to generate that certificate.

  • Generate certificate:

    sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
        -config ~/openssl-temp.cnf
        -keyout /path/to/your.key -out /path/to/your.crt
    

You can then delete openssl-temp.cnf

@Media min-width & max-width

The underlying issue is using max-device-width vs plain old max-width.

Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.

For example:

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE for DEVICES with physical max-screen width of 480px */
}

Versus

@media only screen and (max-width: 480px) {
    /* STYLES HERE for BROWSER WINDOWS with a max-width of 480px. 
       This will work on desktops when the window is narrowed.  */
}

SQL query to get most recent row for each instance of a given key

Nice elegant solution with ROW_NUMBER window function (supported by PostgreSQL - see in SQL Fiddle):

SELECT username, ip, time_stamp FROM (
 SELECT username, ip, time_stamp, 
  ROW_NUMBER() OVER (PARTITION BY username ORDER BY time_stamp DESC) rn
 FROM Users
) tmp WHERE rn = 1;

How can a divider line be added in an Android RecyclerView?

The Right way is to define ItemDecoration for the RecyclerView is as following

SimpleDividerItemDecoration.java

public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;
 
    public SimpleDividerItemDecoration(Context context) {
        mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider);
    }
 
    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();
 
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
 
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
 
            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();
 
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
}

line_divider.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
 
    <size
        android:width="1dp"
        android:height="1dp" />
 
    <solid android:color="@color/dark_gray" />
 
</shape>

Finally set it like this

recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));

Edit

As pointed by @Alan Solitar

context.getResources().getDrawable(R.drawable.line_divider); 

is depreciated instead of that you can use

ContextCompat.getDrawable(context,R.drawable.line_divider);

How to get pip to work behind a proxy server

At least for pip 1.3.1, it honors the http_proxy and https_proxy environment variables. Make sure you define both, as it will access the PYPI index using https.

export https_proxy="http://<proxy.server>:<port>"
pip install TwitterApi

How to get all keys with their values in redis

I had the same problem, and I felt on your post.

I think the easiest way to solve this issue is by using redis Hashtable.

It allows you to save a Hash, with different fields and values associated with every field.

To get all the fiels and values client.HGETALLL does the trick. It returns an array of

all the fields followed by their values.

More informations here https://redis.io/commands/hgetall

Python error: "IndexError: string index out of range"

You are iterating over one string (word), but then using the index into that to look up a character in so_far. There is no guarantee that these two strings have the same length.

How to clear all data in a listBox?

private void cleanlistbox(object sender, EventArgs e)
{
    listBox1.Items.Clear();
}

Deleting rows with Python in a CSV file

You should have if row[2] != "0". Otherwise it's not checking to see if the string value is equal to 0.

Styling twitter bootstrap buttons

You can change background-color and use !important;

_x000D_
_x000D_
.btn-primary {_x000D_
  background-color: #003c79 !important;_x000D_
  border-color: #15548b !important;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.btn-primary:hover {_x000D_
  background-color: #4289c6 !important;_x000D_
  border-color: #3877ae !important;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.btn-primary.focus, .btn-primary:focus {_x000D_
   background-color: #4289c6 !important;_x000D_
   border-color: #3877ae !important;_x000D_
   color: #fff;_x000D_
}
_x000D_
_x000D_
_x000D_

Remove last character from C++ string

Simple solution if you are using C++11. Probably O(1) time as well:

st.pop_back();

How to solve a timeout error in Laravel 5

Add above query

ini_set("memory_limit", "10056M");

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

Close a MessageBox after several seconds

I know this question is 8 year old, however there was and is a better solution for this purpose. It's always been there, and still is: User32.dll!MessageBoxTimeout.

This is an undocumented function used by Microsoft Windows, and it does exactly what you want and even more. It supports different languages as well.

C# Import:

[DllImport("user32.dll", SetLastError = true)]
public static extern int MessageBoxTimeout(IntPtr hWnd, String lpText, String lpCaption, uint uType, Int16 wLanguageId, Int32 dwMilliseconds);

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetForegroundWindow();

How to use it in C#:

uint uiFlags = /*MB_OK*/ 0x00000000 | /*MB_SETFOREGROUND*/  0x00010000 | /*MB_SYSTEMMODAL*/ 0x00001000 | /*MB_ICONEXCLAMATION*/ 0x00000030;

NativeFunctions.MessageBoxTimeout(NativeFunctions.GetForegroundWindow(), $"Kitty", $"Hello", uiFlags, 0, 5000);

Work smarter, not harder.

Checking network connection

A modern portable solution with requests:

import requests

def internet():
    """Detect an internet connection."""

    connection = None
    try:
        r = requests.get("https://google.com")
        r.raise_for_status()
        print("Internet connection detected.")
        connection = True
    except:
        print("Internet connection not detected.")
        connection = False
    finally:
        return connection

Or, a version that raises an exception:

import requests
from requests.exceptions import ConnectionError

def internet():
    """Detect an internet connection."""

    try:
        r = requests.get("https://google.com")
        r.raise_for_status()
        print("Internet connection detected.")
    except ConnectionError as e:
        print("Internet connection not detected.")
        raise e

bootstrap 3 wrap text content within div for horizontal alignment

Now Update word-wrap is replace by :

overflow-wrap:break-word;

Compatible old navigator and css 3 it's good alternative !

it's evolution of word-wrap ( since 2012... )

See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap

See compatibility full : http://caniuse.com/#search=overflow-wrap

Android EditText Max Length

I had the same problem.

Here is a workaround

android:inputType="textNoSuggestions|textVisiblePassword"
android:maxLength="6"

Thx to How can I turnoff suggestions in EditText?

Configure Flask dev server to be visible across the network

If none of the above solutions are working, try manually adding "http://" to the beginning of the url.

Chrome can distinguish "[ip-address]:5000" from a search query. But sometimes that works for a while, and then stops connecting, seemingly without me changing anything. My hypothesis is that the browser might sometimes automatically prepend https:// (which it shouldn't, but this fixed it in my case).

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Alternatively to Martin's answer, you could also add the INTO part at the end of the query to make the query more readable:

SELECT Id, dateCreated FROM products INTO iId, dCreate

How to resolve TypeError: Cannot convert undefined or null to object

Replace

if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged

with

if (obj === undefined) { return undefined;} // return undefined for undefined 
if (obj === null) { return null;} // null unchanged

How to convert Set<String> to String[]?

Java 11

The new default toArray method in Collection interface allows the elements of the collection to be transferred to a newly created array of the desired runtime type. It takes IntFunction<T[]> generator as argument and can be used as:

 String[] array = set.toArray(String[]::new);

There is already a similar method Collection.toArray(T[]) and this addition means we no longer be able to pass null as argument because in that case reference to the method would be ambiguous. But it is still okay since both methods throw a NPE anyways.

Java 8

In Java 8 we can use streams API:

String[] array = set.stream().toArray(String[]::new);

We can also make use of the overloaded version of toArray() which takes IntFunction<A[]> generator as:

String[] array = set.stream().toArray(n -> new String[n]);

The purpose of the generator function here is to take an integer (size of desired array) and produce an array of desired size. I personally prefer the former approach using method reference than the later one using lambda expression.

Excel Date to String conversion

Couldnt get the TEXT() formula to work

Easiest solution was to copy paste into Notepad and back into Excel with the column set to Text before pasting back

Or you can do the same with a formula like this

=DAY(A2)&"/"&MONTH(A2)&"/"&YEAR(A2)& " "&HOUR(B2)&":"&MINUTE(B2)&":"&SECOND(B2)

How to specify in crontab by what user to run script?

Mike's suggestion sounds like the "right way". I came across this thread wanting to specify the user to run vncserver under on reboot and wanted to keep all my cron jobs in one place.

I was getting the following error for the VNC cron:

vncserver: The USER environment variable is not set. E.g.:

In my case, I was able to use sudo to specify who to run the task as.

@reboot sudo -u [someone] vncserver ...

Pretty-print a Map in Java

When I have org.json.JSONObject in the classpath, I do:

Map<String, Object> stats = ...;
System.out.println(new JSONObject(stats).toString(2));

(this beautifully indents lists, sets and maps which may be nested)

How to get current page URL in MVC 3

I too was looking for this for Facebook reasons and none of the answers given so far worked as needed or are too complicated.

@Request.Url.GetLeftPart(UriPartial.Path)

Gets the full protocol, host and path "without" the querystring. Also includes the port if you are using something other than the default 80.

Running shell command and capturing the output

Something like that:

def runProcess(exe):    
    p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while(True):
        # returns None while subprocess is running
        retcode = p.poll() 
        line = p.stdout.readline()
        yield line
        if retcode is not None:
            break

Note, that I'm redirecting stderr to stdout, it might not be exactly what you want, but I want error messages also.

This function yields line by line as they come (normally you'd have to wait for subprocess to finish to get the output as a whole).

For your case the usage would be:

for line in runProcess('mysqladmin create test -uroot -pmysqladmin12'.split()):
    print line,

Radio/checkbox alignment in HTML/CSS

This is a simple solution which solved the problem for me:

label 
{

/* for firefox */
vertical-align:middle; 

/*for internet explorer */
*bottom:3px;
*position:relative; 

padding-bottom:7px; 

}

How to create a density plot in matplotlib?

Sven has shown how to use the class gaussian_kde from Scipy, but you will notice that it doesn't look quite like what you generated with R. This is because gaussian_kde tries to infer the bandwidth automatically. You can play with the bandwidth in a way by changing the function covariance_factor of the gaussian_kde class. First, here is what you get without changing that function:

alt text

However, if I use the following code:

import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
density = gaussian_kde(data)
xs = np.linspace(0,8,200)
density.covariance_factor = lambda : .25
density._compute_covariance()
plt.plot(xs,density(xs))
plt.show()

I get

alt text

which is pretty close to what you are getting from R. What have I done? gaussian_kde uses a changable function, covariance_factor to calculate its bandwidth. Before changing the function, the value returned by covariance_factor for this data was about .5. Lowering this lowered the bandwidth. I had to call _compute_covariance after changing that function so that all of the factors would be calculated correctly. It isn't an exact correspondence with the bw parameter from R, but hopefully it helps you get in the right direction.

How to change the playing speed of videos in HTML5?

javascript:document.getElementsByClassName("video-stream html5-main-video")[0].playbackRate = 0.1;

you can put any number here just don't go to far so you don't overun your computer.

Target elements with multiple classes, within one rule

Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.

The following:

.blue-border, .background {
    border: 1px solid #00f;
    background: #fff;
}

is for when you want to add styles to elements that have either the blue-border or background class, for example:

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

would all get a blue border and white background applied to them.

However, the accepted answer is different.

.blue-border.background {
    border: 1px solid #00f;
    background: #fff;
}

This applies the styles to elements that have both classes so in this example only the <div> with both classes should get the styles applied (in browsers that interpret the CSS properly):

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.

How to remove illegal characters from path and filenames?

The best way to remove illegal character from user input is to replace illegal character using Regex class, create method in code behind or also it validate at client side using RegularExpression control.

public string RemoveSpecialCharacters(string str)
{
    return Regex.Replace(str, "[^a-zA-Z0-9_]+", "_", RegexOptions.Compiled);
}

OR

<asp:RegularExpressionValidator ID="regxFolderName" 
                                runat="server" 
                                ErrorMessage="Enter folder name with  a-z A-Z0-9_" 
                                ControlToValidate="txtFolderName" 
                                Display="Dynamic" 
                                ValidationExpression="^[a-zA-Z0-9_]*$" 
                                ForeColor="Red">

Reverse a comparator in Java 8

Why not to extend the existing comperator and overwrite super and nor the result. The implementation the Comperator Interface is not nessesery but it makes it more clear what happens.

In result you get a easy reusable Class File, testable unit step and clear javadoc.

public class NorCoperator extends ExistingComperator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass a, MyClass b) throws Exception {
        return super.compare(a, b)*-1;
    }
}

Getting Current time to display in Label. VB.net

Try This.....

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load    
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub

What does `void 0` mean?

What does void 0 mean?

void[MDN] is a prefix keyword that takes one argument and always returns undefined.

Examples

void 0
void (0)
void "hello"
void (new Date())
//all will return undefined

What's the point of that?

It seems pretty useless, doesn't it? If it always returns undefined, what's wrong with just using undefined itself?

In a perfect world we would be able to safely just use undefined: it's much simpler and easier to understand than void 0. But in case you've never noticed before, this isn't a perfect world, especially when it comes to Javascript.

The problem with using undefined was that undefined is not a reserved word (it is actually a property of the global object [wtfjs]). That is, undefined is a permissible variable name, so you could assign a new value to it at your own caprice.

alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) // alerts "new value"

Note: This is no longer a problem in any environment that supports ECMAScript 5 or newer (i.e. in practice everywhere but IE 8), which defines the undefined property of the global object as read-only (so it is only possible to shadow the variable in your own local scope). However, this information is still useful for backwards-compatibility purposes.

alert(window.hasOwnProperty('undefined')); // alerts "true"
alert(window.undefined); // alerts "undefined"
alert(undefined === window.undefined); // alerts "true"
var undefined = "new value";
alert(undefined); // alerts "new value"
alert(undefined === window.undefined); // alerts "false"

void, on the other hand, cannot be overidden. void 0 will always return undefined. undefined, on the other hand, can be whatever Mr. Javascript decides he wants it to be.

Why void 0, specifically?

Why should we use void 0? What's so special about 0? Couldn't we just as easily use 1, or 42, or 1000000 or "Hello, world!"?

And the answer is, yes, we could, and it would work just as well. The only benefit of passing in 0 instead of some other argument is that 0 is short and idiomatic.

Why is this still relevant?

Although undefined can generally be trusted in modern JavaScript environments, there is one trivial advantage of void 0: it's shorter. The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace undefined with void 0 to reduce the number of bytes sent to the browser.

Run multiple python scripts concurrently

You try the following ways to run the multiple python scripts:

  import os
  print "Starting script1"
  os.system("python script1.py arg1 arg2 arg3")
  print "script1 ended"
  print "Starting script2"
  os.system("python script2.py arg1 arg2 arg3")
  print "script2 ended"

Note: The execution of multiple scripts depends purely underlined operating system, and it won't be concurrent, I was new comer in Python when I answered it.

Update: I found a package: https://pypi.org/project/schedule/ Above package can be used to run multiple scripts and function, please check this and maybe on weekend will provide some example too.

i.e:

 import schedule
 import time
 import script1, script2

 def job():
     print("I'm working...")

 schedule.every(10).minutes.do(job)
 schedule.every().hour.do(job)
 schedule.every().day.at("10:30").do(job)
 schedule.every(5).to(10).days.do(job)
 schedule.every().monday.do(job)
 schedule.every().wednesday.at("13:15").do(job)

 while True:
     schedule.run_pending()
     time.sleep(1)

Correct format specifier for double in printf

Given the C99 standard (namely, the N1256 draft), the rules depend on the function kind: fprintf (printf, sprintf, ...) or scanf.

Here are relevant parts extracted:

Foreword

This second edition cancels and replaces the first edition, ISO/IEC 9899:1990, as amended and corrected by ISO/IEC 9899/COR1:1994, ISO/IEC 9899/AMD1:1995, and ISO/IEC 9899/COR2:1996. Major changes from the previous edition include:

  • %lf conversion specifier allowed in printf

7.19.6.1 The fprintf function

7 The length modifiers and their meanings are:

l (ell) Specifies that (...) has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument.

The same rules specified for fprintf apply for printf, sprintf and similar functions.

7.19.6.2 The fscanf function

11 The length modifiers and their meanings are:

l (ell) Specifies that (...) that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double;

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to long double.

12 The conversion specifiers and their meanings are: a,e,f,g Matches an optionally signed floating-point number, (...)

14 The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.

The long story short, for fprintf the following specifiers and corresponding types are specified:

  • %f -> double
  • %Lf -> long double.

and for fscanf it is:

  • %f -> float
  • %lf -> double
  • %Lf -> long double.

Can I style an image's ALT text with CSS?

as this question is the first result at search engines

There are a problem with the selected -and right by the way- solution, is that if you want to add style that will apply to images like ( borders for example ) .

for example :

_x000D_
_x000D_
img {_x000D_
  color:#fff;_x000D_
  border: 1px solid black;_x000D_
  padding: 5px;_x000D_
  background-color: #ccc;_x000D_
}
_x000D_
<img src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" /> <hr />_x000D_
<img src="https://cdn4.iconfinder.com/data/icons/miu-square-flat-social/60/stackoverflow-square-social-media-128.png" alt="BLAH BLAH BLAH" />
_x000D_
_x000D_
_x000D_

as you can see, all of images will apply the same style


there is another approach to easily work around such an issue, using onerror and injecting some special class to deal with the interrupted images :

_x000D_
_x000D_
.invalidImageSrc {_x000D_
  color:#fff;_x000D_
  border: 1px solid black;_x000D_
  padding: 5px;_x000D_
  background-color: #ccc;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
_x000D_
<img onerror="$(this).addClass('invalidImageSrc')" src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" /> <hr />_x000D_
<img onerror="$(this).addClass('invalidImageSrc')" src="https://cdn4.iconfinder.com/data/icons/miu-square-flat-social/60/stackoverflow-square-social-media-128.png" alt="BLAH BLAH BLAH" />
_x000D_
_x000D_
_x000D_

Javascript : natural sort of alphanumerical strings

Imagine an 8 digit padding function that transforms:

  • '123asd' -> '00000123asd'
  • '19asd' -> '00000019asd'

We can used the padded strings to help us sort '19asd' to appear before '123asd'.

Use the regular expression /\d+/g to help find all the numbers that need to be padded:

str.replace(/\d+/g, pad)

The following demonstrates sorting using this technique:

_x000D_
_x000D_
var list = [_x000D_
    '123asd',_x000D_
    '19asd',_x000D_
    '12345asd',_x000D_
    'asd123',_x000D_
    'asd12'_x000D_
];_x000D_
_x000D_
function pad(n) { return ("00000000" + n).substr(-8); }_x000D_
function natural_expand(a) { return a.replace(/\d+/g, pad) };_x000D_
function natural_compare(a, b) {_x000D_
    return natural_expand(a).localeCompare(natural_expand(b));_x000D_
}_x000D_
_x000D_
console.log(list.map(natural_expand).sort()); // intermediate values_x000D_
console.log(list.sort(natural_compare)); // result
_x000D_
_x000D_
_x000D_

The intermediate results show what the natural_expand() routine does and gives you an understanding of how the subsequent natural_compare routine will work:

[
  "00000019asd",
  "00000123asd",
  "00012345asd",
  "asd00000012",
  "asd00000123"
]

Outputs:

[
  "19asd",
  "123asd",
  "12345asd",
  "asd12",
  "asd123"
]

Disable keyboard on EditText

You can also use setShowSoftInputOnFocus(boolean) directly on API 21+ or through reflection on API 14+:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    editText.setShowSoftInputOnFocus(false);
} else {
    try {
        final Method method = EditText.class.getMethod(
                "setShowSoftInputOnFocus"
                , new Class[]{boolean.class});
        method.setAccessible(true);
        method.invoke(editText, false);
    } catch (Exception e) {
        // ignore
    }
}

remove empty lines from text file with PowerShell

To resolve this with RegEx, you need to use the multiline flag (?m):

((Get-Content file.txt -Raw) -replace "(?m)^\s*`r`n",'').trim() | Set-Content file.txt

Language Books/Tutorials for popular languages

The defacto standard for learning Grails is the excellent Getting Started with Grails by Jason Rudolph. You can debate whether it is an online tutorial or a book since it can be purchased but is available as a free download. There are more "real" books being published and I recommend Beginning Groovy and Grails.

Component is not part of any NgModule or the module has not been imported into your module

I ran into this error message on 2 separate occasions, with lazy loading in Angular 7 and the above did not help. For both of the below to work you MUST stop and restart ng serve for it to completely update correctly.

1) First time I had somehow incorrectly imported my AppModule into the lazy loaded feature module. I removed this import from the lazy loaded module and it started working again.

2) Second time I had a separate CoreModule that I was importing into the AppModule AND same lazy loaded module as #1. I removed this import from the lazy loaded module and it started working again.

Basically, check your hierarchy of imports and pay close attention to the order of the imports (if they are imported where they should be). Lazy loaded modules only need their own route component / dependencies. App and parent dependencies will be passed down whether they are imported into AppModule, or imported from another feature module that is NOT-lazy loaded and already imported in a parent module.

Cannot read property 'getContext' of null, using canvas

I guess the problem is your js runs before the html is loaded.

If you are using jquery, you can use the document ready function to wrap your code:

$(function() {
    var Grid = function(width, height) {
        // codes...
    }
});

Or simply put your js after the <canvas>.

How to check if a value exists in an object using JavaScript

var obj = {"a": "test1", "b": "test2"};
var getValuesOfObject = Object.values(obj)
for(index = 0; index < getValuesOfObject.length; index++){
    return Boolean(getValuesOfObject[index] === "test1")
}

The Object.values() method returned an array (assigned to getValuesOfObject) containing the given object's (obj) own enumerable property values. The array was iterated using the for loop to retrieve each value (values in the getValuesfromObject) and returns a Boolean() function to find out if the expression ("text1" is a value in the looping array) is true.

Ubuntu - Run command on start-up with "sudo"

Edit the tty configuration in /etc/init/tty*.conf with a shellscript as a parameter :

(...)
exec /sbin/getty -n -l  theInputScript.sh -8 38400 tty1
(...)

This is assuming that we're editing tty1 and the script that reads input is theInputScript.sh.

A word of warning this script is run as root, so when you are inputing stuff to it you have root priviliges. Also append a path to the location of the script.

Important: the script when it finishes, has to invoke the /sbin/login otherwise you wont be able to login in the terminal.

How to tell if a string is not defined in a Bash shell script

The explicit way to check for a variable being defined would be:

[ -v mystr ]

Credentials for the SQL Server Agent service are invalid

I found I had to be logged in as a domain user.

It gave me this error when I was logged in as local machine Administrator and trying to add domain service account.

Logged in as domain user (but admin on machine) and it accepted the credentials.

Display Images Inline via CSS

Place this css in your page:

<style>
   #client_logos {
    display: inline-block;
    width:100%;
    }
  </style>

Replace

<p><img class="alignnone" style="display: inline; margin: 0 10px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" /></p>

To

<div id="client_logos">
<img style="display: inline; margin: 0 5px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="piiholo_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" />
</div>

How to get file name when user select a file via <input type="file" />?

just tested doing this and it seems to work in firefox & IE

<html>
    <head>
        <script type="text/javascript">
            function alertFilename()
            {
                var thefile = document.getElementById('thefile');
                alert(thefile.value);
            }
        </script>
    </head>
    <body>
        <form>
            <input type="file" id="thefile" onchange="alertFilename()" />
            <input type="button" onclick="alertFilename()" value="alert" />
        </form>
    </body>
</html>

PHP substring extraction. Get the string before the first '/' or the whole string

why not use:

function getwhatiwant($s)
{
    $delimiter='/';
    $x=strstr($s,$delimiter,true);
    return ($x?$x:$s);
}

OR:

   function getwhatiwant($s)
   {
       $delimiter='/';
       $t=explode($delimiter, $s);
       return ($t[1]?$t[0]:$s);
   }

How to have an auto incrementing version number (Visual Studio)?

Use AssemblyInfo.cs

Create the file in App_Code: and fill out the following or use Google for other attribute/property possibilities.

AssemblyInfo.cs

using System.Reflection;

[assembly: AssemblyDescription("Very useful stuff here.")]
[assembly: AssemblyCompany("companyname")]
[assembly: AssemblyCopyright("Copyright © me 2009")]
[assembly: AssemblyProduct("NeatProduct")]
[assembly: AssemblyVersion("1.1.*")]

AssemblyVersion being the part you are really after.

Then if you are working on a website, in any aspx page, or control, you can add in the <Page> tag, the following:

CompilerOptions="<folderpath>\App_Code\AssemblyInfo.cs"

(replacing folderpath with appropriate variable of course).

I don't believe you need to add compiler options in any manner for other classes; all the ones in the App_Code should receive the version information when they are compiled.

Hope that helps.

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

I'm posting my solution for the other sleep-deprived souls out there:

If you're using RVM, double-check that you're in the correct folder, using the correct ruby version and gemset. I had an array of terminal tabs open, and one of them was in a different directory. typing "rails console" produced the error because my default rails distro is 2.3.x.

I noticed the error on my part, cd'd to the correct directory, and my .rvmrc file did the rest.

RVM is not like Git. In git, changing branches in one shell changes it everywhere. It's literally rewriting the files in question. RVM, on the other hand, is just setting shell variables, and must be set for each new shell you open.

In case you're not familiar with .rvmrc, you can put a file with that name in any directory, and rvm will pick it up and use the version/gemset specified therein, whenever you change to that directory. Here's a sample .rvmrc file:

rvm use 1.9.2@turtles

This will switch to the latest version of ruby 1.9.2 in your RVM collection, using the gemset "turtles". Now you can open up a hundred tabs in Terminal (as I end up doing) and never worry about the ruby version it's pointing to.

jQuery get the rendered height of an element?

I use this to get the height of an element (returns float):

document.getElementById('someDiv').getBoundingClientRect().height

It also works when you use the virtual DOM. I use it in Vue like this:

this.$refs['some-ref'].getBoundingClientRect().height

For a Vue component:

this.$refs['some-ref'].$el.getBoundingClientRect().height

JQuery/Javascript: check if var exists

To test for existence there are two methods.

a. "property" in object

This method checks the prototype chain for existence of the property.

b. object.hasOwnProperty( "property" )

This method does not go up the prototype chain to check existence of the property, it must exist in the object you are calling the method on.

var x; // variable declared in global scope and now exists

"x" in window; // true
window.hasOwnProperty( "x" ); //true

If we were testing using the following expression then it would return false

typeof x !== 'undefined'; // false

How do I enable index downloads in Eclipse for Maven dependency search?

Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories, and it should work.

The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.

How to delete the top 1000 rows from a table using Sql Server 2008?

As defined in the link below, you can delete in a straight forward manner

USE AdventureWorks2008R2;
GO
DELETE TOP (20) 
FROM Purchasing.PurchaseOrderDetail
WHERE DueDate < '20020701';
GO

http://technet.microsoft.com/en-us/library/ms175486(v=sql.105).aspx

Darkening an image with CSS (In any shape)

Webkit only solution

Quick solution, relies on the -webkit-mask-image property. -webkit-mask-image sets a mask image for an element.

There are a few gotchas with this method:

  • Obviously, only works in Webkit browsers
  • Requires an additional wrapper to apply the :after psuedo-element (IMG tags can't have :before/:after pseudo elements, grr)
  • Because there's an additional wrapper, I'm not sure how to use the attr(…) CSS function to get the IMG tag URL, so it's hard-coded into the CSS separately.

If you can look past those issues, this might be a possible solution. SVG filters will be even more flexible, and Canvas solutions will be even more flexible and have a wider range of support (SVG doesn't have Android 2.x support).

What is the "realm" in basic authentication

A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.

Please enter your username and password for <realm name>:

When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

You have to make a change in the asterisk.conf file located at /etc/asterisk

astrundir => /var/run/asterisk

Reboot your system and check

Hope this helps you

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

String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
   char c = s.charAt(i);
}

 

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

What is the difference between a generative and a discriminative algorithm?

Let's say you have input data x and you want to classify the data into labels y. A generative model learns the joint probability distribution p(x,y) and a discriminative model learns the conditional probability distribution p(y|x) - which you should read as "the probability of y given x".

Here's a really simple example. Suppose you have the following data in the form (x,y):

(1,0), (1,0), (2,0), (2, 1)

p(x,y) is

      y=0   y=1
     -----------
x=1 | 1/2   0
x=2 | 1/4   1/4

p(y|x) is

      y=0   y=1
     -----------
x=1 | 1     0
x=2 | 1/2   1/2

If you take a few minutes to stare at those two matrices, you will understand the difference between the two probability distributions.

The distribution p(y|x) is the natural distribution for classifying a given example x into a class y, which is why algorithms that model this directly are called discriminative algorithms. Generative algorithms model p(x,y), which can be transformed into p(y|x) by applying Bayes rule and then used for classification. However, the distribution p(x,y) can also be used for other purposes. For example, you could use p(x,y) to generate likely (x,y) pairs.

From the description above, you might be thinking that generative models are more generally useful and therefore better, but it's not as simple as that. This paper is a very popular reference on the subject of discriminative vs. generative classifiers, but it's pretty heavy going. The overall gist is that discriminative models generally outperform generative models in classification tasks.

How to clear input buffer in C?

Try this:

stdin->_IO_read_ptr = stdin->_IO_read_end;

How can I check if given int exists in array?

You can use std::find for this:

#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end

int main () 
{
  int a[] = {3, 6, 8, 33};
  int x = 8;
  bool exists = std::find(std::begin(a), std::end(a), x) != std::end(a);
}

std::find returns an iterator to the first occurrence of x, or an iterator to one-past the end of the range if x is not found.

Return file in ASP.Net Core Web API

If this is ASP.net-Core then you are mixing web API versions. Have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model.

[Route("api/[controller]")]
public class DownloadController : Controller {
    //GET api/download/12345abc
    [HttpGet("{id}"]
    public async Task<IActionResult> Download(string id) {
        Stream stream = await {{__get_stream_based_on_id_here__}}

        if(stream == null)
            return NotFound(); // returns a NotFoundResult with Status404NotFound response.

        return File(stream, "application/octet-stream"); // returns a FileStreamResult
    }    
}

Replace input type=file by an image

This works really well for me:

_x000D_
_x000D_
.image-upload>input {_x000D_
  display: none;_x000D_
}
_x000D_
<div class="image-upload">_x000D_
  <label for="file-input">_x000D_
    <img src="https://icon-library.net/images/upload-photo-icon/upload-photo-icon-21.jpg"/>_x000D_
  </label>_x000D_
_x000D_
  <input id="file-input" type="file" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Basically the for attribute of the label makes it so that clicking the label is the same as clicking the specified input.

Also, the display property set to none makes it so that the file input isn't rendered at all, hiding it nice and clean.

Tested in Chrome but according to the web should work on all major browsers. :)

EDIT: Added JSFiddle here: https://jsfiddle.net/c5s42vdz/

How to upgrade docker-compose to latest version

If you have homebrew you can also install via brew

$ brew install docker-compose

This is a good way to install on a Mac OS system

What is the problem with shadowing names defined in outer scopes?

Do this:

data = [4, 5, 6]

def print_data():
    global data
    print(data)

print_data()

How do I "decompile" Java class files?

Update February 2016:

www.javadecompilers.com lists JAD as being:

the most popular Java decompiler, but primarily of this age only. Written in C++, so very fast.
Outdated, unsupported and does not decompile correctly Java 5 and later

So your mileage may vary with recent jdk (7, 8).

The same site list other tools.

And javadecompiler, as noted by Salvador Valencia in the comments (Sept 2017), offers a SaaS where you upload the .class file to the cloud and it returns you the decompiled code.


Original answer: Oct. 2008

  • The final release of JSR 176, defining the major features of J2SE 5.0 (Java SE 5), has been published on September 30, 2004.
  • The lastest Java version supported by JAD, the famous Java decompiler written by Mr. Pavel Kouznetsov, is JDK 1.3.
  • Most of the Java decompilers downloadable today from the Internet, such as “DJ Java Decompiler” or “Cavaj Java Decompiler”, are powered by JAD: they can not display Java 5 sources.

Java Decompiler (Yet another Fast Java decompiler) has:

  • Explicit support for decompiling and analyzing Java 5+ “.class” files.
  • A nice GUI:

screenshot

It works with compilers from JDK 1.1.8 up to JDK 1.7.0, and others (Jikes, JRockit, etc.).

It features an online live demo version that is actually fully functional! You can just drop a jar file on the page and see the decompiled source code without installing anything.

Rails DateTime.now without Time

You can use just:

Date.current

How do you specify table padding in CSS? ( table, not cell padding )

You can try the border-spacing property. That should do what you want. But you may want to see this answer.

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

The above error can occur for multiple cases during servlet startup / request. Hope you check the full stack trace of the server log, If you have tomcat, you can also see the exact causes in html preview of the 500 Internal Server Error page.

Weird thing is, if you try to hit the request url a second time, you would get 404 Not Found page.

You can also debug this issue, by placing breakpoints on all the classes constructor initialization block, whose objects are created during servlet startup/request.

In my case, I didn't had javaassist jar loaded for the Weld CDI injection to work. And it shown NoClassDefFound Error.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

plot a circle with pyplot

If you aim to have the "circle" maintain a visual aspect ratio of 1 no matter what the data coordinates are, you could use the scatter() method. http://matplotlib.org/1.3.1/api/pyplot_api.html#matplotlib.pyplot.scatter

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
r = [100, 80, 60, 40, 20] # in points, not data units
fig, ax = plt.subplots(1, 1)
ax.scatter(x, y, s=r)
fig.show()

Image is a scatter plot. Five circles along the line y=10x have decreasing radii from bottom left to top right. Although the graph is square-shaped, the y-axis has 10 times the range of the x-axis. Even so, the aspect ratio of the circles is 1 on the screen.

Check if a string matches a regex in Bash script

In bash version 3 you can use the '=~' operator:

if [[ "$date" =~ ^[0-9]{8}$ ]]; then
    echo "Valid date"
else
    echo "Invalid date"
fi

Reference: http://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF

NOTE: The quoting in the matching operator within the double brackets, [[ ]], is no longer necessary as of Bash version 3.2

How do I get some variable from another class in Java?

Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.

Unicode via CSS :before

Fileformat.info is a pretty good reference for this stuff. In your case, it's already in hex, so the hex value is f066. So you'd do:

content: "\f066";

How do I raise the same Exception with a custom message in Python?

Try below:

try:
    raise ValueError("Original message. ")
except Exception as err:
    message = 'My custom error message. '
    # Change the order below to "(message + str(err),)" if custom message is needed first. 
    err.args = (str(err) + message,)
    raise 

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
      1 try:
----> 2     raise ValueError("Original message")
      3 except Exception as err:
      4     message = 'My custom error message.'
      5     err.args = (str(err) + ". " + message,)

ValueError: Original message. My custom error message.

Pass command parameter to method in ViewModel in WPF?

Try this:

 public class MyVmBase : INotifyPropertyChanged
{
  private ICommand _clickCommand;
   public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler( MyAction));
        }
    }
    
       public void MyAction(object message)
    {
        if(message == null)
        {
            Notify($"Method {message} not defined");
            return;
        }
        switch (message.ToString())
        {
            case "btnAdd":
                {
                    btnAdd_Click();
                    break;
                }

            case "BtnEdit_Click":
                {
                    BtnEdit_Click();
                    break;
                }

            default:
                throw new Exception($"Method {message} not defined");
                break;
        }
    }
}

  public class CommandHandler : ICommand
{
    private Action<object> _action;
    private Func<object, bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action<object> action, Func<object, bool> canExecute)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));
        _action = action;
        _canExecute = canExecute ?? (x => true);
    }
    public CommandHandler(Action<object> action) : this(action, null)
    {
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _action(parameter);
    }
    public void Refresh()
    {
        CommandManager.InvalidateRequerySuggested();
    }
}

And in xaml:

     <Button
    Command="{Binding ClickCommand}"
    CommandParameter="BtnEdit_Click"/>

What is the color code for transparency in CSS?

In the CSS write:

.exampleclass {
    background:#000000;
    opacity: 10; /* you can always adjust this */
}

.gitignore all the .DS_Store files in every folder and subfolder

You should add following lines while creating a project. It will always ignore .DS_Store to be pushed to the repository.

*.DS_Store this will ignore .DS_Store while code commit.
git rm --cached .DS_Store this is to remove .DS_Store files from your repository, in case you need it, you can uncomment it.

## ignore .DS_Store file.
# git rm --cached .DS_Store
*.DS_Store

Get the Query Executed in Laravel 3/4

You can also listen for query events using this:

DB::listen(function($sql, $bindings, $time)
{
    var_dump($sql);
});

See the information from the docs here under Listening For Query Events

Get changes from master into branch in Git

First check out to master:

git checkout master

Do all changes, hotfix and commits and push your master.

Go back to your branch, 'aq', and merge master in it:

git checkout aq
git merge master

Your branch will be up-to-date with master. A good and basic example of merge is 3.2 Git Branching - Basic Branching and Merging.

What's the difference between Git Revert, Checkout and Reset?

If you broke the tree but didn't commit the code, you can use git reset, and if you just want to restore one file, you can use git checkout.

If you broke the tree and committed the code, you can use git revert HEAD.

http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html

When should I use semicolons in SQL Server?

If you like getting random Command Timeout errors in SQLServer then leave off the semi-colon at the end of your CommandText strings.

I don't know if this is documented anywhere or if it is a bug, but it does happen and I have learnt this from bitter experience.

I have verifiable and reproducible examples using SQLServer 2008.

aka -> In practice, always include the terminator even if you're just sending one statement to the database.

Creating an Instance of a Class with a variable in Python

Given your edit i assume you have the class name as a string and want to instantiate the class? Just use a dictionary as a dispatcher.

class Foo(object):
    pass

class Bar(object):
    pass

dispatch_dict = {"Foo": Foo, "Bar": Bar}
dispatch_dict["Foo"]() # returns an instance of Foo

converting json to string in python

json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

But the dumps() would convert None into null making a valid JSON string that can be loaded:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

Javascript: formatting a rounded number to N decimals

This works for rounding to N digits (if you just want to truncate to N digits remove the Math.round call and use the Math.trunc one):

function roundN(value, digits) {
   var tenToN = 10 ** digits;
   return /*Math.trunc*/(Math.round(value * tenToN)) / tenToN;
}

Had to resort to such logic at Java in the past when I was authoring data manipulation E-Slate components. That is since I had found out that adding 0.1 many times to 0 you'd end up with some unexpectedly long decimal part (this is due to floating point arithmetics).

A user comment at Format number to always show 2 decimal places calls this technique scaling.

Some mention there are cases that don't round as expected and at http://www.jacklmoore.com/notes/rounding-in-javascript/ this is suggested instead:

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

HttpUtility does not exist in the current context

It worked for by following process:

Add Reference:

system.net
system.web

also, include the namespace

using system.net
using system.web