Programs & Examples On #Headless

Headless systems are those which do not support standard user interface devices, such as monitors, keyboards and mice.

how to add the missing RANDR extension

I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.

The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).

New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/ (eg /opt/firefox31/). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.

"No X11 DISPLAY variable" - what does it mean?

Very Easy, Had this same problem then what i did was to download and install an app that would help in displaying then fixed the error.

Download this app xming:

http://sourceforge.net/project/downloading.php?

Install, then use settings on this link:

http://www.geo.mtu.edu/geoschem/docs/putty_install.html or follow this steps:

Installing/Configuring PuTTy and Xming

Once PuTTy and Xming have been downloaded to the PC, install according to their respective instructions.

Configuring Xming

Once Xming is installed, run the application called 'XLaunch' and verify that the settings are as shown:

  • select Default entries on Display Settings windows, click next
  • click next on Session Type window.
  • click next on Additional parameters window(Notice clipboard checkbox is true)
  • save configuration and click to finish.

Configuring PuTTy

After installing PuTTy, double-click on the PuTTy icon on the desktop and configure as shown:

This shows creating a login profile then saving it.

  • On ssh -> X11, click on checkbox to enable X11 forwarding.
  • on X display location textbox, type localhost:0.0

save profile then connect remotely to server to test.

Cheers!!!

Gradients on UIView and UILabels On iPhone

You can use Core Graphics to draw the gradient, as pointed to in Mike's response. As a more detailed example, you could create a UIView subclass to use as a background for your UILabel. In that UIView subclass, override the drawRect: method and insert code similar to the following:

- (void)drawRect:(CGRect)rect 
{
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGGradientRef glossGradient;
    CGColorSpaceRef rgbColorspace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { 1.0, 1.0, 1.0, 0.35,  // Start color
         1.0, 1.0, 1.0, 0.06 }; // End color

    rgbColorspace = CGColorSpaceCreateDeviceRGB();
    glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);

    CGRect currentBounds = self.bounds;
    CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
    CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
    CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);

    CGGradientRelease(glossGradient);
    CGColorSpaceRelease(rgbColorspace); 
}

This particular example creates a white, glossy-style gradient that is drawn from the top of the UIView to its vertical center. You can set the UIView's backgroundColor to whatever you like and this gloss will be drawn on top of that color. You can also draw a radial gradient using the CGContextDrawRadialGradient function.

You just need to size this UIView appropriately and add your UILabel as a subview of it to get the effect you desire.

EDIT (4/23/2009): Per St3fan's suggestion, I have replaced the view's frame with its bounds in the code. This corrects for the case when the view's origin is not (0,0).

Why am I getting this error Premature end of file?

When you do this,

while((inputLine = buff_read.readLine())!= null){
        System.out.println(inputLine);
    }

You consume everything in instream, so instream is empty. Now when try to do this,

Document doc = builder.parse(instream);

The parsing will fail, because you have passed it an empty stream.

Preventing iframe caching in browser

To get the iframe to always load fresh content, add the current Unix timestamp to the end of the GET parameters. The browser then sees it as a 'different' request and will seek new content.

In Javascript, it might look like:

frames['my_iframe'].location.href='load_iframe_content.php?group_ID=' + group_ID + '&timestamp=' + timestamp;

Is there a naming convention for git repositories?

lowercase-with-hyphens is the style I most often see on GitHub.*

lowercase_with_underscores is probably the second most popular style I see.

The former is my preference because it saves keystrokes.

* Anecdotal; I haven't collected any data.

Fatal error: Call to undefined function pg_connect()

You have to follow these steps:

Open the php configuration file, which is located in the following directory

C: \ xampp \ php \ php.ini

Within that file search the extension section and uncomment the following lines

extension = php_pdo_pgsql.dll  
extension = php_pgsql.dll

and restart your apache

Killing a process created with Python's subprocess.Popen()

process.terminate() doesn't work when using shell=True. This answer will help you.

Where do I get servlet-api.jar from?

You can find a recent servlet-api.jar in Tomcat 6 or 7 lib directory. If you don't have Tomcat on your machine, download the binary distribution of version 6 or 7 from http://tomcat.apache.org/download-70.cgi

Printing the last column of a line in a file

Using Perl

$ cat rayne.txt
A1 123 456
B1 234 567
C1 345 678
A1 098 766
B1 987 6545
C1 876 5434


$ perl -lane ' /A1/ and $x=$F[2] ; END { print "$x" } ' rayne.txt
766

$

Parse large JSON file in Nodejs

If you have control over the input file, and it's an array of objects, you can solve this more easily. Arrange to output the file with each record on one line, like this:

[
   {"key": value},
   {"key": value},
   ...

This is still valid JSON.

Then, use the node.js readline module to process them one line at a time.

var fs = require("fs");

var lineReader = require('readline').createInterface({
    input: fs.createReadStream("input.txt")
});

lineReader.on('line', function (line) {
    line = line.trim();

    if (line.charAt(line.length-1) === ',') {
        line = line.substr(0, line.length-1);
    }

    if (line.charAt(0) === '{') {
        processRecord(JSON.parse(line));
    }
});

function processRecord(record) {
    // Process the records one at a time here! 
}

How do I run a program with commandline arguments using GDB within a Bash script?

You can run gdb with --args parameter,

gdb --args executablename arg1 arg2 arg3

If you want it to run automatically, place some commands in a file (e.g. 'run') and give it as argument: -x /tmp/cmds. Optionally you can run with -batch mode.

gdb -batch -x /tmp/cmds --args executablename arg1 arg2 arg3

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

Printing Even and Odd using two Threads in Java

I think the solutions being provided have unnecessarily added stuff and does not use semaphores to its full potential. Here's what my solution is.

package com.test.threads;

import java.util.concurrent.Semaphore;

public class EvenOddThreadTest {

    public static int MAX = 100;
    public static Integer number = new Integer(0);

    //Unlocked state
    public Semaphore semaphore = new Semaphore(1);
    class PrinterThread extends Thread {

        int start = 0;
        String name;

        PrinterThread(String name ,int start) {
            this.start = start;
            this.name = name;
        }

        @Override
        public void run() {
            try{
                while(start < MAX){
                    // try to acquire the number of semaphore equal to your value
                    // and if you do not get it then wait for it.
                semaphore.acquire(start);
                System.out.println(name + " : " + start);
                // prepare for the next iteration.
                start+=2;
                // release one less than what you need to print in the next iteration.
                // This will release the other thread which is waiting to print the next number.
                semaphore.release(start-1);
                }
            } catch(InterruptedException e){

            }
        }
    }

    public static void main(String args[]) {
        EvenOddThreadTest test = new EvenOddThreadTest();
        PrinterThread a = test.new PrinterThread("Even",1);
        PrinterThread b = test.new PrinterThread("Odd", 2);
        try {
            a.start();
            b.start();
        } catch (Exception e) {

        }
    }
}

How to pass in parameters when use resource service?

I think I see your problem, you need to use the @ syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?

This is what I can suggest based on what I see so far:

.factory('MagComments', function ($resource) {
    return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
      loginID : organEntity,
      password : organCommpassword,
      id : '@magId'
    });
  })

The @magId string will tell the resource to replace :id with the property magId on the object you pass it as parameters.

I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.

How do you check current view controller class in Swift?

You can easily iterate over your view controllers if you are using a navigation controller. And then you can check for the particular instance as:
Swift 5

 if let viewControllers = navigationController?.viewControllers {
            for viewController in viewControllers {
                if viewController.isKind(of: LoginViewController.self) {
                    
                }
            }
        }

Difference between Date(dateString) and new Date(dateString)

Correct ways to use Date : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Also, the following piece of code shows how, with a single definition of the function "Animal", it can be a) called directly and b) instantiated by treating it as a constructor function

function Animal(){
    this.abc = 1;
    return 1234; 
}

var x = new Animal();
var y = Animal();

console.log(x); //prints object containing property abc set to value 1
console.log(y); // prints 1234

SQL Query Where Field DOES NOT Contain $x

What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:

-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);

If you are searching a string, go for the LIKE operator (but this will be slow):

-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';

If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:

-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';

Calling a javascript function recursively

You can access the function itself using arguments.callee [MDN]:

if (counter>0) {
    arguments.callee(counter-1);
}

This will break in strict mode, however.

How do I get the last character of a string?

Simple solution is:

public String frontBack(String str) {
  if (str == null || str.length() == 0) {
    return str;
  }
  char[] cs = str.toCharArray();
  char first = cs[0];
  cs[0] = cs[cs.length -1];
  cs[cs.length -1] = first;
  return new String(cs);
}

Using a character array (watch out for the nasty empty String or null String argument!)

Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.

public String frontBack(String str) {
  if (str == null || str.length() == 0) {
    return str;
  }
  StringBuilder sb = new StringBuilder(str);  
  char first = sb.charAt(0);
  sb.setCharAt(0, sb.charAt(sb.length()-1));
  sb.setCharAt(sb.length()-1, first);
  return sb.toString();
}

Yet another approach (more for instruction than actual use) is this one:

public String frontBack(String str) {
  if (str == null || str.length() < 2) {
    return str;
  }
  StringBuilder sb = new StringBuilder(str);
  String sub = sb.substring(1, sb.length() -1);
  return sb.reverse().replace(1, sb.length() -1, sub).toString();
}

Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)

Checking out Git tag leads to "detached HEAD state"

Okay, first a few terms slightly oversimplified.

In git, a tag (like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.

Now a branch is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.

Your HEAD is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD will point to master which in turn will point to a commit. When you then do something like git checkout experimental, you switch the HEAD to point to the experimental branch which might point to a different commit.

Now the explanation.

When you do a git checkout v2.0, you are switching to a commit that is not pointed to by a branch. The HEAD is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.

Usually, what you can do is to say git checkout -b v2.0-fixes v2.0. This will create a new branch pointer at the commit pointed to by the treeish v2.0 (a tag in this case) and then shift your HEAD to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0 code. If however, you want to make any alterations there which you want to track, you'll need a branch.

You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.

Removing duplicates in the lists

Unfortunately. Most answers here either do not preserve the order or are too long. Here is a simple, order preserving answer.

s = [1,2,3,4,5,2,5,6,7,1,3,9,3,5]
x=[]

[x.append(i) for i in s if i not in x]
print(x)

This will give you x with duplicates removed but preserving the order.

How to move div vertically down using CSS

if div.title is a div then put this:

left: 0;
bottom: 0;

How to parse/format dates with LocalDateTime? (Java 8)

Both answers above explain very well the question regarding string patterns. However, just in case you are working with ISO 8601 there is no need to apply DateTimeFormatter since LocalDateTime is already prepared for it:

Convert LocalDateTime to Time Zone ISO8601 String

LocalDateTime ldt = LocalDateTime.now(); 
ZonedDateTime zdt = ldt.atZone(ZoneOffset.UTC); //you might use a different zone
String iso8601 = zdt.toString();

Convert from ISO8601 String back to a LocalDateTime

String iso8601 = "2016-02-14T18:32:04.150Z";
ZonedDateTime zdt = ZonedDateTime.parse(iso8601);
LocalDateTime ldt = zdt.toLocalDateTime();

How do I negate a condition in PowerShell?

if you don't like the double brackets or you don't want to write a function, you can just use a variable.

$path = Test-Path C:\Code
if (!$path) {
    write "it doesn't exist!"
}

Tomcat 7 is not running on browser(http://localhost:8080/ )

When you start tomcat independently and type http://localhost:8080/, tomcat show its default page (tomcat has its default page at TOMCAT_ROOT_DIRECTORY\webapps\ROOT\index.jsp).

When you start tomcat from eclipse, eclipse doesn't have any default page for url http://localhost:8080/ so it show error message. This doesn't mean that tomcat7 is not running.when you put your project specific url like http://localhost:8080/PROJECT_NAME_YOU_HAVE_CREATE_USING_ECLIPSE will display the default page of your web project.

How to send HTTP request in java?

You may use Socket for this like

String host = "www.yourhost.com";
Socket socket = new Socket(host, 80);
String request = "GET / HTTP/1.0\r\n\r\n";
OutputStream os = socket.getOutputStream();
os.write(request.getBytes());
os.flush();

InputStream is = socket.getInputStream();
int ch;
while( (ch=is.read())!= -1)
    System.out.print((char)ch);
socket.close();    

Facebook key hash does not match any stored key hashes

I got simular problem. After signing and publishing my app to the google PlayStore it seems the Hash has changed. I added the new Hash (as mentioned) in the Facebook messaged to the Key Hashes in my app on developers.facebook.com/app//settings. Now it works again.

Using UPDATE in stored procedure with optional parameters

   UPDATE tbl_ClientNotes
    SET 
      ordering=ISNULL@ordering,ordering), 
      title=isnull(@title,title), 
      content=isnull(@content,content)
    WHERE id=@id

I think I remember seeing before that if you are updating to the same value SQL Server will actually recognize this and won't do an unnecessary write.

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

There are a couple of commonly quoted solutions to this problem. Unfortunately neither of these are entirely satisfactory:

  • Install the unlimited strength policy files. While this is probably the right solution for your development workstation, it quickly becomes a major hassle (if not a roadblock) to have non-technical users install the files on every computer. There is no way to distribute the files with your program; they must be installed in the JRE directory (which may even be read-only due to permissions).
  • Skip the JCE API and use another cryptography library such as Bouncy Castle. This approach requires an extra 1MB library, which may be a significant burden depending on the application. It also feels silly to duplicate functionality included in the standard libraries. Obviously, the API is also completely different from the usual JCE interface. (BC does implement a JCE provider, but that doesn't help because the key strength restrictions are applied before handing over to the implementation.) This solution also won't let you use 256-bit TLS (SSL) cipher suites, because the standard TLS libraries call the JCE internally to determine any restrictions.

But then there's reflection. Is there anything you can't do using reflection?

private static void removeCryptographyRestrictions() {
    if (!isRestrictedCryptography()) {
        logger.fine("Cryptography restrictions removal not needed");
        return;
    }
    try {
        /*
         * Do the following, but with reflection to bypass access checks:
         *
         * JceSecurity.isRestricted = false;
         * JceSecurity.defaultPolicy.perms.clear();
         * JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
         */
        final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
        final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
        final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");

        final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
        isRestrictedField.setAccessible(true);
        final Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
        isRestrictedField.set(null, false);

        final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
        defaultPolicyField.setAccessible(true);
        final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);

        final Field perms = cryptoPermissions.getDeclaredField("perms");
        perms.setAccessible(true);
        ((Map<?, ?>) perms.get(defaultPolicy)).clear();

        final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
        instance.setAccessible(true);
        defaultPolicy.add((Permission) instance.get(null));

        logger.fine("Successfully removed cryptography restrictions");
    } catch (final Exception e) {
        logger.log(Level.WARNING, "Failed to remove cryptography restrictions", e);
    }
}

private static boolean isRestrictedCryptography() {
    // This matches Oracle Java 7 and 8, but not Java 9 or OpenJDK.
    final String name = System.getProperty("java.runtime.name");
    final String ver = System.getProperty("java.version");
    return name != null && name.equals("Java(TM) SE Runtime Environment")
            && ver != null && (ver.startsWith("1.7") || ver.startsWith("1.8"));
}

Simply call removeCryptographyRestrictions() from a static initializer or such before performing any cryptographic operations.

The JceSecurity.isRestricted = false part is all that is needed to use 256-bit ciphers directly; however, without the two other operations, Cipher.getMaxAllowedKeyLength() will still keep reporting 128, and 256-bit TLS cipher suites won't work.

This code works on Oracle Java 7 and 8, and automatically skips the process on Java 9 and OpenJDK where it's not needed. Being an ugly hack after all, it likely doesn't work on other vendors' VMs.

It also doesn't work on Oracle Java 6, because the private JCE classes are obfuscated there. The obfuscation does not change from version to version though, so it is still technically possible to support Java 6.

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

I have the same problem, the difference is I don't have access to the source code. I've fixed my problem by putting correct version of EntityFramework.SqlServer.dll in the bin directory of the application.

Press TAB and then ENTER key in Selenium WebDriver

In javascript (node.js) this works for me:

describe('UI', function() {

describe('gets results from Bing', function() {
    this.timeout(10000);

    it('makes a search', function(done) {
        var driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.chrome()).
        build();


        driver.get('http://bing.com');
        var input = driver.findElement(webdriver.By.name('q'));
        input.sendKeys('something');
        input.sendKeys(webdriver.Key.ENTER);

        driver.wait(function() {
            driver.findElement(webdriver.By.className('sb_count')).
                getText().
                then(function(result) {
                  console.log('result: ', result);
                  done();
            });
        }, 8000);


    });
  });
});

For tab use webdriver.Key.TAB

How can you tell when a layout has been drawn?

Simply check it by calling post method on your layout or view

 view.post( new Runnable() {
     @Override
     public void run() {
        // your layout is now drawn completely , use it here.
      }
});

How do I install boto?

  1. install pip: https://pip.pypa.io/en/latest/installing.html

  2. insatll boto: https://github.com/boto/boto

    $ git clone git://github.com/boto/boto.git
    $ cd boto
    $ python setup.py install

Spring Boot yaml configuration for a list of strings

Ahmet's answer provides on how to assign the comma separated values to String array.

To use the above configuration in different classes you might need to create getters/setters for this.. But if you would like to load this configuration once and keep using this as a bean with Autowired annotation, here is the how I accomplished:

In ConfigProvider.java

@Bean (name = "ignoreFileNames")
@ConfigurationProperties ( prefix = "ignore.filenames" )
public List<String> ignoreFileNames(){
    return new ArrayList<String>();
}

In outside classes:

@Autowired
@Qualifier("ignoreFileNames")
private List<String> ignoreFileNames;

you can use the same list everywhere else by autowiring.

How to identify object types in java

You want instanceof:

if (value instanceof Integer)

This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do

if (value.getClass() == Integer.class)

or

if (Integer.class.equals(value.getClass())

loading json data from local file into React JS

My JSON file name: terrifcalculatordata.json

[
    {
      "id": 1,
      "name": "Vigo",
      "picture": "./static/images/vigo.png",
      "charges": "PKR 100 per excess km"
    },
    {
      "id": 2,
      "name": "Mercedes",
      "picture": "./static/images/Marcedes.jpg",
      "charges": "PKR 200 per excess km"
    },
    {
        "id": 3,
        "name": "Lexus",
        "picture": "./static/images/Lexus.jpg",
        "charges": "PKR 150 per excess km"
      }
]

First , import on top:

import calculatorData from "../static/data/terrifcalculatordata.json";

then after return:

  <div>
  {
    calculatorData.map((calculatedata, index) => {
        return (
            <div key={index}>
                <img
                    src={calculatedata.picture}
                    class="d-block"
                    height="170"
                />
                <p>
                    {calculatedata.charges}
                </p>
            </div>
                  

Checking if a string is empty or null in Java

You can use Apache commons-lang

StringUtils.isEmpty(String str) - Checks if a String is empty ("") or null.

or

StringUtils.isBlank(String str) - Checks if a String is whitespace, empty ("") or null.

the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API

Reading an image file in C/C++

Try out the CImg library. The tutorial will help you get familiarized. Once you have a CImg object, the data() function will give you access to the 2D pixel buffer array.

Change remote repository credentials (authentication) on Intellij IDEA 14

  1. Go to [project]/.git directory.
  2. Open for edit 'config' file.
  3. In '[remote "origin"]' section find 'url' property and replace your old password with new one.
  4. Press Ctrl+T in Intellij IDEA to update project.

IIS7 Settings File Locations

Also check this answer from here: Cannot manually edit applicationhost.config

The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.

So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.

How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.

What is the fastest way to create a checksum for large files in C#

Ok - thanks to all of you - let me wrap this up:

  1. using a "native" exe to do the hashing took time from 6 Minutes to 10 Seconds which is huge.
  2. Increasing the buffer was even faster - 1.6GB file took 5.2 seconds using MD5 in .Net, so I will go with this solution - thanks again

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

Set title background color

This code helps to change the background of the title bar programmatically in Android. Change the color to any color you want.

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1c2833")));

}

How do I reference a local image in React?

Inside public folder create an assets folder and place image path accordingly.

<img className="img-fluid" 
     src={`${process.env.PUBLIC_URL}/assets/images/uc-white.png`} 
     alt="logo"/>

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

Try it this way, I just made some light changes:

MailMessage msg = new MailMessage();

msg.From = new MailAddress("[email protected]");
msg.To.Add("[email protected]");
msg.Subject = "test";
msg.Body = "Test Content";
//msg.Priority = MailPriority.High;


using (SmtpClient client = new SmtpClient())
{
    client.EnableSsl = true;
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential("[email protected]", "mypassword");
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;

    client.Send(msg);
}

Also please show your app.config file, if you have mail settings there.

How to achieve ripple animation using support library?

sometimes will b usable this line on any layout or components.

 android:background="?attr/selectableItemBackground"

Like as.

 <RelativeLayout
                android:id="@+id/relative_ticket_checkin"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="?attr/selectableItemBackground">

Including jars in classpath on commandline (javac or apt)

Try the following:

java -cp jar1:jar2:jar3:dir1:. HelloWorld

The default classpath (unless there is a CLASSPATH environment variable) is the current directory so if you redefine it, make sure you're adding the current directory (.) to the classpath as I have done.

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
(
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
    (
        oneChar := param[index];
        index := index - 1;
    );

    Left(param , index + 1);
)

jQuery find file extension (from string)

You can use a combination of substring and lastIndexOf

Sample

var fileName = "test.jpg";
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1); 

Matrix Transpose in Python

If you want to transpose a matrix like A = np.array([[1,2],[3,4]]), then you can simply use A.T, but for a vector like a = [1,2], a.T does not return a transpose! and you need to use a.reshape(-1, 1), as below

import numpy as np
a = np.array([1,2])
print('a.T not transposing Python!\n','a = ',a,'\n','a.T = ', a.T)
print('Transpose of vector a is: \n',a.reshape(-1, 1))

A = np.array([[1,2],[3,4]])
print('Transpose of matrix A is: \n',A.T)

Adding default parameter value with type hint in Python

I recently saw this one-liner:

def foo(name: str, opts: dict=None) -> str:
    opts = {} if not opts else opts
    pass

Using JavaMail with TLS

As a small note, it only started to work for me when I changed smtp to smtps in the examples above per samples from javamail (see smtpsend.java, https://github.com/javaee/javamail/releases/download/JAVAMAIL-1_6_2/javamail-samples.zip, option -S).

My resulting code is as follow:

Properties props=new Properties();
props.put("mail.smtps.starttls.enable","true");
// Use the following if you need SSL
props.put("mail.smtps.socketFactory.port", port);
props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtps.socketFactory.fallback", "false");
props.put("mail.smtps.host", serverList.get(randNum));
Session session = Session.getDefaultInstance(props);

smtpConnectionPool = new SmtpConnectionPool(
    SmtpConnectionFactories.newSmtpFactory(session));
    
final ClosableSmtpConnection transport = smtpConnectionPool.borrowObject();
...
transport.sendMessage(message, message.getAllRecipients());

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table

Delete everything in a MongoDB database

Use

[databaseName]
db.Drop+databaseName();

drop collection 

use databaseName 
db.collectionName.drop();

Retrieving Data from SQL Using pyodbc

import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
                  'Server=db-server;'
                  'Database=db;'
                  'Trusted_Connection=yes;')
sql = "SELECT * FROM [mytable] "
cursor.execute(sql)
for r in cursor:
    print(r)

Delete topic in Kafka 0.8.1.1

Add below line in ${kafka_home}/config/server.properties

delete.topic.enable=true

Restart the kafka server with new config:

${kafka_home}/bin/kafka-server-start.sh ~/kafka/config/server.properties

Delete the topics you wish to:

${kafka_home}/bin/kafka-topics.sh --delete  --zookeeper localhost:2181  --topic daemon12

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.

How to solve WAMP and Skype conflict on Windows 7?

Options>Advanced>connections

Uncheck the option :

Use port 80 and 443 as alternative....

What is the difference between a "function" and a "procedure"?

In the context of db: Stored procedure is precompiled execution plan where as functions are not.

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

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

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

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

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

I had the same problem on Mac OS Try to run sudo mongod and in a new terminal tab run mongo

How to install multiple python packages at once using pip

pip install -r requirements.txt

and in the requirements.txt file you put your modules in a list, with one item per line.

  • Django=1.3.1

  • South>=0.7

  • django-debug-toolbar

Why does the program give "illegal start of type" error?

You have a misplaced closing brace before the return statement.

Hadoop: «ERROR : JAVA_HOME is not set»

You can add in your .bashrc file:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

and it will dynamically change when you update your packages.

Find object by its property in array of objects with AngularJS way

The solucion that work for me is the following

$filter('filter')(data, {'id':10}) 

Difference between Hive internal tables and external tables?

An internal table data is stored in the warehouse folder, whereas an external table data is stored at the location you mentioned in table creation.

So when you delete an internal table, it deletes the schema as well as the data under the warehouse folder, but for an external table it's only the schema that you will loose.

So when you want an external table back you again after deleting it, can create a table with the same schema again and point it to the original data location. Hope it is clear now.

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

5 days ago from a particular date:

$date = new DateTime('2008-12-02');
$date->sub(new DateInterval('P5D'));
echo $date->format('Y-m-d') . "\n";

How do you get the footer to stay at the bottom of a Web page?

For me the nicest way of displaying it (the footer) is sticking to the bottom but not covering content all the time:

#my_footer {
    position: static
    fixed; bottom: 0
}

How to get screen dimensions as pixels in Android

One way is:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
int height = display.getHeight();

It is deprecated, and you should try the following code instead. The first two lines of code gives you the DisplayMetrics objecs. This objects contains the fields like heightPixels, widthPixels.

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
      
int height = metrics.heightPixels;
int width = metrics.widthPixels;

Api level 30 update

final WindowMetrics metrics = windowManager.getCurrentWindowMetrics();
 // Gets all excluding insets
 final WindowInsets windowInsets = metrics.getWindowInsets();
 Insets insets = windowInsets.getInsetsIgnoreVisibility(WindowInsets.Type.navigationBars()
         | WindowInsets.Type.displayCutout());

 int insetsWidth = insets.right + insets.left;
 int insetsHeight = insets.top + insets.bottom;

 // Legacy size that Display#getSize reports
 final Rect bounds = metrics.getBounds();
 final Size legacySize = new Size(bounds.width() - insetsWidth,
         bounds.height() - insetsHeight);

How do I select text nodes with jQuery?

If you can make the assumption that all children are either Element Nodes or Text Nodes, then this is one solution.

To get all child text nodes as a jquery collection:

$('selector').clone().children().remove().end().contents();

To get a copy of the original element with non-text children removed:

$('selector').clone().children().remove().end();

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

I checked the line 35 of xampp/apache/conf/httpd.conf and it was:

ServerRoot "/xampp/apache"

Which doesn't exist. ...

Create the directory, or change the path to the directory that contains your hypertext documents.

convert date string to mysql datetime field

$time = strtotime($oldtime);

Then use date() to put it into the correct format.

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

While writing this question, I discovered the answer. Installing a CA from Safari no longer automatically trusts it. I had to manually trust it from the Certificate Trust Settings panel (also mentioned in this question).

enter image description here

I debated canceling the question, but I thought it might be helpful to have some of the relevant code and log details someone might be looking for. Also, I never encountered the issue until iOS 11. I even went back and reconfirmed that it automatically works up through iOS 10.

I've never needed to touch that settings panel before, because any installed certificates were automatically trusted. Maybe it will change by the time iOS 11 ships, but I doubt it. Hopefully this helps save someone the time I wasted.

If anyone knows why this behaves differently for some people on different versions of iOS, I'd love to know in comments.

Update 1: Checking out the first iOS 12 beta, it looks like things remain the same. This question/answer/comments are still relevant on iOS 12.

Update 2: Same solution seems to be needed on iOS 13 beta builds as well.

how to prevent css inherit

Using the wildcard * selector in CSS to override inheritance for all attributes of an element (by setting these back to their initial state).

An example of its use:

li * {
   display: initial;
}

Getting a machine's external IP address with Python

Working with Python 2.7.6 and 2.7.13

import urllib2  
req = urllib2.Request('http://icanhazip.com', data=None)  
response = urllib2.urlopen(req, timeout=5)  
print(response.read())

Set value to an entire column of a pandas dataframe

You can use the assign function:

df = df.assign(industry='yyy')

Search for all occurrences of a string in a mysql database

I was looking for this myself when we changed domain on our Wordpress website. It can't be done without some programming so this is what I did.

<?php  
  header("Content-Type: text/plain");

  $host = "localhost";
  $username = "root";
  $password = "";
  $database = "mydatabase";
  $string_to_replace  = 'old.example.com';
  $new_string = 'new.example.com';

  // Connect to database server
  mysql_connect($host, $username, $password);

  // Select database
  mysql_select_db($database);

  // List all tables in database
  $sql = "SHOW TABLES FROM ".$database;
  $tables_result = mysql_query($sql);

  if (!$tables_result) {
    echo "Database error, could not list tables\nMySQL error: " . mysql_error();
    exit;
  }

  echo "In these fields '$string_to_replace' have been replaced with '$new_string'\n\n";
  while ($table = mysql_fetch_row($tables_result)) {
    echo "Table: {$table[0]}\n";
    $fields_result = mysql_query("SHOW COLUMNS FROM ".$table[0]);
    if (!$fields_result) {
      echo 'Could not run query: ' . mysql_error();
      exit;
    }
    if (mysql_num_rows($fields_result) > 0) {
      while ($field = mysql_fetch_assoc($fields_result)) {
        if (stripos($field['Type'], "VARCHAR") !== false || stripos($field['Type'], "TEXT") !== false) {
          echo "  ".$field['Field']."\n";
          $sql = "UPDATE ".$table[0]." SET ".$field['Field']." = replace(".$field['Field'].", '$string_to_replace', '$new_string')";
          mysql_query($sql);
        }
      }
      echo "\n";
    }
  }

  mysql_free_result($tables_result);  
?>

Hope it helps anyone who's stumbling into this problem in the future :)

Git submodule head 'reference is not a tree' error

Your branch may not be up to date, a simple solution but try git fetch

ldap query for group members

The query should be:

(&(objectCategory=user)(memberOf=CN=Distribution Groups,OU=Mybusiness,DC=mydomain.local,DC=com))

You missed & and ()

Exporting result of select statement to CSV format in DB2

This is how you can do it from DB2 client.

  1. Open the Command Editor and Run the select Query in the Commands Tab.

  2. Open the corresponding Query Results Tab

  3. Then from Menu --> Selected --> Export

How to get detailed list of connections to database in sql server 2005?

There is also who is active?:

Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids

Gson: How to exclude specific fields from Serialization without annotations

Another approach (especially useful if you need to make a decision to exclude a field at runtime) is to register a TypeAdapter with your gson instance. Example below:

Gson gson = new GsonBuilder()
.registerTypeAdapter(BloodPressurePost.class, new BloodPressurePostSerializer())

In the case below, the server would expect one of two values but since they were both ints then gson would serialize them both. My goal was to omit any value that is zero (or less) from the json that is posted to the server.

public class BloodPressurePostSerializer implements JsonSerializer<BloodPressurePost> {

    @Override
    public JsonElement serialize(BloodPressurePost src, Type typeOfSrc, JsonSerializationContext context) {
        final JsonObject jsonObject = new JsonObject();

        if (src.systolic > 0) {
            jsonObject.addProperty("systolic", src.systolic);
        }

        if (src.diastolic > 0) {
            jsonObject.addProperty("diastolic", src.diastolic);
        }

        jsonObject.addProperty("units", src.units);

        return jsonObject;
    }
}

Set default format of datetimepicker as dd-MM-yyyy

Ammending as "optional Answer". If you don't need to programmatically solve the problem, here goes the "visual way" in VS2012.

In Visual Studio, you can set custom format directly from the properties Panel: enter image description here

First Set the "Format" property to: "Custom"; Secondly, set your custom format to: "dd-MM-yyyy";

The difference in months between dates in MySQL

The DATEDIFF function can give you the number of days between two dates. Which is more accurate, since... how do you define a month? (28, 29, 30, or 31 days?)

Quickly reading very large tables as dataframes

Instead of the conventional read.table I feel fread is a faster function. Specifying additional attributes like select only the required columns, specifying colclasses and string as factors will reduce the time take to import the file.

data_frame <- fread("filename.csv",sep=",",header=FALSE,stringsAsFactors=FALSE,select=c(1,4,5,6,7),colClasses=c("as.numeric","as.character","as.numeric","as.Date","as.Factor"))

sorting a List of Map<String, String>

You need to create a comparator. I am not sure why each value needs its own map but here is what the comparator would look like:

class ListMapComparator implements Comparator {
    public int compare(Object obj1, Object obj2) {
         Map<String, String> test1 = (Map<String, String>) obj1;
         Map<String, String> test2 = (Map<String, String>) obj2;
         return test1.get("name").compareTo(test2.get("name"));
    }
}

You can see it working with your above example with this:

public class MapSort {
    public List<Map<String, String>> testMap() {
         List<Map<String, String>> list = new ArrayList<Map<String, String>>();
         Map<String, String> myMap1 = new HashMap<String, String>();
         myMap1.put("name", "Josh");
         Map<String, String> myMap2 = new HashMap<String, String>();
         myMap2.put("name", "Anna");

         Map<String, String> myMap3 = new HashMap<String, String>();
         myMap3.put("name", "Bernie");


         list.add(myMap1);
         list.add(myMap2);
         list.add(myMap3);

         return list;
    }

    public static void main(String[] args) {
         MapSort ms = new MapSort();
         List<Map<String, String>> testMap = ms.testMap();
         System.out.println("Before Sort: " + testMap);
         Collections.sort(testMap, new ListMapComparator());
         System.out.println("After Sort: " + testMap);
    }
}

You will have some type safe warnings because I did not worry about these. Hope that helps.

Where do I find the bashrc file on Mac?

The .bashrc file is in your home directory.

So from command line do:

cd
ls -a

This will show all the hidden files in your home directory. "cd" will get you home and ls -a will "list all".

In general when you see ~/ the tilda slash refers to your home directory. So ~/.bashrc is your home directory with the .bashrc file.

And the standard path to homebrew is in /usr/local/ so if you:

cd /usr/local
ls | grep -i homebrew

you should see the homebrew directory (/usr/local/homebrew). Source

Yes sometimes you may have to create this file and the typical format of a .bashrc file is:

# .bashrc

# User specific aliases and functions
. .alias
alias ducks='du -cks * | sort -rn | head -15'

# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

PATH=$PATH:/home/username/bin:/usr/local/homebrew
export PATH

If you create your own .bashrc file make sure that the following line is in your ~/.bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

How to bundle an Angular app for production

"Best" depends on the scenario. There are times when you only care about the smallest possible single bundle, but in large apps you may have to consider lazy loading. At some point it becomes impractical to serve the entire app as a single bundle.

In the latter case Webpack is generally the best way since it supports code splitting.

For a single bundle I would consider Rollup, or the Closure compiler if you are feeling brave :-)

I have created samples of all Angular bundlers I've ever used here: http://www.syntaxsuccess.com/viewarticle/angular-production-builds

The code can be found here: https://github.com/thelgevold/angular-2-samples

Angular version: 4.1.x

ojdbc14.jar vs. ojdbc6.jar

Actually, ojdbc14.jar doesn't really say anything about the real version of the driver (see JDBC Driver Downloads), except that it predates Oracle 11g. In such situation, you should provide the exact version.

Anyway, I think you'll find some explanation in What is going on with DATE and TIMESTAMP? In short, they changed the behavior in 9.2 drivers and then again in 11.1 drivers.

This might explain the differences you're experiencing (and I suggest using the most recent version i.e. the 11.2 drivers).

How to Populate a DataTable from a Stored Procedure

Use the SqlDataAdapter, this would simplify everything.

//Your code to this point
DataTable dt = new DataTable();

using(var cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
  using(var da = new SqlDataAdapter(cmd))
  {
      da.Fill(dt):
  }
}

and your DataTable will have the information you are looking for, so long as your stored proceedure returns a data set (cursor).

Setting up Eclipse with JRE Path

If you are using windows 8 or later:

  1. download and install the jdk or jre with all the default settings and options.
  2. Then download and install eclipse.

Everything should work fine. I don't know if it works exactly the same for other OS, but you don't have to set the PATH manually in Windows 8 or later.

modal View controllers - how to display and dismiss

This line:

[self dismissViewControllerAnimated:YES completion:nil];

isn't sending a message to itself, it's actually sending a message to its presenting VC, asking it to do the dismissing. When you present a VC, you create a relationship between the presenting VC and the presented one. So you should not destroy the presenting VC while it is presenting (the presented VC can't send that dismiss message back…). As you're not really taking account of it you are leaving the app in a confused state. See my answer Dismissing a Presented View Controller in which I recommend this method is more clearly written:

[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];

In your case, you need to ensure that all of the controlling is done in mainVC . You should use a delegate to send the correct message back to MainViewController from ViewController1, so that mainVC can dismiss VC1 and then present VC2.

In VC2 VC1 add a protocol in your .h file above the @interface:

@protocol ViewController1Protocol <NSObject>

    - (void)dismissAndPresentVC2;

@end

and lower down in the same file in the @interface section declare a property to hold the delegate pointer:

@property (nonatomic,weak) id <ViewController1Protocol> delegate;

In the VC1 .m file, the dismiss button method should call the delegate method

- (IBAction)buttonPressedFromVC1:(UIButton *)sender {
    [self.delegate dissmissAndPresentVC2]
}

Now in mainVC, set it as VC1's delegate when creating VC1:

- (IBAction)present1:(id)sender {
    ViewController1* vc = [[ViewController1 alloc] initWithNibName:@"ViewController1" bundle:nil];
    vc.delegate = self;
    [self present:vc];
}

and implement the delegate method:

- (void)dismissAndPresent2 {
    [self dismissViewControllerAnimated:NO completion:^{
        [self present2:nil];
    }];
}

present2: can be the same method as your VC2Pressed: button IBAction method. Note that it is called from the completion block to ensure that VC2 is not presented until VC1 is fully dismissed.

You are now moving from VC1->VCMain->VC2 so you will probably want only one of the transitions to be animated.

update

In your comments you express surprise at the complexity required to achieve a seemingly simple thing. I assure you, this delegation pattern is so central to much of Objective-C and Cocoa, and this example is about the most simple you can get, that you really should make the effort to get comfortable with it.

In Apple's View Controller Programming Guide they have this to say:

Dismissing a Presented View Controller

When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it. Although there are several techniques for notifying the presenting view controller that its presented view controller should be dismissed, the preferred technique is delegation. For more information, see “Using Delegation to Communicate with Other Controllers.”

If you really think through what you want to achieve, and how you are going about it, you will realise that messaging your MainViewController to do all of the work is the only logical way out given that you don't want to use a NavigationController. If you do use a NavController, in effect you are 'delegating', even if not explicitly, to the navController to do all of the work. There needs to be some object that keeps a central track of what's going on with your VC navigation, and you need some method of communicating with it, whatever you do.

In practice Apple's advice is a little extreme... in normal cases, you don't need to make a dedicated delegate and method, you can rely on [self presentingViewController] dismissViewControllerAnimated: - it's when in cases like yours that you want your dismissing to have other effects on remote objects that you need to take care.

Here is something you could imagine to work without all the delegate hassle...

- (IBAction)dismiss:(id)sender {
    [[self presentingViewController] dismissViewControllerAnimated:YES 
                                                        completion:^{
        [self.presentingViewController performSelector:@selector(presentVC2:) 
                                            withObject:nil];
    }];

}

After asking the presenting controller to dismiss us, we have a completion block which calls a method in the presentingViewController to invoke VC2. No delegate needed. (A big selling point of blocks is that they reduce the need for delegates in these circumstances). However in this case there are a few things getting in the way...

  • in VC1 you don't know that mainVC implements the method present2 - you can end up with difficult-to-debug errors or crashes. Delegates help you to avoid this.
  • once VC1 is dismissed, it's not really around to execute the completion block... or is it? Does self.presentingViewController mean anything any more? You don't know (neither do I)... with a delegate, you don't have this uncertainty.
  • When I try to run this method, it just hangs with no warning or errors.

So please... take the time to learn delegation!

update2

In your comment you have managed to make it work by using this in VC2's dismiss button handler:

 [self.view.window.rootViewController dismissViewControllerAnimated:YES completion:nil]; 

This is certainly much simpler, but it leaves you with a number of issues.

Tight coupling
You are hard-wiring your viewController structure together. For example, if you were to insert a new viewController before mainVC, your required behaviour would break (you would navigate to the prior one). In VC1 you have also had to #import VC2. Therefore you have quite a lot of inter-dependencies, which breaks OOP/MVC objectives.

Using delegates, neither VC1 nor VC2 need to know anything about mainVC or it's antecedents so we keep everything loosely-coupled and modular.

Memory
VC1 has not gone away, you still hold two pointers to it:

  • mainVC's presentedViewController property
  • VC2's presentingViewController property

You can test this by logging, and also just by doing this from VC2

[self dismissViewControllerAnimated:YES completion:nil]; 

It still works, still gets you back to VC1.

That seems to me like a memory leak.

The clue to this is in the warning you are getting here:

[self presentViewController:vc2 animated:YES completion:nil];
[self dismissViewControllerAnimated:YES completion:nil];
 // Attempt to dismiss from view controller <VC1: 0x715e460>
 // while a presentation or dismiss is in progress!

The logic breaks down, as you are attempting to dismiss the presenting VC of which VC2 is the presented VC. The second message doesn't really get executed - well perhaps some stuff happens, but you are still left with two pointers to an object you thought you had got rid of. (edit - I've checked this and it's not so bad, both objects do go away when you get back to mainVC)

That's a rather long-winded way of saying - please, use delegates. If it helps, I made another brief description of the pattern here:
Is passing a controller in a construtor always a bad practice?

update 3
If you really want to avoid delegates, this could be the best way out:

In VC1:

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

But don't dismiss anything... as we ascertained, it doesn't really happen anyway.

In VC2:

[self.presentingViewController.presentingViewController 
    dismissViewControllerAnimated:YES
                       completion:nil];

As we (know) we haven't dismissed VC1, we can reach back through VC1 to MainVC. MainVC dismisses VC1. Because VC1 has gone, it's presented VC2 goes with it, so you are back at MainVC in a clean state.

It's still highly coupled, as VC1 needs to know about VC2, and VC2 needs to know that it was arrived at via MainVC->VC1, but it's the best you're going to get without a bit of explicit delegation.

Notepad++ Multi editing

Notepad++ also handles multiple cursors now.

Go into Settings => Preferences => Editing and check "Enable" in "Multi editing settings" Then, just use Ctrl+click to use multiple cursors.

Feature demo on official website here : https://npp-user-manual.org/docs/editing/

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

Create a new txt file using VB.NET

open C:\myfile.txt for append as #1
write #1, text1.text, text2.text
close()

This is the code I use in Visual Basic 6.0. It helps me to create a txt file on my drive, write two pieces of data into it, and then close the file... Give it a try...

JavaScript OR (||) variable assignment explanation

Its called Short circuit operator.

Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.

It could also be used to set a default value for function argument.`

function theSameOldFoo(name){ 
  name = name || 'Bar' ;
  console.log("My best friend's name is " + name);
}
theSameOldFoo();  // My best friend's name is Bar
theSameOldFoo('Bhaskar');  // My best friend's name is Bhaskar`

redirect COPY of stdout to log file from within bash script itself

Using the accepted answer my script kept returning exceptionally early (right after 'exec > >(tee ...)') leaving the rest of my script running in the background. As I couldn't get that solution to work my way I found another solution/work around to the problem:

# Logging setup
logfile=mylogfile
mkfifo ${logfile}.pipe
tee < ${logfile}.pipe $logfile &
exec &> ${logfile}.pipe
rm ${logfile}.pipe

# Rest of my script

This makes output from script go from the process, through the pipe into the sub background process of 'tee' that logs everything to disc and to original stdout of the script.

Note that 'exec &>' redirects both stdout and stderr, we could redirect them separately if we like, or change to 'exec >' if we just want stdout.

Even thou the pipe is removed from the file system in the beginning of the script it will continue to function until the processes finishes. We just can't reference it using the file name after the rm-line.

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

First, your success() handler just returns the data, but that's not returned to the caller of getData() since it's already in a callback. $http is an asynchronous call that returns a $promise, so you have to register a callback for when the data is available.

I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.

For simplicity, here's your same code re-written with a function callback provided by the calling controller:

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function(callbackFunc) {
        $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
        }).success(function(data){
            // With the data succesfully returned, call our callback
            callbackFunc(data);
        }).error(function(){
            alert("error");
        });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Now, $http actually already returns a $promise, so this can be re-written:

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function() {
        // $http() returns a $promise that we can add handlers with .then()
        return $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
         });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Finally, there's better ways to configure the $http service to handle the headers for you using config() to setup the $httpProvider. Checkout the $http documentation for examples.

What is the default access specifier in Java?

Update Java 8 usage of default keyword: As many others have noted The default visibility (no keyword)

the field will be accessible from inside the same package to which the class belongs.

Not to be confused with the new Java 8 feature (Default Methods) that allows an interface to provide an implementation when its labeled with the default keyword.

See: Access modifiers

PHP preg_match - only allow alphanumeric strings and - _ characters

Why to use regex? PHP has some built in functionality to do that

<?php
    $valid_symbols = array('-', '_');
    $string1 = "This is a string*";
    $string2 = "this_is-a-string";

    if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
        echo "String 1 not acceptable acceptable";
    }
?>

preg_match('/\s/',$username) will check for blank space

!ctype_alnum(str_replace($valid_symbols, '', $string1)) will check for valid_symbols

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

Extending from the correct answer of Andrey-Egorov using .executeScript() to conclude my own question example:

inputField = driver.findElement(webdriver.By.id('gbqfq'));
driver.executeScript("arguments[0].setAttribute('value', '" + longstring +"')", inputField);

How can I create an editable combo box in HTML/Javascript?

Forget datalist element that good solution for autocomplete function, but not for combobox feature.

css:

.combobox {
    display: inline-block;
    position: relative;
}

.combobox select {
    display: none;
    position: absolute;
    overflow-y: auto;
}

html:

<div class="combobox">
    <input type="number" name="" value="" min="" max="" step=""/><br/>
    <select size="3">
        <option value="0"> 0</option>
        <option value="25"> 25</option>
        <option value="40"> 40</option>
    </select>
</div>

js (jQuery):

$('.combobox').each(function() {
    var
        $input = $(this).find('input'),
        $select = $(this).find('select');
    function hideSelect() {
        setTimeout(function() {
            if (!$select.is(':focus') && !$input.is(':focus')) {
                $select
                    .hide()
                    .css('z-index', 1);
            }
        }, 20);
    }
    $input
        .focusin(function() {
            if (!$select.is(':visible')) {
                $select
                    .outerWidth($input.outerWidth())
                    .show()
                    .css('z-index', 100);
            }
        })
        .focusout(hideSelect)
        .on('input', function() {
            $select.val('');
        });
    $select
        .change(function() {
            $input.val($select.val());
        })
        .focusout(hideSelect);
});

This works properly even when you use text input instead of number.

Marker content (infoWindow) Google Maps

Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:

Each marker gets an "infowindow" entry :

function createMarker(lat, lon, html) {
    var newmarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        map: map,
        title: html
    });

    newmarker['infowindow'] = new google.maps.InfoWindow({
            content: html
        });

    google.maps.event.addListener(newmarker, 'mouseover', function() {
        this['infowindow'].open(map, this);
    });
}

How to bind RadioButtons to an enum?

You could use a more generic converter

public class EnumBooleanConverter : IValueConverter
{
  #region IValueConverter Members
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string parameterString = parameter as string;
    if (parameterString == null)
      return DependencyProperty.UnsetValue;

    if (Enum.IsDefined(value.GetType(), value) == false)
      return DependencyProperty.UnsetValue;

    object parameterValue = Enum.Parse(value.GetType(), parameterString);

    return parameterValue.Equals(value);
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string parameterString = parameter as string;
    if (parameterString == null)
        return DependencyProperty.UnsetValue;

    return Enum.Parse(targetType, parameterString);
  }
  #endregion
}

And in the XAML-Part you use:

<Grid>
    <Grid.Resources>
      <l:EnumBooleanConverter x:Key="enumBooleanConverter" />
    </Grid.Resources>
    <StackPanel >
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FirstSelection}">first selection</RadioButton>
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=TheOtherSelection}">the other selection</RadioButton>
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=YetAnotherOne}">yet another one</RadioButton>
    </StackPanel>
</Grid>

How to cancel/abort jQuery AJAX request?

The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.

The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.

The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.

$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

How can I format a decimal to always show 2 decimal places?

.format is a more readable way to handle variable formatting:

'{:.{prec}f}'.format(26.034, prec=2)

SQL Server - How to lock a table until a stored procedure finishes

BEGIN TRANSACTION

select top 1 *
from table1
with (tablock, holdlock)

-- You do lots of things here

COMMIT

This will hold the 'table lock' until the end of your current "transaction".

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

You can go here to download the Java JRE.

You can go here to download the Java JDK.

After that you need to set up your environmental variables in Windows:

  1. Right-click My Computer
  2. Click Properties
  3. Go to Advanced System Settings
  4. Click on the Advanced tab
  5. Click on Environment Variables

EDIT: See screenshot for environmental variables

enter image description here

Maven: best way of linking custom external JAR to my project?

I think you should use mvn install:install-file to populate your local repository with the library jars then you should change the scope from system to compile.

If you are starting with maven I suggest to use maven directly not IDE plugins as it adds an extra layer of complexity.

As for the error, do you put the required jars on your classpath? If you are using types from the library, you need to have access to it in the runtime as well. This has nothing to do with maven itself.

I don't understand why you want to put the library to source control - it is for sources code not binary jars.

How to update each dependency in package.json to the latest version?

If you want to use a gentle approach via a beautiful (for terminal) interactive reporting interface I would suggest using npm-check.

It's less of a hammer and gives you more consequential knowledge of, and control over, your dependency updates.

To give you a taste of what awaits here's a screenshot (scraped from the git page for npm-check):

enter image description here

Angular 2 Routing run in new tab

This directive works as a [routerLink] replacement. All you have to do is to replace your [routerLink] usages with [link]. It works with ctrl+click, cmd+click, middle click.

import {Directive, HostListener, Input} from '@angular/core'
import {Router} from '@angular/router'
import _ from 'lodash'
import qs from 'qs'

@Directive({
  selector: '[link]'
})
export class LinkDirective {
  @Input() link: string

  @HostListener('click', ['$event'])
  onClick($event) {
    // ctrl+click, cmd+click
    if ($event.ctrlKey || $event.metaKey) {
      $event.preventDefault()
      $event.stopPropagation()
      window.open(this.getUrl(this.link), '_blank')
    } else {
      this.router.navigate(this.getLink(this.link))
    }
  }

  @HostListener('mouseup', ['$event'])
  onMouseUp($event) {
    // middleclick
    if ($event.which == 2) {

      $event.preventDefault()
      $event.stopPropagation()
      window.open(this.getUrl(this.link), '_blank')
    }
  }

  constructor(private router: Router) {}

  private getLink(link): any[] {
    if ( ! _.isArray(link)) {
      link = [link]
    }

    return link
  }

  private getUrl(link): string {
    let url = ''

    if (_.isArray(link)) {
      url = link[0]

      if (link[1]) {
        url += '?' + qs.stringify(link[1])
      }
    } else {
      url = link
    }

    return url
  }
}

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

In here:

    if (ValidationUtils.isNullOrEmpty(lastName)) {
        registrationErrors.add(ValidationErrors.LAST_NAME);
    }
    if (!ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do

    if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.

Tesseract OCR simple example

Ok. I found the solution here tessnet2 fails to load the Ans given by Adam

Apparently i was using wrong version of tessdata. I was following the the source page instruction intuitively and that caused the problem.

it says

Quick Tessnet2 usage

  1. Download binary here, add a reference of the assembly Tessnet2.dll to your .NET project.

  2. Download language data definition file here and put it in tessdata directory. Tessdata directory and your exe must be in the same directory.

After you download the binary, when you follow the link to download the language file, there are many language files. but none of them are right version. you need to select all version and go to next page for correct version (tesseract-2.00.eng)! They should either update download binary link to version 3 or put the the version 2 language file on the first page. Or at least bold mention the fact that this version issue is a big deal!

Anyway I found it. Thanks everyone.

Stop jQuery .load response from being cached

/**
 * Use this function as jQuery "load" to disable request caching in IE
 * Example: $('selector').loadWithoutCache('url', function(){ //success function callback... });
 **/
$.fn.loadWithoutCache = function (){
 var elem = $(this);
 var func = arguments[1];
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
     success: function(data, textStatus, XMLHttpRequest) {
   elem.html(data);
   if(func != undefined){
    func(data, textStatus, XMLHttpRequest);
   }
     }
 });
 return elem;
}

Center align "span" text inside a div

You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.

You could give the span a set width, then add the margin:0 auto again. This would center-align it.

.left 
{
   background-color: #999999;
   height: 50px;
   width: 24.5%;
}
span.panelTitleTxt 
{
   display:block;
   width:100px;
   height: 100%;
   margin: 0 auto;
}

How to set up java logging using a properties file? (java.util.logging)

Are you searching for the log file in the right path: %h/one%u.log

Here %h resolves to your home : In windows this defaults to : C:\Documents and Settings(user_name).

I have tried the sample code you have posted and it works fine after you specify the configuration file path (logging.properties either through code or java args) .

set background color: Android

By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:

android:background="#fff"

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

I solved it this way:

First, I stopped all running containers:

docker-compose down

Then I executed a lsof command to find the process using the port (for me it was port 9000)

sudo lsof -i -P -n | grep 9000

Finally, I "killed" the process (in my case, it was a VSCode extension):

kill -9 <process id>

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

VBScript How can I Format Date?

For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.

Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)

Which will result in 11-22-2019 (depending on the current date)

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I fixed this using pycharm. At the bottom of pycharm you can see file encoding. I noticed that it is UT-8. I changed it to US-ASCII pycharm encoding depiction

Declare and assign multiple string variables at the same time

Just a reminder: Implicit type var in multiple declaration is not allowed. There might be the following compilation errors.

var Foo = 0, Bar = 0;

Implicitly-typed variables cannot have multiple declarators

Similarly,

var Foo, Bar;

Implicitly-typed variables must be initialized

How do I call a dynamically-named method in Javascript?

Try with this:

var fn_name = "Colours",
fn = eval("populate_"+fn_name);
fn(args1,argsN);

NGinx Default public www location?

On Mac install nginx with brew:

/usr/local/etc/nginx/nginx.conf

location / { 
    root   html;  # **means /usr/local/Cellar/nginx/1.8.0/html and it soft linked to /usr/local/var/www**
    index  index.html;
}  

How do I shrink my SQL Server Database?

This may seem bizarre, but it's worked for me and I have written a C# program to automate this.

Step 1: Truncate the transaction log (Back up only the transaction log, turning on the option to remove inactive transactions)

Step 2: Run a database shrink, moving all the pages to the start of the files

Step 3: Truncate the transaction log again, as step 2 adds log entries

Step 4: Run a database shrink again.

My stripped down code, which uses the SQL DMO library, is as follows:

SQLDatabase.TransactionLog.Truncate();
SQLDatabase.Shrink(5, SQLDMO.SQLDMO_SHRINK_TYPE.SQLDMOShrink_NoTruncate);
SQLDatabase.TransactionLog.Truncate();
SQLDatabase.Shrink(5, SQLDMO.SQLDMO_SHRINK_TYPE.SQLDMOShrink_Default);

Html.RenderPartial() syntax with Razor

  • RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by { }.

  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

Error creating bean with name

It looks like your Spring component scan Base is missing UserServiceImpl

<context:component-scan base-package="org.assessme.com.controller." />

What's the difference between console.dir and console.log?

Following Felix Klings advice I tried it out in my chrome browser.

console.dir([1,2]) gives the following output:

Array[2]
 0: 1
 1: 2
 length: 2
 __proto__: Array[0]

While console.log([1,2]) gives the following output:

[1, 2]

So I believe console.dir() should be used to get more information like prototype etc in arrays and objects.

Setting timezone to UTC (0) in PHP

The problem is that you're displaying time(), which is a UNIX timestamp based on GMT/UTC. That’s why it doesn’t change. date() on the other hand, formats the time based on that timestamp.

A timestamp is the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

echo date('Y-m-d H:i:s T', time()) . "<br>\n";
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s T', time()) . "<br>\n";

Google.com and clients1.google.com/generate_204

The generate 204 might be dynamically loading the suggestions of search criteria. AS i can see from my load test script, this is seemingly responsible for every server call each time the user types into the text box

MongoDB via Mongoose JS - What is findByID?

findById is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.

Example:

// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );

Functionally, it's the same as calling:

UserModel.findOne({_id: id}, function (err, user) { ... });

Note that Mongoose will cast the provided id value to the type of _id as defined in the schema (defaulting to ObjectId).

How to check python anaconda version installed on Windows 10 PC?

If you want to check the python version in a particular cond environment you can also use conda list python

How to scroll to top of the page in AngularJS?

You can use

$window.scrollTo(x, y);

where x is the pixel along the horizontal axis and y is the pixel along the vertical axis.

  1. Scroll to top

    $window.scrollTo(0, 0);
    
  2. Focus on element

    $window.scrollTo(0, angular.element('put here your element').offsetTop);   
    

Example

Update:

Also you can use $anchorScroll

Example

Decompile an APK, modify it and then recompile it

dex2jar with jd-gui will give all the java source files but they are not exactly the same. They are almost equivalent .class files (not 100%). So if you want to change the code for an apk file:

  • decompile using apktool

  • apktool will generate smali(Assembly version of dex) file for every java file with same name.

  • smali is human understandable, make changes in the relevant file, recompile using same apktool(apktool b Nw.apk <Folder Containing Modified Files>)

What is wrong with my SQL here? #1089 - Incorrect prefix key

If you are using a GUI and you are still getting the same problem. Just leave the size value empty, the primary key defaults the value to 11, you should be fine with this. Worked with Bitnami phpmyadmin.

Windows ignores JAVA_HOME: how to set JDK as default?

In Windows 8, you may want to remove C:\ProgramData\Oracle\Java\javapath directory.

from path

It solved my issue.

How to comment/uncomment in HTML code

My view templates are generally .php files. This is what I would be using for now.

<?php // Some comment here ?>

The solution is quite similar to what @Robert suggested, works for me. Is not very clean I guess.

How can I throw CHECKED exceptions from inside Java 8 streams?

Just use any one of NoException (my project), jOO?'s Unchecked, throwing-lambdas, Throwable interfaces, or Faux Pas.

// NoException
stream.map(Exceptions.sneak().function(Class::forName));

// jOO?
stream.map(Unchecked.function(Class::forName));

// throwing-lambdas
stream.map(Throwing.function(Class::forName).sneakyThrow());

// Throwable interfaces
stream.map(FunctionWithThrowable.aFunctionThatUnsafelyThrowsUnchecked(Class::forName));

// Faux Pas
stream.map(FauxPas.throwingFunction(Class::forName));

Convert double/float to string

Go and look at the printf() implementation with "%f" in some C library.

Streaming video from Android camera to server

Mux (my company) has an open source android app that streams RTMP to a server, including setting up the camera and user interactions. It's built to stream to Mux's live streaming API but can easily stream to any RTMP entrypoint.

ClassCastException, casting Integer to Double

specify your marks:

List<Double> marks = new ArrayList<Double>();

This is called generics.

Xcode Error: "The app ID cannot be registered to your development team."

Changing Bundle Identifier worked for me.

  1. Go to Signing & Capabilities tab
  2. Change my Bundle Identifier. "MyApp" > "MyCompanyName.MyApp"
  3. Enter and wait a seconds for generating Signing Certificate

If it still doesn't work, try again with these steps before:

  1. Remove your Provisioning Profiles: cd /Users/my_username/Library/MobileDevice/Provisioning Profiles && rm * (in my case)
  2. Clearn your project
  3. ...

Fastest way to determine if an integer's square root is an integer

I'm not sure if it would be faster, or even accurate, but you could use John Carmack's Magical Square Root, algorithm to solve the square root faster. You could probably easily test this for all possible 32 bit integers, and validate that you actually got correct results, as it's only an appoximation. However, now that I think about it, using doubles is approximating also, so I'm not sure how that would come into play.

How do I import a namespace in Razor View Page?

You can try this

@using MyNamespace

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

Regular expression for first and last name

This regex work for me (was using in Angular 8) :

([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){2,30}

enter image description here

It will be invalid if there is:-

  1. Any whitespace start or end of the name
  2. Got symbols e.g. @
  3. Less than 2 or more than 30

Example invalid First Name (whitespace)

enter image description here

Example valid First Name :

enter image description here

Telegram Bot - how to get a group chat id?

You can retrieve the group ID the same way. It appears in the message body as message.chat.id and it's usually a negative number, where normal chats are positive.

Group IDs and Chat IDs can only be retrieved from a received message, there are no calls available to retrieve active groups etc. You have to remember the group ID when you receive the message and store it in cache or something similar.

Replacing Numpy elements if condition is met

The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):

import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)

which will produce:

a: [[1 4 0 1]
 [1 3 2 4]
 [1 0 2 1]
 [3 1 0 0]
 [1 4 0 1]]

b: [[0 1 0 0]
 [0 1 0 1]
 [0 0 0 0]
 [1 0 0 0]
 [0 1 0 0]]

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

The case is like :

 mysql connects will localhost when network is not up.
 mysql cannot connect when network is up.

You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):

  1. Disconnect the network.
  2. Stop mysql service (if windows, try from services.msc window)
  3. Connect to network.
  4. Try to start the mysql and see if it starts correctly.
  5. Check for system logs anyways to be sure that there is no error in starting mysql service.
  6. If all goes well try connecting.
  7. If fails, try to do a telnet localhost 3306 and see what output it shows.
  8. Try changing the port on which mysql is hosted, default 3306, you can change to some other port which is ununsed.

This should ideally resolve the issue you are facing.

Spring Boot application as a Service

You could also use supervisord which is a very handy daemon, which can be used to easily control services. These services are defined by simple configuration files defining what to execute with which user in which directory and so forth, there are a zillion options. supervisord has a very simple syntax, so it makes a very good alternative to writing SysV init scripts.

Here a simple supervisord configuration file for the program you are trying to run/control. (put this into /etc/supervisor/conf.d/yourapp.conf)

/etc/supervisor/conf.d/yourapp.conf

[program:yourapp]
command=/usr/bin/java -jar /path/to/application.jar
user=usertorun
autostart=true
autorestart=true
startsecs=10
startretries=3
stdout_logfile=/var/log/yourapp-stdout.log
stderr_logfile=/var/log/yourapp-stderr.log

To control the application you would need to execute supervisorctl, which will present you with a prompt where you could start, stop, status yourapp.

CLI

# sudo supervisorctl
yourapp             RUNNING   pid 123123, uptime 1 day, 15:00:00
supervisor> stop yourapp
supervisor> start yourapp

If the supervisord daemon is already running and you've added the configuration for your serivce without restarting the daemon you can simply do a reread and update command in the supervisorctl shell.

This really gives you all the flexibilites you would have using SysV Init scripts, but easy to use and control. Take a look at the documentation.

Check if xdebug is working

Try as following, should return "exists" or "non exists":

<?php
echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';

How to loop through all but the last item of a list?

To compare each item with the next one in an iterator without instantiating a list:

import itertools
it = (x for x in range(10))
data1, data2 = itertools.tee(it)
data2.next()
for a, b in itertools.izip(data1, data2):
  print a, b

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

Laravel 5 PDOException Could Not Find Driver

You should install PDO on your server. Edit your php.ini (look at your phpinfo(), "Loaded Configuration File" line, to find the php.ini file path). Find and uncomment the following line (remove the ; character):

;extension=pdo_mysql.so

Then, restart your Apache server. For more information, please read the documentation.

Using a remote repository with non-standard port

SSH doesn't use the : syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config file and add:

Host git.host.de
  Port 4019

Then specify just git.host.de without a port number.

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

Simplest way to display current month and year like "Aug 2016" in PHP?

Full version:

<? echo date('F Y'); ?>

Short version:

<? echo date('M Y'); ?>

Here is a good reference for the different date options.

update

To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp parameter for the date() function. Like this:

echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));

This will also work (it's typically used to get the last day of the previous month):

echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));

Hope that helps.

PHP - regex to allow letters and numbers only

  • Missing end anchor $
  • Missing multiplier
  • Missing end delimiter

So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.

/^[a-z0-9]+$/i

How to submit http form using C#

I needed to have a button handler that created a form post to another application within the client's browser. I landed on this question but didn't see an answer that suited my scenario. This is what I came up with:

      protected void Button1_Click(object sender, EventArgs e)
        {

            var formPostText = @"<html><body><div>
<form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
  <input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" /> 
  <input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" /> 
</form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
";
            Response.Write(formPostText);
        }

Contain an image within a div?

Use max width and max height. It will keep the aspect ratio

#container img 
{
 max-width: 250px;
 max-height: 250px;
}

http://jsfiddle.net/rV77g/

How to input matrix (2D list) in Python?

If the input is formatted like this,

1 2 3
4 5 6
7 8 9

a one liner can be used

mat = [list(map(int,input().split())) for i in range(row)]

How to run test methods in specific order in JUnit4?

JUnit since 5.5 allows @TestMethodOrder(OrderAnnotation.class) on class and @Order(1) on test-methods.

JUnit old versions allow test methods run ordering using class annotations:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@FixMethodOrder(MethodSorters.JVM)
@FixMethodOrder(MethodSorters.DEFAULT)

By default test methods are run in alphabetical order. So, to set specific methods order you can name them like:

a_TestWorkUnit_WithCertainState_ShouldDoSomething b_TestWorkUnit_WithCertainState_ShouldDoSomething c_TestWorkUnit_WithCertainState_ShouldDoSomething

Or

_1_TestWorkUnit_WithCertainState_ShouldDoSomething _2_TestWorkUnit_WithCertainState_ShouldDoSomething _3_TestWorkUnit_WithCertainState_ShouldDoSomething

You can find examples here.

Getting Textbox value in Javascript

This is because ASP.NET it changing the Id of your textbox, if you run your page, and do a view source, you will see the text box id is something like

ctl00_ContentColumn_txt_model_code

There are a few ways round this:

Use the actual control name:

var TestVar = document.getElementById('ctl00_ContentColumn_txt_model_code').value;

use the ClientID property within ASP script tags

document.getElementById('<%= txt_model_code.ClientID %>').value;

Or if you are running .NET 4 you can use the new ClientIdMode property, see this link for more details.

http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx1

Is there a simple way to use button to navigate page as a link does in angularjs

Your ngClick is correct; you just need the right service. $location is what you're looking for. Check out the docs for the full details, but the solution to your specific question is this:

$location.path( '/new-page.html' );

The $location service will add the hash (#) if it's appropriate based on your current settings and ensure no page reload occurs.

You could also do something more flexible with a directive if you so chose:

.directive( 'goClick', function ( $location ) {
  return function ( scope, element, attrs ) {
    var path;

    attrs.$observe( 'goClick', function (val) {
      path = val;
    });

    element.bind( 'click', function () {
      scope.$apply( function () {
        $location.path( path );
      });
    });
  };
});

And then you could use it on anything:

<button go-click="/go/to/this">Click!</button>

There are many ways to improve this directive; it's merely to show what could be done. Here's a Plunker demonstrating it in action: http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=preview.

Using Regular Expressions to Extract a Value in Java

This function collect all matching sequences from string. In this example it takes all email addresses from string.

static final String EMAIL_PATTERN = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";

public List<String> getAllEmails(String message) {      
    List<String> result = null;
    Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);

    if (matcher.find()) {
        result = new ArrayList<String>();
        result.add(matcher.group());

        while (matcher.find()) {
            result.add(matcher.group());
        }
    }

    return result;
}

For message = "[email protected], <[email protected]>>>> [email protected]" it will create List of 3 elements.

How to change an application icon programmatically in Android?

Applying the suggestions mentioned, I've faced the issue of app getting killed whenever default icon gets changed to new icon. So have implemented the code with some tweaks. Step 1). In file AndroidManifest.xml, create for default activity with android:enabled="true" & other alias with android:enabled="false". Your will not contain but append those in with android:enabled="true".

       <activity
        android:name=".activities.SplashActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/SplashTheme">

    </activity>
    <!-- <activity-alias used to change app icon dynamically>   : default icon, set enabled true    -->
    <activity-alias
        android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:name=".SplashActivityAlias1" <!--put any random name started with dot-->
        android:enabled="true"
        android:targetActivity=".activities.SplashActivity"> <!--target activity class path will be same for all alias-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity-alias>
    <!-- <activity-alias used to change app icon dynamically>  : sale icon, set enabled false initially -->
    <activity-alias
        android:label="@string/app_name"
        android:icon="@drawable/ic_store_marker"
        android:roundIcon="@drawable/ic_store_marker"
        android:name=".SplashActivityAlias" <!--put any random name started with dot-->
        android:enabled="false"
        android:targetActivity=".activities.SplashActivity"> <!--target activity class path will be same for all alias-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity-alias>

Step 2). Make a method that will be used to disable 1st activity-alias that contains default icon & enable 2nd alias that contains icon need to be changed.

/**
 * method to change the app icon dynamically
 *
 * @param context
 * @param isNewIcon  : true if new icon need to be set; false to set default 
 * icon
 */

public static void changeAppIconDynamically(Context context, boolean isNewIcon) {
    PackageManager pm = context.getApplicationContext().getPackageManager();
    if (isNewIcon) {
        pm.setComponentEnabledSetting(
                new ComponentName(context,
                        "com.example.dummy.SplashActivityAlias1"), //com.example.dummy will be your package
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);

        pm.setComponentEnabledSetting(
                new ComponentName(context,
                        "com.example.dummy.SplashActivityAlias"),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    } else {
        pm.setComponentEnabledSetting(
                new ComponentName(context,
                        "com.example.dummy.SplashActivityAlias1"),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        pm.setComponentEnabledSetting(
                new ComponentName(context,
                        "com.example.dummy.SplashActivityAlias"),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }
}

Step 3). Now call this method depending on your requirement, say on button click or date specific or occasion specific conditions, simply like -

// Switch app icon to new icon
    GeneralUtils.changeAppIconDynamically(EditProfileActivity.this, true);
// Switch app icon to default icon
            GeneralUtils.changeAppIconDynamically(EditProfileActivity.this, false);

Hope this will help those who face the issue of app getting killed on icon change. Happy Coding :)

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

How to debug on a real device (using Eclipse/ADT)

in devices which has Android 4.3 and above you should follow these steps:

How to enable Developer Options:

Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.

In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.

python save image from url

import requests

img_data = requests.get(image_url).content
with open('image_name.jpg', 'wb') as handler:
    handler.write(img_data)

Getting value of HTML Checkbox from onclick/onchange events

For React.js, you can do this with more readable code. Hope it helps.

handleCheckboxChange(e) {
  console.log('value of checkbox : ', e.target.checked);
}
render() {
  return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}

Can anonymous class implement interface?

The answer to the question specifically asked is no. But have you been looking at mocking frameworks? I use MOQ but there's millions of them out there and they allow you to implement/stub (partially or fully) interfaces in-line. Eg.

public void ThisWillWork()
{
    var source = new DummySource[0];
    var mock = new Mock<DummyInterface>();

    mock.SetupProperty(m => m.A, source.Select(s => s.A));
    mock.SetupProperty(m => m.B, source.Select(s => s.C + "_" + s.D));

    DoSomethingWithDummyInterface(mock.Object);
}

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

Prevent jQuery UI dialog from setting focus to first textbox

You can Add this :

...

dlg.dialog({ autoOpen:false,
modal: true, 
width: 400,
open: function(){                  // There is new line
  $("#txtStartDate").focus();
  }
});

...

CSS: Hover one element, effect for multiple elements?

This worked for me in Firefox and Chrome and IE8...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html>
    <head>
        <style type="text/css">
        div.section:hover div.image, div.section:hover div.layer {
            border: solid 1px red;
        }
        </style>
    </head>
    <body>
        <div class="section">
            <div class="image"><img src="myImage.jpg" /></div>
            <div class="layer">Lorem Ipsum</div>
        </div>
    </body>
</html>

... you may want to test this with IE6 as well (I'm not sure if it'll work there).

Running conda with proxy

You can configure a proxy with conda by adding it to the .condarc, like

proxy_servers:
    http: http://user:[email protected]:8080
    https: https://user:[email protected]:8080

or set the HTTP_PROXY and HTTPS_PROXY environment variables. Note that in your case you need to add the scheme to the proxy url, like https://proxy-us.bla.com:123.

See http://conda.pydata.org/docs/config.html#configure-conda-for-use-behind-a-proxy-server.

How to convert a String to a Date using SimpleDateFormat?

you can solve the problem much simple like First convert the the given string to the date object eg:

java.util.Date date1 = new Date("11/19/2015"); 
SimpleDateFormat formatter = new SimpleDateFormat("MMM dd yyyy HH:mma");
String format = formatter.format(date);
System.out.println(format);

Doing HTTP requests FROM Laravel to an external API

Basic Solution for Laravel 8 is

use Illuminate\Support\Facades\Http;

$response = Http::get('http://example.com');

I had conflict between "GuzzleHTTP sending requests" and "Illuminate\Http\Request;" don't ask me why... [it's here to be searchable]

So looking for 1sec i found in Laravel 8 Doc...

**Guzzle is inside the Laravel 8 Http Request !**

https://laravel.com/docs/8.x/http-client#making-requests

as you can see

https://laravel.com/docs/8.x/http-client#introduction

Laravel provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications. Laravel's wrapper around Guzzle is focused on its most common use cases and a wonderful developer experience.

It worked for me very well, have fun and if helpful point up!

database vs. flat files

This is an answer I've already given some time ago:

It depends entirely on the domain-specific application needs. A lot of times direct text file/binary files access can be extremely fast, efficient, as well as providing you all the file access capabilities of your OS's file system.

Furthermore, your programming language most likely already has a built-in module (or is easy to make one) for specific parsing.

If what you need is many appends (INSERTS?) and sequential/few access little/no concurrency, files are the way to go.

On the other hand, when your requirements for concurrency, non-sequential reading/writing, atomicity, atomic permissions, your data is relational by the nature etc., you will be better off with a relational or OO database.

There is a lot that can be accomplished with SQLite3, which is extremely light (under 300kb), ACID compliant, written in C/C++, and highly ubiquitous (if it isn't already included in your programming language -for example Python-, there is surely one available). It can be useful even on db files as big as 140 terabytes, or 128 tebibytes (Link to Database Size), possible more.

If your requirements where bigger, there wouldn't even be a discussion, go for a full-blown RDBMS.

As you say in a comment that "the system" is merely a bunch of scripts, then you should take a look at pgbash.

pass post data with window.location.href

As it was said in other answers there is no way to make a POST request using window.location.href, to do it you can create a form and submit it immediately.

You can use this function:

function postForm(path, params, method) {
    method = method || 'post';

    var form = document.createElement('form');
    form.setAttribute('method', method);
    form.setAttribute('action', path);

    for (var key in params) {
        if (params.hasOwnProperty(key)) {
            var hiddenField = document.createElement('input');
            hiddenField.setAttribute('type', 'hidden');
            hiddenField.setAttribute('name', key);
            hiddenField.setAttribute('value', params[key]);

            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
}

postForm('mysite.com/form', {arg1: 'value1', arg2: 'value2'});

https://stackoverflow.com/a/133997/2965158

Hot deploy on JBoss - how do I make JBoss "see" the change?

Just my two cents:

  • Cold deployment is the way of deploying an application when you stop it (or stop the whole server), then you install the new version, and finally restart the application (or start the whole server). It's suitable for official production deployments, but it would be horrible slow to do this during development. Forget about rapid development if you are doing this.

  • Auto deployment is the ability the server has to re-scan periodically for a new EAR/WAR and deploy it automagically behind the scenes for you, or for the IDE (Eclipse) to deploy automagically the whole application when you make changes to the source code. JBoss does this, but JBoss's marketing department call this misleadingly "hot deployment". An auto deployment is not as slow compared to a cold deployment, but is really slow compared to a hot deployment.

  • Hot deployment is the ability to deploy behind the scenes "as you type". No need to redeploy the whole application when you make changes. Hot deployment ONLY deploys the changes. You change a Java source code, and voila! it's running already. You never noticed it was deploying it. JBoss cannot do this, unless you buy for JRebel (or similar) but this is too much $$ for me (I'm cheap).

Now my "sales pitch" :D

What about using Tomcat during development? Comes with hot deployment all day long... for free. I do that all the time during development and then I deploy on WebSphere, JBoss, or Weblogic. Don't get me wrong, these three are great for production, but are really AWFUL for rapid-development on your local machine. Development productivity goes down the drain if you use these three all day long.

In my experience, I stopped using WebSphere, JBoss, and Weblogic for rapid development. I still have them installed in my local environment, though, but only for the occasional test I may need to run. I don't pay for JRebel all the while I get awesome development speed. Did I mention Tomcat is fully compatible with JBoss?

Tomcat is free and not only has auto-deployment, but also REAL hot deployment (Java code, JSP, JSF, XHTML) as you type in Eclipse (Yes, you read well). MYKong has a page (https://www.mkyong.com/eclipse/how-to-configure-hot-deploy-in-eclipse/) with details on how to set it up.

Did you like my sales pitch?

Cheers!

How to update multiple columns in single update statement in DB2

The update statement in all versions of SQL looks like:

update table
    set col1 = expr1,
        col2 = expr2,
        . . .
        coln = exprn
    where some condition

So, the answer is that you separate the assignments using commas and don't repeat the set statement.

How do you set the Content-Type header for an HttpClient request?

Call AddWithoutValidation instead of Add (see this MSDN link).

Alternatively, I'm guessing the API you are using really only requires this for POST or PUT requests (not ordinary GET requests). In that case, when you call HttpClient.PostAsync and pass in an HttpContent, set this on the Headers property of that HttpContent object.

How do I reference the input of an HTML <textarea> control in codebehind?

Missed property runat="server" or in code use Request.Params["TextArea1"]

How to add a line to a multiline TextBox?

You have to use the AppendText method of the textbox directly. If you try to use the Text property, the textbox will not scroll down as new line are appended.

textBox1.AppendText("Hello" + Environment.NewLine);

NumPy first and last element from array

Using Numpy's fancy indexing:

>>> test
array([ 1, 23,  4,  6,  7,  8])

>>> test[::-1]  # test, reversed
array([ 8,  7,  6,  4, 23,  1])

>>> numpy.vstack([test, test[::-1]])  # stack test and its reverse
array([[ 1, 23,  4,  6,  7,  8],
       [ 8,  7,  6,  4, 23,  1]])

>>> # transpose, then take the first half;
>>> # +1 to cater to odd-length arrays
>>> numpy.vstack([test, test[::-1]]).T[:(len(test) + 1) // 2]
array([[ 1,  8],
       [23,  7],
       [ 4,  6]])

vstack copies the array, but all the other operations are constant-time pointer tricks (including reversal) and hence are very fast.

How to get all privileges back to the root user in MySQL?

Log in as root, then run the following MySQL commands:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
FLUSH PRIVILEGES;

a href link for entire div in HTML/CSS

This can be done in many ways. a. Using nested inside a tag.

<a href="link1.html">
   <div> Something in the div </div>
 </a>

b. Using the Inline JavaScript Method

<div onclick="javascript:window.location.href='link1.html' "> 
  Some Text 
</div>

c. Using jQuery inside tag

HTML:

<div class="demo" > Some text here </div>

jQuery:

$(".demo").click( function() {
  window.location.href="link1.html";
 });

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

I don't want to include the Support library just for getColor, so I'm using something like

public static int getColorWrapper(Context context, int id) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return context.getColor(id);
    } else {
        //noinspection deprecation
        return context.getResources().getColor(id);
    }
}

I guess the code should work just fine, and the deprecated getColor cannot disappear from API < 23.

And this is what I'm using in Kotlin:

/**
 * Returns a color associated with a particular resource ID.
 *
 * Wrapper around the deprecated [Resources.getColor][android.content.res.Resources.getColor].
 */
@Suppress("DEPRECATION")
@ColorInt
fun getColorHelper(context: Context, @ColorRes id: Int) =
    if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

For debian, from the 10gen repo, between 2.4.x and 2.6.x, they renamed the init script /etc/init.d/mongodb to /etc/init.d/mongod, and the default config file from /etc/mongodb.conf to /etc/mongod.conf, and the PID and lock files from "mongodb" to "mongod" too. This made upgrading a pain, and I don't see it mentioned in their docs anywhere. Anyway, the solution is to remove the old "mongodb" versions:

update-rc.d -f mongodb remove
rm /etc/init.d/mongodb
rm /var/run/mongodb.pid
diff -ur /etc/mongodb.conf /etc/mongod.conf

Now, look and see what config changes you need to keep, and put them in mongod.conf.

Then:

rm /etc/mongodb.conf

Now you can:

service mongod restart

Upgrade Node.js to the latest version on Mac OS

Simply go to node JS Website and install the latest version.

Do install latest version instead of the recommended stable version. It will give you freedom to use latest ES6 Features on node.

Can be Found here Node JS.

also to update npm, you will have to use this command.

sudo npm i -g npm@latest

All your projects will work fine.

Update: 2020 another good option is to use nvm for node which can then support multiple versions. use nvm install --lts to always be able to update to latest node version use nvm ls-remote command to to check new versions of node.


Other option for mac :: brew update && brew install node && npm -g npm

'any' vs 'Object'

Contrary to .NET where all types derive from an "object", in TypeScript, all types derive from "any". I just wanted to add this comparison as I think it will be a common one made as more .NET developers give TypeScript a try.

How to empty ("truncate") a file on linux that already exists and is protected in someway?

Any one can try this command to truncate any file in linux system

This will surely work in any format :

truncate -s 0 file.txt

How do I make a composite key with SQL Server Management Studio?

enter image description here

  1. Open the design table tab
  2. Highlight your two INT fields (Ctrl/Shift+click on the grey blocks in the very first column)
  3. Right click -> Set primary key

Save Javascript objects in sessionStorage

You can create 2 wrapper methods for saving and retrieving object from session storage.

function saveSession(obj) {
  sessionStorage.setItem("myObj", JSON.stringify(obj));
  return true;
}

function getSession() {
  var obj = {};
  if (typeof sessionStorage.myObj !== "undefined") {
    obj = JSON.parse(sessionStorage.myObj);
  }
  return obj;
}

Use it like this:- Get object, modify some data, and save back.

var obj = getSession();

obj.newProperty = "Prod"

saveSession(obj);

Python def function: How do you specify the end of the function?

So its the indentation that matters. As other users here have pointed out to you, when the indentation level is at the same point as the def function declaration your function has ended. Keep in mind that you cannot mix tabs and spaces in Python. Most editors provide support for this.

Java random number with given length

Would that work for you?

public class Main {

public static void main(String[] args) {
    Random r = new Random(System.currentTimeMillis());
    System.out.println(r.nextInt(100000) * 0.000001);
}

}

result e.g. 0.019007