Programs & Examples On #Dynamic languages

Dynamic languages are a class of high-level programming languages whos behaviors is determined at runtime rather than compile time.

Short description of the scoping rules?

Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply.)

LEGB Rule

  • Local — Names assigned in any way within a function (def or lambda), and not declared global in that function

  • Enclosing-function — Names assigned in the local scope of any and all statically enclosing functions (def or lambda), from inner to outer

  • Global (module) — Names assigned at the top-level of a module file, or by executing a global statement in a def within the file

  • Built-in (Python) — Names preassigned in the built-in names module: open, range, SyntaxError, etc

So, in the case of

code1
class Foo:
    code2
    def spam():
        code3
        for code4:
            code5
            x()

The for loop does not have its own namespace. In LEGB order, the scopes would be

  • L: Local in def spam (in code3, code4, and code5)
  • E: Any enclosing functions (if the whole example were in another def)
  • G: Were there any x declared globally in the module (in code1)?
  • B: Any builtin x in Python.

x will never be found in code2 (even in cases where you might expect it would, see Antti's answer or here).

Dynamic type languages versus static type languages

There are lots of different things about static and dynamic languages. For me, the main difference is that in dynamic languages the variables don't have fixed types; instead, the types are tied to values. Because of this, the exact code that gets executed is undetermined until runtime.

In early or naïve implementations this is a huge performance drag, but modern JITs get tantalizingly close to the best you can get with optimizing static compilers. (in some fringe cases, even better than that).

How does JavaScript .prototype work?

The Definitive Guide to Object-Oriented JavaScript - a very concise and clear ~30min video explanation of the asked question (Prototypal Inheritance topic begins from 5:45, although I'd rather listen to the whole video). The author of this video also made JavaScript object visualizer website http://www.objectplayground.com/.enter image description here enter image description here

removeEventListener on anonymous functions in JavaScript

JavaScript: addEventListener method registers the specified listener on the EventTarget(Element|document|Window) it's called on.

EventTarget.addEventListener(event_type, handler_function, Bubbling|Capturing);

Mouse, Keyboard events Example test in WebConsole:

var keyboard = function(e) {
    console.log('Key_Down Code : ' + e.keyCode);
};
var mouseSimple = function(e) {
    var element = e.srcElement || e.target;
    var tagName = element.tagName || element.relatedTarget;
    console.log('Mouse Over TagName : ' + tagName);    
};
var  mouseComplex = function(e) {
    console.log('Mouse Click Code : ' + e.button);
} 

window.document.addEventListener('keydown',   keyboard,      false);
window.document.addEventListener('mouseover', mouseSimple,   false);
window.document.addEventListener('click',     mouseComplex,  false);

removeEventListener method removes the event listener previously registered with EventTarget.addEventListener().

window.document.removeEventListener('keydown',   keyboard,     false);
window.document.removeEventListener('mouseover', mouseSimple,  false);
window.document.removeEventListener('click',     mouseComplex, false);

caniuse

When to use RSpec let()?

let is functional as its essentially a Proc. Also its cached.

One gotcha I found right away with let... In a Spec block that is evaluating a change.

let(:object) {FactoryGirl.create :object}

expect {
  post :destroy, id: review.id
}.to change(Object, :count).by(-1)

You'll need to be sure to call let outside of your expect block. i.e. you're calling FactoryGirl.create in your let block. I usually do this by verifying the object is persisted.

object.persisted?.should eq true

Otherwise when the let block is called the first time a change in the database will actually happen due to the lazy instantiation.

Update

Just adding a note. Be careful playing code golf or in this case rspec golf with this answer.

In this case, I just have to call some method to which the object responds. So I invoke the _.persisted?_ method on the object as its truthy. All I'm trying to do is instantiate the object. You could call empty? or nil? too. The point isn't the test but bringing the object ot life by calling it.

So you can't refactor

object.persisted?.should eq true

to be

object.should be_persisted 

as the object hasn't been instantiated... its lazy. :)

Update 2

leverage the let! syntax for instant object creation, which should avoid this issue altogether. Note though it will defeat a lot of the purpose of the laziness of the non banged let.

Also in some instances you might actually want to leverage the subject syntax instead of let as it may give you additional options.

subject(:object) {FactoryGirl.create :object}

JAX-WS client : what's the correct path to access the local WSDL?

For those of you using Spring, you can simply reference any classpath-resource using the classpath-protocol. So in case of the wsdlLocation, this becomes:

<wsdlLocation>classpath:META-INF/webservice.wsdl</wsdlLocation>

Note that is not standard Java behavior. See also: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/resources.html

How to Lock the data in a cell in excel using vba

You can first choose which cells you don't want to be protected (to be user-editable) by setting the Locked status of them to False:

Worksheets("Sheet1").Range("B2:C3").Locked = False

Then, you can protect the sheet, and all the other cells will be protected. The code to do this, and still allow your VBA code to modify the cells is:

Worksheets("Sheet1").Protect UserInterfaceOnly:=True

or

Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

I've solved this. In my case I just changed my configuration. 'hostname' became 'localhost'

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';

Error including image in Latex

To include png and jpg, you need to specify the Bounding Box explicitly.

\includegraphics[bb=0 0 1280 960]{images/some_image.png}

Where 1280 and 960 are respectively width and height.

How to send a HTTP OPTIONS request from the command line?

The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)

OPTIONS /path

You can send an OPTIONS request with curl like this:

curl -i -X OPTIONS http://example.org/path

You may also use -v instead of -i to see more output.

OPTIONS *

To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:

curl -i --request-target "*" -X OPTIONS http://example.org

How do I mount a host directory as a volume in docker compose

It was two things:

I added the volume in docker-compose.yml:

node:
  volumes:
    - ./node:/app

I moved the npm install && nodemon app.js pieces into a CMD because RUN adds things to the Union File System, and my volume isn't part of UFS.

# Set the base image to Ubuntu
FROM    node:boron

# File Author / Maintainer
MAINTAINER Amin Shah Gilani <[email protected]>

# Install nodemon
RUN npm install -g nodemon

# Add a /app volume
VOLUME ["/app"]

# Define working directory
WORKDIR /app

# Expose port
EXPOSE  8080

# Run npm install
CMD npm install && nodemon app.js

performSelector may cause a leak because its selector is unknown

Solution

The compiler is warning about this for a reason. It's very rare that this warning should simply be ignored, and it's easy to work around. Here's how:

if (!_controller) { return; }
SEL selector = NSSelectorFromString(@"someMethod");
IMP imp = [_controller methodForSelector:selector];
void (*func)(id, SEL) = (void *)imp;
func(_controller, selector);

Or more tersely (though hard to read & without the guard):

SEL selector = NSSelectorFromString(@"someMethod");
((void (*)(id, SEL))[_controller methodForSelector:selector])(_controller, selector);

Explanation

What's going on here is you're asking the controller for the C function pointer for the method corresponding to the controller. All NSObjects respond to methodForSelector:, but you can also use class_getMethodImplementation in the Objective-C runtime (useful if you only have a protocol reference, like id<SomeProto>). These function pointers are called IMPs, and are simple typedefed function pointers (id (*IMP)(id, SEL, ...))1. This may be close to the actual method signature of the method, but will not always match exactly.

Once you have the IMP, you need to cast it to a function pointer that includes all of the details that ARC needs (including the two implicit hidden arguments self and _cmd of every Objective-C method call). This is handled in the third line (the (void *) on the right hand side simply tells the compiler that you know what you're doing and not to generate a warning since the pointer types don't match).

Finally, you call the function pointer2.

Complex Example

When the selector takes arguments or returns a value, you'll have to change things a bit:

SEL selector = NSSelectorFromString(@"processRegion:ofView:");
IMP imp = [_controller methodForSelector:selector];
CGRect (*func)(id, SEL, CGRect, UIView *) = (void *)imp;
CGRect result = _controller ?
  func(_controller, selector, someRect, someView) : CGRectZero;

Reasoning for Warning

The reason for this warning is that with ARC, the runtime needs to know what to do with the result of the method you're calling. The result could be anything: void, int, char, NSString *, id, etc. ARC normally gets this information from the header of the object type you're working with.3

There are really only 4 things that ARC would consider for the return value:4

  1. Ignore non-object types (void, int, etc)
  2. Retain object value, then release when it is no longer used (standard assumption)
  3. Release new object values when no longer used (methods in the init/ copy family or attributed with ns_returns_retained)
  4. Do nothing & assume returned object value will be valid in local scope (until inner most release pool is drained, attributed with ns_returns_autoreleased)

The call to methodForSelector: assumes that the return value of the method it's calling is an object, but does not retain/release it. So you could end up creating a leak if your object is supposed to be released as in #3 above (that is, the method you're calling returns a new object).

For selectors you're trying to call that return void or other non-objects, you could enable compiler features to ignore the warning, but it may be dangerous. I've seen Clang go through a few iterations of how it handles return values that aren't assigned to local variables. There's no reason that with ARC enabled that it can't retain and release the object value that's returned from methodForSelector: even though you don't want to use it. From the compiler's perspective, it is an object after all. That means that if the method you're calling, someMethod, is returning a non object (including void), you could end up with a garbage pointer value being retained/released and crash.

Additional Arguments

One consideration is that this is the same warning will occur with performSelector:withObject: and you could run into similar problems with not declaring how that method consumes parameters. ARC allows for declaring consumed parameters, and if the method consumes the parameter, you'll probably eventually send a message to a zombie and crash. There are ways to work around this with bridged casting, but really it'd be better to simply use the IMP and function pointer methodology above. Since consumed parameters are rarely an issue, this isn't likely to come up.

Static Selectors

Interestingly, the compiler will not complain about selectors declared statically:

[_controller performSelector:@selector(someMethod)];

The reason for this is because the compiler actually is able to record all of the information about the selector and the object during compilation. It doesn't need to make any assumptions about anything. (I checked this a year a so ago by looking at the source, but don't have a reference right now.)

Suppression

In trying to think of a situation where suppression of this warning would be necessary and good code design, I'm coming up blank. Someone please share if they have had an experience where silencing this warning was necessary (and the above doesn't handle things properly).

More

It's possible to build up an NSMethodInvocation to handle this as well, but doing so requires a lot more typing and is also slower, so there's little reason to do it.

History

When the performSelector: family of methods was first added to Objective-C, ARC did not exist. While creating ARC, Apple decided that a warning should be generated for these methods as a way of guiding developers toward using other means to explicitly define how memory should be handled when sending arbitrary messages via a named selector. In Objective-C, developers are able to do this by using C style casts on raw function pointers.

With the introduction of Swift, Apple has documented the performSelector: family of methods as "inherently unsafe" and they are not available to Swift.

Over time, we have seen this progression:

  1. Early versions of Objective-C allow performSelector: (manual memory management)
  2. Objective-C with ARC warns for use of performSelector:
  3. Swift does not have access to performSelector: and documents these methods as "inherently unsafe"

The idea of sending messages based on a named selector is not, however, an "inherently unsafe" feature. This idea has been used successfully for a long time in Objective-C as well as many other programming languages.


1 All Objective-C methods have two hidden arguments, self and _cmd that are implicitly added when you call a method.

2 Calling a NULL function is not safe in C. The guard used to check for the presence of the controller ensures that we have an object. We therefore know we'll get an IMP from methodForSelector: (though it may be _objc_msgForward, entry into the message forwarding system). Basically, with the guard in place, we know we have a function to call.

3 Actually, it's possible for it to get the wrong info if declare you objects as id and you're not importing all headers. You could end up with crashes in code that the compiler thinks is fine. This is very rare, but could happen. Usually you'll just get a warning that it doesn't know which of two method signatures to choose from.

4 See the ARC reference on retained return values and unretained return values for more details.

Add more than one parameter in Twig path

You can pass as many arguments as you want, separating them by commas:

{{ path('_files_manage', {project: project.id, user: user.id}) }}

Django TemplateDoesNotExist?

Works on Django 3

I found I believe good way, I have the base.html in root folder, and all other html files in App folders, I settings.py

import os

# This settings are to allow store templates,static and media files in root folder

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')

# This is default path from Django, must be added 
#AFTER our BASE_DIR otherwise DB will be broken.
BASE_DIR = Path(__file__).resolve().parent.parent

# add your apps to Installed apps
INSTALLED_APPS = [
    'main',
    'weblogin',
     ..........
]

# Now add TEMPLATE_DIR to  'DIRS' where in TEMPLATES like bellow
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR, BASE_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
# On end of Settings.py put this refferences to Static and Media files
STATICFILES_DIRS = [STATIC_DIR,]
STATIC_URL = '/static/'

MEDIA_ROOT = [MEDIA_DIR,]
MEDIA_URL = '/media/'

If you have problem with Database, please check if you put the original BASE_DIR bellow the new BASE_DIR otherwise change

# Original
'NAME': BASE_DIR / 'db.sqlite3',
# to
'NAME': os.path.join(BASE_DIR,'db.sqlite3'),

Django now will be able to find the HTML and Static files both in the App folders and in Root folder without need of adding the name of App folder in front of the file.

Struture:
-DjangoProject
    -static(css,JS ...)
    -templates(base.html, ....)
    -other django files like (manage.py, ....)
    -App1
        -templates(index1.html, other html files can extend now base.html too)
        -other App1 files
    -App2
        -templates(index2.html, other html files can extend now base.html too)
        -other App2 files

Date ticks and rotation in matplotlib

An easy solution which avoids looping over the ticklabes is to just use

fig.autofmt_xdate()

This command automatically rotates the xaxis labels and adjusts their position. The default values are a rotation angle 30° and horizontal alignment "right". But they can be changed in the function call

fig.autofmt_xdate(bottom=0.2, rotation=30, ha='right')

The additional bottom argument is equivalent to setting plt.subplots_adjust(bottom=bottom), which allows to set the bottom axes padding to a larger value to host the rotated ticklabels.

So basically here you have all the settings you need to have a nice date axis in a single command.

A good example can be found on the matplotlib page.

How to get records randomly from the oracle database?

SELECT column FROM
( SELECT column, dbms_random.value FROM table ORDER BY 2 )
where rownum <= 20;

TypeError: 'NoneType' object is not iterable in Python

Code: for row in data:
Error message: TypeError: 'NoneType' object is not iterable

Which object is it complaining about? Choice of two, row and data. In for row in data, which needs to be iterable? Only data.

What's the problem with data? Its type is NoneType. Only None has type NoneType. So data is None.

You can verify this in an IDE, or by inserting e.g. print "data is", repr(data) before the for statement, and re-running.

Think about what you need to do next: How should "no data" be represented? Do we write an empty file? Do we raise an exception or log a warning or keep silent?

How to add property to a class dynamically?

This is a little different than what OP wanted, but I rattled my brain until I got a working solution, so I'm putting here for the next guy/gal

I needed a way to specify dynamic setters and getters.

class X:
    def __init__(self, a=0, b=0, c=0):
        self.a = a
        self.b = b
        self.c = c

    @classmethod
    def _make_properties(cls, field_name, inc):
        _inc = inc

        def _get_properties(self):
            if not hasattr(self, '_%s_inc' % field_name):
                setattr(self, '_%s_inc' % field_name, _inc)
                inc = _inc
            else:
                inc = getattr(self, '_%s_inc' % field_name)

            return getattr(self, field_name) + inc

        def _set_properties(self, value):
            setattr(self, '_%s_inc' % field_name, value)

        return property(_get_properties, _set_properties)

I know my fields ahead of time so im going to create my properties. NOTE: you cannot do this PER instance, these properties will exist on the class!!!

for inc, field in enumerate(['a', 'b', 'c']):
    setattr(X, '%s_summed' % field, X._make_properties(field, inc))

Let's test it all now..

x = X()
assert x.a == 0
assert x.b == 0
assert x.c == 0

assert x.a_summed == 0  # enumerate() set inc to 0 + 0 = 0
assert x.b_summed == 1  # enumerate() set inc to 1 + 0 = 1
assert x.c_summed == 2  # enumerate() set inc to 2 + 0 = 2

# we set the variables to something
x.a = 1
x.b = 2
x.c = 3

assert x.a_summed == 1  # enumerate() set inc to 0 + 1 = 1
assert x.b_summed == 3  # enumerate() set inc to 1 + 2 = 3
assert x.c_summed == 5  # enumerate() set inc to 2 + 3 = 5

# we're changing the inc now
x.a_summed = 1 
x.b_summed = 3 
x.c_summed = 5

assert x.a_summed == 2  # we set inc to 1 + the property was 1 = 2
assert x.b_summed == 5  # we set inc to 3 + the property was 2 = 5
assert x.c_summed == 8  # we set inc to 5 + the property was 3 = 8

Is it confusing? Yes, sorry I couldn't come up with any meaningful real world examples. Also, this is not for the light hearted.

How to update std::map after using the find method?

std::map::find returns an iterator to the found element (or to the end() if the element was not found). So long as the map is not const, you can modify the element pointed to by the iterator:

std::map<char, int> m;
m.insert(std::make_pair('c', 0));  // c is for cookie

std::map<char, int>::iterator it = m.find('c'); 
if (it != m.end())
    it->second = 42;

How can I get the timezone name in JavaScript?

Try this code refer from here

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js">
</script>
<script type="text/javascript">
  $(document).ready(function(){
    var tz = jstz.determine(); // Determines the time zone of the browser client
    var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.

    alert(timezone);
});
</script>

Get environment variable value in Dockerfile

Load environment variables from a file you create at runtime.

export MYVAR="my_var_outside"
cat > build/env.sh <<EOF
MYVAR=${MYVAR}
EOF

... then in the Dockerfile

ADD build /build
RUN /build/test.sh

where test.sh loads MYVAR from env.sh

#!/bin/bash
. /build/env.sh
echo $MYVAR > /tmp/testfile

Remove all special characters except space from a string using JavaScript

You should use the string replace function, with a single regex. Assuming by special characters, you mean anything that's not letter, here is a solution:

_x000D_
_x000D_
const str = "abc's test#s";_x000D_
console.log(str.replace(/[^a-zA-Z ]/g, ""));
_x000D_
_x000D_
_x000D_

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

JAX-RS implementations automatically support marshalling/unmarshalling of classes based on discoverable JAXB annotations, but because your payload is declared as Object, I think the created JAXBContext misses the Department class and when it's time to marshall it it doesn't know how.

A quick and dirty fix would be to add a XmlSeeAlso annotation to your response class:

@XmlRootElement
@XmlSeeAlso({Department.class})
public class Response implements Serializable {
  ....

or something a little more complicated would be "to enrich" the JAXB context for the Response class by using a ContextResolver:

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

@Provider
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class ResponseResolver implements ContextResolver<JAXBContext> {
    private JAXBContext ctx;

    public ResponseResolver() {
        try {
            this.ctx = JAXBContext.newInstance(

                        Response.class, 
                        Department.class

                    );
        } catch (JAXBException ex) {
            throw new RuntimeException(ex);
        }
    }

    public JAXBContext getContext(Class<?> type) {
        return (type.equals(Response.class) ? ctx : null);
    }
}

Jackson - best way writes a java list to a json array

I can't find toByteArray() as @atrioom said, so I use StringWriter, please try:

public void writeListToJsonArray() throws IOException {  

    //your list
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));


    final StringWriter sw =new StringWriter();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(sw, list);
    System.out.println(sw.toString());//use toString() to convert to JSON

    sw.close(); 
}

Or just use ObjectMapper#writeValueAsString:

    final ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(list));

wordpress contactform7 textarea cols and rows change in smaller screens

Code will be As below.

[textarea id:message 0x0 class:custom-class "Insert text here"]<!-- No Rows No columns -->

[textarea id:message x2 class:custom-class "Insert text here"]<!-- Only Rows -->

[textarea id:message 12x class:custom-class "Insert text here"]<!-- Only Columns -->

[textarea id:message 10x2 class:custom-class "Insert text here"]<!-- Both Rows and Columns -->

For Details: https://contactform7.com/text-fields/

Rename multiple files in a directory in Python

What about this :

import re
p = re.compile(r'_')
p.split(filename, 1) #where filename is CHEESE_CHEESE_TYPE.***

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

You can use another shell to execute the same command:

Error I get when i execute:

[jenkins@localhost jenkins_data]$ docker exec -it mysqldb \bin\bash
OCI runtime exec failed: exec failed: container_linux.go:345: starting container process caused "exec: \"binsh\": executable file not found in $PATH": unknown

Solution: When I execute it with below command, using bash shell it works:

[jenkins@localhost jenkins_data]$ docker exec -it mysqldb bash
root@<container-ID>:/#

foreach with index

You can do the following

foreach (var it in someCollection.Select((x, i) => new { Value = x, Index = i }) )
{
   if (it.Index > SomeNumber) //      
}

This will create an anonymous type value for every entry in the collection. It will have two properties

  • Value: with the original value in the collection
  • Index: with the index within the collection

Tomcat manager/html is not available?

My problem/solution is very embarrassing but who knows... perhaps it happened to someone else:

My solution: Turn off proxy

For the past two hours I've been wondering why my manager would not load. (the root was cached so it loaded). I had set the browser's proxy to proxy traffic to my house. :/

What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

  • RESTful services use REST architectural style,
  • RESTless services use SOAP protocol.

2. Business logic / Functionality

  • RESTful services use URL to expose business logic,
  • RESTless services use the service interface to expose business logic.

3. Security

  • RESTful inherits security from the underlying transport protocols,
  • RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

  • RESTful supports various data formats such as HTML, JSON, text, etc,
  • RESTless supports XML format.

5. Flexibility

  • RESTful is easier and flexible,
  • RESTless is not as easy and flexible.

6. Bandwidth

  • RESTful services consume less bandwidth and resource,
  • RESTless services consume more bandwidth and resources.

In .NET, which loop runs faster, 'for' or 'foreach'?

It will always be close. For an array, sometimes for is slightly quicker, but foreach is more expressive, and offers LINQ, etc. In general, stick with foreach.

Additionally, foreach may be optimised in some scenarios. For example, a linked list might be terrible by indexer, but it might be quick by foreach. Actually, the standard LinkedList<T> doesn't even offer an indexer for this reason.

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

The "ojdbc.jar" is not in the CLASSPATH of your application server.

Just tell us which application server it is and we will tell you where the driver should be placed.

Edit: I saw the tag so it has to be placed in folder "$JBOSS_HOME/server/default/lib/"

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

If you migrated to Laravel 8, you have to add a namespace to the seeders class:

<?php

namespace Database\Seeders;

...

Next, in your composer.json file, remove classmap block from the autoload section and add the new namespaced class directory mappings:

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Database\\Seeders\\": "database/seeds/"
    }
},

An finally, do a composer dump-autoload.

For more information: https://laravel.com/docs/8.x/upgrade#seeder-factory-namespaces

Including all the jars in a directory within the Java classpath

Think of a jar file as the root of a directory structure. Yes, you need to add them all separately.

Getting the inputstream from a classpath resource (XML file)

That depends on where exactly the XML file is. Is it in the sources folder (in the "default package" or the "root") or in the same folder as the class?

In for former case, you must use "/file.xml" (note the leading slash) to find the file and it doesn't matter which class you use to try to locate it.

If the XML file is next to some class, SomeClass.class.getResourceAsStream() with just the filename is the way to go.

In java how to get substring from a string till a character c?

How about using regex?

String firstWord = filename.replaceAll("\\..*","")

This replaces everything from the first dot to the end with "" (ie it clears it, leaving you with what you want)

Here's a test:

System.out.println("abc.def.hij".replaceAll("\\..*", "");

Output:

abc

Can't find @Nullable inside javax.annotation.*

JSR-305 is a "Java Specification Request" to extend the specification. @Nullable etc. were part of it; however it appears to be "dormant" (or frozen) ever since (See this SO question). So to use these annotations, you have to add the library yourself.

FindBugs was renamed to SpotBugs and is being developed under that name.

For maven this is the current annotation-only dependency (other integrations here):

<dependency>
  <groupId>com.github.spotbugs</groupId>
  <artifactId>spotbugs-annotations</artifactId>
  <version>4.2.0</version>
</dependency>

If you wish to use the full plugin, refer to the documentation of SpotBugs.

How to draw in JPanel? (Swing/graphics Java)

When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics object outside the paint()/paintComponent()/etc. methods.

However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics() method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel's paintComponent(), you simply need to draw the BufferedImage instance unto the JPanel. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.

What's the difference between HEAD^ and HEAD~ in Git?

HEAD^^^ is the same as HEAD~3, selecting the third commit before HEAD

HEAD^2 specifies the second head in a merge commit

Multiple distinct pages in one HTML file

Let's say you have multiple pages, with id #page1 #page2 and #page3. #page1 is the ID of your start page. The first thing you want to do is to redirect to your start page each time the webpage is loading. You do this with javascript:

document.location.hash = "#page1";

Then the next thing you want to do is place some links in your document to the different pages, like for example:

<a href="#page2">Click here to get to page 2.</a>

Then, lastly, you'd want to make sure that only the active page, or target-page is visible, and all other pages stay hidden. You do this with the following declarations in the <style> element:

<style>
#page1 {display:none}
#page1:target {display:block}
#page2 {display:none}
#page2:target {display:block}
#page3 {display:none}
#page3:target {display:block}
</style>

How to handle checkboxes in ASP.NET MVC forms?

Just do this on $(document).ready :

$('input:hidden').each(function(el) {
    var that = $(this)[0];
    if(that.id.length < 1 ) {

        console.log(that.id);
        that.parentElement.removeChild(that);

    }
});

How does one reorder columns in a data frame?

The three top-rated answers have a weakness.

If your dataframe looks like this

df <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))

> df
  Time In Out Files
1    1  2   3     4
2    2  3   4     5

then it's a poor solution to use

> df2[,c(1,3,2,4)]

It does the job, but you have just introduced a dependence on the order of the columns in your input.

This style of brittle programming is to be avoided.

The explicit naming of the columns is a better solution

data[,c("Time", "Out", "In", "Files")]

Plus, if you intend to reuse your code in a more general setting, you can simply

out.column.name <- "Out"
in.column.name <- "In"
data[,c("Time", out.column.name, in.column.name, "Files")]

which is also quite nice because it fully isolates literals. By contrast, if you use dplyr's select

data <- data %>% select(Time, out, In, Files)

then you'd be setting up those who will read your code later, yourself included, for a bit of a deception. The column names are being used as literals without appearing in the code as such.

C - error: storage size of ‘a’ isn’t known

In this case the user has done mistake in definition and its usage. If someone has done a typedef to a structure the same should be used without using struct following is the example.

typedef struct
{
   int a;
}studyT;

When using in a function

int main()
{
   struct studyT study; // This will give above error.
   studyT stud; // This will eliminate the above error.
   return 0;
}

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

I had a similar problem, here's my solution:

  1. Right click on your project and select Properties.
  2. Select Java Build Path from the menu on the left.
  3. Select the Order and Export tab.
  4. From the list make sure the libraries or external jars you added to your project are checked.
  5. Finally, clean your project & run.

You may also check this answer.

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

You can use Object.keys() and map() to do this

_x000D_
_x000D_
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [Number(key), obj[key]]);

console.log(result);
_x000D_
_x000D_
_x000D_

not None test in Python

if val is not None:
    # ...

is the Pythonic idiom for testing that a variable is not set to None. This idiom has particular uses in the case of declaring keyword functions with default parameters. is tests identity in Python. Because there is one and only one instance of None present in a running Python script/program, is is the optimal test for this. As Johnsyweb points out, this is discussed in PEP 8 under "Programming Recommendations".

As for why this is preferred to

if not (val is None):
    # ...

this is simply part of the Zen of Python: "Readability counts." Good Python is often close to good pseudocode.

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

UPDATE: Another writeup here: How to add publisher in Installshield 2018 (might be better).


I am not too well informed about this issue, but please see if this answer to another question tells you anything useful (and let us know so I can evolve a better answer here): How to pass the Windows Defender SmartScreen Protection? That question relates to BitRock - a non-MSI installer technology, but the overall issue seems to be the same.

Extract from one of the links pointed to in my answer above: "...a certificate just isn't enough anymore to gain trust... SmartScreen is reputation based, not unlike the way StackOverflow works... SmartScreen trusts installers that don't cause problems. Windows machines send telemetry back to Redmond about installed programs and how much trouble they cause. If you get enough thumbs-up then SmartScreen stops blocking your installer automatically. This takes time and lots of installs to get sufficient thumbs. There is no way to find out how far along you got."

Honestly this is all news to me at this point, so do get back to us with any information you dig up yourself.


The actual dialog text you have marked above definitely relates to the Zone.Identifier alternate data stream with a value of 3 that is added to any file that is downloaded from the Internet (see linked answer above for more details).


I was not able to mark this question as a duplicate of the previous one, since it doesn't have an accepted answer. Let's leave both question open for now? (one question is for MSI, one is for non-MSI).

Compare two List<T> objects for equality, ignoring order

I use this method )

public delegate bool CompareValue<in T1, in T2>(T1 val1, T2 val2);

public static bool CompareTwoArrays<T1, T2>(this IEnumerable<T1> array1, IEnumerable<T2> array2, CompareValue<T1, T2> compareValue)
{
    return array1.Select(item1 => array2.Any(item2 => compareValue(item1, item2))).All(search => search)
            && array2.Select(item2 => array1.Any(item1 => compareValue(item1, item2))).All(search => search);
}

Check if a string is a palindrome

String extension method, easy to use:

    public static bool IsPalindrome(this string str)
    {
        str = new Regex("[^a-zA-Z]").Replace(str, "").ToLower();
        return !str.Where((t, i) => t != str[str.Length - i - 1]).Any();
    }

Translating touch events from Javascript to jQuery

jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent (see the Special Properties subheading on this page).

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

In my case the problem that I faced was:

CodeSign error: code signing is required for product type 'Unit Test Bundle' in SDK 'iOS 8.4'

Fortunatelly, the target did not implemented anything, so a quick solution is remove it.

enter image description here

how to change onclick event with jquery?

@Amirali

console.log(document.getElementById("SAVE_FOOTER"));
document.getElementById("SAVE_FOOTER").attribute("onclick","console.log('c')");

throws:

Uncaught TypeError: document.getElementById(...).attribute is not a function

in chrome.

Element exists and is dumped in console;

C: socket connection timeout

This article might help:

Connect with timeout (or another use for select() )

Looks like you put the socket into non-blocking mode until you've connected, and then put it back into blocking mode once the connection's established.

void connect_w_to(void) { 
  int res; 
  struct sockaddr_in addr; 
  long arg; 
  fd_set myset; 
  struct timeval tv; 
  int valopt; 
  socklen_t lon; 

  // Create socket 
  soc = socket(AF_INET, SOCK_STREAM, 0); 
  if (soc < 0) { 
     fprintf(stderr, "Error creating socket (%d %s)\n", errno, strerror(errno)); 
     exit(0); 
  } 

  addr.sin_family = AF_INET; 
  addr.sin_port = htons(2000); 
  addr.sin_addr.s_addr = inet_addr("192.168.0.1"); 

  // Set non-blocking 
  if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  arg |= O_NONBLOCK; 
  if( fcntl(soc, F_SETFL, arg) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  // Trying to connect with timeout 
  res = connect(soc, (struct sockaddr *)&addr, sizeof(addr)); 
  if (res < 0) { 
     if (errno == EINPROGRESS) { 
        fprintf(stderr, "EINPROGRESS in connect() - selecting\n"); 
        do { 
           tv.tv_sec = 15; 
           tv.tv_usec = 0; 
           FD_ZERO(&myset); 
           FD_SET(soc, &myset); 
           res = select(soc+1, NULL, &myset, NULL, &tv); 
           if (res < 0 && errno != EINTR) { 
              fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno)); 
              exit(0); 
           } 
           else if (res > 0) { 
              // Socket selected for write 
              lon = sizeof(int); 
              if (getsockopt(soc, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon) < 0) { 
                 fprintf(stderr, "Error in getsockopt() %d - %s\n", errno, strerror(errno)); 
                 exit(0); 
              } 
              // Check the value returned... 
              if (valopt) { 
                 fprintf(stderr, "Error in delayed connection() %d - %s\n", valopt, strerror(valopt) 
); 
                 exit(0); 
              } 
              break; 
           } 
           else { 
              fprintf(stderr, "Timeout in select() - Cancelling!\n"); 
              exit(0); 
           } 
        } while (1); 
     } 
     else { 
        fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno)); 
        exit(0); 
     } 
  } 
  // Set to blocking mode again... 
  if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  arg &= (~O_NONBLOCK); 
  if( fcntl(soc, F_SETFL, arg) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  // I hope that is all 
}

Google Maps API v3 adding an InfoWindow to each marker

In My case (Using Javascript insidde Razor) This worked perfectly inside an Foreach loop

google.maps.event.addListener(marker, 'click', function() {
    marker.info.open(map, this);
});

How to export html table to excel or pdf in php

Use a PHP Excel for generatingExcel file. You can find a good one called PHPExcel here: https://github.com/PHPOffice/PHPExcel

And for PDF generation use http://princexml.com/

How does the compilation/linking process work?

GCC compiles a C/C++ program into executable in 4 steps.

For example, gcc -o hello hello.c is carried out as follows:

1. Pre-processing

Preprocessing via the GNU C Preprocessor (cpp.exe), which includes the headers (#include) and expands the macros (#define).

cpp hello.c > hello.i

The resultant intermediate file "hello.i" contains the expanded source code.

2. Compilation

The compiler compiles the pre-processed source code into assembly code for a specific processor.

gcc -S hello.i

The -S option specifies to produce assembly code, instead of object code. The resultant assembly file is "hello.s".

3. Assembly

The assembler (as.exe) converts the assembly code into machine code in the object file "hello.o".

as -o hello.o hello.s

4. Linker

Finally, the linker (ld.exe) links the object code with the library code to produce an executable file "hello".

    ld -o hello hello.o ...libraries...

AttributeError: 'module' object has no attribute 'model'

I also got the same error but I noticed that I had typed in Foreign*k*ey and not Foreign*K*ey,(capital K) if there is a newbie out there, check out spelling and caps.

Converts scss to css

You can use sass /sassFile.scss /cssFile.css

Attention: Before using sass command you must install ruby and then install sass.

For installing sass, after ruby installation type gem install sass in your Terminal

Hint: sass compile SCSS files

React.js, wait for setState to finish before triggering a function?

According to the docs of setState() the new state might not get reflected in the callback function findRoutes(). Here is the extract from React docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

So here is what I propose you should do. You should pass the new states input in the callback function findRoutes().

handleFormSubmit: function(input){
    // Form Input
    this.setState({
        originId: input.originId,
        destinationId: input.destinationId,
        radius: input.radius,
        search: input.search
    });
    this.findRoutes(input);    // Pass the input here
}

The findRoutes() function should be defined like this:

findRoutes: function(me = this.state) {    // This will accept the input if passed otherwise use this.state
    if (!me.originId || !me.destinationId) {
        alert("findRoutes!");
        return;
    }
    var p1 = new Promise(function(resolve, reject) {
        directionsService.route({
            origin: {'placeId': me.originId},
            destination: {'placeId': me.destinationId},
            travelMode: me.travelMode
        }, function(response, status){
            if (status === google.maps.DirectionsStatus.OK) {
                // me.response = response;
                directionsDisplay.setDirections(response);
                resolve(response);
            } else {
                window.alert('Directions config failed due to ' + status);
            }
        });
    });
    return p1
}

Android ACTION_IMAGE_CAPTURE Intent

I had the same problem where the OK button in camera app did nothing, both on emulator and on nexus one.

The problem went away after specifying a safe filename that is without white spaces, without special characters, in MediaStore.EXTRA_OUTPUT Also, if you are specifying a file that resides in a directory that has not yet been created, you have to create it first. Camera app doesn't do mkdir for you.

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Best way to convert an ArrayList to a string

Java 8 introduces a String.join(separator, list) method; see Vitalii Federenko's answer.

Before Java 8, using a loop to iterate over the ArrayList was the only option:

DO NOT use this code, continue reading to the bottom of this answer to see why it is not desirable, and which code should be used instead:

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

String listString = "";

for (String s : list)
{
    listString += s + "\t";
}

System.out.println(listString);

In fact, a string concatenation is going to be just fine, as the javac compiler will optimize the string concatenation as a series of append operations on a StringBuilder anyway. Here's a part of the disassembly of the bytecode from the for loop from the above program:

   61:  new #13; //class java/lang/StringBuilder
   64:  dup
   65:  invokespecial   #14; //Method java/lang/StringBuilder."<init>":()V
   68:  aload_2
   69:  invokevirtual   #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   72:  aload   4
   74:  invokevirtual   #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   77:  ldc #16; //String \t
   79:  invokevirtual   #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   82:  invokevirtual   #17; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;

As can be seen, the compiler optimizes that loop by using a StringBuilder, so performance shouldn't be a big concern.

(OK, on second glance, the StringBuilder is being instantiated on each iteration of the loop, so it may not be the most efficient bytecode. Instantiating and using an explicit StringBuilder would probably yield better performance.)

In fact, I think that having any sort of output (be it to disk or to the screen) will be at least an order of a magnitude slower than having to worry about the performance of string concatenations.

Edit: As pointed out in the comments, the above compiler optimization is indeed creating a new instance of StringBuilder on each iteration. (Which I have noted previously.)

The most optimized technique to use will be the response by Paul Tomblin, as it only instantiates a single StringBuilder object outside of the for loop.

Rewriting to the above code to:

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

StringBuilder sb = new StringBuilder();
for (String s : list)
{
    sb.append(s);
    sb.append("\t");
}

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

Will only instantiate the StringBuilder once outside of the loop, and only make the two calls to the append method inside the loop, as evidenced in this bytecode (which shows the instantiation of StringBuilder and the loop):

   // Instantiation of the StringBuilder outside loop:
   33:  new #8; //class java/lang/StringBuilder
   36:  dup
   37:  invokespecial   #9; //Method java/lang/StringBuilder."<init>":()V
   40:  astore_2

   // [snip a few lines for initializing the loop]
   // Loading the StringBuilder inside the loop, then append:
   66:  aload_2
   67:  aload   4
   69:  invokevirtual   #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   72:  pop
   73:  aload_2
   74:  ldc #15; //String \t
   76:  invokevirtual   #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   79:  pop

So, indeed the hand optimization should be better performing, as the inside of the for loop is shorter and there is no need to instantiate a StringBuilder on each iteration.

Display a jpg image on a JPanel

You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.

Enable UTF-8 encoding for JavaScript

RobW is right on the first comment. You have to save the file in your IDE with encoding UTF-8. I moved my alert from .js file to my .html file and this solved the issue cause Visual Studio saves .html with UTF-8 encoding.

Should you always favor xrange() over range()?

A good example given in book: Practical Python By Magnus Lie Hetland

>>> zip(range(5), xrange(100000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

I wouldn’t recommend using range instead of xrange in the preceding example—although only the first five numbers are needed, range calculates all the numbers, and that may take a lot of time. With xrange, this isn’t a problem because it calculates only those numbers needed.

Yes I read @Brian's answer: In python 3, range() is a generator anyway and xrange() does not exist.

How to force cp to overwrite without confirmation

So I run into this a lot because I keep cp aliased to cp -iv, and I found a neat trick. It turns out that while -i and -n both cancel previous overwrite directives, -f does not. However, if you use -nf it adds the ability to clear the -i. So:

cp -f /foo/* /bar  <-- Prompt
cp -nf /foo/* /bar <-- No Prompt

Pretty neat huh? /necropost

How to stop EditText from gaining focus at Activity startup in Android

If you have another view on your activity like a ListView, you can also do:

ListView.requestFocus(); 

in your onResume() to grab focus from the editText.

I know this question has been answered but just providing an alternative solution that worked for me :)

string comparison in batch file

Just put quotes around the Environment variable (as you have done) :
if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
but it's the way you put opening bracket without a space that is confusing it.

Works for me...

C:\if "%gtk_basepath%" == "C:\Program Files\GtkSharp\2.12\" (echo yes)
yes

How can I dynamically switch web service addresses in .NET without a recompile?

I've struggled with this issue for a few days and finally the light bulb clicked. The KEY to being able to change the URL of a webservice at runtime is overriding the constructor, which I did with a partial class declaration. The above, setting the URL behavior to Dynamic must also be done.

This basically creates a web-service wrapper where if you have to reload web service at some point, via add service reference, you don't loose your work. The Microsoft help for Partial classes specially states that part of the reason for this construct is to create web service wrappers. http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.100).aspx

// Web Service Wrapper to override constructor to use custom ConfigSection 
// app.config values for URL/User/Pass
namespace myprogram.webservice
{
    public partial class MyWebService
    {
        public MyWebService(string szURL)
        {
            this.Url = szURL;
            if ((this.IsLocalFileSystemWebService(this.Url) == true))
            {
                this.UseDefaultCredentials = true;
                this.useDefaultCredentialsSetExplicitly = false;
            }
            else
            {
                this.useDefaultCredentialsSetExplicitly = true;
            }
        }
    }
}

Can (domain name) subdomains have an underscore "_" in it?

No, you can't use underscore in subdomain but hypen (dash). i.e my-subdomain.agahost.com is acceptable and my_subdomain.agahost.com would not be acceptable.

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

How to uncheck a checkbox in pure JavaScript?

<html>
    <body>
        <input id="check1" type="checkbox" checked="" name="copyNewAddrToBilling">
    </body>
    <script language="javascript">
        document.getElementById("check1").checked = true;
        document.getElementById("check1").checked = false;
    </script>
</html>

I have added the language attribute to the script element, but it is unnecessary because all browsers use this as a default, but it leaves no doubt what this example is showing.

If you want to use javascript to access elements, it has a very limited set of GetElement* functions. So you are going to need to get into the habit of giving every element a UNIQUE id attribute.

How do I use IValidatableObject?

I liked cocogza's answer except that calling base.IsValid resulted in a stack overflow exception as it would re-enter the IsValid method again and again. So I modified it to be for a specific type of validation, in my case it was for an e-mail address.

[AttributeUsage(AttributeTargets.Property)]
class ValidEmailAddressIfTrueAttribute : ValidationAttribute
{
    private readonly string _nameOfBoolProp;

    public ValidEmailAddressIfTrueAttribute(string nameOfBoolProp)
    {
        _nameOfBoolProp = nameOfBoolProp;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext == null)
        {
            return null;
        }

        var property = validationContext.ObjectType.GetProperty(_nameOfBoolProp);
        if (property == null)
        {
            return new ValidationResult($"{_nameOfBoolProp} not found");
        }

        var boolVal = property.GetValue(validationContext.ObjectInstance, null);

        if (boolVal == null || boolVal.GetType() != typeof(bool))
        {
            return new ValidationResult($"{_nameOfBoolProp} not boolean");
        }

        if ((bool)boolVal)
        {
            var attribute = new EmailAddressAttribute {ErrorMessage = $"{value} is not a valid e-mail address."};
            return attribute.GetValidationResult(value, validationContext);
        }
        return null;
    }
}

This works much better! It doesn't crash and produces a nice error message. Hope this helps someone!

Split an NSString to access one particular piece

NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
NSString* firstBit = [foo objectAtIndex: 0];

Update 7/3/2018:

Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:

let substrings = "10/04/2011".split(separator: "/")
let firstBit = substrings[0]

Although note that it gives you an array of Substring. If you need to convert these back to ordinary strings, use map

let strings = "10/04/2011".split(separator: "/").map{ String($0) }
let firstBit = strings[0]

or

let firstBit = String(substrings[0])

Calculating the sum of two variables in a batch script

You can solve any equation including adding with this code:

@echo off

title Richie's Calculator 3.0

:main

echo Welcome to Richie's Calculator 3.0

echo Press any key to begin calculating...

pause>nul

echo Enter An Equation

echo Example: 1+1

set /p 

set /a sum=%equation%

echo.

echo The Answer Is:

echo %sum%

echo.

echo Press any key to return to the main menu

pause>nul

cls

goto main

How to change to an older version of Node.js

Easiest way i found -

  1. Uninstall current version
  2. Download the appropriate .msi installer (x64 or x86) for the desired version from https://nodejs.org/download/release/

How to make clang compile to llvm IR

Did you read clang documentation ? You're probably looking for -emit-llvm.

Correct modification of state arrays in React.js

This worked for me to add an array within an array

this.setState(prevState => ({
    component: prevState.component.concat(new Array(['new', 'new']))
}));

How do I compute derivative using Numpy?

Assuming you want to use numpy, you can numerically compute the derivative of a function at any point using the Rigorous definition:

def d_fun(x):
    h = 1e-5 #in theory h is an infinitesimal
    return (fun(x+h)-fun(x))/h

You can also use the Symmetric derivative for better results:

def d_fun(x):
    h = 1e-5
    return (fun(x+h)-fun(x-h))/(2*h)

Using your example, the full code should look something like:

def fun(x):
    return x**2 + 1

def d_fun(x):
    h = 1e-5
    return (fun(x+h)-fun(x-h))/(2*h)

Now, you can numerically find the derivative at x=5:

In [1]: d_fun(5)
Out[1]: 9.999999999621423

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

If you have saved the excel file in the same folder as your python program (relative paths) then you just need to mention sheet number along with file name.

Example:

 data = pd.read_excel("wt_vs_ht.xlsx", "Sheet2")
 print(data)
 x = data.Height
 y = data.Weight
 plt.plot(x,y,'x')
 plt.show()

How to install JDK 11 under Ubuntu?

To install Openjdk 11 in Ubuntu, the following commands worked well.

sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt install openjdk-11-jdk

Drop all duplicate rows across multiple columns in Python Pandas

Actually, drop rows 0 and 1 only requires (any observations containing matched A and C is kept.):

In [335]:

df['AC']=df.A+df.C
In [336]:

print df.drop_duplicates('C', take_last=True) #this dataset is a special case, in general, one may need to first drop_duplicates by 'c' and then by 'a'.
     A  B  C    AC
2  foo  1  B  fooB
3  bar  1  A  barA

[2 rows x 4 columns]

But I suspect what you really want is this (one observation containing matched A and C is kept.):

In [337]:

print df.drop_duplicates('AC')
     A  B  C    AC
0  foo  0  A  fooA
2  foo  1  B  fooB
3  bar  1  A  barA

[3 rows x 4 columns]

Edit:

Now it is much clearer, therefore:

In [352]:
DG=df.groupby(['A', 'C'])   
print pd.concat([DG.get_group(item) for item, value in DG.groups.items() if len(value)==1])
     A  B  C
2  foo  1  B
3  bar  1  A

[2 rows x 3 columns]

How To Accept a File POST

Complementing Matt Frear's answer - This would be an ASP NET Core alternative for reading the file directly from Stream, without saving&reading it from disk:

public ActionResult OnPostUpload(List<IFormFile> files)
    {
        try
        {
            var file = files.FirstOrDefault();
            var inputstream = file.OpenReadStream();

            XSSFWorkbook workbook = new XSSFWorkbook(stream);

            var FIRST_ROW_NUMBER = {{firstRowWithValue}};

            ISheet sheet = workbook.GetSheetAt(0);
            // Example: var firstCellRow = (int)sheet.GetRow(0).GetCell(0).NumericCellValue;

            for (int rowIdx = 2; rowIdx <= sheet.LastRowNum; rowIdx++)
               {
                  IRow currentRow = sheet.GetRow(rowIdx);

                  if (currentRow == null || currentRow.Cells == null || currentRow.Cells.Count() < FIRST_ROW_NUMBER) break;

                  var df = new DataFormatter();                

                  for (int cellNumber = {{firstCellWithValue}}; cellNumber < {{lastCellWithValue}}; cellNumber++)
                      {
                         //business logic & saving data to DB                        
                      }               
                }
        }
        catch(Exception ex)
        {
            throw new FileFormatException($"Error on file processing - {ex.Message}");
        }
    }

How to find sitemap.xml path on websites?

According to protocol documentation there are at least three options website designers can use to inform sitemap.xml location to search engines:

  • Informing each search engine of the location through their provided interface
  • Adding url to the robots.txt file
  • Submiting url to search engines through http

So, unless they have chosen to publish the sitemap location on their robots.txt file, you cannot really know where they have put their sitemap.xml files.

How to initialise memory with new operator in C++?

std::fill is one way. Takes two iterators and a value to fill the region with. That, or the for loop, would (I suppose) be the more C++ way.

For setting an array of primitive integer types to 0 specifically, memset is fine, though it may raise eyebrows. Consider also calloc, though it's a bit inconvenient to use from C++ because of the cast.

For my part, I pretty much always use a loop.

(I don't like to second-guess people's intentions, but it is true that std::vector is, all things being equal, preferable to using new[].)

Putty: Getting Server refused our key Error

In the case of mine it was a wrong user:group attribution. I solved setting the right user and group:

sudo chown [user]:[group] -R /home/[user]

What is the difference between a hash join and a merge join (Oracle RDBMS )?

I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.

Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.

Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.

Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.

How to get subarray from array?

For a simple use of slice, use my extension to Array Class:

Array.prototype.subarray = function(start, end) {
    if (!end) { end = -1; } 
    return this.slice(start, this.length + 1 - (end * -1));
};

Then:

var bigArr = ["a", "b", "c", "fd", "ze"];

Test1:

bigArr.subarray(1, -1);

< ["b", "c", "fd", "ze"]

Test2:

bigArr.subarray(2, -2);

< ["c", "fd"]

Test3:

bigArr.subarray(2);

< ["c", "fd","ze"]

Might be easier for developers coming from another language (i.e. Groovy).

Use custom build output folder when using create-react-app

Create-react-app Version 2+ answer

For recent (> v2) versions of create-react-app (and possible older as well), add the following line to your package.json, then rebuild.

"homepage": "./"

You should now see the build/index.html will have relative links ./static/... instead of links to the server root: /static/....

Adding 1 hour to time variable

You can use:

$time = strtotime("10:09") + 3600;
echo date('H:i', $time);

Or date_add: http://www.php.net/manual/en/datetime.add.php

Delete a row in DataGridView Control in VB.NET

Assuming you are using Windows forms, you could allow the user to select a row and in the delete key click event. It is recommended that you allow the user to select 1 row only and not a group of rows (myDataGridView.MultiSelect = false)

Private Sub pbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If myDataGridView.SelectedRows.Count > 0 Then
            'you may want to add a confirmation message, and if the user confirms delete
            myDataGridView.Rows.Remove(myDataGridView.SelectedRows(0))
        Else
            MessageBox.Show("Select 1 row before you hit Delete")
        End If

    End Sub

Note that this will not delete the row form the database until you perform the delete in the database.

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

How to delete an app from iTunesConnect / App Store Connect

Easy.

(as of 2021)

Click your app, click App Information in the left side menu, scroll all the way down to the Additional Information section, click Remove App.

Boom. done.

What underlies this JavaScript idiom: var self = this?

As others have explained, var self = this; allows code in a closure to refer back to the parent scope.

However, it's now 2018 and ES6 is widely supported by all major web browsers. The var self = this; idiom isn't quite as essential as it once was.

It's now possible to avoid var self = this; through the use of arrow functions.

In instances where we would have used var self = this:

function test() {
    var self = this;
    this.hello = "world";
    document.getElementById("test_btn").addEventListener("click", function() {
        console.log(self.hello); // logs "world"
    });
};

We can now use an arrow function without var self = this:

function test() {
    this.hello = "world";
    document.getElementById("test_btn").addEventListener("click", () => {
        console.log(this.hello); // logs "world"
    });
};

Arrow functions do not have their own this and simply assume the enclosing scope.

How to create an Array with AngularJS's ng-model

One way is to convert your array to an object and use it in scope (simulation of an array). This way has the benefit of maintaining the template.

$scope.telephone = {};
for (var i = 0, l = $scope.phones.length; i < l; i++) {
  $scope.telephone[i.toString()] = $scope.phone[i];
}

<input type="text" ng-model="telephone[0.toString()]" />
<input type="text" ng-model="telephone[1.toString()]" />

and on save, change it back.

$scope.phones = [];
for (var i in $scope.telephone) {
  $scope.phones[parseInt(i)] = $scope.telephone[i];
}

Django values_list vs values

values()

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

values_list()

Returns a QuerySet that returns list of tuples, rather than model instances, when used as an iterable.

distinct()

distinct are used to eliminate the duplicate elements.

Example:

>>> list(Article.objects.values_list('id', flat=True)) # flat=True will remove the tuples and return the list   
[1, 2, 3, 4, 5, 6]

>>> list(Article.objects.values('id'))
[{'id':1}, {'id':2}, {'id':3}, {'id':4}, {'id':5}, {'id':6}]

Error :The remote server returned an error: (401) Unauthorized

I add credentials for HttpWebRequest.

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;

How to hide form code from view code/inspect element browser?

if someones is interested you can delete the form node from the DOM after the submission and it won't be there using the inspector.

https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove

How to get the path of a running JAR file?

I tried to get the jar running path using

String folder = MyClassName.class.getProtectionDomain().getCodeSource().getLocation().getPath();

c:\app>java -jar application.jar

Running the jar application named "application.jar", on Windows in the folder "c:\app", the value of the String variable "folder" was "\c:\app\application.jar" and I had problems testing for path's correctness

File test = new File(folder);
if(file.isDirectory() && file.canRead()) { //always false }

So I tried to define "test" as:

String fold= new File(folder).getParentFile().getPath()
File test = new File(fold);

to get path in a right format like "c:\app" instead of "\c:\app\application.jar" and I noticed that it work.

csv.Error: iterator should return strings, not bytes

You open the file in text mode.

More specifically:

ifile  = open('sample.csv', "rt", encoding=<theencodingofthefile>)

Good guesses for encoding is "ascii" and "utf8". You can also leave the encoding off, and it will use the system default encoding, which tends to be UTF8, but may be something else.

Change SQLite database mode to read-write

To share personal experience I encountered with this error that eventually fix both. Might not necessarily be related to your issue but it appears this error is so generic that it can be attributed to gazillion things.

  1. Database instance open in another application. My DB appeared to have been in a "locked" state so it transition to read only mode. I was able to track it down by stopping the a 2nd instance of the application sharing the DB.

  2. Directory tree permission - please be sure to ensure user account has permission not just at the file level but at the entire upper directory level all the way to / level.

Thanks

Fastest way to implode an associative array with keys

A one-liner for creating string of HTML attributes (with quotes) from a simple array:

$attrString = str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";

Example:

$attrArray = array("id"    => "email", 
                   "name"  => "email",
                   "type"  => "email",
                   "class" => "active large");

echo str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";

// Output:
// id="email" name="email" type="email" class="active large"

Moment.js with ReactJS (ES6)

I have Used it as follow and it is working perfectly.

import React  from 'react';
import * as moment from 'moment'

exports default class MyComponent extends React.Component {
    render() {
            <div>
              {moment(dateToBeFormate).format('DD/MM/YYYY')}
            </div>            
    }
}

Find position of a node using xpath

I do a lot of Novell Identity Manager stuff, and XPATH in that context looks a little different.

Assume the value you are looking for is in a string variable, called TARGET, then the XPATH would be:

count(attr/value[.='$TARGET']/preceding-sibling::*)+1

Additionally it was pointed out that to save a few characters of space, the following would work as well:

count(attr/value[.='$TARGET']/preceding::*) + 1

I also posted a prettier version of this at Novell's Cool Solutions: Using XPATH to get the position node

How do I programmatically change file permissions?

Just to update this answer unless anyone comes across this later, since JDK 6 you can use

File file = new File('/directory/to/file');
file.setWritable(boolean);
file.setReadable(boolean);
file.setExecutable(boolean);

you can find the documentation on Oracle File(Java Platform SE 7). Bear in mind that these commands only work if the current working user has ownership or write access to that file. I am aware that OP wanted chmod type access for more intricate user configuration. these will set the option across the board for all users.

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

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

astrundir => /var/run/asterisk

Reboot your system and check

Hope this helps you

C# LINQ select from list

In likeness of how I found this question using Google, I wanted to take it one step further. Lets say I have a string[] states and a db Entity of StateCounties and I just want the states from the list returned and not all of the StateCounties.

I would write:

db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();

I found this within the sample of CheckBoxList for nu-get.

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

I think you can use display: inline-block on the element you want to center and set text-align: center; on its parent. This definitely center the div on all screen sizes.

Here you can see a fiddle: http://jsfiddle.net/PwC4T/2/ I add the code here for completeness.

HTML

<div id="container">
    <div id="main">
        <div id="somebackground">
            Hi
        </div>
    </div>
</div>

CSS

#container
{
    text-align: center;
}
#main
{
    display: inline-block;
}
#somebackground
{
    text-align: left;
    background-color: red;
}

For vertical centering, I "dropped" support for some older browsers in favour of display: table;, which absolutely reduce code, see this fiddle: http://jsfiddle.net/jFAjY/1/

Here is the code (again) for completeness:

HTML

<body>
    <div id="table-container">
        <div id="container">
            <div id="main">
                <div id="somebackground">
                    Hi
                </div>
            </div>
        </div>
    </div>
</body>

CSS

body, html
{
    height: 100%;
}
#table-container
{
    display:    table;
    text-align: center;
    width:      100%;
    height:     100%;
}
#container
{
    display:        table-cell;
    vertical-align: middle;
}
#main
{
    display: inline-block;
}
#somebackground
{
    text-align:       left;
    background-color: red;
}

The advantage of this approach? You don't have to deal with any percantage, it also handles correctly the <video> tag (html5), which has two different sizes (one during load, one after load, you can't fetch the tag size 'till video is loaded).

The downside is that it drops support for some older browser (I think IE8 won't handle this correctly)

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also

// 24 = 192 bits
    private const int SaltByteSize = 24;
    private const int HashByteSize = 24;
    private const int HasingIterationsCount = 10101;


    public static string HashPassword(string password)
    {
        // http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing

        byte[] salt;
        byte[] buffer2;
        if (password == null)
        {
            throw new ArgumentNullException("password");
        }
        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
        {
            salt = bytes.Salt;
            buffer2 = bytes.GetBytes(HashByteSize);
        }
        byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
        Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
        Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
        return Convert.ToBase64String(dst);
    }

    public static bool VerifyHashedPassword(string hashedPassword, string password)
    {
        byte[] _passwordHashBytes;

        int _arrayLen = (SaltByteSize + HashByteSize) + 1;

        if (hashedPassword == null)
        {
            return false;
        }

        if (password == null)
        {
            throw new ArgumentNullException("password");
        }

        byte[] src = Convert.FromBase64String(hashedPassword);

        if ((src.Length != _arrayLen) || (src[0] != 0))
        {
            return false;
        }

        byte[] _currentSaltBytes = new byte[SaltByteSize];
        Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);

        byte[] _currentHashBytes = new byte[HashByteSize];
        Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);

        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
        {
            _passwordHashBytes = bytes.GetBytes(SaltByteSize);
        }

        return AreHashesEqual(_currentHashBytes, _passwordHashBytes);

    }

    private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
    {
        int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
        var xor = firstHash.Length ^ secondHash.Length;
        for (int i = 0; i < _minHashLength; i++)
            xor |= firstHash[i] ^ secondHash[i];
        return 0 == xor;
    }

In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.

How can I list ALL DNS records?

host -a works well, similar to dig any.

EG:

$ host -a google.com
Trying "google.com"
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 10403
;; flags: qr rd ra; QUERY: 1, ANSWER: 18, AUTHORITY: 0, ADDITIONAL: 0


;; QUESTION SECTION:
;google.com.            IN  ANY

;; ANSWER SECTION:
google.com.     1165    IN  TXT "v=spf1 include:_spf.google.com ip4:216.73.93.70/31 ip4:216.73.93.72/31 ~all"
google.com.     53965   IN  SOA ns1.google.com. dns-admin.google.com. 2014112500 7200 1800 1209600 300
google.com.     231 IN  A   173.194.115.73
google.com.     231 IN  A   173.194.115.78
google.com.     231 IN  A   173.194.115.64
google.com.     231 IN  A   173.194.115.65
google.com.     231 IN  A   173.194.115.66
google.com.     231 IN  A   173.194.115.67
google.com.     231 IN  A   173.194.115.68
google.com.     231 IN  A   173.194.115.69
google.com.     231 IN  A   173.194.115.70
google.com.     231 IN  A   173.194.115.71
google.com.     231 IN  A   173.194.115.72
google.com.     128 IN  AAAA    2607:f8b0:4000:809::1001
google.com.     40766   IN  NS  ns3.google.com.
google.com.     40766   IN  NS  ns4.google.com.
google.com.     40766   IN  NS  ns1.google.com.
google.com.     40766   IN  NS  ns2.google.com.

How to update Identity Column in SQL Server?

If got your question right you want to do something like

update table
set identity_column_name = some value

Let me tell you, it is not an easy process and it is not advisable to use it, as there may be some foreign key associated on it.

But here are steps to do it, Please take a back-up of table

Step 1- Select design view of the table

enter image description here

Step 2- Turn off the identity column

enter image description here

Now you can use the update query.

Now redo the step 1 and step 2 and Turn on the identity column

Reference

Comments in Markdown

How about putting the comments in a non-eval, non-echo R block? i.e.,

```{r echo=FALSE, eval=FALSE}
All the comments!
```

Seems to work well for me.

How to remove an element from an array in Swift

I use this extension, almost same as Varun's, but this one (below) is all-purpose:

 extension Array where Element: Equatable  {
        mutating func delete(element: Iterator.Element) {
                self = self.filter{$0 != element }
        }
    }

Converting a String to a List of Words?

This is from my attempt on a coding challenge that can't use regex,

outputList = "".join((c if c.isalnum() or c=="'" else ' ') for c in inputStr ).split(' ')

The role of apostrophe seems interesting.

Rearrange columns using cut

Just as an addition to answers that suggest to duplicate the columns and then to do cut. For duplication, paste etc. will work only for files, but not for streams. In that case, use sed instead.

cat file.txt | sed s/'.*'/'&\t&'/ | cut -f2,3

This works on both files and streams, and this is interesting if instead of just reading from a file with cat, you do something interesting before re-arranging the columns.

By comparison, the following does not work:

cat file.txt | paste - - | cut -f2,3

Here, the double stdin placeholder paste does not duplicate stdin, but reads the next line.

Compare and contrast REST and SOAP web services?

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

By way of illustration here are few calls and their appropriate home with commentary.

getUser(User);

This is a rest operation as you are accessing a resource (data).

switchCategory(User, OldCategory, NewCategory)

REST permits many different data formats where as SOAP only permits XML. While this may seem like it adds complexity to REST because you need to handle multiple formats, in my experience it has actually been quite beneficial. JSON usually is a better fit for data and parses much faster. REST allows better support for browser clients due to it’s support for JSON.

JavaScript: Global variables after Ajax requests

The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after the request completes, like you are expecting.

What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,

var it_works = false;

$.ajax({
  url: 'some_file.php',
  async: false,  # makes request synchronous
  success: function() {
    it_works = true;
  }
});

alert(it_works);

Understanding the map function

map creates a new list by applying a function to every element of the source:

xs = [1, 2, 3]

# all of those are equivalent — the output is [2, 4, 6]
# 1. map
ys = map(lambda x: x * 2, xs)
# 2. list comprehension
ys = [x * 2 for x in xs]
# 3. explicit loop
ys = []
for x in xs:
    ys.append(x * 2)

n-ary map is equivalent to zipping input iterables together and then applying the transformation function on every element of that intermediate zipped list. It's not a Cartesian product:

xs = [1, 2, 3]
ys = [2, 4, 6]

def f(x, y):
    return (x * 2, y // 2)

# output: [(2, 1), (4, 2), (6, 3)]
# 1. map
zs = map(f, xs, ys)
# 2. list comp
zs = [f(x, y) for x, y in zip(xs, ys)]
# 3. explicit loop
zs = []
for x, y in zip(xs, ys):
    zs.append(f(x, y))

I've used zip here, but map behaviour actually differs slightly when iterables aren't the same size — as noted in its documentation, it extends iterables to contain None.

What are the best PHP input sanitizing functions?

Sanitizers

Sanitize is a function to check (and remove) harmful data from user input which can harm the software. Sanitizing user input is the most secure method of user input validation to strip out anything that is not on the whitelist.

PHP Support

5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.27, 7.4.0 - 7.4.15, 8.0.0 - 8.0.2

<?php
require_once("path/to/Sanitizers.php");

use Sanitizers\Sanitizers\Sanitizer;

\\ passing `true` in Sanitizer class enables exceptions
$sanitize = new Sanitizer(true);
try {
    echo $sanitize->Username($_GET['username']);
} catch (Exception $e) {
    echo "Could not Sanitize user input." 
    var_dump($e);
}
?>

Download the latest release

See Sanitizers GitHub project.

Eliminating duplicate values based on only one column of the table

I solve such queries using this pattern:

SELECT *
FROM t
WHERE t.field=(
  SELECT MAX(t.field) 
  FROM t AS t0 
  WHERE t.group_column1=t0.group_column1
    AND t.group_column2=t0.group_column2 ...)

That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:

WITH site_history AS (
  SELECT sites.siteName, sites.siteIP, history.date
  FROM sites
  JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
  SELECT MAX(date) 
  FROM site_history h0 
  WHERE h.siteName=h0.siteName)
ORDER BY siteName

It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date field should be unique for each siteName, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history table has an unique index for (site, date), this query is also very fast, index range scan on the history table scanning just the first item can be used.

Escaping backslash in string - javascript

Slightly hacky, but it works:

_x000D_
_x000D_
const input = '\text';_x000D_
const output = JSON.stringify(input).replace(/((^")|("$))/g, "").trim();_x000D_
_x000D_
console.log({ input, output });_x000D_
// { input: '\text', output: '\\text' }
_x000D_
_x000D_
_x000D_

How do I concatenate text in a query in sql server?

The only way would be to convert your text field into an nvarchar field.

Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a

Otherwise, I suggest doing the concatenation in your application.

Adding a simple UIAlertView

UIAlertView is deprecated on iOS 8. Therefore, to create an alert on iOS 8 and above, it is recommended to use UIAlertController:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"Alert Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

    // Enter code here
}];
[alert addAction:defaultAction];

// Present action where needed
[self presentViewController:alert animated:YES completion:nil];

This is how I have implemented it.

How to download files using axios

It's very simple javascript code to trigger a download for the user:

window.open("<insert URL here>")

You don't want/need axios for this operation; it should be standard to just let the browser do it's thing.

Note: If you need authorisation for the download then this might not work. I'm pretty sure you can use cookies to authorise a request like this, provided it's within the same domain, but regardless, this might not work immediately in such a case.


As for whether it's possible... not with the in-built file downloading mechanism, no.

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

How do I get this javascript to run every second?

window.setTimeout(func,1000);

This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.

Reference

How do I put a clear button inside my HTML text input box like the iPhone does?

Of course the best approach is to use the ever-more-supported <input type="search" />.

Anyway for a bit of coding fun I thought that it could be achieved also using the form's reset button, and this is the working result (it is worth noting that you cannot have other inputs in the form but the search field with this approach, or the reset button will erase them too), no javascript needed:

_x000D_
_x000D_
form{
    position: relative;
    width: 200px;
}

form input {
    width: 100%;
    padding-right: 20px;
    box-sizing: border-box;
}

form input:placeholder-shown + button{
  opacity: 0;
  pointer-events: none;
} 

form button {
    position: absolute;
    border: none;
    display: block;
    width: 15px;
    height: 15px;
    line-height: 16px;
    font-size: 12px;
    border-radius: 50%;
    top: 0;
    bottom: 0;
    right: 5px;
    margin: auto;
    background: #ddd;
    padding: 0;
    outline: none;
    cursor: pointer;
    transition: .1s;
}
_x000D_
<form>
        <input type="text" placeholder=" " />
        <button type="reset">&times;</button>
</form>
_x000D_
_x000D_
_x000D_

node and Error: EMFILE, too many open files

For when graceful-fs doesn't work... or you just want to understand where the leak is coming from. Follow this process.

(e.g. graceful-fs isn't gonna fix your wagon if your issue is with sockets.)

From My Blog Article: http://www.blakerobertson.com/devlog/2014/1/11/how-to-determine-whats-causing-error-connect-emfile-nodejs.html

How To Isolate

This command will output the number of open handles for nodejs processes:

lsof -i -n -P | grep nodejs
COMMAND     PID    USER   FD   TYPE    DEVICE SIZE/OFF NODE NAME
...
nodejs    12211    root 1012u  IPv4 151317015      0t0  TCP 10.101.42.209:40371->54.236.3.170:80 (ESTABLISHED)
nodejs    12211    root 1013u  IPv4 151279902      0t0  TCP 10.101.42.209:43656->54.236.3.172:80 (ESTABLISHED)
nodejs    12211    root 1014u  IPv4 151317016      0t0  TCP 10.101.42.209:34450->54.236.3.168:80 (ESTABLISHED)
nodejs    12211    root 1015u  IPv4 151289728      0t0  TCP 10.101.42.209:52691->54.236.3.173:80 (ESTABLISHED)
nodejs    12211    root 1016u  IPv4 151305607      0t0  TCP 10.101.42.209:47707->54.236.3.172:80 (ESTABLISHED)
nodejs    12211    root 1017u  IPv4 151289730      0t0  TCP 10.101.42.209:45423->54.236.3.171:80 (ESTABLISHED)
nodejs    12211    root 1018u  IPv4 151289731      0t0  TCP 10.101.42.209:36090->54.236.3.170:80 (ESTABLISHED)
nodejs    12211    root 1019u  IPv4 151314874      0t0  TCP 10.101.42.209:49176->54.236.3.172:80 (ESTABLISHED)
nodejs    12211    root 1020u  IPv4 151289768      0t0  TCP 10.101.42.209:45427->54.236.3.171:80 (ESTABLISHED)
nodejs    12211    root 1021u  IPv4 151289769      0t0  TCP 10.101.42.209:36094->54.236.3.170:80 (ESTABLISHED)
nodejs    12211    root 1022u  IPv4 151279903      0t0  TCP 10.101.42.209:43836->54.236.3.171:80 (ESTABLISHED)
nodejs    12211    root 1023u  IPv4 151281403      0t0  TCP 10.101.42.209:43930->54.236.3.172:80 (ESTABLISHED)
....

Notice the: 1023u (last line) - that's the 1024th file handle which is the default maximum.

Now, Look at the last column. That indicates which resource is open. You'll probably see a number of lines all with the same resource name. Hopefully, that now tells you where to look in your code for the leak.

If you don't know multiple node processes, first lookup which process has pid 12211. That'll tell you the process.

In my case above, I noticed that there were a bunch of very similar IP Addresses. They were all 54.236.3.### By doing ip address lookups, was able to determine in my case it was pubnub related.

Command Reference

Use this syntax to determine how many open handles a process has open...

To get a count of open files for a certain pid

I used this command to test the number of files that were opened after doing various events in my app.

lsof -i -n -P | grep "8465" | wc -l
# lsof -i -n -P | grep "nodejs.*8465" | wc -l
28
# lsof -i -n -P | grep "nodejs.*8465" | wc -l
31
# lsof -i -n -P | grep "nodejs.*8465" | wc -l
34

What is your process limit?

ulimit -a

The line you want will look like this:

open files                      (-n) 1024

Permanently change the limit:

  • tested on Ubuntu 14.04, nodejs v. 7.9

In case you are expecting to open many connections (websockets is a good example), you can permanently increase the limit:

  • file: /etc/pam.d/common-session (add to the end)

      session required pam_limits.so
    
  • file: /etc/security/limits.conf (add to the end, or edit if already exists)

      root soft  nofile 40000
      root hard  nofile 100000
    
  • restart your nodejs and logout/login from ssh.

  • this may not work for older NodeJS you'll need to restart server

  • use instead of if your node runs with different uid.

How to access global js variable in AngularJS directive

Copy the global variable to a variable in the scope in your controller.

function MyCtrl($scope) {
   $scope.variable1 = variable1;
}

Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).

But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I had the same problem and it resolved by disabling Gradle's offline mode although I could not remember when I did disable it!

Here's the solution:

How to disable Gradle 'offline mode' in android studio? [duplicate]

(change) vs (ngModelChange) in angular

In Angular 7, the (ngModelChange)="eventHandler()" will fire before the value bound to [(ngModel)]="value" is changed while the (change)="eventHandler()" will fire after the value bound to [(ngModel)]="value" is changed.

Using python map and other functional tools

import itertools

foos=[1.0, 2.0, 3.0, 4.0, 5.0]
bars=[1, 2, 3]

print zip(foos, itertools.cycle([bars]))

jQuery disable a link

If you go the href route, you can save it

To disable:

$('a').each(function(){
    $(this).data("href", $(this).attr("href")).removeAttr("href");
});

Then re-enable using:

$('a').each(function(){
    $(this).attr("href", $(this).data("href"));
});

In one case I had to do it this way because the click events were already bound somewhere else and I had no control over it.

Class has no objects member

If you use python 3

python3 -m pip install pylint-django

If python < 3

python -m pip install pylint-django==0.11.1

NOTE: Version 2.0, requires pylint >= 2.0 which doesn’t support Python 2 anymore! (https://pypi.org/project/pylint-django/)

How to compare two maps by their values

All of these are returning equals. They arent actually doing a comparison, which is useful for sort. This will behave more like a comparator:

private static final Comparator stringFallbackComparator = new Comparator() {
    public int compare(Object o1, Object o2) {
        if (!(o1 instanceof Comparable))
            o1 = o1.toString();
        if (!(o2 instanceof Comparable))
            o2 = o2.toString();
        return ((Comparable)o1).compareTo(o2);
    }
};

public int compare(Map m1, Map m2) {
    TreeSet s1 = new TreeSet(stringFallbackComparator); s1.addAll(m1.keySet());
    TreeSet s2 = new TreeSet(stringFallbackComparator); s2.addAll(m2.keySet());
    Iterator i1 = s1.iterator();
    Iterator i2 = s2.iterator();
    int i;
    while (i1.hasNext() && i2.hasNext())
    {
        Object k1 = i1.next();
        Object k2 = i2.next();
        if (0!=(i=stringFallbackComparator.compare(k1, k2)))
            return i;
        if (0!=(i=stringFallbackComparator.compare(m1.get(k1), m2.get(k2))))
            return i;
    }
    if (i1.hasNext())
        return 1;
    if (i2.hasNext())
        return -1;
    return 0;
}

How to open the default webbrowser using java

on windows invoke "cmd /k start http://www.example.com" Infact you can always invoke "default" programs using the start command. For ex start abc.mp3 will invoke the default mp3 player and load the requested mp3 file.

Set the maximum character length of a UITextField

This limits the number of characters, but also make sure that you can paste in the field until the maximum limit.

- (void)textViewDidChange:(UITextView *)textView
{
    NSString* str = [textView text];
    str = [str substringToIndex:MIN(1000,[str length])];
    [textView setText:str];

    if([str length]==1000) {
        // show some label that you've reached the limit of 1000 characters
    }
}

Getting title and meta tags from external website

<?php 

// ------------------------------------------------------ 

function curl_get_contents($url) {

    $timeout = 5; 
    $useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0'; 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 

    return $data; 
}

// ------------------------------------------------------ 

function fetch_meta_tags($url) { 

    $html = curl_get_contents($url); 
    $mdata = array(); 

    $doc = new DOMDocument();
    $doc->loadHTML($html);

    $titlenode = $doc->getElementsByTagName('title'); 
    $title = $titlenode->item(0)->nodeValue;

    $metanodes = $doc->getElementsByTagName('meta'); 
    foreach($metanodes as $node) { 
    $key = $node->getAttribute('name'); 
    $val = $node->getAttribute('content'); 
    if (!empty($key)) { $mdata[$key] = $val; } 
    }

    $res = array($url, $title, $mdata); 

    return $res;
}

// ------------------------------------------------------ 

?>

NodeJS/express: Cache and 304 status code

Old question, I know. Disabling the cache facility is not needed and not the best way to manage the problem. By disabling the cache facility the server needs to work harder and generates more traffic. Also the browser and device needs to work harder, especially on mobile devices this could be a problem.

The empty page can be easily solved by using Shift key+reload button at the browser.

The empty page can be a result of:

  • a bug in your code
  • while testing you served an empty page (you can't remember) that is cached by the browser
  • a bug in Safari (if so, please report it to Apple and don't try to fix it yourself)

Try first the Shift keyboard key + reload button and see if the problem still exists and review your code.

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

The verification of the certificate identity is performed against what the client requests.

When your client uses https://xxx.xxx.xxx.xxx/something (where xxx.xxx.xxx.xxx is an IP address), the certificate identity is checked against this IP address (in theory, only using an IP SAN extension).

If your certificate has no IP SAN, but DNS SANs (or if no DNS SAN, a Common Name in the Subject DN), you can get this to work by making your client use a URL with that host name instead (or a host name for which the cert would be valid, if there are multiple possible values). For example, if you cert has a name for www.example.com, use https://www.example.com/something.

Of course, you'll need that host name to resolve to that IP address.

In addition, if there are any DNS SANs, the CN in the Subject DN will be ignored, so use a name that matches one of the DNS SANs in this case.

Rails: update_attribute vs update_attributes

Recently I ran into update_attribute vs. update_attributes and validation issue, so similar names, so different behavior, so confusing.

In order to pass hash to update_attribute and bypass validation you can do:

object = Object.new
object.attributes = {
  field1: 'value',
  field2: 'value2',
  field3: 'value3'
}
object.save!(validate: false)

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

To avoid adding extra divs when clicking on the link multiple times, and avoid problems when using the script to display forms, you could try a variation of @jek's code.

$('a.ajax').live('click', function() {
    var url = this.href;
    var dialog = $("#dialog");
    if ($("#dialog").length == 0) {
        dialog = $('<div id="dialog" style="display:hidden"></div>').appendTo('body');
    } 

    // load remote content
    dialog.load(
            url,
            {},
            function(responseText, textStatus, XMLHttpRequest) {
                dialog.dialog();
            }
        );
    //prevent the browser to follow the link
    return false;
});`

Parse HTML in Android

Have you tried using Html.fromHtml(source)?

I think that class is pretty liberal with respect to source quality (it uses TagSoup internally, which was designed with real-life, bad HTML in mind). It doesn't support all HTML tags though, but it does come with a handler you can implement to react on tags it doesn't understand.

Best way to create enum of strings?

Get and set with default values.

public enum Status {

    STATUS_A("Status A"),  STATUS_B("Status B"),

    private String status;

    Status(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }
}

How to get an HTML element's style values in javascript?

In jQuery, you can do alert($("#theid").css("width")).

-- if you haven't taken a look at jQuery, I highly recommend it; it makes many simple javascript tasks effortless.

Update

for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.

Can you control how an SVG's stroke-width is drawn?

I found an easy way, which has a few restrictions, but worked for me:

  • define the shape in defs
  • define a clip path referencing the shape
  • use it and double the stroke with as the outside is clipped

Here a working example:

_x000D_
_x000D_
<svg width="240" height="240" viewBox="0 0 1024 1024">_x000D_
<defs>_x000D_
 <path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>_x000D_
 <clipPath id="clip">_x000D_
  <use xlink:href="#ld"/>_x000D_
 </clipPath>_x000D_
</defs>_x000D_
<g>_x000D_
 <use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="#00D2B8" clip-path="url(#clip)"/>_x000D_
</g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Get json value from response

If the response is in json then it would be like:

alert(response.id);

Otherwise

var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

How to send parameters with jquery $.get()

Try this:

$.ajax({
    type: 'get',
    url: 'manageproducts.do',
    data: 'option=1',
    success: function(data) {

        availableProductNames = data.split(",");

        alert(availableProductNames);

    }
});

Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.

Use of Custom Data Types in VBA

Sure you can:

Option Explicit

'***** User defined type
Public Type MyType
     MyInt As Integer
     MyString As String
     MyDoubleArr(2) As Double
End Type

'***** Testing MyType as single variable
Public Sub MyFirstSub()
    Dim MyVar As MyType

    MyVar.MyInt = 2
    MyVar.MyString = "cool"
    MyVar.MyDoubleArr(0) = 1
    MyVar.MyDoubleArr(1) = 2
    MyVar.MyDoubleArr(2) = 3

    Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub

'***** Testing MyType as an array
Public Sub MySecondSub()
    Dim MyArr(2) As MyType
    Dim i As Integer

    MyArr(0).MyInt = 31
    MyArr(0).MyString = "VBA"
    MyArr(0).MyDoubleArr(0) = 1
    MyArr(0).MyDoubleArr(1) = 2
    MyArr(0).MyDoubleArr(2) = 3
    MyArr(1).MyInt = 32
    MyArr(1).MyString = "is"
    MyArr(1).MyDoubleArr(0) = 11
    MyArr(1).MyDoubleArr(1) = 22
    MyArr(1).MyDoubleArr(2) = 33
    MyArr(2).MyInt = 33
    MyArr(2).MyString = "cool"
    MyArr(2).MyDoubleArr(0) = 111
    MyArr(2).MyDoubleArr(1) = 222
    MyArr(2).MyDoubleArr(2) = 333

    For i = LBound(MyArr) To UBound(MyArr)
        Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
    Next
End Sub

Convert MySql DateTime stamp into JavaScript's Date format

var a=dateString.split(" ");
var b=a[0].split("-");
var c=a[1].split(":");
var date = new Date(b[0],(b[1]-1),b[2],b[0],c[1],c[2]);

CSS getting text in one line rather than two

The best way to use is white-space: nowrap; This will align the text to one line.

How to use GNU Make on Windows?

Although this question is old, it is still asked by many who use MSYS2.

I started to use it this year to replace CygWin, and I'm getting pretty satisfied.

To install make, open the MSYS2 shell and type the following commands:

# Update the package database and core system packages
pacman -Syu
# Close shell and open again if needed

# Update again
pacman -Su

# Install make
pacman -S make

# Test it (show version)
make -v

"The given path's format is not supported."

I see that the originator found out that the error occurred when trying to save the filename with an entire path. Actually it's enough to have a ":" in the file name to get this error. If there might be ":" in your file name (for instance if you have a date stamp in your file name) make sure you replace these with something else. I.e:

string fullFileName = fileName.Split('.')[0] + "(" + DateTime.Now.ToString().Replace(':', '-') + ")." + fileName.Split('.')[1];

Embedding DLLs in a compiled executable

To expand on @Bobby's asnwer above. You can edit your .csproj to use IL-Repack to automatically package all files into a single assembly when you build.

  1. Install the nuget ILRepack.MSBuild.Task package with Install-Package ILRepack.MSBuild.Task
  2. Edit the AfterBuild section of your .csproj

Here is a simple sample that merges ExampleAssemblyToMerge.dll into your project output.

<!-- ILRepack -->
<Target Name="AfterBuild" Condition="'$(Configuration)' == 'Release'">

   <ItemGroup>
    <InputAssemblies Include="$(OutputPath)\$(AssemblyName).exe" />
    <InputAssemblies Include="$(OutputPath)\ExampleAssemblyToMerge.dll" />
   </ItemGroup>

   <ILRepack 
    Parallel="true"
    Internalize="true"
    InputAssemblies="@(InputAssemblies)"
    TargetKind="Exe"
    OutputFile="$(OutputPath)\$(AssemblyName).exe"
   />
</Target>

how to convert numeric to nvarchar in sql command

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.

However, if the result must match a specific culture, FORMAT might be the function to go:

DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value)        -->  1505.5698
SELECT FORMAT(@value, 'N2', 'en-us')    --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de')    --> 1.505,57

For more information on FORMAT see here.

Of course, formatting the result should be a matter of the UI layer of the software.

Sass Variable in CSS calc() function

you can use your verbal #{your verbal}

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

Try this:

package my_default;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test {

    public static void main(String[] args) {
        try {
        // Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook();

        // Get first/desired sheet from the workbook
        XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);

        // XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
        // because you get Sheet index (1) is out of range (no sheets)

        //Write some information in the cells or do what you want
        XSSFRow row1 = sheet.createRow(0);
        XSSFCell r1c2 = row1.createCell(0);
        r1c2.setCellValue("NAME");
        XSSFCell r1c3 = row1.createCell(1);
        r1c3.setCellValue("AGE");


        //Save excel to HDD Drive
        File pathToFile = new File("D:\\test.xlsx");
        if (!pathToFile.exists()) {
            pathToFile.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(pathToFile);
        workbook.write(fos);
        fos.close();
        System.out.println("Done");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
    XSSFSheet sheet = null;
    int count = 0;

    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        String sName = wb.getSheetName(i);
        if (sName.startsWith(prefix))
            count++;
    }

    if (count > 0) {
        sheet = wb.createSheet(prefix + count);
    } else
        sheet = wb.createSheet(prefix);

    if (isHidden)
        wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);

        return sheet;
    }

}

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

'node' is not recognized as an internal or external command

Try adding C:\Program Files\Nodejs to your PATH environment variable. The PATH environment variable allows run executables or access files within the folders specified (separated by semicolons).

On the command prompt, the command would be set PATH=%PATH%;C:\Program Files\Nodejs.

Python: converting a list of dictionaries to json

To convert it to a single dictionary with some decided keys value, you can use the code below.

data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
    ListOfDictAsDict[PrecedingText + str(i)] = data[i]

Command to collapse all sections of code?

In case of ugrading to Visual Studio 2010, 2012, 2013 or 2015, there's a Visual Studio extension to show current registered keyboard shortcuts, IntelliCommand.

Various ways to remove local Git changes

Option 1: Discard tracked and untracked file changes

Discard changes made to both staged and unstaged files.

$ git reset --hard [HEAD]

Then discard (or remove) untracked files altogether.

$ git clean [-f]

Option 2: Stash

You can first stash your changes

$ git stash

And then either drop or pop it depending on what you want to do. See https://git-scm.com/docs/git-stash#_synopsis.

Option 3: Manually restore files to original state

First we switch to the target branch

$ git checkout <branch-name>

List all files that have changes

$ git status

Restore each file to its original state manually

$ git restore <file-path>

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

Gradle does not find tools.jar

It may be two years too late, but I ran into the same problem recently and this is the solution I ended up with after finding this post:

import javax.tools.ToolProvider

dependencies {
  compile (
    files(((URLClassLoader) ToolProvider.getSystemToolClassLoader()).getURLs()),
    ...
  }
}

It should work if java.home points to a directory that's not under the JDK directory and even on Mac OS where you'd have classes.jar instead of tools.jar.

Is the practice of returning a C++ reference variable evil?

I find the answers not satisfactory so I'll add my two cents.

Let's analyze the following cases:

Erroneous usage

int& getInt()
{
    int x = 4;
    return x;
}

This is obviously error

int& x = getInt(); // will refer to garbage

Usage with static variables

int& getInt()
{
   static int x = 4;
   return x;
}

This is right, because static variables are existant throughout lifetime of a program.

int& x = getInt(); // valid reference, x = 4

This is also quite common when implementing Singleton pattern

Class Singleton
{
    public:
        static Singleton& instance()
        {
            static Singleton instance;
            return instance;
        };

        void printHello()
        {
             printf("Hello");
        };

}

Usage:

 Singleton& my_sing = Singleton::instance(); // Valid Singleton instance
 my_sing.printHello();  // "Hello"

Operators

Standard library containers depend heavily upon usage of operators which return reference, for example

T & operator*();

may be used in the following

std::vector<int> x = {1, 2, 3}; // create vector with 3 elements
std::vector<int>::iterator iter = x.begin(); // iterator points to first element (1)
*iter = 2; // modify first element, x = {2, 2, 3} now

Quick access to internal data

There are times when & may be used for quick access to internal data

Class Container
{
    private:
        std::vector<int> m_data;

    public:
        std::vector<int>& data()
        {
             return m_data;
        }
}

with usage:

Container cont;
cont.data().push_back(1); // appends element to std::vector<int>
cont.data()[0] // 1

HOWEVER, this may lead to pitfall such as this:

Container* cont = new Container;
std::vector<int>& cont_data = cont->data();
cont_data.push_back(1);
delete cont; // This is bad, because we still have a dangling reference to its internal data!
cont_data[0]; // dangling reference!

What is it exactly a BLOB in a DBMS context

This may seem like a silly question, but what do you actually want to use a RDBMS for ?

If you just want to store files, then the operating system's filesystem is generally adequate. An RDBMS is generally used for structured data and (except for embedded ones like SQLite) handling concurrent manipulation of that data (locking etc). Other useful features are security (handling access to the data) and backup/recovery. In the latter, the primary advantage over a regular filesystem backup is being able to recover to a point in time between backups by applying some form of log files.

BLOBs are, as far as the database concerned, unstructured and opaque. Oracle does have some specific ORDSYS types for multi-media objects (eg images) that also have a bunch of metadata attached, and have associated methods (eg rescaling or recolouring an image).

MySQL - Trigger for updating same table after insert

It seems that you can't do all this in a trigger. According to the documentation:

Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

According to this answer, it seems that you should:

create a stored procedure, that inserts into/Updates the target table, then updates the other row(s), all in a transaction.

With a stored proc you'll manually commit the changes (insert and update). I haven't done this in MySQL, but this post looks like a good example.

How to split a string to 2 strings in C

If you have a char array allocated you can simply put a '\0' wherever you want. Then point a new char * pointer to the location just after the newly inserted '\0'.

This will destroy your original string though depending on where you put the '\0'

Regular Expression for matching parentheses

For any special characters you should use '\'. So, for matching parentheses - /\(/

Twitter Bootstrap Multilevel Dropdown Menu

This example is from http://bootsnipp.com/snippets/featured/multi-level-dropdown-menu-bs3

Works for me in Bootstrap v3.1.1.

HTML

<div class="container">
<div class="row">
    <h2>Multi level dropdown menu in Bootstrap 3</h2>
    <hr>
    <div class="dropdown">
        <a id="dLabel" role="button" data-toggle="dropdown" class="btn btn-primary" data-target="#" href="/page.html">
            Dropdown <span class="caret"></span>
        </a>
        <ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
          <li><a href="#">Some action</a></li>
          <li><a href="#">Some other action</a></li>
          <li class="divider"></li>
          <li class="dropdown-submenu">
            <a tabindex="-1" href="#">Hover me for more options</a>
            <ul class="dropdown-menu">
              <li><a tabindex="-1" href="#">Second level</a></li>
              <li class="dropdown-submenu">
                <a href="#">Even More..</a>
                <ul class="dropdown-menu">
                    <li><a href="#">3rd level</a></li>
                    <li><a href="#">3rd level</a></li>
                </ul>
              </li>
              <li><a href="#">Second level</a></li>
              <li><a href="#">Second level</a></li>
            </ul>
          </li>
        </ul>
    </div>
</div>

CSS

.dropdown-submenu {
position: relative;
}

.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
-webkit-border-radius: 0 6px 6px 6px;
-moz-border-radius: 0 6px 6px;
border-radius: 0 6px 6px 6px;
}

.dropdown-submenu:hover>.dropdown-menu {
display: block;
}

.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #ccc;
margin-top: 5px;
margin-right: -10px;
}

.dropdown-submenu:hover>a:after {
border-left-color: #fff;
}

.dropdown-submenu.pull-left {
float: none;
}

.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
-webkit-border-radius: 6px 0 6px 6px;
-moz-border-radius: 6px 0 6px 6px;
border-radius: 6px 0 6px 6px;
}

How can I send and receive WebSocket messages on the server side?

In addition to the PHP frame encoding function, here follows a decode function:

function Decode($M){
    $M = array_map("ord", str_split($M));
    $L = $M[1] AND 127;

    if ($L == 126)
        $iFM = 4;
    else if ($L == 127)
        $iFM = 10;
    else
        $iFM = 2;

    $Masks = array_slice($M, $iFM, 4);

    $Out = "";
    for ($i = $iFM + 4, $j = 0; $i < count($M); $i++, $j++ ) {
        $Out .= chr($M[$i] ^ $Masks[$j % 4]);
    }
    return $Out;
}

I've implemented this and also other functions in an easy-to-use WebSocket PHP class here.

Facebook user url by id

The marked answer seems outdated and it won't work.

Facebook now only gives unique ID related to app which isn't equal to userId and profileUrl and username will come out to be empty.

Doing me?fields=id,name,links is also depreciated after Graph Version 2.4

The only option now is to request for user_links permission from your developer console.

enter image description here

and the pass it in scope when doing facebook login

scope: ['user_link'] }

or by doing an api call

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

comdlg32.dll is not really a COM dll (you can't register it).

What you need is comdlg32.ocx which contains the MSComDlg.CommonDialog COM class (and indeed relies on comdlg32.dll to work). Once you get ahold on a comdlg32.ocx, then you will be able to do regsvr32 comdlg32.ocx.

AngularJS - How can I do a redirect with a full page load?

I had the same issue. When I use window.location, $window.location or even <a href="..." target="_self"> the route does not refresh the page. So the cached services are used which is not what I want in my app. I resolved it by adding window.location.reload() after window.location to force the page to reload after routing. This method seems to load the page twice though. Might be a dirty trick, but it does the work. This is how I have it now:

  $scope.openPage = function (pageName) {
      window.location = '#/html/pages/' + pageName;
      window.location.reload();
  };

How do I reverse a commit in git?

This article has an excellent explanation as to how to go about various scenarios (where a commit has been done as well as the push OR just a commit, before the push):

http://christoph.ruegg.name/blog/git-howto-revert-a-commit-already-pushed-to-a-remote-reposit.html

From the article, the easiest command I saw to revert a previous commit by its commit id, was:

git revert dd61ab32

check if variable empty

To check for null values you can use is_null() as is demonstrated below.

if (is_null($value)) {
   $value = "MY TEXT"; //define to suit
}

How can I generate a list of consecutive numbers?

Using Python's built in range function:

Python 2

input = 8
output = range(input + 1)

print output
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Python 3

input = 8
output = list(range(input + 1))

print(output)
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Best practices for catching and re-throwing .NET exceptions

When you throw ex, you're essentially throwing a new exception, and will miss out on the original stack trace information. throw is the preferred method.

Run a PostgreSQL .sql file using command line arguments

You have four choices to supply a password:

  1. Set the PGPASSWORD environment variable. For details see the manual:
    http://www.postgresql.org/docs/current/static/libpq-envars.html
  2. Use a .pgpass file to store the password. For details see the manual:
    http://www.postgresql.org/docs/current/static/libpq-pgpass.html
  3. Use "trust authentication" for that specific user: http://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-TRUST
  4. Since PostgreSQL 9.1 you can also use a connection string:
    https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING

How to do "If Clicked Else .."

 var flag = 0;

 $('#target').click(function() {
    flag = 1;
 });

 if (flag == 1)
 {
  alert("Clicked");
 }
 else
 {
   alert("Not clicked");
 }

How to count the number of observations in R like Stata command count

You can also use the filter function from the dplyr package which returns rows with matching conditions.

> library(dplyr)

> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

Facebook database design?

This recent June 2013 post goes into some detail into explaining the transition from relationship databases to objects with associations for some data types.

https://www.facebook.com/notes/facebook-engineering/tao-the-power-of-the-graph/10151525983993920

There's a longer paper available at https://www.usenix.org/conference/atc13/tao-facebook’s-distributed-data-store-social-graph

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

Never ever should you use money. It is not precise, and it is pure garbage; always use decimal/numeric.

Run this to see what I mean:

DECLARE
    @mon1 MONEY,
    @mon2 MONEY,
    @mon3 MONEY,
    @mon4 MONEY,
    @num1 DECIMAL(19,4),
    @num2 DECIMAL(19,4),
    @num3 DECIMAL(19,4),
    @num4 DECIMAL(19,4)

    SELECT
    @mon1 = 100, @mon2 = 339, @mon3 = 10000,
    @num1 = 100, @num2 = 339, @num3 = 10000

    SET @mon4 = @mon1/@mon2*@mon3
    SET @num4 = @num1/@num2*@num3

    SELECT @mon4 AS moneyresult,
    @num4 AS numericresult

Output: 2949.0000 2949.8525

To some of the people who said that you don't divide money by money:

Here is one of my queries to calculate correlations, and changing that to money gives wrong results.

select t1.index_id,t2.index_id,(avg(t1.monret*t2.monret)
    -(avg(t1.monret) * avg(t2.monret)))
            /((sqrt(avg(square(t1.monret)) - square(avg(t1.monret))))
            *(sqrt(avg(square(t2.monret)) - square(avg(t2.monret))))),
current_timestamp,@MaxDate
            from Table1 t1  join Table1 t2  on t1.Date = traDate
            group by t1.index_id,t2.index_id

Counting DISTINCT over multiple columns

What is it about your existing query that you don't like? If you are concerned that DISTINCT across two columns does not return just the unique permutations why not try it?

It certainly works as you might expect in Oracle.

SQL> select distinct deptno, job from emp
  2  order by deptno, job
  3  /

    DEPTNO JOB
---------- ---------
        10 CLERK
        10 MANAGER
        10 PRESIDENT
        20 ANALYST
        20 CLERK
        20 MANAGER
        30 CLERK
        30 MANAGER
        30 SALESMAN

9 rows selected.


SQL> select count(*) from (
  2  select distinct deptno, job from emp
  3  )
  4  /

  COUNT(*)
----------
         9

SQL>

edit

I went down a blind alley with analytics but the answer was depressingly obvious...

SQL> select count(distinct concat(deptno,job)) from emp
  2  /

COUNT(DISTINCTCONCAT(DEPTNO,JOB))
---------------------------------
                                9

SQL>

edit 2

Given the following data the concatenating solution provided above will miscount:

col1  col2
----  ----
A     AA
AA    A

So we to include a separator...

select col1 + '*' + col2 from t23
/

Obviously the chosen separator must be a character, or set of characters, which can never appear in either column.

unknown type name 'uint8_t', MinGW

EDIT:

To Be Clear: If the order of your #includes matters and it is not part of your design pattern (read: you don't know why), then you need to rethink your design. Most likely, this just means you need to add the #include to the header file causing problems.

At this point, I have little interest in discussing/defending the merits of the example but will leave it up as it illustrates some nuances in the compilation process and why they result in errors.

END EDIT

You need to #include the stdint.h BEFORE you #include any other library interfaces that need it.

Example:

My LCD library uses uint8_t types. I wrote my library with an interface (Display.h) and an implementation (Display.c)

In display.c, I have the following includes.

#include <stdint.h>
#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>

And this works.

However, if I re-arrange them like so:

#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>
#include <stdint.h>

I get the error you describe. This is because Display.h needs things from stdint.h but can't access it because that information is compiled AFTER Display.h is compiled.

So move stdint.h above any library that need it and you shouldn't get the error anymore.

SQL SELECT everything after a certain character

select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;

Please use http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php for further reference.

Eclipse Workspaces: What for and why?

Although I've used Eclipse for years, this "answer" is only conjecture (which I'm going to try tonight). If it gets down-voted out of existence, then obviously I'm wrong.

Oracle relies on CMake to generate a Visual Studio "Solution" for their MySQL Connector C source code. Within the Solution are "Projects" that can be compiled individually or collectively (by the Solution). Each Project has its own makefile, compiling its portion of the Solution with settings that are different than the other Projects.

Similarly, I'm hoping an Eclipse Workspace can hold my related makefile Projects (Eclipse), with a master Project whose dependencies compile the various unique-makefile Projects as pre-requesites to building its "Solution". (My folder structure would be as @Rafael describes).

So I'm hoping a good way to use Workspaces is to emulate Visual Studio's ability to combine dissimilar Projects into a Solution.

T-SQL Substring - Last 3 Characters

if you want to specifically find strings which ends with desired characters then this would help you...

select * from tablename where col_name like '%190'

Regular expression for number with length of 4, 5 or 6

Be aware that, as written, Peter's solution will "accept" 0000. If you want to validate numbers between 1000 and 999999, then that is another problem :-)

^[1-9][0-9]{3,5}$

for example will block inserting 0 at the beginning of the string.

If you want to accept 0 padding, but only up to a lengh of 6, so that 001000 is valid, then it becomes more complex. If we use look-ahead then we can write something like

^(?=[0-9]{4,6}$)0*[1-9][0-9]{3,}$

This first checks if the string is long 4-6 (?=[0-9]{4,6}$), then skips the 0s 0*and search for a non-zero [1-9] followed by at least 3 digits [0-9]{3,}.

PHP: How to check if a date is today, yesterday or tomorrow

I think this will help you:

<?php
$date = new DateTime();
$match_date = new DateTime($timestamp);
$interval = $date->diff($match_date);

if($interval->days == 0) {

    //Today

} elseif($interval->days == 1) {
    if($interval->invert == 0) {
        //Yesterday
    } else {
        //Tomorrow
    }
} else {
    //Sometime
}

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

What I did was to create an extension to UITextField and added a Designer editable property. Setting this property to any color would change the border (bottom) to that color (setting other borders to none).

Since this also requires to change the place holder text color, I also added that to the extension.

    extension UITextField {

    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
        }
    }


    @IBInspectable var bottomBorderColor: UIColor? {
        get {
            return self.bottomBorderColor
        }
        set {
            self.borderStyle = UITextBorderStyle.None;
            let border = CALayer()
            let width = CGFloat(0.5)
            border.borderColor = newValue?.CGColor
            border.frame = CGRect(x: 0, y: self.frame.size.height - width,   width:  self.frame.size.width, height: self.frame.size.height)

            border.borderWidth = width
            self.layer.addSublayer(border)
            self.layer.masksToBounds = true

        }
    }
}

Fix footer to bottom of page

The Footer be positioned at the bottom of the page, but not fixed.

CSS

html {
  height: 100%;
}

body {
  position: relative;
  margin: 0;
  min-height: 100%;  
  padding: 0;
}
#header {
  background: #595959;
  height: 90px;
}
#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 90px;
  background-color: #595959;
}

HTML

<html>
   <head></head>
   <body>        
      <div id="header"></div>
      <div id="content"></div>
      <div id="footer"></div>     
   </body>
</html>  

Parsing JSON using Json.net

I don't know about JSON.NET, but it works fine with JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1):

using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
    public string OBJECT_NAME { get; set; }
    public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
    public int id { get; set; }
}
public class SubObject
{
    public NameTypePair attributes { get; set; }
    public Position position { get; set; }
}
public class Position
{
    public int x { get; set; }
    public int y { get; set; }
}
public class Foo
{
    public Foo() { objects = new List<SubObject>(); }
    public string displayFieldName { get; set; }
    public NameTypePair fieldAliases { get; set; }
    public PositionType positionType { get; set; }
    public Ref reference { get; set; }
    public List<SubObject> objects { get; set; }
}
static class Program
{

    const string json = @"{
  ""displayFieldName"" : ""OBJECT_NAME"", 
  ""fieldAliases"" : {
    ""OBJECT_NAME"" : ""OBJECT_NAME"", 
    ""OBJECT_TYPE"" : ""OBJECT_TYPE""
  }, 
  ""positionType"" : ""point"", 
  ""reference"" : {
    ""id"" : 1111
  }, 
  ""objects"" : [
    {
      ""attributes"" : {
        ""OBJECT_NAME"" : ""test name"", 
        ""OBJECT_TYPE"" : ""test type""
      }, 
      ""position"" : 
      {
        ""x"" : 5, 
        ""y"" : 7
      }
    }
  ]
}";


    static void Main()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Foo foo = ser.Deserialize<Foo>(json);
    }


}

Edit:

Json.NET works using the same JSON and classes.

Foo foo = JsonConvert.DeserializeObject<Foo>(json);

Link: Serializing and Deserializing JSON with Json.NET

Getter and Setter declaration in .NET

Just to clarify, in your 3rd example _myProperty isn't actually a property. It's a field with get and set methods (and as has already been mentioned the get and set methods should specify return types).

In C# the 3rd method should be avoided in most situations. You'd only really use it if the type you wanted to return was an array, or if the get method did a lot of work rather than just returning a value. The latter isn't really necessary but for the purpose of clarity a property's get method that does a lot of work is misleading.

"Insufficient Storage Available" even there is lot of free space in device memory

The same problem was coming for my phone and this resolved the problem:

  • Go to Application Manager/ Apps from Settings.

  • Select Google Play Services.

Enter image description here

  • Click Uninstall Updates button to the right of the Force Stop button.

  • Once the updates are uninstalled, you should see Disable button which means you are done.

Enter image description here

You will see lots of free space available now.

How to use gitignore command in git

git ignore is a convention in git. Setting a file by the name of .gitignore will ignore the files in that directory and deeper directories that match the patterns that the file contains. The most common use is just to have one file like this at the top level. But you can add others deeper in your directory structure to ignore even more patterns or stop ignoring them for that directory and subsequently deeper ones.

Likewise, you can "unignore" certain files in a deeper structure or a specific subset (ie, you ignore *.log but want to still track important.log) by specifying patterns beginning with !. eg:

*.log !important.log

will ignore all log files but will track files named important.log

If you are tracking files you meant to ignore, delete them, add the pattern to you .gitignore file and add all the changes

# delete files that should be ignored, or untrack them with 
# git rm --cached <file list or pattern>

# stage all the changes git commit
git add -A 

from now on your repository will not have them tracked.

If you would like to clean up your history, you can

# if you want to correct the last 10 commits
git rebase -i --preserve-merges HEAD~10 

then mark each commit with e or edit. Save the plan. Now git will replay your history stopping at each commit you marked with e. Here you delete the files you don't want, git add -A and then git rebase --continue until you are done. Your history will be clean. Make sure you tell you coworkers as you will have to force push and they will have to rebase what they didn't push yet.

How to Fill an array from user input C#?

readline is for string.. just use read

Simulate a specific CURL in PostMan

As mentioned in multiple answers above you can import the cURL in POSTMAN directly. But if URL is authorized (or is not working for some reason) ill suggest you can manually add all the data points as JSON in your postman body. take the API URL from the cURL.

for the Authorization part- just add an Authorization key and base 64 encoded string as value.

example:

curl -u rzp_test_26ccbdbfe0e84b:69b2e24411e384f91213f22a \ https://api.razorpay.com/v1/orders -X POST \ --data "amount=50000" \ --data "currency=INR" \ --data "receipt=Receipt #20" \ --data "payment_capture=1" https://api.razorpay.com/v1/orders

{ "amount": "5000", "currency": "INR", "receipt": "Receipt #20", "payment_capture": "1" }

Headers: Authorization:Basic cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J where "cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J" is the encoded form of "rzp_test_26ccbdbfe0e84b:69b2e24411e384f91213f22a"`

small tip: for encoding, you can easily go to your chrome console (right-click => inspect) and type : btoa("string you want to encode") ( or use postman basic authorization)

Copying text to the clipboard using Java

I found a better way of doing it so you can get a input from a txtbox or have something be generated in that text box and be able to click a button to do it.!

import java.awt.datatransfer.*;
import java.awt.Toolkit;

private void /* Action performed when the copy to clipboard button is clicked */ {
    String ctc = txtCommand.getText().toString();
    StringSelection stringSelection = new StringSelection(ctc);
    Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
    clpbrd.setContents(stringSelection, null);
}

// txtCommand is the variable of a text box