Programs & Examples On #Instant messaging

Instant messaging (IM) is a form of communication over the Internet, that offers quick transmission of text-based messages from sender to receiver.

Android Whatsapp/Chat Examples

If you are looking to create an instant messenger for Android, this code should get you started somewhere.

Excerpt from the source :

This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.

EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.

There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!

*UPDATE : * Scringo services will be closed down on 15 February, 2015.

How do I import other TypeScript files?

If you are doing something for the web you need to use the js file extension:

import { moo } from 'file.js';


If you are doing something for nodejs I don't think use the js file extension:

import { moo } from 'file';

Spark - repartition() vs coalesce()

repartition - it's recommended to use it while increasing the number of partitions, because it involve shuffling of all the data.

coalesce - it's is recommended to use it while reducing the number of partitions. For example if you have 3 partitions and you want to reduce it to 2, coalesce will move the 3rd partition data to partition 1 and 2. Partition 1 and 2 will remains in the same container. On the other hand, repartition will shuffle data in all the partitions, therefore the network usage between the executors will be high and it will impacts the performance.

coalesce performs better than repartition while reducing the number of partitions.

Set timeout for ajax (jQuery)

Please read the $.ajax documentation, this is a covered topic.

$.ajax({
    url: "test.html",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000 // sets timeout to 3 seconds
});

You can get see what type of error was thrown by accessing the textStatus parameter of the error: function(jqXHR, textStatus, errorThrown) option. The options are "timeout", "error", "abort", and "parsererror".

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

Parameter names are normally not accessible by the Java code at runtime (because it's drop by the compiler), so if you want that functionality you need to either use Java 8's built-in functionality or use a library such as ParaNamer in order to gain access to it.

So in order to not having to utilize annotations for the constructor arguments when using Jackson, you can make use of either of these 2 Jackson modules:

jackson-module-parameter-names

This module allows you to get annotation-free constructor arguments when using Java 8. In order to use it you first need to register the module:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new ParameterNamesModule());

Then compile your code using the -parameters flag:

javac -parameters ...

Link: https://github.com/FasterXML/jackson-modules-java8/tree/master/parameter-names

jackson-module-paranamer

This other one simply requires you to register the module or configure an annotation introspection (but not both as pointed out by the comments). It allows you to use annotation-free constructor arguments on versions of Java prior to 1.8.

ObjectMapper mapper = new ObjectMapper();
// either via module
mapper.registerModule(new ParanamerModule());
// or by directly assigning annotation introspector (but not both!)
mapper.setAnnotationIntrospector(new ParanamerOnJacksonAnnotationIntrospector());

Link: https://github.com/FasterXML/jackson-modules-base/tree/master/paranamer

Fixed height and width for bootstrap carousel

To have a consistent flow of the images on different devices, you'd have to specify the width and height value for each carousel image item, for instance here in my example the image would take the full width but with a height of "400px" (you can specify your personal value instead)

<div class="item">
        <img src="image.jpg" style="width:100%; height: 400px;">
      </div>

grep from tar.gz without extracting [faster one]

Am trying to grep pattern from dozen files .tar.gz but its very slow

tar -ztf file.tar.gz | while read FILENAME
do
        if tar -zxf file.tar.gz "$FILENAME" -O | grep "string" > /dev/null
        then
                echo "$FILENAME contains string"
        fi
done

That's actually very easy with ugrep option -z:

-z, --decompress
        Decompress files to search, when compressed.  Archives (.cpio,
        .pax, .tar, and .zip) and compressed archives (e.g. .taz, .tgz,
        .tpz, .tbz, .tbz2, .tb2, .tz2, .tlz, and .txz) are searched and
        matching pathnames of files in archives are output in braces.  If
        -g, -O, -M, or -t is specified, searches files within archives
        whose name matches globs, matches file name extensions, matches
        file signature magic bytes, or matches file types, respectively.
        Supported compression formats: gzip (.gz), compress (.Z), zip,
        bzip2 (requires suffix .bz, .bz2, .bzip2, .tbz, .tbz2, .tb2, .tz2),
        lzma and xz (requires suffix .lzma, .tlz, .xz, .txz).

Which requires just one command to search file.tar.gz as follows:

ugrep -z "string" file.tar.gz

This greps each of the archived files to display matches. Archived filenames are shown in braces to distinguish them from ordinary filenames. For example:

$ ugrep -z "Hello" archive.tgz
{Hello.bat}:echo "Hello World!"
Binary file archive.tgz{Hello.class} matches
{Hello.java}:public class Hello // prints a Hello World! greeting
{Hello.java}:  { System.out.println("Hello World!");
{Hello.pdf}:(Hello)
{Hello.sh}:echo "Hello World!"
{Hello.txt}:Hello

If you just want the file names, use option -l (--files-with-matches) and customize the filename output with option --format="%z%~" to get rid of the braces:

$ ugrep -z Hello -l --format="%z%~" archive.tgz
Hello.bat
Hello.class
Hello.java
Hello.pdf
Hello.sh
Hello.txt

error opening trace file: No such file or directory (2)

Actually, the problem is that either /sys/kernel/debug is not mounted, or that the running kernel has no ftrace tracers compiled in so that /sys/kernel/debug/tracing is unavailable. This is the code throwing the error (platform_frameworks_native/libs/utils/Trace.cpp):

void Tracer::init() {
    Mutex::Autolock lock(sMutex);

    if (!sIsReady) {
        add_sysprop_change_callback(changeCallback, 0);

        const char* const traceFileName =
                "/sys/kernel/debug/tracing/trace_marker";
        sTraceFD = open(traceFileName, O_WRONLY);
        if (sTraceFD == -1) {
            ALOGE("error opening trace file: %s (%d)", strerror(errno), errno);
            sEnabledTags = 0;   // no tracing can occur
        } else {
            loadSystemProperty();
        }

        android_atomic_release_store(1, &sIsReady);
    }
}

The log message could definitely be a bit more informative.

Simple JavaScript problem: onClick confirm not preventing default action

There's a typo in your code (the tag a is closed too early). You can either use:

<a href="whatever" onclick="return confirm('are you sure?')"><img ...></a>

note the return (confirm): the value returned by scripts in intrinsic evens decides whether the default browser action is run or not; in case you need to run a big piece of code you can of course call another function:

<script type="text/javascript">
function confirm_delete() {
  return confirm('are you sure?');
}
</script>
...
<a href="whatever" onclick="return confirm_delete()"><img ...></a>

(note that delete is a keyword)

For completeness: modern browsers also support DOM events, allowing you to register more than one handler for the same event on each object, access the details of the event, stop the propagation and much more; see DOM Events.

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

To customize tool bar style, first create tool bar custom style inheriting Widget.AppCompat.Toolbar, override properties and then add it to custom app theme as shown below, see http://www.zoftino.com/android-toolbar-tutorial for more information tool bar and styles.

   <style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="toolbarStyle">@style/MyToolBarStyle</item>
    </style>
    <style name="MyToolBarStyle" parent="Widget.AppCompat.Toolbar">
        <item name="android:background">#80deea</item>
        <item name="titleTextAppearance">@style/MyTitleTextAppearance</item>
        <item name="subtitleTextAppearance">@style/MySubTitleTextAppearance</item>
    </style>
    <style name="MyTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <item name="android:textSize">35dp</item>
        <item name="android:textColor">#ff3d00</item>
    </style>
    <style name="MySubTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
        <item name="android:textSize">30dp</item>
        <item name="android:textColor">#1976d2</item>
    </style>

How to disable SSL certificate checking with Spring RestTemplate?

@Bean(name = "restTemplateByPassSSL")
public RestTemplate restTemplateByPassSSL()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    HostnameVerifier hostnameVerifier = (s, sslSession) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}

jQuery each loop in table row

Use immediate children selector >:

$('#tblOne > tbody  > tr')

Description: Selects all direct child elements specified by "child" of elements specified by "parent".

ArrayList - How to modify a member of an object?

I wrote you 2 classes to show you how it's done; Main and Customer. If you run the Main class you see what's going on:

import java.util.*;

public class Customer {

    private String name;
    private String email;

    public Customer(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return name + " | " + email;
    }

    public static String toString(Collection<Customer> customers) {
        String s = "";
        for(Customer customer : customers) {
            s += customer + "\n";
        }
        return s;
    }

}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer("Bert", "[email protected]"));
        customers.add(new Customer("Ernie", "[email protected]"));
        System.out.println("customers before email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
        customers.get(1).setEmail("[email protected]");
        System.out.println("customers after email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
    }

}

to get this running, make 2 classes, Main and Customer and copy paste the contents from both classes to the correct class; then run the Main class.

How can I get the current time in C#?

DateTime.Now.ToString("HH:mm:ss tt");

this gives it to you as a string.

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

In case you are still having this problem, click on the Tests and select a team for them too.

Difference between scaling horizontally and vertically for databases

Horizontal scaling means that you scale by adding more machines into your pool of resources whereas Vertical scaling means that you scale by adding more power (CPU, RAM) to an existing machine.

An easy way to remember this is to think of a machine on a server rack, we add more machines across the horizontal direction and add more resources to a machine in the vertical direction.

                  Horizontal Scaling/Vertical Scaling Visualisation

In the database world, horizontal-scaling is often based on the partitioning of the data i.e. each node contains only part of the data, in vertical-scaling the data resides on a single node and scaling is done through multi-core i.e. spreading the load between the CPU and RAM resources of that machine.

With horizontal-scaling it is often easier to scale dynamically by adding more machines into the existing pool - Vertical-scaling is often limited to the capacity of a single machine, scaling beyond that capacity often involves downtime and comes with an upper limit.

Good examples of horizontal scaling are Cassandra, MongoDB, Google Cloud Spanner .. and a good example of vertical scaling is MySQL - Amazon RDS (The cloud version of MySQL). It provides an easy way to scale vertically by switching from small to bigger machines. This process often involves downtime.

In-Memory Data Grids such as GigaSpaces XAP, Coherence etc.. are often optimized for both horizontal and vertical scaling simply because they're not bound to disk. Horizontal-scaling through partitioning and vertical-scaling through multi-core support.

You can read more on this subject in my earlier posts: Scale-out vs Scale-up and The Common Principles Behind the NOSQL Alternatives

How to pause in C?

Is it a console program, running in Windows? If so, run it from a console you've already opened. i.e. run "cmd", then change to your directory that has the .exe in it (using the cd command), then type in the exe name. Your console window will stay open.

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

The accepted answer of how to create an Index inline a Table creation script did not work for me. This did:

CREATE TABLE [dbo].[TableToBeCreated]
(
    [Id] BIGINT IDENTITY(1, 1) NOT NULL PRIMARY KEY
    ,[ForeignKeyId] BIGINT NOT NULL
    ,CONSTRAINT [FK_TableToBeCreated_ForeignKeyId_OtherTable_Id] FOREIGN KEY ([ForeignKeyId]) REFERENCES [dbo].[OtherTable]([Id])
    ,INDEX [IX_TableToBeCreated_ForeignKeyId] NONCLUSTERED ([ForeignKeyId])
)

Remember, Foreign Keys do not create Indexes, so it is good practice to index them as you will more than likely be joining on them.

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

With Bootstrap 4 .hidden-* classes were completely removed (yes, they were replaced by hidden-*-* but those classes are also gone from v4 alphas).

Starting with v4-beta, you can combine .d-*-none and .d-*-block classes to achieve the same result.

visible-* was removed as well; instead of using explicit .visible-* classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:

<div class="col d-none d-sm-block">
    <span class="vcard">
        …
    </span>
</div>
<div class="col d-none d-xl-block">
    <div class="d-none d-md-block">
                …
    </div>
    <div class="d-none d-sm-block">
                …
    </div>
</div>

class="hidden-xs" becomes class="d-none d-sm-block" (or d-none d-sm-inline-block) ...

<span class="d-none d-sm-inline">hidden-xs</span>

<span class="d-none d-sm-inline-block">hidden-xs</span>

An example of Bootstrap 4 responsive utilities:

<div class="d-none d-sm-block"> hidden-xs           
  <div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
    <div class="d-none d-lg-block"> visible-lg and up  (hidden-md and down)
      <div class="d-none d-xl-block"> visible-xl </div>
    </div>
  </div>
</div>

<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>

<div class="d-xl-none"> hidden-xl (visible-lg and down)         
  <div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
    <div class="d-md-none d-lg-none d-xl-none"> visible-sm and down  (or hidden-md and up)
      <div class="d-sm-none"> visible-xs </div>
    </div>
  </div>
</div>

Documentation

Maven project version inheritance - do I have to specify the parent version?

Maven is not designed to work that way, but a workaround exists to achieve this goal (maybe with side effects, you will have to give a try). The trick is to tell the child project to find its parent via its relative path rather than its pure maven coordinates, and in addition to externalize the version number in a property :

Parent pom

<groupId>com.dummy.bla</groupId>
<artifactId>parent</artifactId>
<version>${global.version}</version>
<packaging>pom</packaging>

<properties>
   <!-- Unique entry point for version number management --> 
   <global.version>0.1-SNAPSHOT</global.version>
</properties>

Child pom

<parent>
   <groupId>com.dummy.bla</groupId>
   <artifactId>parent</artifactId>
   <version>${global.version}</version>
   <relativePath>..</relativePath>    
</parent>

<groupId>com.dummy.bla.sub</groupId>
<artifactId>kid</artifactId>

I used that trick for a while for one of my project, with no specific problem, except the fact that maven logs a lot of warnings at the beginning of the build, which is not very elegant.

EDIT

Seems maven 3.0.4 does not allow such a configuration anymore.

How to count digits, letters, spaces for a string in Python?

You shouldn't be setting x = []. That is setting an empty list to your inputted parameter. Furthermore, use python's for i in x syntax as follows:

for i in x:
    if i.isalpha():
        letters+=1
    elif i.isnumeric():
        digit+=1
    elif i.isspace():
        space+=1
    else:
        other+=1

How to create image slideshow in html?

  1. Set var step=1 as global variable by putting it above the function call
  2. put semicolons

It will look like this

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<2)
                step++;
            else
                step=1;
            setTimeout("slideit()",2500);
        }
        slideit();
</script>
</body>

HTML5 Video tag not working in Safari , iPhone and iPad

I had same issue with apple devices like iPhone and iPad, I turned off the low power mode and it worked and you should also include playsinline attribute in video tag like this:

<video class="video-background" autoplay loop muted playsinline>

It only worked when including playsinline.

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

How to show current time in JavaScript in the format HH:MM:SS?

You can use native function Date.toLocaleTimeString():

var d = new Date();
var n = d.toLocaleTimeString();

This will display e.g.:

"11:33:01"

I found it on http://www.w3schools.com/jsref/jsref_tolocaletimestring.asp

_x000D_
_x000D_
var d = new Date();_x000D_
var n = d.toLocaleTimeString();_x000D_
alert("The time is: \n"+n);
_x000D_
_x000D_
_x000D_

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

Shorter and dealing with a column (entire, not just a section of a column):

=COUNTA(A:A)

COUNTA

Beware, a cell containing just a space would be included in the count.

Android studio, gradle and NDK

In Google IO 2015, Google announced full NDK integration in Android Studio 1.3.

It is now out of preview, and available to everyone: https://developer.android.com/studio/projects/add-native-code.html

Old answer: Gradle automatically calls ndk-build if you have a jni directory in your project sources.

This is working on Android studio 0.5.9 (canary build).

  1. Download the NDK

  2. Either add ANDROID_NDK_HOME to your environment variables or add ndk.dir=/path/to/ndk to your local.properties in your Android Studio project. This allows Android studio to run the ndk automatically.

  3. Download the latest gradle sample projects to see an example of an ndk project. (They're at the bottom of the page). A good sample project is ndkJniLib.

  4. Copy the gradle.build from the NDK sample projects. It'll look something like this. This gradle.build creates a different apk for each architecture. You must select which architecture you want using the build variants pane. build variants pane

    apply plugin: 'android'
    
    dependencies {
        compile project(':lib')
    }
    
    android {
        compileSdkVersion 19
        buildToolsVersion "19.0.2"
    
        // This actual the app version code. Giving ourselves 100,000 values [0, 99999]
        defaultConfig.versionCode = 123
    
        flavorDimensions "api", "abi"
    
        productFlavors {
            gingerbread {
                flavorDimension "api"
                minSdkVersion 10
                versionCode = 1
            }
            icecreamSandwich {
                flavorDimension "api"
                minSdkVersion 14
                versionCode = 2
            }
            x86 {
                flavorDimension "abi"
                ndk {
                    abiFilter "x86"
                }
                // this is the flavor part of the version code.
                // It must be higher than the arm one for devices supporting
                // both, as x86 is preferred.
                versionCode = 3
            }
            arm {
                flavorDimension "abi"
                ndk {
                    abiFilter "armeabi-v7a"
                }
                versionCode = 2
            }
            mips {
                flavorDimension "abi"
                ndk {
                    abiFilter "mips"
                }
                versionCode = 1
            }
            fat {
                flavorDimension "abi"
                // fat binary, lowest version code to be
                // the last option
                versionCode = 0
            }
        }
    
        // make per-variant version code
        applicationVariants.all { variant ->
            // get the version code of each flavor
            def apiVersion = variant.productFlavors.get(0).versionCode
            def abiVersion = variant.productFlavors.get(1).versionCode
    
            // set the composite code
            variant.mergedFlavor.versionCode = apiVersion * 1000000 + abiVersion * 100000 + defaultConfig.versionCode
        }
    
    }
    

Note that this will ignore your Android.mk and Application.mk files. As a workaround, you can tell gradle to disable atuomatic ndk-build call, then specify the directory for ndk sources manually.

sourceSets.main {
    jniLibs.srcDir 'src/main/libs' // use the jni .so compiled from the manual ndk-build command
    jni.srcDirs = [] //disable automatic ndk-build call
}

In addition, you'll probably want to call ndk-build in your gradle build script explicitly, because you just disabled the automatic call.

task ndkBuild(type: Exec) {
   commandLine 'ndk-build', '-C', file('src/main/jni').absolutePath
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}

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']))
}));

Can I change the color of Font Awesome's icon color?

You can change the Font Awesome's icon color with the bootstrap class

use

text-color

example

text-white

Deserialize from string instead TextReader

1-liner, takes a XML string text and YourType as the expected object type. not very different from other answers, just compressed to 1 line:

var result =  (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));

Convert float to std::string in C++

Unless you're worried about performance, use string streams:

#include <sstream>
//..

std::ostringstream ss;
ss << myFloat;
std::string s(ss.str());

If you're okay with Boost, lexical_cast<> is a convenient alternative:

std::string s = boost::lexical_cast<std::string>(myFloat);

Efficient alternatives are e.g. FastFormat or simply the C-style functions.

Java heap terminology: young, old and permanent generations?

The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

CSS background image to fit height, width should auto-scale in proportion

try

.something { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -100;  
}

Python: Checking if a 'Dictionary' is empty doesn't seem to work

Here are three ways you can check if dict is empty. I prefer using the first way only though. The other two ways are way too wordy.

test_dict = {}

if not test_dict:
    print "Dict is Empty"


if not bool(test_dict):
    print "Dict is Empty"


if len(test_dict) == 0:
    print "Dict is Empty"

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

Division in Python 2.7. and 3.3

In python 2.7, the / operator is integer division if inputs are integers.

If you want float division (which is something I always prefer), just use this special import:

from __future__ import division

See it here:

>>> 7 / 2
3
>>> from __future__ import division
>>> 7 / 2
3.5
>>>

Integer division is achieved by using //, and modulo by using %

>>> 7 % 2
1
>>> 7 // 2
3
>>>

EDIT

As commented by user2357112, this import has to be done before any other normal import.

is there a tool to create SVG paths from an SVG file?

(In reply to the "has the situation improved?" part of the question):

Unfortunately, not really. Illustrator's support for SVG has always been a little shaky, and, having mucked around in Illustrator's internals, I doubt we'll see much improvement as far as Illustrator is concerned.

If you're looking for DOM-style access to an Illustrator document, you might want to check out Hanpuku (Disclosure #1: I'm the author. Disclosure #2: It's research code, meaning there are bugs aplenty, and future support is unlikely).

With Hanpuku, you could do something like:

  1. Select the path of interest in Illustrator
  2. Click the "To D3" button
  3. In the script editor, type:

    selection.attr('d', 'M 0 0 L 20 134 L 233 24 Z');

  4. Click run

  5. If the change is as expected, click "To Illustrator" to apply the changes to the document

Granted, this approach doesn't expose the original path string. If you follow the instructions toward the end of the plugin's welcome page, it's possible to edit the Illustrator document with Chrome's developer tools, but there will be lots of ugly engineering exposed everywhere (the SVG DOM that mirrors the Illustrator document is buried inside an iframe deep in the extension—changing the DOM with Chrome's tools and clicking "To Illustrator" should still work, but you will likely encounter lots of problems).

TL;DR: Illustrator uses an internal model that's pretty different from SVG in a lot of ways, meaning that when you iterate between the two, currently, your only choice is to use the subset of features that both support in the same way.

How to downgrade the installed version of 'pip' on windows?

If downgrading from pip version 10 because of PyCharm manage.py or other python errors:

python -m pip install pip==9.0.1

Java: Finding the highest value in an array

It's printing out a number every time it finds one that is higher than the current max (which happens to occur three times in your case.) Move the print outside of the for loop and you should be good.

for (int counter = 1; counter < decMax.length; counter++)
{
     if (decMax[counter] > max)
     {
      max = decMax[counter];
     }
}

System.out.println("The highest maximum for the December is: " + max);

How to search file text for a pattern and replace it with a given value

Here's a solution for find/replace in all files of a given directory. Basically I took the answer provided by sepp2k and expanded it.

# First set the files to search/replace in
files = Dir.glob("/PATH/*")

# Then set the variables for find/replace
@original_string_or_regex = /REGEX/
@replacement_string = "STRING"

files.each do |file_name|
  text = File.read(file_name)
  replace = text.gsub!(@original_string_or_regex, @replacement_string)
  File.open(file_name, "w") { |file| file.puts replace }
end

Nginx: stat() failed (13: permission denied)

I had the same issue, I am using Plesk Onyx 17 with Centos7. I could see this error in proxy_error_log under the affected domain's logs. All the dirs/files in /var/www/vhosts/ are owned by respective users (domain owners) and you can see that all of them are in psacln group. So solution was to add nginx also to this group, so he can see what he needs:

usermod -aG psacln nginx

And indeed, restart nginx and reload page with Ctrl+F5.

PHP - find entry by object property from an array of objects

Using array_column to re-index will save time if you need to find multiple times:

$lookup = array_column($arr, NULL, 'id');   // re-index by 'id'

Then you can simply $lookup[$id] at will.

Content Type text/xml; charset=utf-8 was not supported by service

I saw this problem today when trying to create a WCF service proxy, both using VS2010 and svcutil.

Everything I'm doing is with basicHttpBinding (so no issue with wsHttpBinding).

For the first time in my recollection MSDN actually provided me with the solution, at the following link How to: Publish Metadata for a Service Using a Configuration File. The line I needed to change was inside the behavior element inside the MEX service behavior element inside my service app.config file. I changed it from

&lt;serviceMetadata httpGetEnabled="true"/>  
to  
&lt;serviceMetadata httpGetEnabled="true" policyVersion="Policy15"/>

and like magic the error went away and I was able to create the service proxy. Note that there is a corresponding MSDN entry for using code instead of a config file: How to: Publish Metadata for a Service Using Code.

(Of course, Policy15 - how could I possibly have overlooked that???)

One more "gotcha": my service needs to expose 3 different endpoints, each supporting a different contract. For each proxy that I needed to build, I had to comment out the other 2 endpoints, otherwise svcutil would complain that it could not resolve the base URL address.

Searching word in vim?

If you are working in Ubuntu,follow the steps:

  1. Press / and type word to search
  2. To search in forward press 'SHIFT' key with * key
  3. To search in backward press 'SHIFT' key with # key

Adding a custom header to HTTP request using angular.js

I took what you had, and added another X-Testing header

var config = {headers:  {
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json;odata=verbose',
        "X-Testing" : "testing"
    }
};

$http.get("/test", config);

And in the Chrome network tab, I see them being sent.

GET /test HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Accept: application/json;odata=verbose
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Authorization: Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==
X-Testing: testing
Referer: http://localhost:3000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Are you not seeing them from the browser, or on the server? Try the browser tooling or a debug proxy and see what is being sent out.

How to make cross domain request

If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather). I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.

How to stop (and restart) the Rails Server?

Now in rails 5 yu can do:

rails restart

This print by rails --tasks

Restart app by touching tmp/restart.txt

I think that is usefully if you run rails as a demon

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

You need to create own PCH file
Add New file -> Other-> PCH file

Then add the path of this PCH file to your build setting->prefix header->path

($(SRCROOT)/filename.pch)

enter image description here

How to install a previous exact version of a NPM package?

If you have to install an older version of a package, just specify it

npm install <package>@<version>

For example: npm install [email protected]

You can also add the --save flag to that command to add it to your package.json dependencies, or --save --save-exact flags if you want that exact version specified in your package.json dependencies.

The install command is documented here: https://docs.npmjs.com/cli/install

If you're not sure what versions of a package are available, you can use:

npm view <package> versions

And npm view can be used for viewing other things about a package too. https://docs.npmjs.com/cli/view

Get latitude and longitude automatically using php, API

//add urlencode to your address
$address = urlencode("technopark, Trivandrun, kerala,India");
$region = "IND";
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");

echo $json;

$decoded = json_decode($json);

print_r($decoded);

MySQL Creating tables with Foreign Keys giving errno: 150

I had the same problem with ALTER TABLE ADD FOREIGN KEY.

After an hour, I found that these conditions must be satisfied to not get error 150:

  1. The Parent table must exist before you define a foreign key to reference it. You must define the tables in the right order: Parent table first, then the Child table. If both tables references each other, you must create one table without FK constraints, then create the second table, then add the FK constraint to the first table with ALTER TABLE.

  2. The two tables must both support foreign key constraints, i.e. ENGINE=InnoDB. Other storage engines silently ignore foreign key definitions, so they return no error or warning, but the FK constraint is not saved.

  3. The referenced columns in the Parent table must be the left-most columns of a key. Best if the key in the Parent is PRIMARY KEY or UNIQUE KEY.

  4. The FK definition must reference the PK column(s) in the same order as the PK definition. For example, if the FK REFERENCES Parent(a,b,c) then the Parent's PK must not be defined on columns in order (a,c,b).

  5. The PK column(s) in the Parent table must be the same data type as the FK column(s) in the Child table. For example, if a PK column in the Parent table is UNSIGNED, be sure to define UNSIGNED for the corresponding column in the Child table field.

    Exception: length of strings may be different. For example, VARCHAR(10) can reference VARCHAR(20) or vice versa.

  6. Any string-type FK column(s) must have the same character set and collation as the corresponding PK column(s).

  7. If there is data already in the Child table, every value in the FK column(s) must match a value in the Parent table PK column(s). Check this with a query like:

    SELECT COUNT(*) FROM Child LEFT OUTER JOIN Parent ON Child.FK = Parent.PK 
    WHERE Parent.PK IS NULL;
    

    This must return zero (0) unmatched values. Obviously, this query is an generic example; you must substitute your table names and column names.

  8. Neither the Parent table nor the Child table can be a TEMPORARY table.

  9. Neither the Parent table nor the Child table can be a PARTITIONED table.

  10. If you declare a FK with the ON DELETE SET NULL option, then the FK column(s) must be nullable.

  11. If you declare a constraint name for a foreign key, the constraint name must be unique in the whole schema, not only in the table in which the constraint is defined. Two tables may not have their own constraint with the same name.

  12. If there are any other FK's in other tables pointing at the same field you are attempting to create the new FK for, and they are malformed (i.e. different collation), they will need to be made consistent first. This may be a result of past changes where SET FOREIGN_KEY_CHECKS = 0; was utilized with an inconsistent relationship defined by mistake. See @andrewdotn's answer below for instructions on how to identify these problem FK's.

Hope this helps.

how to change class name of an element by jquery

$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

You need to give the user table an alias the second time you join to it

e.g.

SELECT article . * , section.title, category.title, user.name, u2.name 
FROM article 
INNER JOIN section ON article.section_id = section.id 
INNER JOIN category ON article.category_id = category.id 
INNER JOIN user ON article.author_id = user.id 
LEFT JOIN user u2 ON article.modified_by = u2.id 
WHERE article.id = '1'

How to change the Jupyter start-up folder

In case you are using WinPython and not anaconda then you need to navigate to the directory where you installed the WinPython for e.g. C:\WPy-3670\settings\.jupyter\jupyter_notebook_config.py

You need to edit this file and find the line #c.NotebookApp.notebook_dir = '' change it to for e.g. c.NotebookApp.notebook_dir = 'D:/your_own_folder/containing/jupyter_notes'

You also need to change backslash \to forward slashes /. also make sure to uncomment the line by removing #

How to use ES6 Fat Arrow to .filter() an array of objects

You can't implicitly return with an if, you would need the braces:

let adults = family.filter(person => { if (person.age > 18) return person} );

It can be simplified though:

let adults = family.filter(person => person.age > 18);

PHP send mail to multiple email addresses

Following code will do the task....

<?php

$contacts = array(
"[email protected]",
"[email protected]",
//....as many email address as you need
);

foreach($contacts as $contact) {

$to      =  $contact;
$subject = 'the subject';
$message = 'hello';
mail($to, $subject, $message, $headers);

}

?>

Java sending and receiving file (byte[]) over sockets

Rookie, if you want to write a file to server by socket, how about using fileoutputstream instead of dataoutputstream? dataoutputstream is more fit for protocol-level read-write. it is not very reasonable for your code in bytes reading and writing. loop to read and write is necessary in java io. and also, you use a buffer way. flush is necessary. here is a code sample: http://www.rgagnon.com/javadetails/java-0542.html

Read text file into string. C++ ifstream

getline(fin, buffer, '\n')
where fin is opened file(ifstream object) and buffer is of string/char type where you want to copy line.

How to convert decimal to hexadecimal in JavaScript

var number = 3200;
var hexString = number.toString(16);

The 16 is the radix and there are 16 values in a hexadecimal number :-)

Not an enclosing class error Android Studio

It should be

Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);

You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.

not an enclosing class error is thrown because of your usage of this keyword. this is a reference to the current object — the object whose method or constructor is being called. With this you can only refer to any member of the current object from within an instance method or a constructor.

Katra_home.this is invalid construct

Select datatype of the field in postgres

If you like 'Mike Sherrill' solution but don't want to use psql, I used this query to get the missing information:

select column_name,
case 
    when domain_name is not null then domain_name
    when data_type='character varying' THEN 'varchar('||character_maximum_length||')'
    when data_type='numeric' THEN 'numeric('||numeric_precision||','||numeric_scale||')'
    else data_type
end as myType
from information_schema.columns
where table_name='test'

with result:

column_name |     myType
-------------+-------------------
 test_id     | test_domain
 test_vc     | varchar(15)
 test_n      | numeric(15,3)
 big_n       | bigint
 ip_addr     | inet

Renaming the current file in Vim

This little script isn't perfect (the extra carriage-return you have to press) but it get's the job done.

function Rename()
  let new_file_name = input('New filename: ')
  let full_path_current_file = expand("%:p")
  let new_full_path = expand("%:p:h")."/".new_file_name
  bd    
  execute "!mv ".full_path_current_file." ".new_full_path
  execute "e ".new_full_path
endfunction                                                                                                                                                                                                                                 

command! Rename :call Rename()
nmap RN :Rename<CR>

Why does the Google Play store say my Android app is incompatible with my own device?

Permissions that Imply Feature Requirements

example, the android.hardware.bluetooth feature was added in Android 2.2 (API level 8), but the bluetooth API that it refers to was added in Android 2.0 (API level 5). Because of this, some apps were able to use the API before they had the ability to declare that they require the API via the system.

To prevent those apps from being made available unintentionally, Google Play assumes that certain hardware-related permissions indicate that the underlying hardware features are required by default. For instance, applications that use Bluetooth must request the BLUETOOTH permission in a element — for legacy apps, Google Play assumes that the permission declaration means that the underlying android.hardware.bluetooth feature is required by the application and sets up filtering based on that feature.

The table below lists permissions that imply feature requirements equivalent to those declared in elements. Note that declarations, including any declared android:required attribute, always take precedence over features implied by the permissions below.

For any of the permissions below, you can disable filtering based on the implied feature by explicitly declaring the implied feature explicitly, in a element, with an android:required="false" attribute. For example, to disable any filtering based on the CAMERA permission, you would add this declaration to the manifest file:

<uses-feature android:name="android.hardware.camera" android:required="false" />


<uses-feature android:name="android.hardware.bluetooth" android:required="false" />
<uses-feature android:name="android.hardware.location" android:required="false" />
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
<uses-feature android:name="android.hardware.telephony" android:required="false" />
<uses-feature android:name="android.hardware.wifi" android:required="false" />

http://developer.android.com/guide/topics/manifest/uses-feature-element.html#permissions

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

I was going to leave this after this comment: Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

But Stack Overflow was formatting it weirdly.

If you don't have identical machines and are checking in node_modules, do a .gitignore on the native extensions. Our .gitignore looks like:

# Ignore native extensions in the node_modules folder (things changed by npm rebuild)
node_modules/**/*.node
node_modules/**/*.o
node_modules/**/*.a
node_modules/**/*.mk
node_modules/**/*.gypi
node_modules/**/*.target
node_modules/**/.deps/
node_modules/**/build/Makefile
node_modules/**/**/build/Makefile

Test this by first checking everything in, and then have another developer do the following:

rm -rf node_modules
git checkout -- node_modules
npm rebuild
git status

Ensure that no files changed.

List all employee's names and their managers by manager name using an inner join

Your query is close you need to join using the mgr and the empid

on e1.mgr = e2.empid

So the full query is:

select e1.ename Emp,
  e2.eName Mgr
from employees e1
inner join employees e2
  on e1.mgr = e2.empid

See SQL Fiddle with Demo

If you want to return all rows including those without a manager then you would change it to a LEFT JOIN (for example the president):

select e1.ename Emp,
  e2.eName Mgr
from employees e1
left join employees e2
  on e1.mgr = e2.empid

See SQL Fiddle with Demo

The president in your sample data will return a null value for the manager because they do not have a manager.

How do I extend a class with c# extension methods?

They provide the capability to extend existing types by adding new methods with no modifications necessary to the type. Calling methods from objects of the extended type within an application using instance method syntax is known as ‘‘extending’’ methods. Extension methods are not instance members on the type. The key point to remember is that extension methods, defined as static methods, are in scope only when the namespace is explicitly imported into your application source code via the using directive. Even though extension methods are defined as static methods, they are still called using instance syntax.

Check the full example here http://www.dotnetreaders.com/articles/Extension_methods_in_C-sharp.net,Methods_in_C_-sharp/201

Example:

class Extension
    {
        static void Main(string[] args)
        {
            string s = "sudhakar";
            Console.WriteLine(s.GetWordCount());
            Console.ReadLine();
        }

    }
    public static class MyMathExtension
    {

        public static int GetWordCount(this System.String mystring)
        {
            return mystring.Length;
        }
    }

Passing Arrays to Function in C++

The syntaxes

int[]

and

int[X] // Where X is a compile-time positive integer

are exactly the same as

int*

when in a function parameter list (I left out the optional names).

Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3] and int secondarray[5] decay to int*s.

It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]) yield an lvalue to the same element when you use the same index.

These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.

Detect Safari using jQuery

Apparently the only reliable and accepted solution would be to do feature detection like this:

browser_treats_urls_like_safari_does = false;
var last_location_hash = location.hash;
location.hash = '"blah"';
if (location.hash == '#%22blah%22')
    browser_treats_urls_like_safari_does = true;
location.hash = last_location_hash;

Display a message in Visual Studio's output window when not debug mode?

To write in the Visual Studio output window I used IVsOutputWindow and IVsOutputWindowPane. I included as members in my OutputWindow class which look like this :

public class OutputWindow : TextWriter
{
  #region Members

  private static readonly Guid mPaneGuid = new Guid("AB9F45E4-2001-4197-BAF5-4B165222AF29");
  private static IVsOutputWindow mOutputWindow = null;
  private static IVsOutputWindowPane mOutputPane = null;

  #endregion

  #region Constructor

  public OutputWindow(DTE2 aDte)
  {
    if( null == mOutputWindow )
    {
      IServiceProvider serviceProvider = 
      new ServiceProvider(aDte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
      mOutputWindow = serviceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;
    }

    if (null == mOutputPane)
    {
      Guid generalPaneGuid = mPaneGuid;
      mOutputWindow.GetPane(ref generalPaneGuid, out IVsOutputWindowPane pane);

      if ( null == pane)
      {
        mOutputWindow.CreatePane(ref generalPaneGuid, "Your output window name", 0, 1);
        mOutputWindow.GetPane(ref generalPaneGuid, out pane);
      }
      mOutputPane = pane;
    }
  }

  #endregion

  #region Properties

  public override Encoding Encoding => System.Text.Encoding.Default;

  #endregion

  #region Public Methods

  public override void Write(string aMessage) => mOutputPane.OutputString($"{aMessage}\n");

  public override void Write(char aCharacter) => mOutputPane.OutputString(aCharacter.ToString());

  public void Show(DTE2 aDte)
  {
    mOutputPane.Activate();
    aDte.ExecuteCommand("View.Output", string.Empty);
  }

  public void Clear() => mOutputPane.Clear();

  #endregion
}

If you have a big text to write in output window you usually don't want to freeze the UI. In this purpose you can use a Dispatcher. To write something in output window using this implementation now you can simple do this:

Dispatcher mDispatcher = HwndSource.FromHwnd((IntPtr)mDte.MainWindow.HWnd).RootVisual.Dispatcher;

using (OutputWindow outputWindow = new OutputWindow(mDte))
{
  mDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
  {
    outputWindow.Write("Write what you want here");
  }));
}

How to add include path in Qt Creator?

If you use custom Makefiles, you can double click on the .includes file and add it there.

fatal: could not read Username for 'https://github.com': No such file or directory

I found my answer here:

edit ~/.gitconfig and add the following:

[url "[email protected]:"]
 insteadOf = https://github.com/

Although it solves a different problem, the error code is the same...

Disable asp.net button after click to prevent double clicking

I like to disable the button and call a postback, this way the code behind still gets run after the button is disabled.

this is how i attach from code behind:

btnProcess.Attributes.Add("onclick", " this.disabled = true; __doPostBack('btnProcess', ''); return false;")

Then re-enable the button in code behind:

btnProcess.Enabled = True

How can I get my Twitter Bootstrap buttons to right align?

Can you try a custom CSS aside the bootstrap CSS to see if any changes. Try

.move-rigth{
    display: block;
    float: right;
}

If it works then you can try manipulating what you have or adding other formatting to this and achieving what you desire. Because you are using bootstrap doesn't mean if it doesn't offer you what you want then you just manage it. You are working with your codes and so you command it to do as you say. Cheers!

How can I call a function using a function pointer?

Slightly different approach:

bool A() {...}
bool B() {...}
bool C() {...}

int main(void)
{
  /**
   * Declare an array of pointers to functions returning bool
   * and initialize with A, B, and C
   */
  bool (*farr[])() = {A, B, C};
  ...
  /**
   * Call A, B, or C based on the value of i
   * (assumes i is in range of array)
   */
  if (farr[i]()) // or (*farr[i])()
  {
    ...
  }
  ...
}

How do I make a branch point at a specific commit?

git reset --hard 1258f0d0aae

But be careful, if the descendant commits between 1258f0d0aae and HEAD are not referenced in other branches it'll be tedious (but not impossible) to recover them, so you'd better to create a "backup" branch at current HEAD, checkout master, and reset to the commit you want.

Also, be sure that you don't have uncommitted changes before a reset --hard, they will be truly lost (no way to recover).

How to get a json string from url?

Use the WebClient class in System.Net:

var json = new WebClient().DownloadString("url");

Keep in mind that WebClient is IDisposable, so you would probably add a using statement to this in production code. This would look like:

using (WebClient wc = new WebClient())
{
   var json = wc.DownloadString("url");
}

SSRS Query execution failed for dataset

In my situation, I created a new SSRS report and new stored procedure for the dataset. I forgot to add the stored procedure to the database role that had permission to execute it. Once I added the permissions to SQL database role with EXECUTE, all was fine!

The error message encountered by the user was "An error occurred during client rendering. An error has occurred during report processing (rsProcessingAborted). Query execution failed for dataset "DataSet1'. (rsErrorExecutingCommand) For more information..."

Paging with Oracle

Ask Tom on pagination and very, very useful analytic functions.

This is excerpt from that page:

select * from (
    select /*+ first_rows(25) */
     object_id,object_name,
     row_number() over
    (order by object_id) rn
    from all_objects
)
where rn between :n and :m
order by rn;

Is there a replacement for unistd.h for Windows (Visual C)?

No, IIRC there is no getopt() on Windows.

Boost, however, has the program_options library... which works okay. It will seem like overkill at first, but it isn't terrible, especially considering it can handle setting program options in configuration files and environment variables in addition to command line options.

List<T> or IList<T>

public void Foo(IList<Bar> list)
{
     // Do Something with the list here.
}

In this case you could pass in any class which implements the IList<Bar> interface. If you used List<Bar> instead, only a List<Bar> instance could be passed in.

The IList<Bar> way is more loosely coupled than the List<Bar> way.

Is there a need for range(len(a))?

Short answer: mathematically speaking, no, in practical terms, yes, for example for Intentional Programming.

Technically, the answer would be "no, it's not needed" because it's expressible using other constructs. But in practice, I use for i in range(len(a) (or for _ in range(len(a)) if I don't need the index) to make it explicit that I want to iterate as many times as there are items in a sequence without needing to use the items in the sequence for anything.

So: "Is there a need?"? — yes, I need it to express the meaning/intent of the code for readability purposes.

See also: https://en.wikipedia.org/wiki/Intentional_programming

And obviously, if there is no collection that is associated with the iteration at all, for ... in range(len(N)) is the only option, so as to not resort to i = 0; while i < N; i += 1 ...

Trying to get Laravel 5 email to work

My opinion after making changes on your .env files restart your server and serve the app again. Just to be sure of the actual error. The php artisan clear and cache afterwards works pretty fine.

Restrict varchar() column to specific values?

Have you already looked at adding a check constraint on that column which would restrict values? Something like:

CREATE TABLE SomeTable
(
   Id int NOT NULL,
   Frequency varchar(200),
   CONSTRAINT chk_Frequency CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
)

How do I find the version of Apache running without access to the command line?

The method

Connect to port 80 on the host and send it

HEAD / HTTP/1.0

This needs to be followed by carriage-return + line-feed twice

You'll get back something like this

HTTP/1.1 200 OK
Date: Fri, 03 Oct 2008 12:39:43 GMT
Server: Apache/2.2.9 (Ubuntu) DAV/2 SVN/1.5.0 PHP/5.2.6-1ubuntu4 with Suhosin-Patch mod_perl/2.0.4 Perl/v5.10.0
Last-Modified: Thu, 02 Aug 2007 20:50:09 GMT
ETag: "438118-197-436bd96872240"
Accept-Ranges: bytes
Content-Length: 407
Connection: close
Content-Type: text/html; charset=UTF-8

You can then extract the apache version from the Server: header

Typical tools you can use

You could use the HEAD utility which comes with a full install of Perl's LWP library, e.g.

HEAD http://your.webserver.com/

Or, use the curl utility, e.g.

 curl --head http://your.webserver.com/

You could also use a browser extension which lets you view server headers, such as Live HTTP Headers or Firebug for Firefox, or Fiddler for IE

Stuck with Windows?

Finally. if you're on Windows, and have nothing else at your disposal, open a command prompt (Start Menu->Run, type "cmd" and press return), and then type this

telnet your.webserver.com 80

Then type (carefully, your characters won't be echoed back)

HEAD / HTTP/1.0

Press return twice and you'll see the server headers.

Other methods

As mentioned by cfeduke and Veynom, the server may be set to return limited information in the Server: header. Try and upload a PHP script to your host with this in it

<?php phpinfo() ?>

Request the page with a web browser and you should see the Apache version reported there.

You could also try and use PHPShell to have a poke around, try a command like

/usr/sbin/apache2 -V

Making an asynchronous task in Flask

You can also try using multiprocessing.Process with daemon=True; the process.start() method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.

I experienced similar problem while working with falcon framework and using daemon process helped.

You'd need to do the following:

from multiprocessing import Process

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    heavy_process = Process(  # Create a daemonic process with heavy "my_func"
        target=my_func,
        daemon=True
    )
    heavy_process.start()
    return Response(
        mimetype='application/json',
        status=200
    )

# Define some heavy function
def my_func():
    time.sleep(10)
    print("Process finished")

You should get a response immediately and, after 10s you should see a printed message in the console.

NOTE: Keep in mind that daemonic processes are not allowed to spawn any child processes.

C# Get/Set Syntax Usage

By the way, in C# 3.5 you can instantiate your object's properties like so:

Person TOM=new Person 
{ 
   title = "My title", ID = 1 
};

But again, properties must be public.

lvalue required as left operand of assignment error when using C++

It is just a typo(I guess)-

p+=1;

instead of p +1=p; is required .

As name suggest lvalue expression should be left-hand operand of the assignment operator.

Process with an ID #### is not running in visual studio professional 2013 update 3

I tried the first error and that didn't help me. However What did work for me was to delete the hidden ".vs" folder which is at the solution root.

Matplotlib: "Unknown projection '3d'" error

I encounter the same problem, and @Joe Kington and @bvanlew's answer solve my problem.

but I should add more infomation when you use pycharm and enable auto import.

when you format the code, the code from mpl_toolkits.mplot3d import Axes3D will auto remove by pycharm.

so, my solution is

from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D  # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

and it works well!

Check time difference in Javascript

You can use moment js for this purpose. momentJs 'fromNow()' will give you any time difference from current time.

var m1 = any date time on moment format;

console.log(m1.fromNow());

How to make Bootstrap Panel body with fixed height

HTML :

<div class="span4">
  <div class="panel panel-primary">
    <div class="panel-heading">jhdsahfjhdfhs</div>
    <div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
  </div>
</div>

CSS :

.panel-height {
  height: 100px; / change according to your requirement/
}

Difference between JE/JNE and JZ/JNZ

  je : Jump if equal:

  399  3fb:   64 48 33 0c 25 28 00    xor    %fs:0x28,%rcx
  400  402:   00 00
  401  404:   74 05                   je     40b <sims_get_counter+0x51>

Simulate Keypress With jQuery

The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.

http://docs.jquery.com/Events/trigger#eventdata

Read the above documentation for more details.

Array inside a JavaScript Object?

_x000D_
_x000D_
var data = {_x000D_
  name: "Ankit",_x000D_
  age: 24,_x000D_
  workingDay: ["Mon", "Tue", "Wed", "Thu", "Fri"]_x000D_
};_x000D_
_x000D_
for (const key in data) {_x000D_
  if (data.hasOwnProperty(key)) {_x000D_
    const element = data[key];_x000D_
      console.log(key+": ", element);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Extract hostname name from string

I tried to use the Given solutions, the Chosen one was an overkill for my purpose and "Creating a element" one messes up for me.

It's not ready for Port in URL yet. I hope someone finds it useful

function parseURL(url){
    parsed_url = {}

    if ( url == null || url.length == 0 )
        return parsed_url;

    protocol_i = url.indexOf('://');
    parsed_url.protocol = url.substr(0,protocol_i);

    remaining_url = url.substr(protocol_i + 3, url.length);
    domain_i = remaining_url.indexOf('/');
    domain_i = domain_i == -1 ? remaining_url.length - 1 : domain_i;
    parsed_url.domain = remaining_url.substr(0, domain_i);
    parsed_url.path = domain_i == -1 || domain_i + 1 == remaining_url.length ? null : remaining_url.substr(domain_i + 1, remaining_url.length);

    domain_parts = parsed_url.domain.split('.');
    switch ( domain_parts.length ){
        case 2:
          parsed_url.subdomain = null;
          parsed_url.host = domain_parts[0];
          parsed_url.tld = domain_parts[1];
          break;
        case 3:
          parsed_url.subdomain = domain_parts[0];
          parsed_url.host = domain_parts[1];
          parsed_url.tld = domain_parts[2];
          break;
        case 4:
          parsed_url.subdomain = domain_parts[0];
          parsed_url.host = domain_parts[1];
          parsed_url.tld = domain_parts[2] + '.' + domain_parts[3];
          break;
    }

    parsed_url.parent_domain = parsed_url.host + '.' + parsed_url.tld;

    return parsed_url;
}

Running this:

parseURL('https://www.facebook.com/100003379429021_356001651189146');

Result:

Object {
    domain : "www.facebook.com",
    host : "facebook",
    path : "100003379429021_356001651189146",
    protocol : "https",
    subdomain : "www",
    tld : "com"
}

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

How to write new line character to a file in Java

Here is a snippet that gets the default newline character for the current platform. Use System.getProperty("os.name") and System.getProperty("os.version"). Example:

public static String getSystemNewline(){
    String eol = null;
    String os = System.getProperty("os.name").toLowerCase();
    if(os.contains("mac"){
        int v = Integer.parseInt(System.getProperty("os.version"));
        eol = (v <= 9 ? "\r" : "\n");
    }
    if(os.contains("nix"))
        eol = "\n";
    if(os.contains("win"))
        eol = "\r\n";

    return eol;
}

Where eol is the newline

How to import an Excel file into SQL Server?

There are many articles about writing code to import an excel file, but this is a manual/shortcut version:

If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.

The quickest way to get your Excel file into SQL is by using the import wizard:

  1. Open SSMS (Sql Server Management Studio) and connect to the database where you want to import your file into.
  2. Import Data: in SSMS in Object Explorer under 'Databases' right-click the destination database, select Tasks, Import Data. An import wizard will pop up (you can usually just click 'Next' on the first screen).

enter image description here

  1. The next window is 'Choose a Data Source', select Excel:

    • In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).

    • Click the 'Browse' button to select the path to the Excel file you want to import.

    • Select the version of the excel file (97-2003 is usually fine for files with a .XLS extension, or use 2007 for newer files with a .XLSX extension)
    • Tick the 'First Row has headers' checkbox if your excel file contains headers.
    • Click next.

enter image description here

  1. On the 'Choose a Destination' screen, select destination database:
    • Select the 'Server name', Authentication (typically your sql username & password) and select a Database as destination. Click Next.

enter image description here

  1. On the 'Specify Table Copy or Query' window:

    • For simplicity just select 'Copy data from one or more tables or views', click Next.
  2. 'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.

enter image description here

  1. Click Finish.

How does one reorder columns in a data frame?

dplyr version 1.0.0 includes the relocate() function to easily reorder columns:

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

library(dplyr) # from version 1.0.0 only

dat %>%
  relocate(Out, .before = In)

or

dat %>%
  relocate(Out, .after = Time)

What's the difference between “mod” and “remainder”?

Does '%' mean either "mod" or "rem" in C?

In C, % is the remainder1.

..., the result of the / operator is the algebraic quotient with any fractional part discarded ... (This is often called "truncation toward zero".) C11dr §6.5.5 6

The operands of the % operator shall have integer type. C11dr §6.5.5 2

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder ... C11dr §6.5.5 5


What's the difference between “mod” and “remainder”?

C does not define "mod", such as the integer modulus function used in Euclidean division or other modulo. "Euclidean mod" differs from C's a%b operation when a is negative.

 // a % b
 7 %  3 -->  1  
 7 % -3 -->  1  
-7 %  3 --> -1  
-7 % -3 --> -1   

Modulo as Euclidean division

 7 modulo  3 -->  1  
 7 modulo -3 -->  1  
-7 modulo  3 -->  2  
-7 modulo -3 -->  2   

Candidate modulo code:

int modulo_Euclidean(int a, int b) {
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

Note about floating point: double fmod(double x, double y), even though called "fmod", it is not the same as Euclidean division "mod", but similar to C integer remainder:

The fmod functions compute the floating-point remainder of x/y. C11dr §7.12.10.1 2

fmod( 7,  3) -->  1.0  
fmod( 7, -3) -->  1.0  
fmod(-7,  3) --> -1.0  
fmod(-7, -3) --> -1.0   

Disambiguation: C also has a similar named function double modf(double value, double *iptr) which breaks the argument value into integral and fractional parts, each of which has the same type and sign as the argument. This has little to do with the "mod" discussion here except name similarity.


[Edit Dec 2020]

For those who want proper functionality in all cases, an improved modulo_Euclidean() that 1) detects mod(x,0) and 2) a good and no UB result with modulo_Euclidean2(INT_MIN, -1). Inspired by 4 different implementations of modulo with fully defined behavior.

int modulo_Euclidean2(int a, int b) {
  if (b == 0) TBD_Code(); // perhaps return -1 to indicate failure?
  if (b == -1) return 0; // This test needed to prevent UB of `INT_MIN % -1`.
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

1 Prior to C99, C's definition of % was still the remainder from division, yet then / allowed negative quotients to round down rather than "truncation toward zero". See Why do you get different values for integer division in C89?. Thus with some pre-C99 compilation, % code can act just like the Euclidean division "mod". The above modulo_Euclidean() will work with this alternate old-school remainder too.

Axios get access to response header fields

For Spring Boot 2 if you don't want to use global CORS configuration, you can do it by method or class/controller level using @CrossOrigin adnotation with exposedHeaders atribute.

For example, to add header authorization for YourController methods:

@CrossOrigin(exposedHeaders = "authorization")
@RestController
public class YourController {
    ...
}

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

Having call helps. However today it didn't.

This is how I solved it:

Bat file contents (if you want to stop batch when one of cmds errors)

cmd1 && ^
cmd2 && ^
cmd3 && ^
cmd4

Bat file contents (if you want to continue batch when one of cmds errors)

cmd1 & ^
cmd2 & ^
cmd3 & ^
cmd4

Convert JSON string to dict using Python

If you trust the data source, you can use eval to convert your string into a dictionary:

eval(your_json_format_string)

Example:

>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)

>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}

>>> print type(x), type(y)
<type 'str'> <type 'dict'>

>>> print y['a'], type(y['a'])
1 <type 'int'>

>>> print y['a'], type(y['b'])
1 <type 'bool'>

>>> print y['a'], type(y['c'])
1 <type 'str'>

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

What are the undocumented features and limitations of the Windows FINDSTR command?

The findstr command sets the ErrorLevel (or exit code) to one of the following values, given that there are no invalid or incompatible switches and no search string exceeds the applicable length limit:

  • 0 when at least a single match is encountered in one line throughout all specified files;
  • 1 otherwise;

A line is considered to contain a match when:

  • no /V option is given and the search expression occurs at least once;
  • the /V option is given and the search expression does not occur;

This means that the /V option also changes the returned ErrorLevel, but it does not just revert it!

For example, when you have got a file test.txt with two lines, one of which contains the string text but the other one does not, both findstr "text" "test.txt" and findstr /V "text" "test.txt" return an ErrorLevel of 0.

Basically you can say: if findstr returns at least a line, ErrorLevel is set to 0, else to 1.

Note that the /M option does not affect the ErrorLevel value, it just alters the output.

(Just for the sake of completeness: the find command behaves exactly the same way with respect to the /V option and ErrorLevel; the /C option does not affect ErrorLevel.)

Cannot set property 'innerHTML' of null

This error can appear even if you load your script after the html render is finished. In this given example your code

<div id="hello"></div>

has no value inside the div. So the error is raised, because there is no value to change inside. It should have been

<div id="hello">Some random text to change</div>

then.

Byte[] to ASCII

As an alternative to reading a data from a stream to a byte array, you could let the framework handle everything and just use a StreamReader set up with an ASCII encoding to read in the string. That way you don't need to worry about getting the appropriate buffer size or larger data sizes.

using (var reader = new StreamReader(stream, Encoding.ASCII))
{
    string theString = reader.ReadToEnd();
    // do something with theString
}

wget command to download a file and save as a different filename

You would use the command Mechanical snail listed. Notice the uppercase O. Full command line to use could be:

wget www.examplesite.com/textfile.txt --output-document=newfile.txt

or

wget www.examplesite.com/textfile.txt -O newfile.txt

Hope that helps.

Index (zero based) must be greater than or equal to zero

String.Format must start with zero index "{0}" like this:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

How to handle a lost KeyStore password in Android?

Open taskHistory.bin and search for storePassword

Using NOT operator in IF conditions

It is generally not a bad idea to avoid the !-operator if you have the choice. One simple reason is that it can be a source of errors, because it is possible to overlook it. More readable can be: if(conditionA==false) in some cases. This mainly plays a role if you skip the else part. If you have an else-block anyway you should not use the negation in the if-condition.

Except for composed-conditions like this:

if(!isA() && isB() && !isNotC())

Here you have to use some sort of negation to get the desired logic. In this case, what really is worth thinking about is the naming of the functions or variables. Try to name them so you can often use them in simple conditions without negation.

In this case you should think about the logic of isNotC() and if it could be replaced by a method isC() if it makes sense.

Finally your example has another problem when it comes to readability which is even more serious than the question whether to use negation or not: Does the reader of the code really knows when doSomething() returns true and when false? If it was false was it done anyway? This is a very common problem, which ends in the reader trying to find out what the return values of functions really mean.

Printing hexadecimal characters in C

You can create an unsigned char:

unsigned char c = 0xc5;

Printing it will give C5 and not ffffffc5.

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

Or you can cast the char while printing:

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

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

Thread pooling in C++11

Something like this might help (taken from a working app).

#include <memory>
#include <boost/asio.hpp>
#include <boost/thread.hpp>

struct thread_pool {
  typedef std::unique_ptr<boost::asio::io_service::work> asio_worker;

  thread_pool(int threads) :service(), service_worker(new asio_worker::element_type(service)) {
    for (int i = 0; i < threads; ++i) {
      auto worker = [this] { return service.run(); };
      grp.add_thread(new boost::thread(worker));
    }
  }

  template<class F>
  void enqueue(F f) {
    service.post(f);
  }

  ~thread_pool() {
    service_worker.reset();
    grp.join_all();
    service.stop();
  }

private:
  boost::asio::io_service service;
  asio_worker service_worker;
  boost::thread_group grp;
};

You can use it like this:

thread_pool pool(2);

pool.enqueue([] {
  std::cout << "Hello from Task 1\n";
});

pool.enqueue([] {
  std::cout << "Hello from Task 2\n";
});

Keep in mind that reinventing an efficient asynchronous queuing mechanism is not trivial.

Boost::asio::io_service is a very efficient implementation, or actually is a collection of platform-specific wrappers (e.g. it wraps I/O completion ports on Windows).

When is layoutSubviews called?

have you looked at layoutIfNeeded?

The documentation snippet is below. Does the animation work if you call this method explicitly during the animation?

layoutIfNeeded Lays out the subviews if needed.

- (void)layoutIfNeeded

Discussion Use this method to force the layout of subviews before drawing.

Availability Available in iPhone OS 2.0 and later.

How to refresh datagrid in WPF

From MSDN -

CollectionViewSource.GetDefaultView(myGrid.ItemsSource).Refresh();

How do I import .sql files into SQLite 3?

Alternatively, you can do this from a Windows commandline prompt/batch file:

sqlite3.exe DB.db ".read db.sql"

Where DB.db is the database file, and db.sql is the SQL file to run/import.

How to capitalize the first letter in a String in Ruby

Rails 5+

As of Active Support and Rails 5.0.0.beta4 you can use one of both methods: String#upcase_first or ActiveSupport::Inflector#upcase_first.

"my API is great".upcase_first #=> "My API is great"
"?????".upcase_first           #=> "?????"
"?????".upcase_first           #=> "?????"
"NASA".upcase_first            #=> "NASA"
"MHz".upcase_first             #=> "MHz"
"sputnik".upcase_first         #=> "Sputnik"

Check "Rails 5: New upcase_first Method" for more info.

How to return a resolved promise from an AngularJS Service using $q?

How to simply return a pre-resolved promise in AngularJS

Resolved promise:

return $q.when( someValue );    // angularjs 1.2+
return $q.resolve( someValue ); // angularjs 1.4+, alias to `when` to match ES6

Rejected promise:

return $q.reject( someValue );

jQuery Date Picker - disable past dates

$( "#date" ).datetimepicker({startDate:new Date()}).datetimepicker('update', new Date());

new Date() : function get the todays date previous date are locked. 100% working

How do I get the last word in each line with bash

You can do it easily with grep:

grep -oE '[^ ]+$' file

(-E use extended regex; -o output only the matched text instead of the full line)

Is it still valid to use IE=edge,chrome=1?

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> serves two purposes.

  1. IE=edge: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.
  2. chrome=1: specifies that Google Chrome frame should start if the user has it installed

The IE=edge flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.

As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1 will do nothing more than consume a few bytes of bandwidth.

I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.

Note, the W3C validator will flag chrome=1 as an error:

Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.

How to forcefully set IE's Compatibility Mode off from the server-side?

Changing my header to the following solve the problem:

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

Write a number with two decimal places SQL Server

Use Str() Function. It takes three arguments(the number, the number total characters to display, and the number of decimal places to display

  Select Str(12345.6789, 12, 3)

displays: ' 12345.679' ( 3 spaces, 5 digits 12345, a decimal point, and three decimal digits (679). - it rounds if it has to truncate, (unless the integer part is too large for the total size, in which case asterisks are displayed instead.)

for a Total of 12 characters, with 3 to the right of decimal point.

Basic example for sharing text or image with UIActivityViewController in Swift

Just as a note you can also use this for iPads:

activityViewController.popoverPresentationController?.sourceView = sender

So the popover pops from the sender (the button in that case).

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):

The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:

[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }

Will output the following if it is over the character limit: "Address can have a max of 100 characters"

The placeholders I am aware of are:

  • {0} = Property Name
  • {1} = Max Length
  • {2} = Min Length

Much thanks to bloudraak for initially pointing this out.

Using new line(\n) in string and rendering the same in HTML

Set your css in the table cell to

white-space:pre-wrap;

_x000D_
_x000D_
document.body.innerHTML = 'First line\nSecond line\nThird line';
_x000D_
body{ white-space:pre-wrap; }
_x000D_
_x000D_
_x000D_

Correct way to push into state array

You should not be operating the state at all. At least, not directly. If you want to update your array, you'll want to do something like this.

var newStateArray = this.state.myArray.slice();
newStateArray.push('new value');
this.setState(myArray: newStateArray);

Working on the state object directly is not desirable. You can also take a look at React's immutability helpers.

https://facebook.github.io/react/docs/update.html

Extract number from string with Oracle function

If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr function like this:

regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')

How do I bind a WPF DataGrid to a variable number of columns?

You might be able to do this with AutoGenerateColumns and a DataTemplate. I'm not positive if it would work without a lot of work, you would have to play around with it. Honestly if you have a working solution already I wouldn't make the change just yet unless there's a big reason. The DataGrid control is getting very good but it still needs some work (and I have a lot of learning left to do) to be able to do dynamic tasks like this easily.

How can I protect my .NET assemblies from decompilation?

Host your service in any cloud service provider.

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

WSDL vs REST Pros and Cons

The two protocols have very different uses in the real world.

SOAP(using WSDL) is a heavy-weight XML standard that is centered around document passing. The advantage with this is that your requests and responses can be very well structured, and can even use a DTD. The downside is it is XML, and is very verbose. However, this is good if two parties need to have a strict contract(say for inter-bank communication). SOAP also lets you layer things like WS-Security on your documents. SOAP is generally transport-agnostic, meaning you don't necessarily need to use HTTP.

REST is very lightweight, and relies upon the HTTP standard to do it's work. It is great to get a useful web service up and running quickly. If you don't need a strict API definition, this is the way to go. Most web services fall into this category. You can version your API so that updates to the API do not break it for people using old versions(as long as they specify a version). REST essentially requires HTTP, and is format-agnostic(meaning you can use XML, JSON, HTML, whatever).

Generally I use REST, because I don't need fancy WS-* features. SOAP is good though if you want computers to understand your webservice using a WSDL. REST specifications are generally human-readable only.

Callback when CSS3 transition finishes

There is an animationend Event that can be observed see documentation here, also for css transition animations you could use the transitionend event

There is no need for additional libraries these all work with vanilla JS

_x000D_
_x000D_
document.getElementById("myDIV").addEventListener("transitionend", myEndFunction);_x000D_
function myEndFunction() {_x000D_
 this.innerHTML = "transition event ended";_x000D_
}
_x000D_
#myDIV {transition: top 2s; position: relative; top: 0;}_x000D_
div {background: #ede;cursor: pointer;padding: 20px;}
_x000D_
<div id="myDIV" onclick="this.style.top = '55px';">Click me to start animation.</div>
_x000D_
_x000D_
_x000D_

how to implement a pop up dialog box in iOS

Different people who come to this question mean different things by a popup box. I highly recommend reading the Temporary Views documentation. My answer is largely a summary of this and other related documentation.

Alert (show me an example)

enter image description here

Alerts display a title and an optional message. The user must acknowledge it (a one-button alert) or make a simple choice (a two-button alert) before going on. You create an alert with a UIAlertController.

It is worth quoting the documentation's warning and advice about creating unnecessary alerts.

enter image description here

Notes:

Action Sheet (show me an example)

enter image description here

Action Sheets give the user a list of choices. They appear either at the bottom of the screen or in a popover depending on the size and orientation of the device. As with alerts, a UIAlertController is used to make an action sheet. Before iOS 8, UIActionSheet was used, but now the documentation says:

Important: UIActionSheet is deprecated in iOS 8. (Note that UIActionSheetDelegate is also deprecated.) To create and manage action sheets in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleActionSheet.

Modal View (show me an example)

enter image description here

A modal view is a self-contained view that has everything it needs to complete a task. It may or may not take up the full screen. To create a modal view, use a UIPresentationController with one of the Modal Presentation Styles.

See also

Popover (show me an example)

enter image description here

A Popover is a view that appears when a user taps on something and disappears when tapping off it. It has an arrow showing the control or location from where the tap was made. The content can be just about anything you can put in a View Controller. You make a popover with a UIPopoverPresentationController. (Before iOS 8, UIPopoverController was the recommended method.)

In the past popovers were only available on the iPad, but starting with iOS 8 you can also get them on an iPhone (see here, here, and here).

See also

Notifications

enter image description here

Notifications are sounds/vibrations, alerts/banners, or badges that notify the user of something even when the app is not running in the foreground.

enter image description here

See also

A note about Android Toasts

enter image description here

In Android, a Toast is a short message that displays on the screen for a short amount of time and then disappears automatically without disrupting user interaction with the app.

People coming from an Android background want to know what the iOS version of a Toast is. Some examples of these questions can he found here, here, here, and here. The answer is that there is no equivalent to a Toast in iOS. Various workarounds that have been presented include:

  • Make your own with a subclassed UIView
  • Import a third party project that mimics a Toast
  • Use a buttonless Alert with a timer

However, my advice is to stick with the standard UI options that already come with iOS. Don't try to make your app look and behave exactly the same as the Android version. Think about how to repackage it so that it looks and feels like an iOS app.

Check if a string is palindrome

// The below C++ function checks for a palindrome and 
// returns true if it is a palindrome and returns false otherwise

bool checkPalindrome ( string s )
{
    // This calculates the length of the string

    int n = s.length();

    // the for loop iterates until the first half of the string
    // and checks first element with the last element,
    // second element with second last element and so on.
    // if those two characters are not same, hence we return false because
    // this string is not a palindrome 

    for ( int i = 0; i <= n/2; i++ ) 
    {
        if ( s[i] != s[n-1-i] )
            return false;
    }
    
    // if the above for loop executes completely , 
    // this implies that the string is palindrome, 
    // hence we return true and exit

    return true;
}

"Too many values to unpack" Exception

This happens to me when I'm using Jinja2 for templates. The problem can be solved by running the development server using the runserver_plus command from django_extensions.

It uses the werkzeug debugger which also happens to be a lot better and has a very nice interactive debugging console. It does some ajax magic to launch a python shell at any frame (in the call stack) so you can debug.

add title attribute from css

It is possible to imitate this with HTML & CSS

If you really really want dynamically applied tooltips to work, this (not so performance and architecture friendly) solution can allow you to use browser rendered tooltips without resorting to JS. I can imagine situations where this would be better than JS.

If you have a fixed subset of title attribute values, then you can generate additional elements server-side and let the browser read title from another element positioned above the original one using CSS.

Example:

_x000D_
_x000D_
div{_x000D_
  position: relative;_x000D_
}_x000D_
div > span{_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.pick-tooltip-1 > .tooltip-1, .pick-tooltip-2 > .tooltip-2{_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}
_x000D_
<div class="pick-tooltip-1">_x000D_
  Hover to see first tooltip_x000D_
  <span class="tooltip-1" title="Tooltip 1"></span>_x000D_
  <span class="tooltip-2" title="Tooltip 2"></span>_x000D_
</div>_x000D_
_x000D_
<div class="pick-tooltip-2">_x000D_
  Hover to see second tooltip_x000D_
  <span class="tooltip-1" title="Tooltip 1"></span>_x000D_
  <span class="tooltip-2" title="Tooltip 2"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note: It's not recommended for large scale applications because of unnecessary HTML, possible content repetitions and the fact that your extra elements for tooltip would steal mouse events (text selection, etc)

Confused about UPDLOCK, HOLDLOCK

UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.

Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.

You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.

You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.

How to view AndroidManifest.xml from APK file?

Android Studio can now show this. Go to Build > Analyze APK... and select your apk. Then you can see the content of the AndroidManifset file.

Does java have a int.tryparse that doesn't throw an exception for bad data?

No. You have to make your own like this:

boolean tryParseInt(String value) {  
     try {  
         Integer.parseInt(value);  
         return true;  
      } catch (NumberFormatException e) {  
         return false;  
      }  
}

...and you can use it like this:

if (tryParseInt(input)) {  
   Integer.parseInt(input);  // We now know that it's safe to parse
}

EDIT (Based on the comment by @Erk)

Something like follows should be better

public int tryParse(String value, int defaultVal) {
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        return defaultVal;
    }
}

When you overload this with a single string parameter method, it would be even better, which will enable using with the default value being optional.

public int tryParse(String value) {
    return tryParse(value, 0)
}

How do I make a WPF TextBlock show my text on multiple lines?

Use the property TextWrapping of the TextBlock element:

<TextBlock Text="StackOverflow Forum"
           Width="100"
           TextWrapping="WrapWithOverflow"/>

How to check which version of Keras is installed?

You can write:

python
import keras
keras.__version__

With android studio no jvm found, JAVA_HOME has been set

When you set to install it "for all users" (not for the current user only), you won't need to route Android Studio for the JAVA_HOME. Of course, have JDK installed.

How to use cURL to send Cookies?

You can refer to https://curl.haxx.se/docs/http-cookies.html for a complete tutorial of how to work with cookies. You can use

curl -c /path/to/cookiefile http://yourhost/

to write to a cookie file and start engine and to use cookie you can use

curl -b /path/to/cookiefile  http://yourhost/

to read cookies from and start the cookie engine, or if it isn't a file it will pass on the given string.

How to split and modify a string in NodeJS?

Use split and map function:

var str = "123, 124, 234,252";
var arr = str.split(",");
arr = arr.map(function (val) { return +val + 1; });

Notice +val - string is casted to a number.

Or shorter:

var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) { return +val + 1; });

edit 2015.07.29

Today I'd advise against using + operator to cast variable to a number. Instead I'd go with a more explicit but also more readable Number call:

_x000D_
_x000D_
var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(function (val) {_x000D_
  return Number(val) + 1;_x000D_
});_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

edit 2017.03.09

ECMAScript 2015 introduced arrow function so it could be used instead to make the code more concise:

_x000D_
_x000D_
var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(val => Number(val) + 1);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Stored procedure - return identity as output parameter or scalar

Another option would be as the return value for the stored procedure (I don't suggest this though, as that's usually best for error values).

I've included it as both when it's inserting a single row in cases where the stored procedure was being consumed by both other SQL procedures and a front-end which couldn't work with OUTPUT parameters (IBATIS in .NET I believe):

CREATE PROCEDURE My_Insert
    @col1            VARCHAR(20),
    @new_identity    INT    OUTPUT
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO My_Table (col1)
    VALUES (@col1)

    SELECT @new_identity = SCOPE_IDENTITY()

    SELECT @new_identity AS id

    RETURN
END

The output parameter is easier to work with in T-SQL when calling from other stored procedures IMO, but some programming languages have poor or no support for output parameters and work better with result sets.

Manually type in a value in a "Select" / Drop-down HTML list?

I love the Shadow Wizard answer, which accually answers the question pretty nicelly. My jQuery twist on this which i use is here. http://jsfiddle.net/UJAe4/

After typing new value, the form is ready to send, just need to handle new values on the back end.

jQuery is:

(function ($) 
{
 $.fn.otherize = function (option_text, texts_placeholder_text) {
    oSel = $(this);
    option_id = oSel.attr('id') + '_other';
    textbox_id = option_id + "_tb";

    this.append("<option value='' id='" + option_id + "' class='otherize' >" + option_text + "</option>");
    this.after("<input type='text' id='" + textbox_id + "' style='display: none; border-bottom: 1px solid black' placeholder='" + texts_placeholder_text + "'/>");
    this.change(

    function () {
        oTbox = oSel.parent().children('#' + textbox_id);
        oSel.children(':selected').hasClass('otherize') ? oTbox.show() : oTbox.hide();
    });

    $("#" + textbox_id).change(

    function () {
        $("#" + option_id).val($("#" + textbox_id).val());
    });
};
}(jQuery));

So you apply this to the below html:

<form>
    <select id="otherize_me">
        <option value=1>option 1</option>
        <option value=2>option 2</option>
        <option value=3>option 3</option>
    </select>
</form>

Just like this:

$(function () {

   $("#otherize_me").otherize("other..", "put new option vallue here");

});

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

You can skip the var declaration and the stringify. Otherwise, that will work just fine.

$.ajax({
    url: '/home/check',
    type: 'POST',
    data: {
        Address1: "423 Judy Road",
        Address2: "1001",
        City: "New York",
        State: "NY",
        ZipCode: "10301",
        Country: "USA"
    },
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert(data.success);
    },
    error: function () {
        alert("error");
    }
});

Is there a GUI design app for the Tkinter / grid geometry?

You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.

On the other hand, you have PAGE that seems active and works in python 2.7 and py3k

As you indicate on your comment, none of these use the grid geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.

It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:

enter image description here

By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.

Android Stop Emulator from Command Line

List of devices attached emulator-5584 host emulator-5580 host emulator-5576 host emulator-5572 host emulator-5568 host emulator-5564 host emulator-5560 host

C:\Users\Administrator>adb -s emulator-5584 emu kill error: could not connect to TCP port 5584: cannot connect to 127.0.0.1:5584: No connection could be made because the target machine actively refused it. (10061)

NOTE: gui of emulator is not running but still it's showing

SOLUTION:

adb kill-server

start emulator using:

emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_19

I hope this will help you!

"SyntaxError: Unexpected token < in JSON at position 0"

This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in. the redirected url responds to html, not json. The first character in a html response is <.

How can I use MS Visual Studio for Android Development?

You can use Visual Studio 2015 to building cross-platform apps for Android, iOS, and Windows.

IDE: https://www.visualstudio.com/en-US/explore/cordova-vs

Hope this will help!

Convert data.frame column to a vector?

I use lists to filter dataframes by whether or not they have a value %in% a list.

I had been manually creating lists by exporting a 1 column dataframe to Excel where I would add " ", around each element, before pasting into R: list <- c("el1", "el2", ...) which was usually followed by FilteredData <- subset(Data, Column %in% list).

After searching stackoverflow and not finding an intuitive way to convert a 1 column dataframe into a list, I am now posting my first ever stackoverflow contribution:

# assuming you have a 1 column dataframe called "df"
list <- c()
for(i in 1:nrow(df)){
  list <- append(list, df[i,1])
}
View(list)
# This list is not a dataframe, it is a list of values
# You can filter a dataframe using "subset([Data], [Column] %in% list")

What are the parameters for the number Pipe - Angular 2

  1. Regarding your first question.The pipe works as follows:

    numberValue | number: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

    • minIntegerDigits: Minimum number of integer digits to show before decimal point,set to 1by default
    • minFractionDigits: Minimum number of integer digits to show after the decimal point

    • maxFractionDigits: Maximum number of integer digits to show after the decimal point

2.Regarding your second question, Filter to zero decimal places as follows:

{{ numberValue | number: '1.0-0' }}

For further reading, checkout the following blog

Correct MIME Type for favicon.ico?

I think the root for this confusion is well explained in this wikipedia article.

While the IANA-registered MIME type for ICO files is image/vnd.microsoft.icon, it was submitted to IANA in 2003 by a third party and is not recognised by Microsoft software, which uses image/x-icon instead.

If even the inventor of the ICO format does not use the official MIME type, I will use image/x-icon, too.

How to copy data from one HDFS to another HDFS?

Hadoop comes with a useful program called distcp for copying large amounts of data to and from Hadoop Filesystems in parallel. The canonical use case for distcp is for transferring data between two HDFS clusters. If the clusters are running identical versions of hadoop, then the hdfs scheme is appropriate to use.

$ hadoop distcp hdfs://namenode1/foo hdfs://namenode2/bar

The data in /foo directory of namenode1 will be copied to /bar directory of namenode2. If the /bar directory does not exist, it will create it. Also we can mention multiple source paths.

Similar to rsync command, distcp command by default will skip the files that already exist. We can also use -overwrite option to overwrite the existing files in destination directory. The option -update will only update the files that have changed.

$ hadoop distcp -update hdfs://namenode1/foo hdfs://namenode2/bar/foo

distcp can also be implemented as a MapReduce job where the work of copying is done by the maps that run in parallel across the cluster. There will be no reducers.

If trying to copy data between two HDFS clusters that are running different versions, the copy will process will fail, since the RPC systems are incompatible. In that case we need to use the read-only HTTP based HFTP filesystems to read from the source. Here the job has to run on destination cluster.

$ hadoop distcp hftp://namenode1:50070/foo hdfs://namenode2/bar

50070 is the default port number for namenode's embedded web server.

how to add json library

AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.

Bootstrap combining rows (rowspan)

Divs stack vertically by default, so there is no need for special handling of "rows" within a column.

_x000D_
_x000D_
div {_x000D_
  height:50px;_x000D_
}_x000D_
.short-div {_x000D_
  height:25px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
  <h1>Responsive Bootstrap</h1>_x000D_
  <div class="row">_x000D_
    <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="background-color:red;">Span 5</div>_x000D_
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="background-color:blue">Span 3</div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="padding:0px">_x000D_
      <div class="short-div" style="background-color:green">Span 2</div>_x000D_
      <div class="short-div" style="background-color:purple">Span 2</div>_x000D_
    </div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="background-color:yellow">Span 2</div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container-fluid">_x000D_
  <div class="row-fluid">_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">_x000D_
      <div class="short-div" style="background-color:#999">Span 6</div>_x000D_
      <div class="short-div">Span 6</div>_x000D_
    </div>_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="background-color:#ccc">Span 6</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's the fiddle.

What is the Java ?: operator called and what does it do?

I happen to really like this operator, but the reader should be taken into consideration.

You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.

First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.

Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:

callMethodWhatever(Long + Expression + with + syntax) if conditional

If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.

The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.

When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

How do you run a single query through mysql from the command line?

If it's a query you run often, you can store it in a file. Then any time you want to run it:

mysql < thefile

(with all the login and database flags of course)

How to create file object from URL object (image)

You can make use of ImageIO in order to load the image from an URL and then write it to a file. Something like this:

URL url = new URL("http://google.com/pathtoaimage.jpg");
BufferedImage img = ImageIO.read(url);
File file = new File("downloaded.jpg");
ImageIO.write(img, "jpg", file);

This also allows you to convert the image to some other format if needed.

Is there a CSS selector by class prefix?

You can't do this no. There is one attribute selector that matches exactly or partial until a - sign, but it wouldn't work here because you have multiple attributes. If the class name you are looking for would always be first, you could do this:

<html>
<head>
<title>Test Page</title>
<style type="text/css">
div[class|=status] { background-color:red; }
</style>
</head>
<body>
<div id='A' class='status-important bar-class'>A</div>
<div id='B' class='bar-class'>B</div>
<div id='C' class='status-low-priority bar-class'>C</div>

</body>
</html>

Note that this is just to point out which CSS attribute selector is the closest, it is not recommended to assume class names will always be in front since javascript could manipulate the attribute.

Use of PUT vs PATCH methods in REST API real life scenarios

A very nice explanation is here-

https://blog.segunolalive.com/posts/restful-api-design-%E2%80%94-put-vs-patch/#:~:text=RFC%205789,not%20required%20to%20be%20idempotent.

A Normal Payload- // House on plot 1 { address: 'plot 1', owner: 'segun', type: 'duplex', color: 'green', rooms: '5', kitchens: '1', windows: 20 } PUT For Updated- // PUT request payload to update windows of House on plot 1 { address: 'plot 1', owner: 'segun', type: 'duplex', color: 'green', rooms: '5', kitchens: '1', windows: 21 } Note: In above payload we are trying to update windows from 20 to 21.

Now see the PATH payload- // Patch request payload to update windows on the House { windows: 21 }

Since PATCH is not idempotent, failed requests are not automatically re-attempted on the network. Also, if a PATCH request is made to a non-existent url e.g attempting to replace the front door of a non-existent building, it should simply fail without creating a new resource unlike PUT, which would create a new one using the payload. Come to think of it, it’ll be odd having a lone door at a house address.

Is there a conditional ternary operator in VB.NET?

Just for the record, here is the difference between If and IIf:

IIf(condition, true-part, false-part):

  • This is the old VB6/VBA Function
  • The function always returns an Object type, so if you want to use the methods or properties of the chosen object, you have to re-cast it with DirectCast or CType or the Convert.* Functions to its original type
  • Because of this, if true-part and false-part are of different types there is no matter, the result is just an object anyway

If(condition, true-part, false-part):

  • This is the new VB.NET Function
  • The result type is the type of the chosen part, true-part or false-part
  • This doesn't work, if Strict Mode is switched on and the two parts are of different types. In Strict Mode they have to be of the same type, otherwise you will get an Exception
  • If you really need to have two parts of different types, switch off Strict Mode (or use IIf)
  • I didn't try so far if Strict Mode allows objects of different type but inherited from the same base or implementing the same Interface. The Microsoft documentation isn't quite helpful about this issue. Maybe somebody here knows it.

Wheel file installation

You normally use a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.

For this to work, you do need to install the wheel package:

pip install wheel

You can then tell pip to install the project (and it'll download the wheel if available), or the wheel file directly:

pip install project_name  # discover, download and install
pip install wheel_file.whl  # directly install the wheel

The wheel module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:

python -m wheel install wheel_file.whl

Also see the wheel project documentation.

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

REST security is transport dependent while SOAP security is not.

REST inherits security measures from the underlying transport while SOAP defines its own via WS-Security.

When we talk about REST, over HTTP - all security measures applied HTTP are inherited and this is known as transport level security.

Transport level security, secures your message only while its on the wire - as soon as it leaves the wire, the message is no more secured.

But, with WS-Security, its message level security - even though the message leaves the transport channel it will be still protected. Also - with message level security you can partly encrypt the message [not the entire message, but only the parts you want] - but with transport level security you can't do it.

WS-Security has measures for authentication, integrity, confidentiality and non-repudiation while SSL doesn't support non repudiation [with 2-legged OAuth it does].

In performance-wise SSL is very much faster than WS-Security.

Thanks...

Reading column names alone in a csv file

import pandas as pd
data = pd.read_csv("data.csv")
cols = data.columns

Select parent element of known element in Selenium

There are a couple of options there. The sample code is in Java, but a port to other languages should be straightforward.

Java:

WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = (WebElement) ((JavascriptExecutor) driver).executeScript(
                                   "return arguments[0].parentNode;", myElement);

XPath:

WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = myElement.findElement(By.xpath("./.."));

Obtaining the driver from the WebElement

Note: As you can see, for the JavaScript version you'll need the driver. If you don't have direct access to it, you can retrieve it from the WebElement using:

WebDriver driver = ((WrapsDriver) myElement).getWrappedDriver();

Read/Parse text file line by line in VBA

You Can use this code to read line by line in text file and You could also check about the first character is "*" then you can leave that..

Public Sub Test()

    Dim ReadData as String

    Open "C:\satheesh\myfile\file.txt" For Input As #1

    Do Until EOF(1) 
       Line Input #1, ReadData 'Adding Line to read the whole line, not only first 128 positions
    If Not Left(ReadData, 1) = "*" then
       '' you can write the variable ReadData into the database or file
    End If 

    Loop

    Close #1

End Sub

Getting error "The package appears to be corrupt" while installing apk file

When you are releasing signed apk , please make sure you tick both v1 and v2 in signature versions

See below screenshot for more info Signed APK generation

How to comment lines in rails html.erb files?

This is CLEANEST, SIMPLEST ANSWER for CONTIGUOUS NON-PRINTING Ruby Code:

The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.


  1. CONTIGUOUS NON-PRINTING Ruby Code

    • This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml, etc.

    • This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>

    • DETAILS:

      Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:

        <%# if flash[:myErrors] %>
          <%# if flash[:myErrors].any? %>
            <%# if @post.id.nil? %>
              <%# if @myPost!=-1 %>
                <%# @post = @myPost %>
              <%# else %>
                <%# @post = Post.new %>
              <%# end %>
            <%# end %>
          <%# end %>
        <%# end %>
      

      YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:

        <%# 
          if flash[:myErrors] then
            if flash[:myErrors].any? then
              if @post.id.nil? then
                if @myPost!=-1 then
                  @post = @myPost 
                else 
                  @post = Post.new 
                end 
              end 
            end 
          end 
        %>
      

How to format an inline code in Confluence?

I use a combination of Zelphir and Peter Gluck's answers. i.e.

  1. (Mac-speak) Click COMMAND + SHIFT + D
  2. Select Markdown in the dropdown of the model pop-up
  3. Surround your text with the code tag - i.e. <code>bovvered</code>
  4. Click INSERT

How to temporarily exit Vim and go back

You can switch to shell mode temporarily by:

:! <command>

such as

:! ls

jQuery Show-Hide DIV based on Checkbox Value

Try this

$('.yourchkboxes').change(function(){
    $('.yourbutton').toggle($('.yourchkboxes:checked').length > 0);
});

So it will check for at least one checkbox is checked or not.

Text not wrapping in p tag

Give this style to the <p> tag.

p {
    word-break: break-all;
    white-space: normal;
}

How to remove space from string?

A funny way to remove all spaces from a variable is to use printf:

$ myvar='a cool variable    with   lots of   spaces in it'
$ printf -v myvar '%s' $myvar
$ echo "$myvar"
acoolvariablewithlotsofspacesinit

It turns out it's slightly more efficient than myvar="${myvar// /}", but not safe regarding globs (*) that can appear in the string. So don't use it in production code.

If you really really want to use this method and are really worried about the globbing thing (and you really should), you can use set -f (which disables globbing altogether):

$ ls
file1  file2
$ myvar='  a cool variable with spaces  and  oh! no! there is  a  glob  *  in it'
$ echo "$myvar"
  a cool variable with spaces  and  oh! no! there is  a  glob  *  in it
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglobfile1file2init
$ # See the trouble? Let's fix it with set -f:
$ set -f
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglob*init
$ # Since we like globbing, we unset the f option:
$ set +f

I posted this answer just because it's funny, not to use it in practice.

How can I implement prepend and append with regular JavaScript?

If you want to insert a raw HTML string no matter how complex, you can use: insertAdjacentHTML, with appropriate first argument:

'beforebegin' Before the element itself. 'afterbegin' Just inside the element, before its first child. 'beforeend' Just inside the element, after its last child. 'afterend' After the element itself.

Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.

An example of usage:

document.getElementById("foo").insertAdjacentHTML("beforeBegin",
          "<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");

DEMO

Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.

No module named _sqlite3

I found lots of people meet this problem because the Multi-version Python, on my own vps (cent os 7 x64), I solved it in this way:

  1. Find the file "_sqlite3.so"

    find / -name _sqlite3.so
    

    out: /usr/lib64/python2.7/lib-dynload/_sqlite3.so

  2. Find the dir of python Standard library you want to use,

    for me /usr/local/lib/python3.6/lib-dynload

  3. Copy the file:

    cp   /usr/lib64/python2.7/lib-dynload/_sqlite3.so /usr/local/lib/python3.6/lib-dynload
    

Finally, everything will be ok.

LINQ to SQL Left Outer Join

Public Sub LinqToSqlJoin07()
Dim q = From e In db.Employees _
        Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
        From o In ords.DefaultIfEmpty _
        Select New With {e.FirstName, e.LastName, .Order = o}

ObjectDumper.Write(q) End Sub

Check http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx

Batch file to delete files older than N days

IMO, JavaScript is gradually becoming a universal scripting standard: it is probably available in more products than any other scripting language (in Windows, it is available using the Windows Scripting Host). I have to clean out old files in lots of folders, so here is a JavaScript function to do that:

// run from an administrator command prompt (or from task scheduler with full rights):  wscript jscript.js
// debug with:   wscript /d /x jscript.js

var fs = WScript.CreateObject("Scripting.FileSystemObject");

clearFolder('C:\\temp\\cleanup');

function clearFolder(folderPath)
{
    // calculate date 3 days ago
    var dateNow = new Date();
    var dateTest = new Date();
    dateTest.setDate(dateNow.getDate() - 3);

    var folder = fs.GetFolder(folderPath);
    var files = folder.Files;

    for( var it = new Enumerator(files); !it.atEnd(); it.moveNext() )
    {
        var file = it.item();

        if( file.DateLastModified < dateTest)
        {
            var filename = file.name;
            var ext = filename.split('.').pop().toLowerCase();

            if (ext != 'exe' && ext != 'dll')
            {
                file.Delete(true);
            }
        }
    }

    var subfolders = new Enumerator(folder.SubFolders);
    for (; !subfolders.atEnd(); subfolders.moveNext())
    {
        clearFolder(subfolders.item().Path);
    }
}

For each folder to clear, just add another call to the clearFolder() function. This particular code also preserves exe and dll files, and cleans up subfolders as well.

MySQL string replace

UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'

Now rows that were like

http://www.example.com/articles/updates/43

will be

http://www.example.com/articles/news/43

http://www.electrictoolbox.com/mysql-find-replace-text/

int to string in MySQL

select t2.* 
from t1 join t2 on t2.url='site.com/path/%' + cast(t1.id as varchar)  + '%/more' 
where t1.id > 9000

Using concat like suggested is even better though

Python try-else

Try-except-else is great for combining the EAFP pattern with duck-typing:

try:
  cs = x.cleanupSet
except AttributeError:
  pass
else:
  for v in cs:
    v.cleanup()

You might thing this naïve code is fine:

try:
  for v in x.cleanupSet:
    v.clenaup()
except AttributeError:
  pass

This is a great way of accidentally hiding severe bugs in your code. I typo-ed cleanup there, but the AttributeError that would let me know is being swallowed. Worse, what if I'd written it correctly, but the cleanup method was occasionally being passed a user type that had a misnamed attribute, causing it to silently fail half-way through and leave a file unclosed? Good luck debugging that one.

ASP.NET IIS Web.config [Internal Server Error]

For me it was a fresh NetCore application that was just not loading via IIS. When run standalone it was OK though.

I removed the <aspNetCore line and then I got a normal error message from IIS saying that NetCoreModule could not be loaded. That module is required to understand this new web.config line.

The error message 0x8007000d actually says that the web.config is malformed and that error shows up before the error loading module making this error message really crap. (and an unfortunate race condition problem)

I installed the NetCoreSDK and stopped and started IIS (restart didnt work)

The NetCore API started working via IIS as expected.

LINQ with groupby and count

userInfos.GroupBy(userInfo => userInfo.metric)
        .OrderBy(group => group.Key)
        .Select(group => Tuple.Create(group.Key, group.Count()));

How to perform grep operation on all files in a directory?

If you want to do multiple commands, you could use:

for I in `ls *.sql`
do
    grep "foo" $I >> foo.log
    grep "bar" $I >> bar.log
done

ERROR in Cannot find module 'node-sass'

There is an issue with downloading npm dependencies due to network which you have. try to download the npm dependencies in open network . you won't get any issue. i am also faced this similar issue and resolved finally.

use below commands: npm install (it will download all depedencies) npm start to start the angular application

Add 2 hours to current time in MySQL?

The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)

For your query, this would be:

SELECT * 
FROM courses 
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time

Or,

SELECT * 
FROM courses 
WHERE ADDTIME(now(), '02:00:00') > start_time

Retrofit 2 - URL Query Parameter

 public interface IService { 

  String BASE_URL = "https://api.demo.com/";

  @GET("Login") //i.e https://api.demo.com/Search? 
  Call<Products> getUserDetails(@Query("email") String emailID, @Query("password") String password)

} 

It will be called this way. Considering you did the rest of the code already.

Call<Results> call = service.getUserDetails("[email protected]", "Password@123");

For example when a query is returned, it will look like this.

https://api.demo.com/[email protected]&password=Password@123

What is the syntax for an inner join in LINQ to SQL?

It goes something like:

from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}

It would be nice to have sensible names and fields for your tables for a better example. :)

Update

I think for your query this might be more appropriate:

var dealercontacts = from contact in DealerContact
                     join dealer in Dealer on contact.DealerId equals dealer.ID
                     select contact;

Since you are looking for the contacts, not the dealers.

What to do about Eclipse's "No repository found containing: ..." error messages?

I had the same problem but while doing updates. I solved it by

  • In Window->Preferences->Install/Updates->Available Software Sites, mark the site that is causing the problem and hit the Reload button.

Setting values on a copy of a slice from a DataFrame

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

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

x = x.copy()

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

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

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

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

I solved this by installing the correct version of Jquery that my project required using npm

PHP: How to use array_filter() to filter array keys?

Here's a less flexible alternative using unset():

$array = array(
    1 => 'one',
    2 => 'two',
    3 => 'three'
);
$disallowed = array(1,3);
foreach($disallowed as $key){
    unset($array[$key]);
}

The result of print_r($array) being:

Array
(
    [2] => two
)

This is not applicable if you want to keep the filtered values for later use but tidier, if you're certain that you don't.

OpenSSL and error in reading openssl.conf file

On Windows you can also set the environment property OPENSSL_CONF. For example from the commandline you can type:

set OPENSSL_CONF=c:/libs/openssl-0.9.8k/openssl.cnf

to validate it you can type:

echo %OPENSSL_CONF%

You can also set it as part of the computer's environmental variables so all users and services have it available by default. See, for example, Environment variables in Windows NT and How To Manage Environment Variables in Windows XP.

Now you can run openssl commands without having to pass the config location parameter.

Plotting categorical data with pandas and matplotlib

You can simply use value_counts on the series:

df['colour'].value_counts().plot(kind='bar')

enter image description here

Amazon Interview Question: Design an OO parking lot

Models don't exist in isolation. The structures you'd define for a simulation of cars entering a car park, an embedded system which guides you to a free space, a car parking billing system or for the automated gates/ticket machines usual in car parks are all different.