Programs & Examples On #Lightspeed

Lightspeed is an Object-Relational Mapper (ORM) for .NET.

How to check whether mod_rewrite is enable on server?

console:

<VirtualHost *:80>
        ...
    <Directory ...>
        AllowOverride All
    </Directory>
</VirtualHost>

sudo a2enmod rewrite
sudo service apache2 restart

COUNT / GROUP BY with active record?

I believe you'll want something like this:

 $this->db->select('user_id, COUNT(user_id) as total');
 $this->db->group_by('user_id'); 
 $this->db->order_by('total', 'desc'); 
 $this->db->get('tablename', 10);

This will produce a result like

|  USER_ID |  TOTAL  |
|    12    |    3    |
|    15    |    2    |
|    18    |    1    |

UPDATE: As some pointed out in the comments the original query was summing the user_ids rather than counting them. I've updated the active record query to correct this.

IntelliJ cannot find any declarations

If you are new to IntelliJ u May take some time to understand IntelliJ. If a Code has written in Java and using cucumber framework then we have two main files -

  1. Feature file
  2. Step definition file

Goal : what are things we have defined in feature file it must be navigate towards Step Definition File. (Ctrl +click ) Note :feature file has to contain some colourful gherkins keywords too .if it’s not follow the below steps

Solution : go to file >>settings >> plugins - search “Cucumber for Java” Add the plugin restart IntelliJ it will work for sure .

Python logging: use milliseconds in time format

Adding msecs was the better option, Thanks. Here is my amendment using this with Python 3.5.3 in Blender

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
log = logging.getLogger(__name__)
log.info("Logging Info")
log.debug("Logging Debug")

How to return a PNG image from Jersey REST service method to the browser

I'm not convinced its a good idea to return image data in a REST service. It ties up your application server's memory and IO bandwidth. Much better to delegate that task to a proper web server that is optimized for this kind of transfer. You can accomplish this by sending a redirect to the image resource (as a HTTP 302 response with the URI of the image). This assumes of course that your images are arranged as web content.

Having said that, if you decide you really need to transfer image data from a web service you can do so with the following (pseudo) code:

@Path("/whatever")
@Produces("image/png")
public Response getFullImage(...) {

    BufferedImage image = ...;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    byte[] imageData = baos.toByteArray();

    // uncomment line below to send non-streamed
    // return Response.ok(imageData).build();

    // uncomment line below to send streamed
    // return Response.ok(new ByteArrayInputStream(imageData)).build();
}

Add in exception handling, etc etc.

ImportError: No module named dateutil.parser

On Ubuntu you may need to install the package manager pip first:

sudo apt-get install python-pip

Then install the python-dateutil package with:

sudo pip install python-dateutil

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

I had the same problem as you do and I could solve it by following @CarlosRojas instructions with a little difference. Instead of create a new firewall rule I edited the default-allow-internal one to accept traffic from anywhere since creating new rules didn't make any difference.

What does the DOCKER_HOST variable do?

Ok, I think I got it.

The client is the docker command installed into OS X.

The host is the Boot2Docker VM.

The daemon is a background service running inside Boot2Docker.

This variable tells the client how to connect to the daemon.

When starting Boot2Docker, the terminal window that pops up already has DOCKER_HOST set, so that's why docker commands work. However, to run Docker commands in other terminal windows, you need to set this variable in those windows.

Failing to set it gives a message like this:

$ docker run hello-world
2014/08/11 11:41:42 Post http:///var/run/docker.sock/v1.13/containers/create: 
dial unix /var/run/docker.sock: no such file or directory

One way to fix that would be to simply do this:

$ export DOCKER_HOST=tcp://192.168.59.103:2375

But, as pointed out by others, it's better to do this:

$ $(boot2docker shellinit)
$ docker run hello-world
Hello from Docker. [...]

To spell out this possibly non-intuitive Bash command, running boot2docker shellinit returns a set of Bash commands that set environment variables:

export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1

Hence running $(boot2docker shellinit) generates those commands, and then runs them.

Add a duration to a moment (moment.js)

I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.

So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:

var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format

var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes 

var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format

It fulfills my requirement. May be it can help you.

Get item in the list in Scala?

Safer is to use lift so you can extract the value if it exists and fail gracefully if it does not.

data.lift(2)

This will return None if the list isn't long enough to provide that element, and Some(value) if it is.

scala> val l = List("a", "b", "c")
scala> l.lift(1)
Some("b")
scala> l.lift(5)
None

Whenever you're performing an operation that may fail in this way it's great to use an Option and get the type system to help make sure you are handling the case where the element doesn't exist.

Explanation:

This works because List's apply (which sugars to just parentheses, e.g. l(index)) is like a partial function that is defined wherever the list has an element. The List.lift method turns the partial apply function (a function that is only defined for some inputs) into a normal function (defined for any input) by basically wrapping the result in an Option.

Usage of __slots__?

The original question was about general use cases not only about memory. So it should be mentioned here that you also get better performance when instantiating large amounts of objects - interesting e.g. when parsing large documents into objects or from a database.

Here is a comparison of creating object trees with a million entries, using slots and without slots. As a reference also the performance when using plain dicts for the trees (Py2.7.10 on OSX):

********** RUN 1 **********
1.96036410332 <class 'css_tree_select.element.Element'>
3.02922606468 <class 'css_tree_select.element.ElementNoSlots'>
2.90828204155 dict
********** RUN 2 **********
1.77050495148 <class 'css_tree_select.element.Element'>
3.10655999184 <class 'css_tree_select.element.ElementNoSlots'>
2.84120798111 dict
********** RUN 3 **********
1.84069895744 <class 'css_tree_select.element.Element'>
3.21540498734 <class 'css_tree_select.element.ElementNoSlots'>
2.59615707397 dict
********** RUN 4 **********
1.75041103363 <class 'css_tree_select.element.Element'>
3.17366290092 <class 'css_tree_select.element.ElementNoSlots'>
2.70941114426 dict

Test classes (ident, appart from slots):

class Element(object):
    __slots__ = ['_typ', 'id', 'parent', 'childs']
    def __init__(self, typ, id, parent=None):
        self._typ = typ
        self.id = id
        self.childs = []
        if parent:
            self.parent = parent
            parent.childs.append(self)

class ElementNoSlots(object): (same, w/o slots)

testcode, verbose mode:

na, nb, nc = 100, 100, 100
for i in (1, 2, 3, 4):
    print '*' * 10, 'RUN', i, '*' * 10
    # tree with slot and no slot:
    for cls in Element, ElementNoSlots:
        t1 = time.time()
        root = cls('root', 'root')
        for i in xrange(na):
            ela = cls(typ='a', id=i, parent=root)
            for j in xrange(nb):
                elb = cls(typ='b', id=(i, j), parent=ela)
                for k in xrange(nc):
                    elc = cls(typ='c', id=(i, j, k), parent=elb)
        to =  time.time() - t1
        print to, cls
        del root

    # ref: tree with dicts only:
    t1 = time.time()
    droot = {'childs': []}
    for i in xrange(na):
        ela =  {'typ': 'a', id: i, 'childs': []}
        droot['childs'].append(ela)
        for j in xrange(nb):
            elb =  {'typ': 'b', id: (i, j), 'childs': []}
            ela['childs'].append(elb)
            for k in xrange(nc):
                elc =  {'typ': 'c', id: (i, j, k), 'childs': []}
                elb['childs'].append(elc)
    td = time.time() - t1
    print td, 'dict'
    del droot

How to include view/partial specific styling in AngularJS

@tennisgent's solution is great. However, I think is a little limited.

Modularity and Encapsulation in Angular goes beyond routes. Based on the way the web is moving towards component-based development, it is important to apply this in directives as well.

As you already know, in Angular we can include templates (structure) and controllers (behavior) in pages and components. AngularCSS enables the last missing piece: attaching stylesheets (presentation).

For a full solution I suggest using AngularCSS.

  1. Supports Angular's ngRoute, UI Router, directives, controllers and services.
  2. Doesn't required to have ng-app in the <html> tag. This is important when you have multiple apps running on the same page
  3. You can customize where the stylesheets are injected: head, body, custom selector, etc...
  4. Supports preloading, persisting and cache busting
  5. Supports media queries and optimizes page load via matchMedia API

https://github.com/door3/angular-css

Here are some examples:

Routes

  $routeProvider
    .when('/page1', {
      templateUrl: 'page1/page1.html',
      controller: 'page1Ctrl',
      /* Now you can bind css to routes */
      css: 'page1/page1.css'
    })
    .when('/page2', {
      templateUrl: 'page2/page2.html',
      controller: 'page2Ctrl',
      /* You can also enable features like bust cache, persist and preload */
      css: {
        href: 'page2/page2.css',
        bustCache: true
      }
    })
    .when('/page3', {
      templateUrl: 'page3/page3.html',
      controller: 'page3Ctrl',
      /* This is how you can include multiple stylesheets */
      css: ['page3/page3.css','page3/page3-2.css']
    })
    .when('/page4', {
      templateUrl: 'page4/page4.html',
      controller: 'page4Ctrl',
      css: [
        {
          href: 'page4/page4.css',
          persist: true
        }, {
          href: 'page4/page4.mobile.css',
          /* Media Query support via window.matchMedia API
           * This will only add the stylesheet if the breakpoint matches */
          media: 'screen and (max-width : 768px)'
        }, {
          href: 'page4/page4.print.css',
          media: 'print'
        }
      ]
    });

Directives

myApp.directive('myDirective', function () {
  return {
    restrict: 'E',
    templateUrl: 'my-directive/my-directive.html',
    css: 'my-directive/my-directive.css'
  }
});

Additionally, you can use the $css service for edge cases:

myApp.controller('pageCtrl', function ($scope, $css) {

  // Binds stylesheet(s) to scope create/destroy events (recommended over add/remove)
  $css.bind({ 
    href: 'my-page/my-page.css'
  }, $scope);

  // Simply add stylesheet(s)
  $css.add('my-page/my-page.css');

  // Simply remove stylesheet(s)
  $css.remove(['my-page/my-page.css','my-page/my-page2.css']);

  // Remove all stylesheets
  $css.removeAll();

});

You can read more about AngularCSS here:

http://door3.com/insights/introducing-angularcss-css-demand-angularjs

Why is String immutable in Java?

You are right. String in java uses concept of String Pool literal. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.If a string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

I would add one more thing, since String is immutable, it is safe for multi threading and a single String instance can be shared across different threads. This avoid the usage of synchronization for thread safety, Strings are implicitly thread safe.

What is the use of static constructors?

you can use static constructor to initializes static fields. It runs at an indeterminate time before those fields are used. Microsoft's documentation and many developers warn that static constructors on a type impose a substantial overhead.
It is best to avoid static constructors for maximum performance.
update: you can't use more than one static constructor in the same class, however you can use other instance constructors with (maximum) one static constructor.

How can I read large text files in Python, line by line, without loading it into memory?

Please try this:

with open('filename','r',buffering=100000) as f:
    for line in f:
        print line

Integrating MySQL with Python in Windows

upvoted itsadok's answer because it led me to the installation for python 2.7 as well, which is located here: http://www.codegood.com/archives/129

Javascript: 'window' is not defined

It is from an external js file and it is the only file linked to the page.

OK.

When I double click this file I get the following error

Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:

Windows Script Host Error: 'window' is not defined Code: 800A1391

... not an error you'll see in a browser. And of course, the browser is what supplies the window object.

ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload definition is simply being hit after the browser fires the window.onload event.

Flexbox Not Centering Vertically in IE

I don't have much experience with Flexbox but it seems to me that the forced height on the html and body tags cause the text to disappear on top when resized-- I wasn't able to test in IE but I found the same effect in Chrome.

I forked your fiddle and removed the height and width declarations.

body
{
    margin: 0;
}

It also seemed like the flex settings must be applied to other flex elements. However, applying display: flex to the .inner caused issues so I explicitly set the .inner to display: block and set the .outer to flex for positioning.

I set the minimum .outer height to fill the viewport, the display: flex, and set the horizontal and vertical alignment:

.outer
{
    display:flex;
    min-height: 100%;
    min-height: 100vh;
    align-items: center;
    justify-content: center;
}

I set .inner to display: block explicitly. In Chrome, it looked like it inherited flex from .outer. I also set the width:

.inner
{
    display:block;
    width: 80%;
}

This fixed the issue in Chrome, hopefully it might do the same in IE11. Here's my version of the fiddle: http://jsfiddle.net/ToddT/5CxAy/21/

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

This is a popular question. It is important to understand what the question author is asking, and that it is different from what is likely the most common need. To discourage misuse of the code where it is not needed, I've answered the later first.

Common Need

Every string has a character set and encoding. When you convert a System.String object to an array of System.Byte you still have a character set and encoding. For most usages, you'd know which character set and encoding you need and .NET makes it simple to "copy with conversion." Just choose the appropriate Encoding class.

// using System.Text;
Encoding.UTF8.GetBytes(".NET String to byte array")

The conversion may need to handle cases where the target character set or encoding doesn't support a character that's in the source. You have some choices: exception, substitution or skipping. The default policy is to substitute a '?'.

// using System.Text;
var text = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes("You win €100")); 
                                                      // -> "You win ?100"

Clearly, conversions are not necessarily lossless!

Note: For System.String the source character set is Unicode.

The only confusing thing is that .NET uses the name of a character set for the name of one particular encoding of that character set. Encoding.Unicode should be called Encoding.UTF16.

That's it for most usages. If that's what you need, stop reading here. See the fun Joel Spolsky article if you don't understand what an encoding is.

Specific Need

Now, the question author asks, "Every string is stored as an array of bytes, right? Why can't I simply have those bytes?"

He doesn't want any conversion.

From the C# spec:

Character and string processing in C# uses Unicode encoding. The char type represents a UTF-16 code unit, and the string type represents a sequence of UTF-16 code units.

So, we know that if we ask for the null conversion (i.e., from UTF-16 to UTF-16), we'll get the desired result:

Encoding.Unicode.GetBytes(".NET String to byte array")

But to avoid the mention of encodings, we must do it another way. If an intermediate data type is acceptable, there is a conceptual shortcut for this:

".NET String to byte array".ToCharArray()

That doesn't get us the desired datatype but Mehrdad's answer shows how to convert this Char array to a Byte array using BlockCopy. However, this copies the string twice! And, it too explicitly uses encoding-specific code: the datatype System.Char.

The only way to get to the actual bytes the String is stored in is to use a pointer. The fixed statement allows taking the address of values. From the C# spec:

[For] an expression of type string, ... the initializer computes the address of the first character in the string.

To do so, the compiler writes code skip over the other parts of the string object with RuntimeHelpers.OffsetToStringData. So, to get the raw bytes, just create a pointer to the string and copy the number of bytes needed.

// using System.Runtime.InteropServices
unsafe byte[] GetRawBytes(String s)
{
    if (s == null) return null;
    var codeunitCount = s.Length;
    /* We know that String is a sequence of UTF-16 codeunits 
       and such codeunits are 2 bytes */
    var byteCount = codeunitCount * 2; 
    var bytes = new byte[byteCount];
    fixed(void* pRaw = s)
    {
        Marshal.Copy((IntPtr)pRaw, bytes, 0, byteCount);
    }
    return bytes;
}

As @CodesInChaos pointed out, the result depends on the endianness of the machine. But the question author is not concerned with that.

JavaScript - document.getElementByID with onClick

The onclick property is all lower-case, and accepts a function, not a string.

document.getElementById("test").onclick = foo2;

See also addEventListener.

How to get memory usage at runtime using C++?

Old:

maxrss states the maximum available memory for the process. 0 means that no limit is put upon the process. What you probably want is unshared data usage ru_idrss.

New: It seems that the above does not actually work, as the kernel does not fill most of the values. What does work is to get the information from proc. Instead of parsing it oneself though, it is easier to use libproc (part of procps) as follows:

// getrusage.c
#include <stdio.h>
#include <proc/readproc.h>

int main() {
  struct proc_t usage;
  look_up_our_self(&usage);
  printf("usage: %lu\n", usage.vsize);
}

Compile with "gcc -o getrusage getrusage.c -lproc"

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This error is caused by:

Y = Dataset.iloc[:,18].values

Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.

Center HTML Input Text Field Placeholder

By using the code snippet below, you are selecting the placeholder inside your input, and any code placed inside will affect only the placeholder.

input::-webkit-input-placeholder {
      text-align: center
}

Pandas: change data type of Series to String

A new answer to reflect the most current practices: as of version 1.0.1, neither astype('str') nor astype(str) work.

As per the documentation, a Series can be converted to the string datatype in the following ways:

df['id'] = df['id'].astype("string")

df['id'] = pandas.Series(df['id'], dtype="string")

df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)

PHPExcel - set cell type before writing a value in it

try this

$currencyFormat = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)';
$textFormat='@';//'General','0.00','@'
$excel->getActiveSheet()->getStyle('B1')->getNumberFormat()->setFormatCode($currencyFormat);
$excel->getActiveSheet()->getStyle('C1')->getNumberFormat()->setFormatCode($textFormat);`

Where value in column containing comma delimited values

Since you don't know how many comma-delimited entries you can find, you may need to create a function with 'charindex' and 'substring' SQL Server functions. Values, as returned by the function could be used in a 'in' expression.

You function can be recursively invoked or you can create loop, searching for entries until no more entries are present in the string. Every call to the function uses the previous found index as the starting point of the next call. The first call starts at 0.

Angular 2 change event - model changes

That's a known issue. Currently you have to use a workaround like shown in your question.

This is working as intended. When the change event is emitted ngModelChange (the (...) part of [(ngModel)] hasn't updated the bound model yet:

<input type="checkbox"  (ngModelChange)="myModel=$event" [ngModel]="mymodel">

See also

First Heroku deploy failed `error code=H10`

I had a typo

const PORT = process.env.PORT||'8080';

used to be

const PORT = process.env.port||'8080';

Impact of Xcode build options "Enable bitcode" Yes/No

  • What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?

I'm not sure at what level you are looking for an answer at, so let's take a little trip. Some of this you may already know.

When you build your project, Xcode invokes clang for Objective-C targets and swift/swiftc for Swift targets. Both of these compilers compile the app to an intermediate representation (IR), one of these IRs is bitcode. From this IR, a program called LLVM takes over and creates the binaries needed for x86 32 and 64 bit modes (for the simulator) and arm6/arm7/arm7s/arm64 (for the device). Normally, all of these different binaries are lumped together in a single file called a fat binary.

The ENABLE_BITCODE option cuts out this final step. It creates a version of the app with an IR bitcode binary. This has a number of nice features, but one giant drawback: it can't run anywhere. In order to get an app with a bitcode binary to run, the bitcode needs to be recompiled (maybe assembled or transcoded… I'm not sure of the correct verb) into an x86 or ARM binary.

When a bitcode app is submitted to the App Store, Apple will do this final step and create the finished binaries.

Right now, bitcode apps are optional, but history has shown Apple turns optional things into requirements (like 64 bit support). This usually takes a few years, so third party developers (like Parse) have time to update.

  • can I use the above method without any negative impact and without compromising a future appstore submission?

Yes, you can turn off ENABLE_BITCODE and everything will work just like before. Until Apple makes bitcode apps a requirement for the App Store, you will be fine.

  • Are there any performance impacts if I enable / disable it?

There will never be negative performance impacts for enabling it, but internal distribution of an app for testing may get more complicated.

As for positive impacts… well that's complicated.

For distribution in the App Store, Apple will create separate versions of your app for each machine architecture (arm6/arm7/arm7s/arm64) instead of one app with a fat binary. This means the app installed on iOS devices will be smaller.

In addition, when bitcode is recompiled (maybe assembled or transcoded… again, I'm not sure of the correct verb), it is optimized. LLVM is always working on creating new a better optimizations. In theory, the App Store could recreate the separate version of the app in the App Store with each new release of LLVM, so your app could be re-optimized with the latest LLVM technology.

com.jcraft.jsch.JSchException: UnknownHostKey

You can also simply do

session.setConfig("StrictHostKeyChecking", "no");

It's not secure and it's a workaround not suitable for live environment as it will disable globally known host keys checking.

How to install numpy on windows using pip install?

Check installation of python 2.7 than install/reinstall pip which described here than open command line and write

pip install numpy

or

pip install scipy

if already installed try this

pip install -U numpy

How to parse dates in multiple formats using SimpleDateFormat

This solution checks all the possible formats before throwing an exception. This solution is more convenient if you are trying to test for multiple date formats.

Date extractTimestampInput(String strDate){
    final List<String> dateFormats = Arrays.asList("yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd");    

    for(String format: dateFormats){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try{
            return sdf.parse(strDate);
        } catch (ParseException e) {
             //intentionally empty
        }
    }
        throw new IllegalArgumentException("Invalid input for date. Given '"+strDate+"', expecting format yyyy-MM-dd HH:mm:ss.SSS or yyyy-MM-dd.");

}

Regular expressions in C: examples?

It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.

MongoDB query with an 'or' condition

Using a $where query will be slow, in part because it can't use indexes. For this sort of problem, I think it would be better to store a high value for the "expires" field that will naturally always be greater than Now(). You can either store a very high date millions of years in the future, or use a separate type to indicate never. The cross-type sort order is defined at here.

An empty Regex or MaxKey (if you language supports it) are both good choices.

npm start error with create-react-app

I had the same error when running

npm start

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.

I broke my head on several tabs and applying Solutions from other devs and nothing.

Until, even using Ubuntu, I closed my vscode and restarted my pc and all my problems were solved. (kkkk zueira) just this one.

Using BufferedReader to read Text File

you can store it in array and then use whichever line you want.. this is the code snippet that i have used to read line from file and store it in a string array, hope this will be useful for you :)

public class user {
 public static void main(String x[]) throws IOException{
  BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
  String[] user=new String[30];
  String line="";
  while ((line = b.readLine()) != null) {
   user[i]=line; 
   System.out.println(user[1]);
   i++;  
   }

 }
}

Returning http 200 OK with error within response body

HTTP Is the Protocol handling the transmission of data over the internet.

If that transmission breaks for whatever reason the HTTP error codes tell you why it can't be sent to you.

The data being transmitted is not handled by HTTP Error codes. Only the method of transmission.

HTTP can't say 'Ok, this answer is gobbledigook, but here it is'. it just says 200 OK.

i.e : I've completed my job of getting it to you, the rest is up to you.

I know this has been answered already but I put it in words I can understand. sorry for any repetition.

Android eclipse DDMS - Can't access data/data/ on phone to pull files

You must edit permission of data folder.

I use "Root Explorer" (see market) app on root mode.

On top select "Monunted as r/w"

then press over data folder (long click) and find Permission option

Have a somenthing like that

        read    write  execute

User

Group

Others

Make sure that "Others" have a check for read

Then go Eclpse and try again.

Sorry about my english,I hope can help you.

Does Internet Explorer 8 support HTML 5?

You can use this to make IE8 understand/support basic HTML5 tags.

<!--[if lt IE 9 ]> 
    <script type="text/javascript">
        var html5Elem = ['header', 'nav', 'menu', 'section', 'article', 'aside', 'footer'];
        for (var i = 0; i < html5Elem.length; i++){
            document.createElement(html5Elem[i]);
        }
    </script>
<![endif]-->

Element-wise addition of 2 lists?

I haven't timed it but I suspect this would be pretty quick:

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

list_sum = (np.add(list1, list2)).tolist()

[5, 7, 9]

How can I declare a Boolean parameter in SQL statement?

The same way you declare any other variable, just use the bit type:

DECLARE @MyVar bit
Set @MyVar = 1  /* True */
Set @MyVar = 0  /* False */

SELECT * FROM [MyTable] WHERE MyBitColumn = @MyVar

bundle install fails with SSL certificate verification error

For Windows machine, check your gem version with

gem --version

Then update your gem as follow:

Please download the file in a directory that you can later point to (eg. the root of your hard drive C:)

Now, using your Command Prompt:

C:\>gem install --local C:\rubygems-update-1.8.30.gem
C:\>update_rubygems --no-ri --no-rdoc

Now, bundle install will success without SSL certificate verification error.

More detailed instruction is here

How do I generate random integers within a specific range in Java?

public static void main(String[] args) {

    Random ran = new Random();

    int min, max;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter min range:");
    min = sc.nextInt();
    System.out.println("Enter max range:");
    max = sc.nextInt();
    int num = ran.nextInt(min);
    int num1 = ran.nextInt(max);
    System.out.println("Random Number between given range is " + num1);

}

How to show a GUI message box from a bash script in linux?

I believe Zenity will do what you want. It's specifically designed for displaying GTK dialogs from the command line, and it's available as an Ubuntu package.

How do I get the parent directory in Python?

An alternate solution of @kender

import os
os.path.dirname(os.path.normpath(yourpath))

where yourpath is the path you want the parent for.

But this solution is not perfect, since it will not handle the case where yourpath is an empty string, or a dot.

This other solution will handle more nicely this corner case:

import os
os.path.normpath(os.path.join(yourpath, os.pardir))

Here the outputs for every case that can find (Input path is relative):

os.path.dirname(os.path.normpath('a/b/'))          => 'a'
os.path.normpath(os.path.join('a/b/', os.pardir))  => 'a'

os.path.dirname(os.path.normpath('a/b'))           => 'a'
os.path.normpath(os.path.join('a/b', os.pardir))   => 'a'

os.path.dirname(os.path.normpath('a/'))            => ''
os.path.normpath(os.path.join('a/', os.pardir))    => '.'

os.path.dirname(os.path.normpath('a'))             => ''
os.path.normpath(os.path.join('a', os.pardir))     => '.'

os.path.dirname(os.path.normpath('.'))             => ''
os.path.normpath(os.path.join('.', os.pardir))     => '..'

os.path.dirname(os.path.normpath(''))              => ''
os.path.normpath(os.path.join('', os.pardir))      => '..'

os.path.dirname(os.path.normpath('..'))            => ''
os.path.normpath(os.path.join('..', os.pardir))    => '../..'

Input path is absolute (Linux path):

os.path.dirname(os.path.normpath('/a/b'))          => '/a'
os.path.normpath(os.path.join('/a/b', os.pardir))  => '/a'

os.path.dirname(os.path.normpath('/a'))            => '/'
os.path.normpath(os.path.join('/a', os.pardir))    => '/'

os.path.dirname(os.path.normpath('/'))             => '/'
os.path.normpath(os.path.join('/', os.pardir))     => '/'

Pie chart with jQuery

A few others that have not been mentioned:

For mini pies, lines and bars, Peity is brilliant, simple, tiny, fast, uses really elegant markup.

I'm not sure of it's relationship with Flot (given its name), but Flotr2 is pretty good, certainly does better pies than Flot.

Bluff produces nice-looking line graphs, but I had a bit of trouble with its pies.

Not what I was after, but another commercial product (much like Highcharts) is TeeChart.

How do I make a JAR from a .java file?

Although it is not recommended method but still it works
[7-Zip Software is needed]
Procedure to get jar from java files:

  • place all java files in one folder

  • right click on the folder enter image description here

  • now click on Add to archive you will get something like shown below enter image description here

  • now just change zip to jar and click on ok

How to scroll up or down the page to an anchor using jQuery?

I stuck with my original code and also included a fade in 'back-to-top' link making use of this code and a bit from here too:

http://webdesignerwall.com/tutorials/animated-scroll-to-top

Works well :)

How the int.TryParse actually works

Check this simple program to understand int.TryParse

 class Program
 {
    static void Main()
    {
        string str = "7788";
        int num1;
        bool n = int.TryParse(str, out num1);
        Console.WriteLine(num1);
        Console.ReadLine();
    }
}

Output is : 7788

Printing hexadecimal characters in C

You can create an unsigned char:

unsigned char c = 0xc5;

Printing it will give C5 and not ffffffc5.

Only the chars bigger than 127 are printed with the ffffff because they are negative (char is signed).

Or you can cast the char while printing:

char c = 0xc5; 
printf("%x", (unsigned char)c);

Check file extension in upload form in PHP

file type can be checked in other ways also. I believe this is the easiest way to check the uploaded file type.. if u are dealing with an image file then go for the following code. if you are dealing with a video file then replace the image check with a video check in the if block.. have fun

     $img_up = $_FILES['video_file']['type'];
$img_up_type = explode("/", $img_up);
$img_up_type_firstpart = $img_up_type[0];

if($img_up_type_firstpart == "image") { // image is the image file type, you can deal with video if you need to check video file type

/* do your logical code */ }

Quickly create large file on a Windows system

Short of writing a full application, us Python guys can achieve files of any size with four lines, same snippet on Windows and Linux (the os.stat() line is just a check):

>>> f = open('myfile.txt','w')
>>> f.seek(1024-1) # an example, pick any size
>>> f.write('\x00')
>>> f.close()
>>> os.stat('myfile.txt').st_size
1024L
>>>

Online code beautifier and formatter

I've used Quick Highlighter a lot. Works great for a huge list of languages.

How do I divide so I get a decimal value?

Check this out: http://download.oracle.com/javase/1,5.0/docs/api/java/math/BigDecimal.html#divideAndRemainder%28java.math.BigDecimal%29

You just need to wrap your int or long variable in a BigDecimal object, then invoke the divideAndRemainder method on it. The returned array will contain the quotient and the remainder (in that order).

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

Newer Oracle JVMs such as 1.7.0_21-b12 seem to install here:

/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

What is Activity.finish() method doing exactly?

My 2 cents on @K_Anas answer. I performed a simple test on finish() method. Listed important callback methods in activity life cycle

  1. Calling finish() in onCreate(): onCreate() -> onDestroy()
  2. Calling finish() in onStart() : onCreate() -> onStart() -> onStop() -> onDestroy()
  3. Calling finish() in onResume(): onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onDestroy()

What I mean to say is that counterparts of the methods along with any methods in between are called when finish() is executed.

eg:

 onCreate() counter part is onDestroy()
 onStart() counter part is onStop()
 onPause() counter part is onResume()

Fatal error: Class 'SoapClient' not found

For Docker* add this line:

RUN apt-get update && \
    apt-get install -y libxml2-dev && \
    docker-php-ext-install soap

*: For debian based images, ie. won't work for alpine variants.

Best way to format if statement with multiple conditions

The question was asked and has, so far, been answered as though the decision should be made purely on "syntactic" grounds.

I would say that the right answer of how you lay-out a number of conditions within an if, ought to depend on "semantics" too. So conditions should be broken up and grouped according to what things go together "conceptually".

If two tests are really two sides of the same coin eg. if (x>0) && (x<=100) then put them together on the same line. If another condition is conceptually far more distant eg. user.hasPermission(Admin()) then put it on it's own line

Eg.

if user.hasPermission(Admin()) {
   if (x >= 0) && (x < 100) {
      // do something
   }
}

How do I check if a cookie exists?

You can call the function getCookie with the name of the cookie you want, then check to see if it is = null.

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
        end = dc.length;
        }
    }
    // because unescape has been deprecated, replaced with decodeURI
    //return unescape(dc.substring(begin + prefix.length, end));
    return decodeURI(dc.substring(begin + prefix.length, end));
} 

function doSomething() {
    var myCookie = getCookie("MyCookie");

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
    }
    else {
        // do cookie exists stuff
    }
}

Create a batch file to run an .exe with an additional parameter

You can use

start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi

or

"%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

cd /D "%USERPROFILE%\Desktop\BGInfo"
bginfo.exe dc_bginfo.bgi

Help on commands start and cd is output by executing in a command prompt window help start or start /? and help cd or cd /?.

But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi" as parameter.

Example of multipart/form-data

Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:

Example:

POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"

content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"

content of picture_of_sunset.jpg ...
--12345--

I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:

POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde

--abcde
Content-Disposition: file; file="picture.jpg"

content of jpg...
--abcde
Content-Disposition: file; file="test.py"

content of test.py file ....
--abcde--
--12345--

Take a look at the link above.

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

SmartGit Installation and Usage on Ubuntu

What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon

In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.

Java ArrayList of Doubles

You can use Arrays.asList to get some list (not necessarily ArrayList) and then use addAll() to add it to an ArrayList:

new ArrayList<Double>().addAll(Arrays.asList(1.38L, 2.56L, 4.3L));

If you're using Java6 (or higher) you can also use the ArrayList constructor that takes another list:

new ArrayList<Double>(Arrays.asList(1.38L, 2.56L, 4.3L));

Make an HTTP request with android

This is the new code for HTTP Get/POST request in android. HTTPClient is depricated and may not be available as it was in my case.

Firstly add the two dependencies in build.gradle:

compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'

Then write this code in ASyncTask in doBackground method.

 URL url = new URL("http://localhost:8080/web/get?key=value");
 HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
 urlConnection.setRequestMethod("GET");
 int statusCode = urlConnection.getResponseCode();
 if (statusCode ==  200) {
      InputStream it = new BufferedInputStream(urlConnection.getInputStream());
      InputStreamReader read = new InputStreamReader(it);
      BufferedReader buff = new BufferedReader(read);
      StringBuilder dta = new StringBuilder();
      String chunks ;
      while((chunks = buff.readLine()) != null)
      {
         dta.append(chunks);
      }
 }
 else
 {
     //Handle else
 }

How to get the name of the current Windows user in JavaScript

Working for me on IE:

<script type="text/javascript">
  var WinNetwork = new ActiveXObject("WScript.Network");
  document.write(WinNetwork.UserName);
</script>

...but ActiveX controls needs to be on in security settings.

How can I check if an argument is defined when starting/calling a batch file?

Get rid of the parentheses.

Sample batch file:

echo "%1"

if ("%1"=="") echo match1

if "%1"=="" echo match2

Output from running above script:

C:\>echo "" 
""

C:\>if ("" == "") echo match1 

C:\>if "" == "" echo match2 
match2

I think it is actually taking the parentheses to be part of the strings and they are being compared.

How to fix Subversion lock error

We had the same repeating problem. It's a disaster. What can you do if cleanup and unlock does not help because there is no existing lock?

  1. Search the hidden .svn folder in your directory structure. It contains a wc.db file which is an sql lite file.
  2. Open it with an sql client, e.g. DBeaver. Add an sql lite connection to the dbeaver by selecting the wc.db file.
  3. Open the WC_LOCK table. You can see one or more rows that contains the URL which was mentioned in the phantom lock error window.
  4. Delete these rows from the table.
  5. Try to update your project from the repo.
  6. If you use more than 1 repo in 1 project (externals) another phantom lock may appear during the update. In this case repeat the process with that folder.

Best way to test for a variable's existence in PHP; isset() is clearly broken

Object properties can be checked for existence by property_exists

Example from a unit test:

function testPropertiesExist()
{
    $sl =& $this->system_log;
    $props = array('log_id',
                   'type',
                   'message',
                   'username',
                   'ip_address',
                   'date_added');

    foreach($props as $prop) {
        $this->assertTrue(property_exists($sl, $prop),
                           "Property <{$prop}> exists");
    }
}

ASP.net vs PHP (What to choose)

There are a couple of topics that might provide you with an answer. You could also run some tests yourself. Doesn't see too hard to get some loops started and adding a timer to calculate the execution time ;-)

Determining if a number is prime

I follow same algorithm but different implementation that loop to sqrt(n) with step 2 only odd numbers because I check that if it is divisible by 2 or 2*k it is false. Here is my code

public class PrimeTest {

    public static boolean isPrime(int i) {
        if (i < 2) {
            return false;
        } else if (i % 2 == 0 && i != 2) {
            return false;
        } else {
            for (int j = 3; j <= Math.sqrt(i); j = j + 2) {
                if (i % j == 0) {
                    return false;
                }
            }
            return true;
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        for (int i = 1; i < 100; i++) {
            if (isPrime(i)) {
                System.out.println(i);
            }
        }
    }

}

Convert character to ASCII numeric value in java

The several answers that purport to show how to do this are all wrong because Java characters are not ASCII characters. Java uses a multibyte encoding of Unicode characters. The Unicode character set is a super set of ASCII. So there can be characters in a Java string that do not belong to ASCII. Such characters do not have an ASCII numeric value, so asking how to get the ASCII numeric value of a Java character is unanswerable.

But why do you want to do this anyway? What are you going to do with the value?

If you want the numeric value so you can convert the Java String to an ASCII string, the real question is "how do I encode a Java String as ASCII". For that, use the object StandardCharsets.US_ASCII.

How to find lines containing a string in linux

The usual way to do this is with grep, which uses a pattern to match lines:

grep 'pattern' file

Each line which matches the pattern will be output. If you want to search for fixed strings only, use grep -F 'pattern' file.

Conversion failed when converting the nvarchar value ... to data type int

I have faced to the same problem, i deleted the constraint for the column in question and it worked for me. You can check the folder Constraints.

Capture :

enter image description here

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

I used file_get_contents using stream_create_context and it works fine:

$postdataStr = http_build_query($postdataArr);

$context_options = array (
        'http' => array (    <blink> // this will allways be http!!!</blink>
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($postdataArr) . "\r\n"
                . "Cookie: " . $cookies."\r\n"
            'content' => $postdataStr
            )
        );

$context = stream_context_create($context_options);
$HTTPSReq = file_get_contents('https://www.example.com/', false, $context);

What is the command to truncate a SQL Server log file?

For SQL 2008 you can backup log to nul device:

BACKUP LOG [databaseName]
TO DISK = 'nul:' WITH STATS = 10

And then use DBCC SHRINKFILE to truncate the log file.

Iteration over std::vector: unsigned vs signed index variable

A bit of history:

To represent whether a number is negative or not computer use a 'sign' bit. int is a signed data type meaning it can hold positive and negative values (about -2billion to 2billion). Unsigned can only store positive numbers (and since it doesn't waste a bit on metadata it can store more: 0 to about 4billion).

std::vector::size() returns an unsigned, for how could a vector have negative length?

The warning is telling you that the right operand of your inequality statement can hold more data then the left.

Essentially if you have a vector with more then 2 billion entries and you use an integer to index into you'll hit overflow problems (the int will wrap back around to negative 2 billion).

How to call loading function with React useEffect only once

function useOnceCall(cb, condition = true) {
  const isCalledRef = React.useRef(false);

  React.useEffect(() => {
    if (condition && !isCalledRef.current) {
      isCalledRef.current = true;
      cb();
    }
  }, [cb, condition]);
}

and use it.

useOnceCall(()=>{
  console.log('called');
})

or

useOnceCall(()=>{
  console.log('isLoading');
},isLoading);

jQuery 1.9 .live() is not a function

The jQuery API documentation lists live() as deprecated as of version 1.7 and removed as of version 1.9: link.

version deprecated: 1.7, removed: 1.9

Furthermore it states:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()

PySpark: multiple conditions in when clause

it should works at least in pyspark 2.4

tdata = tdata.withColumn("Age",  when((tdata.Age == "") & (tdata.Survived == "0") , "NewValue").otherwise(tdata.Age))

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

You don't fetch a branch, you fetch an entire remote:

git fetch origin
git merge origin/an-other-branch

How do I convert two lists into a dictionary?

method without zip function

l1 = [1,2,3,4,5]
l2 = ['a','b','c','d','e']
d1 = {}
for l1_ in l1:
    for l2_ in l2:
        d1[l1_] = l2_
        l2.remove(l2_)
        break  

print (d1)


{1: 'd', 2: 'b', 3: 'e', 4: 'a', 5: 'c'}

VBA (Excel) Initialize Entire Array without Looping

You can initialize the array by specifying the dimensions. For example

Dim myArray(10) As Integer
Dim myArray(1 to 10) As Integer

If you are working with arrays and if this is your first time then I would recommend visiting Chip Pearson's WEBSITE.

What does this initialize to? For example, what if I want to initialize the entire array to 13?

When you want to initailize the array of 13 elements then you can do it in two ways

Dim myArray(12) As Integer
Dim myArray(1 to 13) As Integer

In the first the lower bound of the array would start with 0 so you can store 13 elements in array. For example

myArray(0) = 1
myArray(1) = 2
'
'
'
myArray(12) = 13

In the second example you have specified the lower bounds as 1 so your array starts with 1 and can again store 13 values

myArray(1) = 1
myArray(2) = 2
'
'
'
myArray(13) = 13

Wnen you initialize an array using any of the above methods, the value of each element in the array is equal to 0. To check that try this code.

Sub Sample()
    Dim myArray(12) As Integer
    Dim i As Integer

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print myArray(i)
    Next i
End Sub

or

Sub Sample()
    Dim myArray(1 to 13) As Integer
    Dim i As Integer

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print myArray(i)
    Next i
End Sub

FOLLOWUP FROM COMMENTS

So, in this example every value would be 13. So if I had an array Dim myArray(300) As Integer, all 300 elements would hold the value 13

Like I mentioned, AFAIK, there is no direct way of achieving what you want. Having said that here is one way which uses worksheet function Rept to create a repetitive string of 13's. Once we have that string, we can use SPLIT using "," as a delimiter. But note this creates a variant array but can be used in calculations.

Note also, that in the following examples myArray will actually hold 301 values of which the last one is empty - you would have to account for that by additionally initializing this value or removing the last "," from sNum before the Split operation.

Sub Sample()
    Dim sNum As String
    Dim i As Integer
    Dim myArray

    '~~> Create a string with 13 three hundred times separated by comma
    '~~> 13,13,13,13...13,13 (300 times)
    sNum = WorksheetFunction.Rept("13,", 300)
    sNum = Left(sNum, Len(sNum) - 1)

    myArray = Split(sNum, ",")

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print myArray(i)
    Next i
End Sub

Using the variant array in calculations

Sub Sample()
    Dim sNum As String
    Dim i As Integer
    Dim myArray

    '~~> Create a string with 13 three hundred times separated by comma
    sNum = WorksheetFunction.Rept("13,", 300)
    sNum = Left(sNum, Len(sNum) - 1)

    myArray = Split(sNum, ",")

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print Val(myArray(i)) + Val(myArray(i))
    Next i
End Sub

Datetime equal or greater than today in MySQL

If 'created' is datetime type

SELECT * FROM users WHERE created < DATE_ADD(CURDATE(), INTERVAL 1 DAY);

CURDATE() means also '2013-05-09 00:00:00'

Hibernate error: ids for this class must be manually assigned before calling save():

Resolved this problem using a Sequence ID defined in Oracle database.

ORACLE_DB_SEQ_ID is defined as a sequence for the table. Also look at the console to see the Hibernate SQL that is used to verify.

@Id
@Column(name = "MY_ID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "id_Sequence")
@SequenceGenerator(name = "id_Sequence", sequenceName = "ORACLE_DB_SEQ_ID")
Long myId;

How to search multiple columns in MySQL?

1)

select *
from employee em
where CONCAT(em.firstname, ' ', em.lastname) like '%parth pa%';

2)

select *
from employee em
where CONCAT_ws('-', em.firstname, em.lastname) like '%parth-pa%';

First is usefull when we have data like : 'firstname lastname'.

e.g

  • parth patel
  • parth p
  • patel parth

Second is usefull when we have data like : 'firstname-lastname'. In it you can also use special characters.

e.g

  • parth-patel
  • parth_p
  • patel#parth

make bootstrap twitter dialog modal draggable

$("#myModal").draggable({
    handle: ".modal-header"
}); 

it works for me. I got it from there. if you give me thanks please give 70% to Andres Ilich

How to resize a custom view programmatically?

I used this way to increase width of custom view

customDrawingView.post(new Runnable() {
                            @Override
                            public void run() {
                                View view_instance = customDrawingView;
                                android.view.ViewGroup.LayoutParams params = view_instance
                                        .getLayoutParams();
                                int newLayoutWidth = customDrawingView
                                        .getWidth()
                                        + customDrawingView.getWidth();
                                params.width = newLayoutWidth;
                                view_instance.setLayoutParams(params);
                                screenWidthBackup = params.width;
                            }
                        });

C - function inside struct

You can pass the struct pointer to function as function argument. It called pass by reference.

If you modify something inside that pointer, the others will be updated to. Try like this:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;
};

pno AddClient(client_t *client)
{
        /* this will change the original client value */
        client.password = "secret";
}

int main()
{
    client_t client;

    //code ..

    AddClient(&client);
}

Printing all global variables/local variables?

In addition, since info locals does not display the arguments to the function you're in, use

(gdb) info args

For example:

int main(int argc, char *argv[]) {
    argc = 6*7;    //Break here.
    return 0;
}

argc and argv won't be shown by info locals. The message will be "No locals."

Reference: info locals command.

Get element by id - Angular2

if you want to set value than you can do the same in some function on click or on some event fire.

also you can get value using ViewChild using local variable like this

<input type='text' id='loginInput' #abc/>

and get value like this

this.abc.nativeElement.value

here is working example

Update

okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this

ngAfterViewInit(){
    document.getElementById('loginInput').value = '123344565';
  }

ngAfterViewInit will not throw any error because it will render after template loading

RichTextBox (WPF) does not have string property "Text"

RichTextBox rtf = new RichTextBox();
System.IO.MemoryStream stream = new System.IO.MemoryStream(ASCIIEncoding.Default.GetBytes(yourText));

rtf.Selection.Load(stream, DataFormats.Rtf);

OR

rtf.Selection.Text = yourText;

In MVC, how do I return a string result?

As of 2020, using ContentResult is still the right approach as proposed above, but the usage is as follows:

return new System.Web.Mvc.ContentResult
{
    Content = "Hi there! ?",
    ContentType = "text/plain; charset=utf-8"
}

How to set an "Accept:" header on Spring RestTemplate request?

If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...

private HttpHeaders createHttpHeaders(String user, String password)
{
    String notEncoded = user + ":" + password;
    String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Basic " + encodedAuth);
    return headers;
}

private void doYourThing() 
{
    String theUrl = "http://blah.blah.com:8080/rest/api/blah";
    RestTemplate restTemplate = new RestTemplate();
    try {
        HttpHeaders headers = createHttpHeaders("fred","1234");
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
        System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
    }
    catch (Exception eek) {
        System.out.println("** Exception: "+ eek.getMessage());
    }
}

Padding or margin value in pixels as integer using jQuery

You could also extend the jquery framework yourself with something like:

jQuery.fn.margin = function() {
var marginTop = this.outerHeight(true) - this.outerHeight();
var marginLeft = this.outerWidth(true) - this.outerWidth();

return {
    top: marginTop,
    left: marginLeft
}};

Thereby adding a function on your jquery objects called margin(), which returns a collection like the offset function.

fx.

$("#myObject").margin().top

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

Execute the following command:

git pull origin master --allow-unrelated-histories

A merge vim will open. Add some merging message and:

  1. Press ESC
  2. Press Shift + ';'
  3. Press 'w' and then press 'q'.

And you are good to go.

Sending simple message body + file attachment using Linux Mailx

The best way is to use mpack!

mpack -s "Subject" -d "./body.txt" "././image.png" mailadress

mpack - subject - body - attachment - mailadress

REST / SOAP endpoints for a WCF service

You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>

An example of endpoint configuration in your scenario is

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>

so, the service will be available at

Apply [WebGet] to the operation contract to make it RESTful. e.g.

public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}

Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.

Reply to the post for SOAP and RESTful POX(XML)

For plain old XML as return format, this is an example that would work both for SOAP and XML.

[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}

POX behavior for REST Plain Old XML

<behavior name="poxBehavior">
  <webHttp/>
</behavior>

Endpoints

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>

Service will be available at

REST request try it in browser,

http://www.example.com/xml/accounts/A123

SOAP request client endpoint configuration for SOAP service after adding the service reference,

  <client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>

in C#

TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");

Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.

Window.open and pass parameters by post method

Instead of writing a form into the new window (which is tricky to get correct, with encoding of values in the HTML code), just open an empty window and post a form to it.

Example:

<form id="TheForm" method="post" action="test.asp" target="TheWindow">
<input type="hidden" name="something" value="something" />
<input type="hidden" name="more" value="something" />
<input type="hidden" name="other" value="something" />
</form>

<script type="text/javascript">
window.open('', 'TheWindow');
document.getElementById('TheForm').submit();
</script>

Edit:

To set the values in the form dynamically, you can do like this:

function openWindowWithPost(something, additional, misc) {
  var f = document.getElementById('TheForm');
  f.something.value = something;
  f.more.value = additional;
  f.other.value = misc;
  window.open('', 'TheWindow');
  f.submit();
}

To post the form you call the function with the values, like openWindowWithPost('a','b','c');.

Note: I varied the parameter names in relation to the form names to show that they don't have to be the same. Usually you would keep them similar to each other to make it simpler to track the values.

is python capable of running on multiple cores?

Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.

How to check if an environment variable exists and get its value?

There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.

You can check if a variable is defined:

if [ -z "$a" ]
then
    echo "not defined"
else 
    echo "defined"
fi

and then set a default value for undefined variables or do something else.

The -z checks for a zero-length (i.e. empty) string. See man bash and look for the CONDITIONAL EXPRESSIONS section.

You can also use set -u at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.

CSS endless rotation animation

Without any prefixes, e.g. at it's simplest:

.loading-spinner {
  animation: rotate 1.5s linear infinite;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

Postgres: INSERT if does not exist already

There is a nice way of doing conditional INSERT in PostgreSQL using WITH query: Like:

WITH a as(
select 
 id 
from 
 schema.table_name 
where 
 column_name = your_identical_column_value
)
INSERT into 
 schema.table_name
(col_name1, col_name2)
SELECT
    (col_name1, col_name2)
WHERE NOT EXISTS (
     SELECT
         id
     FROM
         a
        )
  RETURNING id 

How to find the Center Coordinate of Rectangle?

Center x = x + 1/2 of width

Center y = y + 1/2 of height 

If you know the width and height already then you only need one set of coordinates.

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

How to unload a package without restarting R

I would like to add an alternative solution. This solution does not directly answer your question on unloading a package but, IMHO, provides a cleaner alternative to achieve your desired goal, which I understand, is broadly concerned with avoiding name conflicts and trying different functions, as stated:

mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use

Solution

Function with_package offered via the withr package offers the possibility to:

attache a package to the search path, executes the code, then removes the package from the search path. The package namespace is not unloaded, however.

Example

library(withr)
with_package("ggplot2", {
  ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context 
exists("geom_point")
# [1] FALSE

geom_point used in the example is not accessible from the global namespace. I reckon it may be a cleaner way of handling conflicts than loading and unloading packages.

In python, what is the difference between random.uniform() and random.random()?

According to the documentation on random.uniform:

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

while random.random:

Return the next random floating point number in the range [0.0, 1.0).

I.e. with random.uniform you specify a range you draw pseudo-random numbers from, e.g. between 3 and 10. With random.random you get a number between 0 and 1.

Using the Web.Config to set up my SQL database connection string?

Web.config file

<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;    Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>

.cs file

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

Can you write virtual functions / methods in Java?

All non-private instance methods are virtual by default in Java.

In C++, private methods can be virtual. This can be exploited for the non-virtual-interface (NVI) idiom. In Java, you'd need to make the NVI overridable methods protected.

From the Java Language Specification, v3:

8.4.8.1 Overriding (by Instance Methods) An instance method m1 declared in a class C overrides another instance method, m2, declared in class A iff all of the following are true:

  1. C is a subclass of A.
  2. The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
  3. Either * m2 is public, protected or declared with default access in the same package as C, or * m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.

How to check Network port access and display useful message?

I tried to improve the suggestion from mshutov. I added the option to use the output as an object.

 function Test-Port($hostname, $port)
    {
    # This works no matter in which form we get $host - hostname or ip address
    try {
        $ip = [System.Net.Dns]::GetHostAddresses($hostname) | 
            select-object IPAddressToString -expandproperty  IPAddressToString
        if($ip.GetType().Name -eq "Object[]")
        {
            #If we have several ip's for that address, let's take first one
            $ip = $ip[0]
        }
    } catch {
        Write-Host "Possibly $hostname is wrong hostname or IP"
        return
    }
    $t = New-Object Net.Sockets.TcpClient
    # We use Try\Catch to remove exception info from console if we can't connect
    try
    {
        $t.Connect($ip,$port)
    } catch {}

    if($t.Connected)
    {
        $t.Close()
        $object = [pscustomobject] @{
                        Hostname = $hostname
                        IP = $IP
                        TCPPort = $port
                        GetResponse = $True }
        Write-Output $object
    }
    else
    {
        $object = [pscustomobject] @{
                        Computername = $IP
                        TCPPort = $port
                        GetResponse = $False }
        Write-Output $object

    }
    Write-Host $msg
}

Find duplicate records in a table using SQL Server

Just add all fields to the query and remember to add them to Group By as well.

Select shoppername, a, b, amountpayed, item, count(*) as cnt
from dbo.sales
group by shoppername, a, b, amountpayed, item
having count(*) > 1

How to get subarray from array?

Take a look at Array.slice(begin, end)

_x000D_
_x000D_
const ar  = [1, 2, 3, 4, 5];

// slice from 1..3 - add 1 as the end index is not included

const ar2 = ar.slice(1, 3 + 1);

console.log(ar2);
_x000D_
_x000D_
_x000D_

Selecting multiple classes with jQuery

// Due to this Code ): Syntax problem.    
$('.myClass', '.myOtherClass').removeClass('theclass'); 

According to jQuery documentation: https://api.jquery.com/multiple-selector/

When can select multiple classes in this way:

jQuery(“selector1, selector2, selectorN”) // double Commas. // IS valid.
jQuery('selector1, selector2, selectorN') // single Commas. // Is valid.

by enclosing all the selectors in a single '...' ' or double commas, "..."

So in your case the correct way to call multiple classes is:

$('.myClass', '.myOtherClass').removeClass('theclass'); // your Code // Invalid.
$('.myClass , .myOtherClass').removeClass('theclass');  // Correct Code // Is valid.

What is the difference between a static and a non-static initialization code block

"final" guarantees that a variable must be initialized before end of object initializer code. Likewise "static final" guarantees that a variable will be initialized by the end of class initialization code. Omitting the "static" from your initialization code turns it into object initialization code; thus your variable no longer satisfies its guarantees.

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

You could just create a new database and then go to tasks, import data, and import all the data from the database you want to duplicate to the database you just created.

How to Get a Specific Column Value from a DataTable?

I suggest such way based on extension methods:

IEnumerable<Int32> countryIDs =
    dataTable
    .AsEnumerable()
    .Where(row => row.Field<String>("CountryName") == countryName)
    .Select(row => row.Field<Int32>("CountryID"));

System.Data.DataSetExtensions.dll needs to be referenced.

Convert String to double in Java

To convert a string back into a double, try the following

String s = "10.1";
Double d = Double.parseDouble(s);

The parseDouble method will achieve the desired effect, and so will the Double.valueOf() method.

Set cookie and get cookie with JavaScript

I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.

This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Mozilla has some tests to prove this works in all cases.

There is an alternative snippet here:

Saving and loading objects and using pickle

You didn't open the file in binary mode.

open("Fruits.obj",'rb')

Should work.

For your second error, the file is most likely empty, which mean you inadvertently emptied it or used the wrong filename or something.

(This is assuming you really did close your session. If not, then it's because you didn't close the file between the write and the read).

I tested your code, and it works.

Getting the source of a specific image element with jQuery

If you do not specifically need the alt text of an image, then you can just target the class/id of the image.

$('img.propImg').each(function(){ 
     enter code here
}

I know it’s not quite answering the question, though I’d spent ages trying to figure this out and this question gave me the solution :). In my case I needed to hide any image tags with a specific src.

$('img.propImg').each(function(){ //for each loop that gets all the images. 
        if($(this).attr('src') == "img/{{images}}") { // if the src matches this
        $(this).css("display", "none") // hide the image.
    }
});

Illegal mix of collations error in MySql

In short, this error is caused by MySQL trying to do an operation on two things which have different collation settings. If you make the settings match, the error will go away. Of course, you need to choose the right setting for your database, depending on what it is going to be used for.

Here's some good advice on choosing between two very common utf8 collations: What's the difference between utf8_general_ci and utf8_unicode_ci

If you are using phpMyAdmin you can do this systematically by working through the tables mentioned in your error message, and checking the collation type for each column. First you should check which is the overall collation setting for your database - phpMyAdmin can tell you this and change it if necessary. But each column in each table can have its own setting. Normally you will want all these to match.

In a small database this is easy enough to do by hand, and in any case if you read the error message in full it will usually point you to the right place. Don't forget to look at the 'structure' settings for columns with subtables in as well. When you find a collation that does not match you can change it using phpMyAdmin directly, no need to use the query window. Then try your operation again. If the error persists, keep looking!

Remove by _id in MongoDB console

Well, the _id is an object in your example, so you just need to pass an object

'db.test_users.remove({"_id": { "$oid" : "4d513345cc9374271b02ec6c" }})'

This should work

Edit: Added trailing paren to ensure that it compiled.

How to properly stop the Thread in Java?

Simple answer: You can stop a thread INTERNALLY in one of two common ways:

  • The run method hits a return subroutine.
  • Run method finishes, and returns implicitly.

You can also stop threads EXTERNALLY:

  • Call system.exit (this kills your entire process)
  • Call the thread object's interrupt() method *
  • See if the thread has an implemented method that sounds like it would work (like kill() or stop())

*: The expectation is that this is supposed to stop a thread. However, what the thread actually does when this happens is entirely up to what the developer wrote when they created the thread implementation.

A common pattern you see with run method implementations is a while(boolean){}, where the boolean is typically something named isRunning, it's a member variable of its thread class, it's volatile, and typically accessible by other threads by a setter method of sorts, e.g. kill() { isRunnable=false; }. These subroutines are nice because they allow the thread to release any resources it holds before terminating.

Positioning background image, adding padding

this is actually pretty easily done. You're almost there, doing what you've done with background-position: right center;. What is actually needed in this case is something very much like that. Let's convert these to percentages. We know that center=50%, so that's easy enough. Now, in order to get the padding you wanted, you need to position the background like so: background-position: 99% 50%.

The second, and more effective way of going about this, is to use the same background-position idea, and just use background-position: 400px (width of parent) 50%;. Of course, this method requires a static width, but will give you the same thing every time.

Method 1 (99% 50%)
Method 2 (400px 50%)

How to overcome root domain CNAME restrictions?

The reason this question still often arises is because, as you mentioned, somewhere somehow someone presumed as important wrote that the RFC states domain names without subdomain in front of them are not valid. If you read the RFC carefully, however, you'll find that this is not exactly what it says. In fact, RFC 1912 states:

Don't go overboard with CNAMEs. Use them when renaming hosts, but plan to get rid of them (and inform your users).

Some DNS hosts provide a way to get CNAME-like functionality at the zone apex (the root domain level, for the naked domain name) using a custom record type. Such records include, for example:

  • ALIAS at DNSimple
  • ANAME at DNS Made Easy
  • ANAME at easyDNS
  • CNAME at CloudFlare

For each provider, the setup is similar: point the ALIAS or ANAME entry for your apex domain to example.domain.com, just as you would with a CNAME record. Depending on the DNS provider, an empty or @ Name value identifies the zone apex.

ALIAS or ANAME or @ example.domain.com.

If your DNS provider does not support such a record-type, and you are unable to switch to one that does, you will need to use subdomain redirection, which is not that hard, depending on the protocol or server software that needs to do it.

I strongly disagree with the statement that it's done only by "amateur admins" or such ideas. It's a simple "What does the name and its service need to do?" deal, and then to adapt your DNS config to serve those wishes; If your main services are web and e-mail, I don' t see any VALID reason why dropping the CNAMEs for-good would be problematic. After all, who would prefer @subdomain.domain.org over @domain.org ? Who needs "www" if you're already set with the protocol itself? It's illogical to assume that use of a root-domainname would be invalid.

java.net.ConnectException :connection timed out: connect?

Exception : java.net.ConnectException

This means your request didn't getting response from server in stipulated time. And their are some reasons for this exception:

  • Too many requests overloading the server
  • Request packet loss because of wrong network configuration or line overload
  • Sometimes firewall consume request packet before sever getting
  • Also depends on thread connection pool configuration and current status of connection pool
  • Response packet lost during transition

C++ Boost: undefined reference to boost::system::generic_category()

Same problem on building a simple boost example, solved after i changed the g++ compiler flag from -std=c++14 to -std=c++11.

And I noticed that it's a C++11 Example...

Python: How to create a unique file name?

If you want to make temporary files in Python, there's a module called tempfile in Python's standard libraries. If you want to launch other programs to operate on the file, use tempfile.mkstemp() to create files, and os.fdopen() to access the file descriptors that mkstemp() gives you.

Incidentally, you say you're running commands from a Python program? You should almost certainly be using the subprocess module.

So you can quite merrily write code that looks like:

import subprocess
import tempfile
import os

(fd, filename) = tempfile.mkstemp()
try:
    tfile = os.fdopen(fd, "w")
    tfile.write("Hello, world!\n")
    tfile.close()
    subprocess.Popen(["/bin/cat", filename]).wait()        
finally:
    os.remove(filename)

Running that, you should find that the cat command worked perfectly well, but the temporary file was deleted in the finally block. Be aware that you have to delete the temporary file that mkstemp() returns yourself - the library has no way of knowing when you're done with it!

(Edit: I had presumed that NamedTemporaryFile did exactly what you're after, but that might not be so convenient - the file gets deleted immediately when the temp file object is closed, and having other processes open the file before you've closed it won't work on some platforms, notably Windows. Sorry, fail on my part.)

Laravel Eloquent limit and offset

Please try like this,

return Article::where('id',$article)->with(['products'=>function($products, $offset, $limit) {
    return $products->offset($offset*$limit)->limit($limit);
}])

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

The advantages of EditorFor is that your code is not tied to an <input type="text". So if you decide to change something to the aspect of how your textboxes are rendered like wrapping them in a div you could simply write a custom editor template (~/Views/Shared/EditorTemplates/string.cshtml) and all your textboxes in your application will automatically benefit from this change whereas if you have hardcoded Html.TextBoxFor you will have to modify it everywhere. You could also use Data Annotations to control the way this is rendered.

Array as session variable

Yes, PHP supports arrays as session variables. See this page for an example.

As for your second question: once you set the session variable, it will remain the same until you either change it or unset it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.

Adding Apostrophe in every field in particular column for excel

The way I'd do this is:

  • In Cell L2, enter the formula ="'"&K2
  • Use the fill handle or Ctrl+D to fill it down to the length of Column K's values.
  • Select the whole of Column L's values and copy them to the clipboard
  • Select the same range in Column K, right-click to select 'Paste Special' and choose 'Values'

Launch an event when checking a checkbox in Angular2

You can use ngModel like

<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>

To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.

can't start MySql in Mac OS 10.6 Snow Leopard

First of all can I just say that I really really love the Internet community for all that it does in providing answers to everybody. I don't post a lot but everybody's posting here and on so many boards helped me so much! None of them gave me the right answer mind you, but here is my unique solution to this nightmare of a spending 2 solid days trying to install MySQL 5.5.9 on Snow Leopard 10.6. Skip to bottom for resolution.

Here's what happened.

I had a server crash recently. The server was rebuilt and of course MySQL 5.5.8 didn't work. What a worthless piece. I had 5.1.54 on my other machine. That had been a pain to install as well but not like this.

I had all sorts of issues installing with the dmg from mysql.org, installing mysql5 using macports, uninstalling trying to revert to 5.1.54 (couldn't because I couldn't find the receipt file with that info even though I followed the directions). After rming everything I could find related to mysql and then reinstalling 5.5.8 everything worked! Until I rebooted... ? I looked in my system preference mysql pane and found mysql server wasn't starting. (skip to end for resolution)

My first error (super common) included: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' and numerous other EXTREMELY common issues related to mysql.sock http://forums.mysql.com/read.php?11,9689,13272

Here were things I tried: 1)Create /etc/my.cnf file with the proper paths to mysql.sock. I even tried modifying mysql.server with vi directly. Modifying the php.ini was worthless. Nothing worked because MySQL wasn't starting, therefore it wasn't creating mysql.sock in the first place. Maybe you can point to the directory it is being created, and not the actual full file path i.e. not /tmp/mysql.sock but /tmp It was suggested but wasn't working because there was no mysql.sock because mysqld wasn't spawning.

2)Basedir and datadir modifications didn't work because there was no mysql.sock to point too.

Why? Because the mysql daemon wasn't starting. Without anything to start mysqld and thereby create mysql.sock I was doomed. They are an important part of the solution but if you try them and still get errors, you will know why.

3)sudo chown -R root:wheel /Library/StartupItems/MySQLCOM/

didn't solve my problem. I ended up having that folder and all items set to root:wheel though in the end, because it was one of the many things recommended and its working. Maybe it could remain _mysql but wheel works.

4)Copy mysql.sock from another machine. Doesn't work. I had searched and searched my new machine and couldn't find mysql.sock. I was using find / | grep mysql.sock because locate mysql wasn't finding anything. Besides I was trying so many different things it wasn't updating enough to find my new installs. I now like find much more than locate, even though you can update the locate db. Anyhow you can't copy mysql.sock, even if you tar it because its a 0 byte file.

THE RESOLUTION: I finally stumbled onto the solution. I finally just typed mysqld from command line while I was in the proper bin directory. It said another process was running. _mysql was spawning a process that I could see in the Activity Monitor. I killed the active mysql process and when I typed mysqld again I found it was creating my mysql.sock file in the /private/tmp/mysql.sock

The mysql pref pane wouldn't start the right process on login, so I just disabled that for being worthless. It wouldn't start mysql because no mysql.sock was being created.

By then I had figured out that mysqld creates mysql.sock. I then found /opt/local/mysql/ and typed "open bin" in the terminal window. This opened the directory with mysqld in it.

I went to login items in the system preferences in my account settings and dragged and dropped the mysqld file onto the startup items there. THAT worked. Finally!

It works flawlessly because mysqld is starting up at login, which means mysql.sock is being created so no more errors about not being able to find mysql.sock.

What's a good way to extend Error in JavaScript?

The only standard field Error object has is the message property. (See MDN, or EcmaScript Language Specification, section 15.11) Everything else is platform specific.

Mosts environments set the stack property, but fileName and lineNumber are practically useless to be used in inheritance.

So, the minimalistic approach is:

function MyError(message) {
    this.name = 'MyError';
    this.message = message;
    this.stack = (new Error()).stack;
}
MyError.prototype = new Error;  // <-- remove this if you do not 
                                //     want MyError to be instanceof Error

You could sniff the stack, unshift unwanted elements from it and extract information like fileName and lineNumber, but doing so requires information about the platform JavaScript is currently running upon. Most cases that is unnecessary -- and you can do it in post-mortem if you really want.

Safari is a notable exception. There is no stack property, but the throw keyword sets sourceURL and line properties of the object that is being thrown. Those things are guaranteed to be correct.

Test cases I used can be found here: JavaScript self-made Error object comparison.

Convert date time string to epoch in Bash

Just be sure what timezone you want to use.

datetime="06/12/2012 07:21:22"

Most popular use takes machine timezone.

date -d "$datetime" +"%s" #depends on local timezone, my output = "1339456882"

But in case you intentionally want to pass UTC datetime and you want proper timezone you need to add -u flag. Otherwise you convert it from your local timezone.

date -u -d "$datetime" +"%s" #general output = "1339485682"

How do I hide an element when printing a web page?

The best thing to do is to create a "print-only" version of the page.

Oh, wait... this isn't 1999 anymore. Use a print CSS with "display: none".

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

Reading InputStream as UTF-8

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

Clear terminal in Python

If you are on a Linux/UNIX system then printing the ANSI escape sequence to clear the screen should do the job. You will also want to move cursor to the top of the screen. This will work on any terminal that supports ANSI.

import sys
sys.stderr.write("\x1b[2J\x1b[H")

This will not work on Windows unless ANSI support has been enabled. There may be an equivalent control sequence for Windows, but I do not know.

Converting 'ArrayList<String> to 'String[]' in Java

List<String> list = ..;
String[] array = list.toArray(new String[0]);

For example:

List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);

The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.

How to run specific test cases in GoogleTest

Finally I got some answer, ::test::GTEST_FLAG(list_tests) = true; //From your program, not w.r.t console.

If you would like to use --gtest_filter =*; /* =*, =xyz*... etc*/ // You need to use them in Console.

So, my requirement is to use them from the program not from the console.

Updated:-

Finally I got the answer for updating the same in from the program.

 ::testing::GTEST_FLAG(filter) = "*Counter*:*IsPrime*:*ListenersTest.DoesNotLeak*";//":-:*Counter*";
      InitGoogleTest(&argc, argv);
RUN_ALL_TEST();

So, Thanks for all the answers.

You people are great.

GridView sorting: SortDirection always Ascending

It's been awhile since I used a GridView, but I think you need to set the grid's SortDirection property to whatever it currently is before leaving the OnSorting method.

So....

List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();
items.Sort(new Helpers.GenericComparer<V_ReportPeriodStatusEntity>(e.SortExpression, e.SortDirection));
grdHeader.SortDirection = e.SortDirection.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
grdHeader.DataSource = items;
grdHeader.DataBind();

Visual Studio 2015 doesn't have cl.exe

Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++

A Generic error occurred in GDI+ in Bitmap.Save method

for me it was a path issue when saving the image.

int count = Directory.EnumerateFiles(System.Web.HttpContext.Current.Server.MapPath("~/images/savedimages"), "*").Count();

var img = Base64ToImage(imgRaw);

string path = "images/savedimages/upImages" + (count + 1) + ".png";

img.Save(Path.Combine(System.Web.HttpContext.Current.Server.MapPath(path)));

return path;

So I fixed it by adding the following forward slash

String path = "images/savedimages....

should be

String path = "/images/savedimages....

Hope that helps anyone stuck!

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

How to get a Color from hexadecimal Color String

Try:

myLayout.setBackgroundColor(Color.parseColor("#636161"));

How to display both icon and title of action inside ActionBar?

Using app:showAsAction="always|withText". I am using Android 4.1.1, but it should applicable anyway. Mine look like below

<item
        android:id="@+id/action_sent_current_data"
        android:icon="@drawable/ic_upload_cloud"
        android:orderInCategory="100"
        android:title="@string/action_sent_current_data"
        app:showAsAction="always|withText"/>

how to modify the size of a column

If you run it, it will work, but in order for SQL Developer to recognize and not warn about a possible error you can change it as:

ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(300));

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

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

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

echo %WORKSPACE%

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

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

The output of the above is

Normal Expansion = BEFORE
Delayed Expansion = AFTER

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

String to Dictionary in Python

Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.

>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}

WPF - add static items to a combo box

You can also add items in code:

cboWhatever.Items.Add("SomeItem");

Also, to add something where you control display/value, (almost categorically needed in my experience) you can do so. I found a good stackoverflow reference here:

Key Value Pair Combobox in WPF

Sum-up code would be something like this:

ComboBox cboSomething = new ComboBox();
cboSomething.DisplayMemberPath = "Key";
cboSomething.SelectedValuePath = "Value";
cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I'm using rescu with Kotlin and resolved it by using @ConstructorProperties

    data class MyResponse @ConstructorProperties("message", "count") constructor(
        val message: String,
        val count: Int
    )

Jackson uses @ConstructorProperties. This should fix Lombok @Data as well.

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

When using VS2019, MVC5 - look under Migrations folder for file Configuration.cs Edit : AutomaticMigrationsEnabled = true

    -

Select Last Row in the Table

Don't use Model::latest()->first(); because if your collection has multiple rows created at the same timestamp (this will happen when you use database transaction DB::beginTransaction(); and DB::commit()) then the first row of the collection will be returned and obviously this will not be the last row.

Suppose row with id 11, 12, 13 are created using transaction then all of them will have the same timestamp so what you will get by Model::latest()->first(); is the row with id: 11.

Conversion between UTF-8 ArrayBuffer and String

Using TextEncoder and TextDecoder

var uint8array = new TextEncoder("utf-8").encode("Plain Text");
var string = new TextDecoder().decode(uint8array);
console.log(uint8array ,string )

How can one check to see if a remote file exists using PHP?

You can use :

$url=getimagesize(“http://www.flickr.com/photos/27505599@N07/2564389539/”);

if(!is_array($url))
{
   $default_image =”…/directoryFolder/junal.jpg”;
}

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

Like it has been already mentioned, you are reading the file in binary mode and then creating a list of bytes. In your following for loop you are comparing string to bytes and that is where the code is failing.

Decoding the bytes while adding to the list should work. The changed code should look as follows:

with open(fname, 'rb') as f:
    lines = [x.decode('utf8').strip() for x in f.readlines()]

The bytes type was introduced in Python 3 and that is why your code worked in Python 2. In Python 2 there was no data type for bytes:

>>> s=bytes('hello')
>>> type(s)
<type 'str'>

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

exports.handler = async (event) => {
    let query = event.queryStringParameters;
    console.log(`id: ${query.id}`);
    const response = {
        statusCode: 200,
        body: "Hi",
    };
    return response;
};

pip: no module named _internal

This issue maybe due to common user do not have privilege to access packages py file.
1. root user can run 'pip list'
2. other common user cannot run 'pip list'

[~]$ pip list
Traceback (most recent call last):
  File "/usr/bin/pip", line 7, in <module>
from pip._internal import main
ImportError: No module named pip._internal

Check pip py file privilege.

[root@]# ll /usr/lib/python2.7/site-packages/pip/  
?? 24  
-rw-------  1 root root   24  6?  7 16:57 __init__.py  
-rw-------  1 root root  163  6?  7 16:57 __init__.pyc  
-rw-------  1 root root  629  6?  7 16:57 __main__.py  
-rw-------  1 root root  510  6?  7 16:57 __main__.pyc  
drwx------  8 root root 4096  6?  7 16:57 _internal  
drwx------ 18 root root 4096  6?  7 16:57 _vendor  

solution : root user login and run

chmod -R 755 /usr/lib/python2.7 

fix this issue.

How to create standard Borderless buttons (like in the design guideline mentioned)?

Another solution that should work on both older and newer android platform is to use

android:background="@android:color/transparent"

attribute for Button view. But after adding above line button will not provide touch feedback.

To provide touch feedback add the following code to Activity class

button.setOnTouchListener(new View.OnTouchListener() {          
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:    
                ((Button)view).setBackgroundColor(Color.LTGRAY);
                break;
            case MotionEvent.ACTION_UP:
                ((Button)view).setBackgroundColor(Color.TRANSPARENT);
        }
        return false;
    }
});

Its working fine for me.

Which is better: <script type="text/javascript">...</script> or <script>...</script>

<script type="text/javascript"></script> because its the right way and compatible with all browsers

A Space between Inline-Block List Items

I had the same problem, when I used a inline-block on my menu I had the space between each "li" I found a simple solution, I don't remember where I found it, anyway here is what I did.

<li><a href="index.html" title="home" class="active">Home</a></li><!---->
<li><a href="news.html" title="news">News</a></li><!---->
<li><a href="about.html" title="about">About Us</a></li><!---->
<li><a href="contact.html" title="contact">Contact Us</a></li>

You add a comment sign between each end of, and start of : "li" Then the horizontal space disappear. Hope that answer to the question Thanks

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

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

enter image description here

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

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

Where can I find decent visio templates/diagrams for software architecture?

There should be templates already included in Visio 2007 for software architecture but you might want to check out Visio 2007 templates.

Reading numbers from a text file into an array in C

Loop with %c to read the stream character by character instead of %d.

Laravel: Get base url

To get it to work with non-pretty URLs I had to do:

asset('/');

What are Aggregates and PODs and how/why are they special?

Changes in C++17

Download the C++17 International Standard final draft here.

Aggregates

C++17 expands and enhances aggregates and aggregate initialization. The standard library also now includes an std::is_aggregate type trait class. Here is the formal definition from section 11.6.1.1 and 11.6.1.2 (internal references elided):

An aggregate is an array or a class with
— no user-provided, explicit, or inherited constructors,
— no private or protected non-static data members,
— no virtual functions, and
— no virtual, private, or protected base classes.
[ Note: Aggregate initialization does not allow accessing protected and private base class’ members or constructors. —end note ]
The elements of an aggregate are:
— for an array, the array elements in increasing subscript order, or
— for a class, the direct base classes in declaration order, followed by the direct non-static data members that are not members of an anonymous union, in declaration order.

What changed?

  1. Aggregates can now have public, non-virtual base classes. Furthermore, it is not a requirement that base classes be aggregates. If they are not aggregates, they are list-initialized.
struct B1 // not a aggregate
{
    int i1;
    B1(int a) : i1(a) { }
};
struct B2
{
    int i2;
    B2() = default;
};
struct M // not an aggregate
{
    int m;
    M(int a) : m(a) { }
};
struct C : B1, B2
{
    int j;
    M m;
    C() = default;
};
C c { { 1 }, { 2 }, 3, { 4 } };
cout
    << "is C aggregate?: " << (std::is_aggregate<C>::value ? 'Y' : 'N')
    << " i1: " << c.i1 << " i2: " << c.i2
    << " j: " << c.j << " m.m: " << c.m.m << endl;

//stdout: is C aggregate?: Y, i1=1 i2=2 j=3 m.m=4
  1. Explicit defaulted constructors are disallowed
struct D // not an aggregate
{
    int i = 0;
    D() = default;
    explicit D(D const&) = default;
};
  1. Inheriting constructors are disallowed
struct B1
{
    int i1;
    B1() : i1(0) { }
};
struct C : B1 // not an aggregate
{
    using B1::B1;
};


Trivial Classes

The definition of trivial class was reworked in C++17 to address several defects that were not addressed in C++14. The changes were technical in nature. Here is the new definition at 12.0.6 (internal references elided):

A trivially copyable class is a class:
— where each copy constructor, move constructor, copy assignment operator, and move assignment operator is either deleted or trivial,
— that has at least one non-deleted copy constructor, move constructor, copy assignment operator, or move assignment operator, and
— that has a trivial, non-deleted destructor.
A trivial class is a class that is trivially copyable and has one or more default constructors, all of which are either trivial or deleted and at least one of which is not deleted. [ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]

Changes:

  1. Under C++14, for a class to be trivial, the class could not have any copy/move constructor/assignment operators that were non-trivial. However, then an implicitly declared as defaulted constructor/operator could be non-trivial and yet defined as deleted because, for example, the class contained a subobject of class type that could not be copied/moved. The presence of such non-trivial, defined-as-deleted constructor/operator would cause the whole class to be non-trivial. A similar problem existed with destructors. C++17 clarifies that the presence of such constructor/operators does not cause the class to be non-trivially copyable, hence non-trivial, and that a trivially copyable class must have a trivial, non-deleted destructor. DR1734, DR1928
  2. C++14 allowed a trivially copyable class, hence a trivial class, to have every copy/move constructor/assignment operator declared as deleted. If such as class was also standard layout, it could, however, be legally copied/moved with std::memcpy. This was a semantic contradiction, because, by defining as deleted all constructor/assignment operators, the creator of the class clearly intended that the class could not be copied/moved, yet the class still met the definition of a trivially copyable class. Hence in C++17 we have a new clause stating that trivially copyable class must have at least one trivial, non-deleted (though not necessarily publicly accessible) copy/move constructor/assignment operator. See N4148, DR1734
  3. The third technical change concerns a similar problem with default constructors. Under C++14, a class could have trivial default constructors that were implicitly defined as deleted, yet still be a trivial class. The new definition clarifies that a trivial class must have a least one trivial, non-deleted default constructor. See DR1496

Standard-layout Classes

The definition of standard-layout was also reworked to address defect reports. Again the changes were technical in nature. Here is the text from the standard (12.0.7). As before, internal references are elided:

A class S is a standard-layout class if it:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,
— has no virtual functions and no virtual base classes,
— has the same access control for all non-static data members,
— has no non-standard-layout base classes,
— has at most one base class subobject of any given type,
— has all non-static data members and bit-fields in the class and its base classes first declared in the same class, and
— has no element of the set M(S) of types (defined below) as a base class.108
M(X) is defined as follows:
— If X is a non-union class type with no (possibly inherited) non-static data members, the set M(X) is empty.
— If X is a non-union class type whose first non-static data member has type X0 (where said member may be an anonymous union), the set M(X) consists of X0 and the elements of M(X0).
— If X is a union type, the set M(X) is the union of all M(Ui) and the set containing all Ui, where each Ui is the type of the ith non-static data member of X.
— If X is an array type with element type Xe, the set M(X) consists of Xe and the elements of M(Xe).
— If X is a non-class, non-array type, the set M(X) is empty.
[ Note: M(X) is the set of the types of all non-base-class subobjects that are guaranteed in a standard-layout class to be at a zero offset in X. —end note ]
[ Example:

struct B { int i; }; // standard-layout class
struct C : B { }; // standard-layout class
struct D : C { }; // standard-layout class
struct E : D { char : 4; }; // not a standard-layout class
struct Q {};
struct S : Q { };
struct T : Q { };
struct U : S, T { }; // not a standard-layout class
—end example ]
108) This ensures that two subobjects that have the same class type and that belong to the same most derived object are not allocated at the same address.

Changes:

  1. Clarified that the requirement that only one class in the derivation tree "has" non-static data members refers to a class where such data members are first declared, not classes where they may be inherited, and extended this requirement to non-static bit fields. Also clarified that a standard-layout class "has at most one base class subobject of any given type." See DR1813, DR1881
  2. The definition of standard-layout has never allowed the type of any base class to be the same type as the first non-static data member. It is to avoid a situation where a data member at offset zero has the same type as any base class. The C++17 standard provides a more rigorous, recursive definition of "the set of the types of all non-base-class subobjects that are guaranteed in a standard-layout class to be at a zero offset" so as to prohibit such types from being the type of any base class. See DR1672, DR2120.

Note: The C++ standards committee intended the above changes based on defect reports to apply to C++14, though the new language is not in the published C++14 standard. It is in the C++17 standard.

Elasticsearch query to return all records

If it's a small dataset (e.g. 1K records), you can simply specify size:

curl localhost:9200/foo_index/_search?size=1000

The match all query isn't needed, as it's implicit.

If you have a medium-sized dataset, like 1M records, you may not have enough memory to load it, so you need a scroll.

A scroll is like a cursor in a DB. In Elasticsearch, it remembers where you left off and keeps the same view of the index (i.e. prevents the searcher from going away with a refresh, prevents segments from merging).

API-wise, you have to add a scroll parameter to the first request:

curl 'localhost:9200/foo_index/_search?size=100&scroll=1m&pretty'

You get back the first page and a scroll ID:

{
  "_scroll_id" : "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAADEWbmJlSmxjb2hSU0tMZk12aEx2c0EzUQ==",
  "took" : 0,
...

Remember that both the scroll ID you get back and the timeout are valid for the next page. A common mistake here is to specify a very large timeout (value of scroll), that would cover for processing the whole dataset (e.g. 1M records) instead of one page (e.g. 100 records).

To get the next page, fill in the last scroll ID and a timeout that should last until fetching the following page:

curl -XPOST -H 'Content-Type: application/json' 'localhost:9200/_search/scroll' -d '{
  "scroll": "1m",
  "scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAADAWbmJlSmxjb2hSU0tMZk12aEx2c0EzUQ=="
}'

If you have a lot to export (e.g. 1B documents), you'll want to parallelise. This can be done via sliced scroll. Say you want to export on 10 threads. The first thread would issue a request like this:

curl -XPOST -H 'Content-Type: application/json' 'localhost:9200/test/_search?scroll=1m&size=100' -d '{
  "slice": {
    "id": 0, 
    "max": 10 
  }
}'

You get back the first page and a scroll ID, exactly like a normal scroll request. You'd consume it exactly like a regular scroll, except that you get 1/10th of the data.

Other threads would do the same, except that id would be 1, 2, 3...

Why is "npm install" really slow?

Problem: NPM does not perform well if you do not keep it up to date. However, bleeding edge versions have been broken for me in the past.

Solution: As Kraang mentioned, use node version manager nvm, with its --lts flag

Install it:

curl -o- https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash

Then use this often to upgrade to the latest "long-term support" version of NPM:

nvm install --lts

Big caveat: you'll likely have to reinstall all packages when you get a new npm version.

How can I verify if an AD account is locked?

This ScriptingGuy guest post links to a script by a Microsoft Powershell Expert can help you find this information, but to fully audit why it was locked and which machine triggered the lock you probably need to turn on additional levels of auditing via GPO.

https://gallery.technet.microsoft.com/scriptcenter/Get-LockedOutLocation-b2fd0cab#content

How to convert string to long

You can also try following,

long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);

VB.NET - Click Submit Button on Webbrowser page

I am quite benefited with http://stackoverflow.com. I was wandering from hours for automatic login and submit from vb application to another web site. Due to help of this site I am able to complete my task

I have to login following web php page.

<HTML>

<body>
<div align="center"><img src="banner.png" height="80px" /></div>
<script type="text/javascript">
$(document).ready(function(){
            $("#login").validate();
            $("#login_container").css({'position': 'absolute', 
                'top' : (($(window).height()/2) - $("#login_container").height()/2)+'px'});
            $("#login_container").css({'left' : (($(window).width()/2) - $("#login_container").width()/2)+'px'});
        });
    </script>
    <div id="login_container">
        <form name="login" id="login" action="?q=login" method="post">
        <table>
          <tr><td>Username</td><td><input type="text" name="name" class="required"/></td></tr>
          <tr><td>Password</td><td><input type="password" name="password" class="required"/></td></tr>
          <tr><td></td><td><input type="submit" name="subimt" value="Login" /></td></tr>
        </table>
        </form>
    </div>
</body>
</html>

For automatic Login and clicking I wrote following VB.Net Code. In form1 I placed a button and a Webbrowser control

Imports System.IO
Imports System.Windows.Forms



Public Class Form1


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        WebBrowser1.Navigate("http://xyz.com")



    End Sub

    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        WebBrowser1.Document.GetElementById("name").SetAttribute("Value", "bharatlal")
        WebBrowser1.Document.GetElementById("password").SetAttribute("Value", "mahato")
        WebBrowser1.Document.GetElementById("subimt").Focus()
        WebBrowser1.Document.GetElementById("subimt").InvokeMember("click")
    End Sub
End Class

Convert Json String to C# Object List

using dynamic variable in C# is the simplest.

Newtonsoft.Json.Linq has class JValue that can be used. Below is a sample code which displays Question id and text from the JSON string you have.

        string jsonString = "[{\"Question\":{\"QuestionId\":49,\"QuestionText\":\"Whats your name?\",\"TypeId\":1,\"TypeName\":\"MCQ\",\"Model\":{\"options\":[{\"text\":\"Rahul\",\"selectedMarks\":\"0\"},{\"text\":\"Pratik\",\"selectedMarks\":\"9\"},{\"text\":\"Rohit\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":true,\"selectedOption\":\"1\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"02\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"\",\"S8\":\"\",\"S9\":\"Pratik\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"},{\"Question\":{\"QuestionId\":51,\"QuestionText\":\"Are you smart?\",\"TypeId\":3,\"TypeName\":\"True-False\",\"Model\":{\"options\":[{\"text\":\"True\",\"selectedMarks\":\"7\"},{\"text\":\"False\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":false,\"selectedOption\":\"3\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"01\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"True\",\"S8\":\"\",\"S9\":\"\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"}]";
        dynamic myObject = JValue.Parse(jsonString);
        foreach (dynamic questions in myObject)
        {
            Console.WriteLine(questions.Question.QuestionId + "." + questions.Question.QuestionText.ToString());
        }
        Console.Read();

Output from the code => Output from the code

Java Regex to Validate Full Name allow only Spaces and Letters

This works for me with validation of bootstrap

$(document).ready(function() {
$("#fname").keypress(function(e) {
var regex = new RegExp("^[a-zA-Z ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
 return true;
}

Setting default values to null fields when mapping with Jackson

Looks like the solution is to set the value of the properties inside the default constructor. So in this case the java class is:

class JavaObject {

    public JavaObject() {

        optionalMember = "Value";
    }

    @NotNull
    public String notNullMember;

    public String optionalMember;
}

After the mapping with Jackson, if the optionalMember is missing from the JSON its value in the Java class is "Value".

However, I am still interested to know if there is a solution with annotations and without the default constructor.

How to get Bitmap from an Uri?

Here's the correct way of doing it:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Uri imageUri = data.getData();
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    }
}

If you need to load very large images, the following code will load it in in tiles (avoiding large memory allocations):

BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(myStream, false);  
Bitmap region = decoder.decodeRegion(new Rect(10, 10, 50, 50), null);

See the answer here

How to Validate Google reCaptcha on Form Submit

You can first verify in the frontend side that the checkbox is marked:

    var recaptchaRes = grecaptcha.getResponse();
    var message = "";

    if(recaptchaRes.length == 0) {
        // You can return the message to user
        message = "Please complete the reCAPTCHA challenge!";
        return false;
    } else {
       // Add reCAPTCHA response to the POST
       form.recaptchaRes = recaptchaRes;
    }

And then in the server side verify the received response using Google reCAPTCHA API:

    $receivedRecaptcha = $_POST['recaptchaRes'];
    $verifiedRecaptcha = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$google_secret.'&response='.$receivedRecaptcha);

    $verResponseData = json_decode($verifiedRecaptcha);

    if(!$verResponseData->success)
    {
        return "reCAPTCHA is not valid; Please try again!";
    }

For more info you can visit Google docs.

Equivalent of Oracle's RowID in SQL Server

Several of the answers above will work around the lack of a direct reference to a specific row, but will not work if changes occur to the other rows in a table. That is my criteria for which answers fall technically short.

A common use of Oracle's ROWID is to provide a (somewhat) stable method of selecting rows and later returning to the row to process it (e.g., to UPDATE it). The method of finding a row (complex joins, full-text searching, or browsing row-by-row and applying procedural tests against the data) may not be easily or safely re-used to qualify the UPDATE statement.

The SQL Server RID seems to provide the same functionality, but does not provide the same performance. That is the only issue I see, and unfortunately the purpose of retaining a ROWID is to avoid repeating an expensive operation to find the row in, say, a very large table. Nonetheless, performance for many cases is acceptable. If Microsoft adjusts the optimizer in a future release, the performance issue could be addressed.

It is also possible to simply use FOR UPDATE and keep the CURSOR open in a procedural program. However, this could prove expensive in large or complex batch processing.

Caveat: Even Oracle's ROWID would not be stable if the DBA, between the SELECT and the UPDATE, for example, were to rebuild the database, because it is the physical row identifier. So the ROWID device should only be used within a well-scoped task.

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

In my experience, to use wmic in a script, you need to get the nested quoting right:

wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive 

quoting both the query and the name. But wmic will only uninstall things installed via windows installer.

Best Practices: working with long, multiline strings in PHP?

I use similar system as pix0r and I think that makes the code quite readable. Sometimes I would actually go as far as separating the line breaks in double quotes and use single quotes for the rest of the string. That way they stand out from the rest of the text and variables also stand out better if you use concatenation rather than inject them inside double quoted string. So I might do something like this with your original example:

$text = 'Hello ' . $vars->name . ','
      . "\r\n\r\n"
      . 'The second line starts two lines below.'
      . "\r\n\r\n"
      . 'I also don\'t want any spaces before the new line,'
      . ' so it\'s butted up against the left side of the screen.';

return $text;

Regarding the line breaks, with email you should always use \r\n. PHP_EOL is for files that are meant to be used in the same operating system that php is running on.

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

Replacing blank values (white space) with NaN in pandas

For a very fast and simple solution where you check equality against a single value, you can use the mask method.

df.mask(df == ' ')

How to get the hostname of the docker host from inside a docker container on that host without env vars

I ran

docker info | grep Name: | xargs | cut -d' ' -f2

inside my container.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Claiming that the C++ compiler can produce more optimal code than a competent assembly language programmer is a very bad mistake. And especially in this case. The human always can make the code better than the compiler can, and this particular situation is a good illustration of this claim.

The timing difference you're seeing is because the assembly code in the question is very far from optimal in the inner loops.

(The below code is 32-bit, but can be easily converted to 64-bit)

For example, the sequence function can be optimized to only 5 instructions:

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

The whole code looks like:

include "%lib%/freshlib.inc"
@BinaryType console, compact
options.DebugMode = 1
include "%lib%/freshlib.asm"

start:
        InitializeAll
        mov ecx, 999999
        xor edi, edi        ; max
        xor ebx, ebx        ; max i

    .main_loop:

        xor     esi, esi
        mov     eax, ecx

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

        cmp     edi, esi
        cmovb   edi, esi
        cmovb   ebx, ecx

        dec     ecx
        jnz     .main_loop

        OutputValue "Max sequence: ", edi, 10, -1
        OutputValue "Max index: ", ebx, 10, -1

        FinalizeAll
        stdcall TerminateAll, 0

In order to compile this code, FreshLib is needed.

In my tests, (1 GHz AMD A4-1200 processor), the above code is approximately four times faster than the C++ code from the question (when compiled with -O0: 430 ms vs. 1900 ms), and more than two times faster (430 ms vs. 830 ms) when the C++ code is compiled with -O3.

The output of both programs is the same: max sequence = 525 on i = 837799.

Extract subset of key-value pairs from Python dictionary object?

Using map (halfdanrump's answer) is best for me, though haven't timed it...

But if you go for a dictionary, and if you have a big_dict:

  1. Make absolutely certain you loop through the the req. This is crucial, and affects the running time of the algorithm (big O, theta, you name it)
  2. Write it generic enough to avoid errors if keys are not there.

so e.g.:

big_dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w']

{k:big_dict.get(k,None) for k in req )
# or 
{k:big_dict[k] for k in req if k in big_dict)

Note that in the converse case, that the req is big, but my_dict is small, you should loop through my_dict instead.

In general, we are doing an intersection and the complexity of the problem is O(min(len(dict)),min(len(req))). Python's own implementation of intersection considers the size of the two sets, so it seems optimal. Also, being in c and part of the core library, is probably faster than most not optimized python statements. Therefore, a solution that I would consider is:

dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w',...................]

{k:dic[k] for k in set(req).intersection(dict.keys())}

It moves the critical operation inside python's c code and will work for all cases.

Moving from position A to position B slowly with animation

You can animate it after the fadeIn completes using the callback as shown below:

$("#Friends").fadeIn('slow',function(){
  $(this).animate({'top': '-=30px'},'slow');
});

Android Saving created bitmap to directory on sd card

just change the extension to .bmp.

Do this:

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);

//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "test.bmp")

It'll sound that I'm just fooling around, but try it once and it'll get saved in BMP format. Cheers!

Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;  

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B

The resulting distance is in meters.

How to merge two sorted arrays into a sorted array?

public int[] merge(int[] a, int[] b) {
    int[] result = new int[a.length + b.length];
    int aIndex, bIndex = 0;

    for (int i = 0; i < result.length; i++) {
        if (aIndex < a.length && bIndex < b.length) {
            if (a[aIndex] < b[bIndex]) {
                result[i] = a[aIndex];
                aIndex++;
            } else {
                result[i] = b[bIndex];
                bIndex++;
            }
        } else if (aIndex < a.length) {
            result[i] = a[aIndex];
            aIndex++;
        } else {
            result[i] = b[bIndex];
            bIndex++;
        }
    }

    return result;
}

Run ScrollTop with offset of element by ID

No magic involved, just subtract from the offset top of the element

$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow');

When should we use intern method of String on String literals

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String s1 = "test";
    String s2 = new String("test");
    System.out.println(s1==s2);              //false
    System.out.println(s1==s2.intern());    //true --> because this time compiler is checking from string constant pool.
}

C# DLL config file

ConfigurationManager.AppSettings returns the settings defined for the application, not for the specific DLL, you can access them but it's the application settings that will be returned.

If you're using you dll from another application then the ConnectionString shall be in the app.settings of the application.

What does the clearfix class do in css?

clearfix is the same as overflow:hidden. Both clear floated children of the parent, but clearfix will not cut off the element which overflow to it's parent. It also works in IE8 & above.

There is no need to define "." in content & .clearfix. Just write like this:

.clr:after {
    clear: both;
    content: "";
    display: block;
}

HTML

<div class="parent clr"></div>

Read these links for more

http://css-tricks.com/snippets/css/clear-fix/,

What methods of ‘clearfix’ can I use?

Angular routerLink does not navigate to the corresponding component

I was using routerlink instead of routerLink.