Programs & Examples On #Tlv

TLV is the short for Type Length Value. It is a technique mostly used to encode optional information within data communication protocols.

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

No mapping found for HTTP request with URI.... in DispatcherServlet with name

If you are using Java code based on Spring MVC configuration then enable the DefaultServletHandlerConfigurer in the WebMvcConfigurerAdapter object.

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 
        configurer.enable();
}

org.apache.jasper.JasperException: Unable to compile class for JSP:

This maybe caused by jar conflict. Remove the servlet-api.jar in your servlet/WEB-INF/ directory, %Tomcat home%/lib already have this lib.

My Application Could not open ServletContext resource

I encountered this exception in WebLogic, turns out it is a bug in WebLogic. Please see here for more details: Spring Boot exception: Could not open ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<mvc:annotation-driven /> means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository to tell spring that a class is a Dao without having to extend JpaDaoSupport or some other subclass of DaoSupport. Similarly @Controller tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.

When spring starts up it reads its XML configuration file and looks for <bean elements within it if it sees something like <bean class="com.example.Foo" /> and Foo was marked up with @Controller it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.

Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" /> is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." /> in the XML configuration files.

In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.

<servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.

Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.

Hope this helps.

Could not autowire field in spring. why?

Well there's a problem with the creation of the ContactServiceImpl bean. First, make sure that the class is actually instantiated by debugging the no-args constructor when the Spring context is initiated and when an instance of ContactController is created.

If the ContactServiceImpl is actually instantiated by the Spring context, but it's simply not matched against your @Autowire annotation, try being more explicit in your annotation injection. Here's a guy dealing with a similar problem as yours and giving some possible solutions:

http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/

If you ask me, I think you'll be ok if you replace

@Autowired
private ContactService contactService;

with:

@Resource
@Qualifier("contactService")
private ContactService contactService;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Getting RSA private key from PEM BASE64 Encoded private key file

You will find below some code for reading unencrypted RSA keys encoded in the following formats:

  • PKCS#1 PEM (-----BEGIN RSA PRIVATE KEY-----)
  • PKCS#8 PEM (-----BEGIN PRIVATE KEY-----)
  • PKCS#8 DER (binary)

It works with Java 7+ (and after 9) and doesn't use third-party libraries (like BouncyCastle) or internal Java APIs (like DerInputStream or DerValue).

private static final String PKCS_1_PEM_HEADER = "-----BEGIN RSA PRIVATE KEY-----";
private static final String PKCS_1_PEM_FOOTER = "-----END RSA PRIVATE KEY-----";
private static final String PKCS_8_PEM_HEADER = "-----BEGIN PRIVATE KEY-----";
private static final String PKCS_8_PEM_FOOTER = "-----END PRIVATE KEY-----";

public static PrivateKey loadKey(String keyFilePath) throws GeneralSecurityException, IOException {
    byte[] keyDataBytes = Files.readAllBytes(Paths.get(keyFilePath));
    String keyDataString = new String(keyDataBytes, StandardCharsets.UTF_8);

    if (keyDataString.contains(PKCS_1_PEM_HEADER)) {
        // OpenSSL / PKCS#1 Base64 PEM encoded file
        keyDataString = keyDataString.replace(PKCS_1_PEM_HEADER, "");
        keyDataString = keyDataString.replace(PKCS_1_PEM_FOOTER, "");
        return readPkcs1PrivateKey(Base64.decodeBase64(keyDataString));
    }

    if (keyDataString.contains(PKCS_8_PEM_HEADER)) {
        // PKCS#8 Base64 PEM encoded file
        keyDataString = keyDataString.replace(PKCS_8_PEM_HEADER, "");
        keyDataString = keyDataString.replace(PKCS_8_PEM_FOOTER, "");
        return readPkcs8PrivateKey(Base64.decodeBase64(keyDataString));
    }

    // We assume it's a PKCS#8 DER encoded binary file
    return readPkcs8PrivateKey(Files.readAllBytes(Paths.get(keyFilePath)));
}

private static PrivateKey readPkcs8PrivateKey(byte[] pkcs8Bytes) throws GeneralSecurityException {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SunRsaSign");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes);
    try {
        return keyFactory.generatePrivate(keySpec);
    } catch (InvalidKeySpecException e) {
        throw new IllegalArgumentException("Unexpected key format!", e);
    }
}

private static PrivateKey readPkcs1PrivateKey(byte[] pkcs1Bytes) throws GeneralSecurityException {
    // We can't use Java internal APIs to parse ASN.1 structures, so we build a PKCS#8 key Java can understand
    int pkcs1Length = pkcs1Bytes.length;
    int totalLength = pkcs1Length + 22;
    byte[] pkcs8Header = new byte[] {
            0x30, (byte) 0x82, (byte) ((totalLength >> 8) & 0xff), (byte) (totalLength & 0xff), // Sequence + total length
            0x2, 0x1, 0x0, // Integer (0)
            0x30, 0xD, 0x6, 0x9, 0x2A, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0, // Sequence: 1.2.840.113549.1.1.1, NULL
            0x4, (byte) 0x82, (byte) ((pkcs1Length >> 8) & 0xff), (byte) (pkcs1Length & 0xff) // Octet string + length
    };
    byte[] pkcs8bytes = join(pkcs8Header, pkcs1Bytes);
    return readPkcs8PrivateKey(pkcs8bytes);
}

private static byte[] join(byte[] byteArray1, byte[] byteArray2){
    byte[] bytes = new byte[byteArray1.length + byteArray2.length];
    System.arraycopy(byteArray1, 0, bytes, 0, byteArray1.length);
    System.arraycopy(byteArray2, 0, bytes, byteArray1.length, byteArray2.length);
    return bytes;
}

Source: https://github.com/Mastercard/client-encryption-java/blob/master/src/main/java/com/mastercard/developer/utils/EncryptionUtils.java

Spring MVC: how to create a default controller for index page?

Just put one more entry in your spring xml file i.e.mvc-dispatcher-servlet.xml

<mvc:view-controller path="/" view-name="index"/>

After putting this to your xml put your default view or jsp file in your custom JSP folder as you have mentioned in mvc-dispatcher-servlet.xml file.

change index with your jsp name.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

I had the same problem, Of course there was a little difference. The story was that when I was removing the below line:

<mvc:resources mapping="/resources/**" location="classpath:/resources/" />

Everything was OK but in presence of that line the same error raise.

After some trial and error I found I have to add the below line to my spring application context file:

<mvc:annotation-driven />

Hope it helps!

How to change value of ArrayList element in java

The list is maintaining an object reference to the original value stored in the list. So when you execute this line:

Integer x = i.next();

Both x and the list are storing a reference to the same object. However, when you execute:

x = Integer.valueOf(9);

nothing has changed in the list, but x is now storing a reference to a different object. The list has not changed. You need to use some of the list manipulation methods, such as

list.set(index, Integer.valueof(9))

Note: this has nothing to do with the immutability of Integer, as others are suggesting. This is just basic Java object reference behaviour.


Here's a complete example, to help explain the point. Note that this makes use of the ListIterator class, which supports removing/setting items mid-iteration:

import java.util.*;

public class ListExample {

  public static void main(String[] args) {

    List<Foo> fooList = new ArrayList<Foo>();
    for (int i = 0; i < 9; i++)
      fooList.add(new Foo(i, i));

    // Standard iterator sufficient for altering elements
    Iterator<Foo> iterator = fooList.iterator();

    if (iterator.hasNext()) {
      Foo foo = iterator.next();
      foo.x = 99;
      foo.y = 42;
    }

    printList(fooList);    

    // List iterator needed for replacing elements
    ListIterator<Foo> listIterator = fooList.listIterator();

    if (listIterator.hasNext()) {
      // Need to call next, before set.
      listIterator.next();
      // Replace item returned from next()
      listIterator.set(new Foo(99,99));
    }

    printList(fooList);
  }

  private static void printList(List<?> list) {
    Iterator<?> iterator = list.iterator();
    while (iterator.hasNext()) {
      System.out.print(iterator.next());
    }
    System.out.println();
  }

  private static class Foo {
    int x;
    int y;

    Foo(int x, int y) {
      this.x = x;
      this.y = y;
    }

    @Override
    public String toString() {
      return String.format("[%d, %d]", x, y);
    }
  }
}

This will print:

[99, 42][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
[99, 99][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]

How do I programmatically determine operating system in Java?

This code for displaying all information about the system os type,name , java information and so on.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Properties pro = System.getProperties();
    for(Object obj : pro.keySet()){
        System.out.println(" System  "+(String)obj+"     :  "+System.getProperty((String)obj));
    }
}

Check if event exists on element

I wrote a plugin called hasEventListener which exactly does that.

Hope this helps.

How do I check if a Sql server string is null or empty

SELECT              
    COALESCE(listing.OfferText, 'company.OfferText') AS Offer_Text,         
FROM 
    tbl_directorylisting listing  
    INNER JOIN tbl_companymaster company ON listing.company_id= company.company_id

Spring Boot - Handle to Hibernate SessionFactory

You can accomplish this with:

SessionFactory sessionFactory = 
    entityManagerFactory.unwrap(SessionFactory.class);

where entityManagerFactory is an JPA EntityManagerFactory.

package net.andreaskluth.hibernatesample;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SomeService {

  private SessionFactory hibernateFactory;

  @Autowired
  public SomeService(EntityManagerFactory factory) {
    if(factory.unwrap(SessionFactory.class) == null){
      throw new NullPointerException("factory is not a hibernate factory");
    }
    this.hibernateFactory = factory.unwrap(SessionFactory.class);
  }

}

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

Around 1:51 in the video, notice how she puts a <script> tag in there? The way it works is like this:

Create an html file (that's just a text file with a .html ending) somewhere on your computer. In the same folder that you put index.html, put a javascript file (that's just a textfile with a .js ending - let's call it game.js). Then, in your index.html file, put some html that includes the script tag with game.js, like Mary did in the video. index.html should look something like this:

<html>
    <head>
        <script src="game.js"></script>
    </head>
</html>

Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).

Good luck on your journey, hope it's as fun for you as it has been for me so far :)

Error: fix the version conflict (google-services plugin)

Please change your project-level build.gradle file in which you have to change your dependencies class path of google-services or build.gradle path.

buildscript {

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

CSS: how do I create a gap between rows in a table?

All you need:

table {
    border-collapse: separate;
    border-spacing: 0 1em;
}

That assumes you want a 1em vertical gap, and no horizontal gap. If you're doing this, you should probably also look at controlling your line-height.

Sort of weird that some of the answers people gave involve border-collapse: collapse, whose effect is the exact opposite of what the question asked for.

How to add Active Directory user group as login in SQL Server

In SQL Server Management Studio, go to Object Explorer > (your server) > Security > Logins and right-click New Login:

enter image description here

Then in the dialog box that pops up, pick the types of objects you want to see (Groups is disabled by default - check it!) and pick the location where you want to look for your objects (e.g. use Entire Directory) and then find your AD group.

enter image description here

You now have a regular SQL Server Login - just like when you create one for a single AD user. Give that new login the permissions on the databases it needs, and off you go!

Any member of that AD group can now login to SQL Server and use your database.

TypeError: $(...).modal is not a function with bootstrap Modal

I have resolved this issue in react by using it like this.

window.$('#modal-id').modal();

yii2 redirect in controller action does not work?

here is another way to do this

if(!Yii::$app->request->getIsPost()) {
    return Yii::$app->getResponse()->redirect(array('/user/index',302));
}

What's "this" in JavaScript onclick?

this referes to the object the onclick method belongs to. So inside func this would be the DOM node of the a element and this.innerText would be here.

How do I change the string representation of a Python class?

The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self):
     return "foo"

You may also want to implement __repr__ to aid in debugging.

See here for more information:

Can we execute a java program without a main() method?

You should also be able to accomplish a similar thing using the premain method of a Java agent.

The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static premain method similar in principle to the main application entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.

How are echo and print different in PHP?

To add to the answers above, while print can only take one parameter, it will allow for concatenation of multiple values, ie:

$count = 5;

print "This is " . $count . " values in " . $count/5 . " parameter";

This is 5 values in 1 parameter

How to calculate mean, median, mode and range from a set of numbers

Yes, there does seem to be 3rd libraries (none in Java Math). Two that have come up are:

http://opsresearch.com/app/

http://www.iro.umontreal.ca/~simardr/ssj/indexe.html

but, it is actually not that difficult to write your own methods to calculate mean, median, mode and range.

MEAN

public static double mean(double[] m) {
    double sum = 0;
    for (int i = 0; i < m.length; i++) {
        sum += m[i];
    }
    return sum / m.length;
}

MEDIAN

// the array double[] m MUST BE SORTED
public static double median(double[] m) {
    int middle = m.length/2;
    if (m.length%2 == 1) {
        return m[middle];
    } else {
        return (m[middle-1] + m[middle]) / 2.0;
    }
}

MODE

public static int mode(int a[]) {
    int maxValue, maxCount;

    for (int i = 0; i < a.length; ++i) {
        int count = 0;
        for (int j = 0; j < a.length; ++j) {
            if (a[j] == a[i]) ++count;
        }
        if (count > maxCount) {
            maxCount = count;
            maxValue = a[i];
        }
    }

    return maxValue;
}

UPDATE

As has been pointed out by Neelesh Salpe, the above does not cater for multi-modal collections. We can fix this quite easily:

public static List<Integer> mode(final int[] numbers) {
    final List<Integer> modes = new ArrayList<Integer>();
    final Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();

    int max = -1;

    for (final int n : numbers) {
        int count = 0;

        if (countMap.containsKey(n)) {
            count = countMap.get(n) + 1;
        } else {
            count = 1;
        }

        countMap.put(n, count);

        if (count > max) {
            max = count;
        }
    }

    for (final Map.Entry<Integer, Integer> tuple : countMap.entrySet()) {
        if (tuple.getValue() == max) {
            modes.add(tuple.getKey());
        }
    }

    return modes;
}

ADDITION

If you are using Java 8 or higher, you can also determine the modes like this:

public static List<Integer> getModes(final List<Integer> numbers) {
    final Map<Integer, Long> countFrequencies = numbers.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    final long maxFrequency = countFrequencies.values().stream()
            .mapToLong(count -> count)
            .max().orElse(-1);

    return countFrequencies.entrySet().stream()
            .filter(tuple -> tuple.getValue() == maxFrequency)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
}

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

In my case, I forgot to add git to the respository name at the end.

Use Mockito to mock some methods but not others

To directly answer your question, yes, you can mock some methods without mocking others. This is called a partial mock. See the Mockito documentation on partial mocks for more information.

For your example, you can do something like the following, in your test:

Stock stock = mock(Stock.class);
when(stock.getPrice()).thenReturn(100.00);    // Mock implementation
when(stock.getQuantity()).thenReturn(200);    // Mock implementation
when(stock.getValue()).thenCallRealMethod();  // Real implementation

In that case, each method implementation is mocked, unless specify thenCallRealMethod() in the when(..) clause.

There is also a possibility the other way around with spy instead of mock:

Stock stock = spy(Stock.class);
when(stock.getPrice()).thenReturn(100.00);    // Mock implementation
when(stock.getQuantity()).thenReturn(200);    // Mock implementation
// All other method call will use the real implementations

In that case, all method implementation are the real one, except if you have defined a mocked behaviour with when(..).

There is one important pitfall when you use when(Object) with spy like in the previous example. The real method will be called (because stock.getPrice() is evaluated before when(..) at runtime). This can be a problem if your method contains logic that should not be called. You can write the previous example like this:

Stock stock = spy(Stock.class);
doReturn(100.00).when(stock).getPrice();    // Mock implementation
doReturn(200).when(stock).getQuantity();    // Mock implementation
// All other method call will use the real implementations

Another possibility may be to use org.mockito.Mockito.CALLS_REAL_METHODS, such as:

Stock MOCK_STOCK = Mockito.mock( Stock.class, CALLS_REAL_METHODS );

This delegates unstubbed calls to real implementations.


However, with your example, I believe it will still fail, since the implementation of getValue() relies on quantity and price, rather than getQuantity() and getPrice(), which is what you've mocked.

Another possibility is to avoid mocks altogether:

@Test
public void getValueTest() {
    Stock stock = new Stock(100.00, 200);
    double value = stock.getValue();
    assertEquals("Stock value not correct", 100.00*200, value, .00001);
}

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

This variable can be saved in json. For example envsettings.json with content as below

  {
   // Possible string values reported below. When empty it use ENV variable value or 
     // Visual Studio setting.
     // - Production
     // - Staging
     // - Test
     // - Development

   "ASPNETCORE_ENVIRONMENT": "Development"
  }

Later modify your program.cs as below

  public class Program
  {
    public static IConfiguration Configuration { get; set; }
    public static void Main(string[] args)
    {
        var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var environmentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();

        var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
          var webHostBuilder = new WebHostBuilder()
            .UseKestrel()
            .CaptureStartupErrors(true)
            .UseContentRoot(currentDirectoryPath)
            .UseIISIntegration()
            .UseStartup<Startup>();

        // If none is set it use Operative System hosting enviroment
        if (!string.IsNullOrWhiteSpace(environmentValue))
        {
            webHostBuilder.UseEnvironment(environmentValue);
        }

        var host = webHostBuilder.Build();

        host.Run();
     }
 }

This way it will always be included in publish and you can change to required value according to environment where website is hosted. This method can also be used in console app as the changes are in Program.cs

phpMyAdmin + CentOS 6.0 - Forbidden

I tried all answers provided here: editing phpMyAdmin.conf, changing selinux context for phpmyadmin folder, disabling selinux... but I still got a 'Forbidden' from the web server.

I finally found what I was missing in Edouard Thiel post here :

$ yum install php

then restart httpd :

$ service httpd restart => for centos 6 hots

$ systemctl restart httpd => for centos 7 hosts

What has me amazed is why php is not installed as dependency for phpmyadmin in the first place.

Regards, Fred

Java 8, Streams to find the duplicate elements

You can get the duplicated like this :

List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
Set<Integer> duplicated = numbers
  .stream()
  .filter(n -> numbers
        .stream()
        .filter(x -> x == n)
        .count() > 1)
   .collect(Collectors.toSet());

Are HTTP headers case-sensitive?

officially, headers are case insensitive, however, it is common practice to capitalize the first letter of every word.
but, because it is common practice, certain programs like IE assume the headers are capitalized.
so while the docs say the are case insensitive, bad programmers have basically changed the docs.

PHP Unset Session Variable

Destroying a PHP Session

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable

<?php    unset($_SESSION['counter']); ?>

Here is the call which will destroy all the session variables

<?php    session_destroy(); ?>

Definition of int64_t

My 2 cents, from a current implementation Point of View and for SWIG users on k8 (x86_64) architecture.

Linux

First long long and long int are different types but sizeof(long long) == sizeof(long int) == sizeof(int64_t)

Gcc

First try to find where and how the compiler define int64_t and uint64_t

grepc -rn "typedef.*INT64_TYPE" /lib/gcc
/lib/gcc/x86_64-linux-gnu/9/include/stdint-gcc.h:43:typedef __INT64_TYPE__ int64_t;
/lib/gcc/x86_64-linux-gnu/9/include/stdint-gcc.h:55:typedef __UINT64_TYPE__ uint64_t;

So we need to find this compiler macro definition

gcc -dM -E -x c /dev/null | grep __INT64                 
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int

gcc -dM -E -x c++ /dev/null | grep __INT64
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int

Clang

clang -dM -E -x c++ /dev/null | grep INT64_TYPE
#define __INT64_TYPE__ long int
#define __UINT64_TYPE__ long unsigned int

Clang, GNU compilers:
-dM dumps a list of macros.
-E prints results to stdout instead of a file.
-x c and -x c++ select the programming language when using a file without a filename extension, such as /dev/null

Ref: https://web.archive.org/web/20190803041507/http://nadeausoftware.com/articles/2011/12/c_c_tip_how_list_compiler_predefined_macros

note: for swig user, on Linux x86_64 use -DSWIGWORDSIZE64

MacOS

On Catalina 10.15 IIRC

Clang

clang -dM -E -x c++ /dev/null | grep INT64_TYPE
#define __INT64_TYPE__ long long int
#define __UINT64_TYPE__ long long unsigned int

Clang:
-dM dumps a list of macros.
-E prints results to stdout instead of a file.
-x c and -x c++ select the programming language when using a file without a filename extension, such as /dev/null

Ref: https://web.archive.org/web/20190803041507/http://nadeausoftware.com/articles/2011/12/c_c_tip_how_list_compiler_predefined_macros

note: for swig user, on macOS x86_64 don't use -DSWIGWORDSIZE64

Visual Studio 2019

First sizeof(long int) == 4 and sizeof(long long) == 8

in stdint.h we have:

#if _VCRT_COMPILER_PREPROCESSOR

typedef signed char        int8_t;
typedef short              int16_t;
typedef int                int32_t;
typedef long long          int64_t;
typedef unsigned char      uint8_t;
typedef unsigned short     uint16_t;
typedef unsigned int       uint32_t;
typedef unsigned long long uint64_t;

note: for swig user, on windows x86_64 don't use -DSWIGWORDSIZE64

SWIG Stuff

First see https://github.com/swig/swig/blob/3a329566f8ae6210a610012ecd60f6455229fe77/Lib/stdint.i#L20-L24 so you can control the typedef using SWIGWORDSIZE64 but...

now the bad: SWIG Java and SWIG CSHARP do not take it into account

So you may want to use

#if defined(SWIGJAVA)
#if defined(SWIGWORDSIZE64)
%define PRIMITIVE_TYPEMAP(NEW_TYPE, TYPE)
%clear NEW_TYPE;
%clear NEW_TYPE *;
%clear NEW_TYPE &;
%clear const NEW_TYPE &;
%apply TYPE { NEW_TYPE };
%apply TYPE * { NEW_TYPE * };
%apply TYPE & { NEW_TYPE & };
%apply const TYPE & { const NEW_TYPE & };
%enddef // PRIMITIVE_TYPEMAP
PRIMITIVE_TYPEMAP(long int, long long);
PRIMITIVE_TYPEMAP(unsigned long int, long long);
#undef PRIMITIVE_TYPEMAP
#endif // defined(SWIGWORDSIZE64)
#endif // defined(SWIGJAVA)

and

#if defined(SWIGCSHARP)
#if defined(SWIGWORDSIZE64)
%define PRIMITIVE_TYPEMAP(NEW_TYPE, TYPE)
%clear NEW_TYPE;
%clear NEW_TYPE *;
%clear NEW_TYPE &;
%clear const NEW_TYPE &;
%apply TYPE { NEW_TYPE };
%apply TYPE * { NEW_TYPE * };
%apply TYPE & { NEW_TYPE & };
%apply const TYPE & { const NEW_TYPE & };
%enddef // PRIMITIVE_TYPEMAP
PRIMITIVE_TYPEMAP(long int, long long);
PRIMITIVE_TYPEMAP(unsigned long int, unsigned long long);
#undef PRIMITIVE_TYPEMAP
#endif // defined(SWIGWORDSIZE64)
#endif // defined(SWIGCSHARP)

So int64_t aka long int will be bind to Java/C# long on Linux...

Should composer.lock be committed to version control?

If you’re concerned about your code breaking, you should commit the composer.lock to your version control system to ensure all your project collaborators are using the same version of the code. Without a lock file, you will get new third-party code being pulled down each time.

The exception is when you use a meta apps, libraries where the dependencies should be updated on install (like the Zend Framework 2 Skeleton App). So the aim is to grab the latest dependencies each time when you want to start developing.

Source: Composer: It’s All About the Lock File

See also: What are the differences between composer update and composer install?

String comparison - Android

The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them). Use the .equals() method to compare strings for equality.

http://www.leepoint.net/notes-java/data/strings/12stringcomparison.html

How do I know the script file name in a Bash script?

To answer Chris Conway, on Linux (at least) you would do this:

echo $(basename $(readlink -nf $0))

readlink prints out the value of a symbolic link. If it isn't a symbolic link, it prints the file name. -n tells it to not print a newline. -f tells it to follow the link completely (if a symbolic link was a link to another link, it would resolve that one as well).

Java: How to stop thread?

JavaSun recomendation is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread to terminate.

You can that way kill the other process, and the current one afterwards.

How to change Android version and code version number?

Go in the build.gradle and set the version code and name inside the defaultConfig element

defaultConfig { minSdkVersion 9 targetSdkVersion 19 versionCode 1 versionName "1.0" }

How can I specify the schema to run an sql file against in the Postgresql command line

More universal way is to set search_path (should work in PostgreSQL 7.x and above):

SET search_path TO myschema;

Note that set schema myschema is an alias to above command that is not available in 8.x.

See also: http://www.postgresql.org/docs/9.3/static/ddl-schemas.html

ECONNREFUSED error when connecting to mongodb from node.js

Mongodb was not running but I had the module for node.js The database path was missing. Fix was create new folder in the root so run sudo mkdir -p /data/db/ then run sudo chown id -u /data/db

Select from multiple tables without a join?

In this case we are assuming that we have two tables: SMPPMsgLogand SMSService with common column serviceid:

SELECT sp.SMS,ss.CMD 
FROM vas.SMPPMsgLog AS sp,vas.SMSService AS ss 
WHERE sp.serviceid=5431 
AND ss.ServiceID = 5431 
AND Receiver ="232700000" 
AND date(TimeStamp) <='2013-08-07' 
AND date(TimeStamp) >='2013-08-06' \G;

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

How to remove the border highlight on an input text element

You can remove the orange or blue border (outline) around text/input boxes by using: outline:none

input {
    background-color: transparent;
    border: 0px solid;
    height: 20px;
    width: 160px;
    color: #CCC;
    outline:none !important;
}

How to position text over an image in css

as Harry Joy points out, set the image as the div's background and then, if you only have one line of text you can set the line-height of the text to be the same as the div height and this will place your text in the center of the div.

If you have more than one line you'll want to set the display to be table-cell and vertical-alignment to middle.

How to Delete Session Cookie?

There are known issues with IE and Opera not removing session cookies when setting the expire date to the past (which is what the jQuery cookie plugin does)

This works fine in Safari and Mozilla/FireFox.

SQL select only rows with max value on a column

Here is a nice way of doing that

Use following code :

with temp as  ( 
select count(field1) as summ , field1
from table_name
group by field1 )
select * from temp where summ = (select max(summ) from temp)

How to delete columns in a CSV file?

You can directly delete the column with just

del variable_name['year']

How to pass arguments to entrypoint in docker-compose.yml

Whatever is specified in the command in docker-compose.yml should get appended to the entrypoint defined in the Dockerfile, provided entrypoint is defined in exec form in the Dockerfile.

If the EntryPoint is defined in shell form, then any CMD arguments will be ignored.

What is the meaning of ToString("X2")?

It prints the byte in Hexadecimal format.

No format string: 13

'X2' format string: 0D

http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx

Bootstrap 3 .col-xs-offset-* doesn't work?

A suggestion for when you want to do an offset but find yourself incapable at extra small widths:

Use .hidden-xs and .visible-xs to make one version of your html block for extra small widths, and one for everything else (where you can still use an offset)

Example:

<div class="hero container">
  <div class="row">
    <div class="hidden-xs col-sm-8 col-sm-offset-2 col-md-4 col-md-offset-4 text-center">
      <h2>This is a banner at the top of my site. It shows in everything except XS</h2>
      <p>Here are some supporting details about my banner.</p>
    </div>
    <div class="visible-xs col-xs-12">
      <h2 class="pull-right">This is my banner at XS width.</h2>
      <p class="pull-right">This is my supporting content at XS width.</p>
    </div>
  </div>
</div>

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

Solr vs. ElasticSearch

I have created a table of major differences between elasticsearch and Solr and splunk, you can use it as 2016 update: enter image description here

Laravel orderBy on a relationship

Using sortBy... could help.

$users = User::all()->with('rated')->get()->sortByDesc('rated.rating');

How do you properly use namespaces in C++?

Another difference between java and C++, is that in C++, the namespace hierarchy does not need to mach the filesystem layout. So I tend to put an entire reusable library in a single namespace, and subsystems within the library in subdirectories:

#include "lib/module1.h"
#include "lib/module2.h"

lib::class1 *v = new lib::class1();

I would only put the subsystems in nested namespaces if there was a possibility of a name conflict.

How do I increase modal width in Angular UI Bootstrap?

If you want to just go with the default large size you can add 'modal-lg':

var modal = $modal.open({
          templateUrl: "/partials/welcome",
          controller: "welcomeCtrl",
          backdrop: "static",
          scope: $scope,
          windowClass: 'modal-lg'
});

Console.log not working at all

Click on the restore button. console.log will start to work.

enter image description here

Conditionally hide CommandField or ButtonField in Gridview

First, convert your ButtonField or CommandField to a TemplateField, then bind the Visible property of the button to a method that implements the business logic:

<asp:GridView runat="server" ID="GV1" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Age" HeaderText="Age" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button runat="server" Text="Reject" 
                Visible='<%# IsOverAgeLimit((Decimal)Eval("Age")) %>' 
                CommandName="Select"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Then, in the code behind, add in the method:

protected Boolean IsOverAgeLimit(Decimal Age) {
    return Age > 35M;
}

The advantage here is you can test the IsOverAgeLimit method fairly easily.

Scale an equation to fit exact page width

\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

or

\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

Check file size before upload

I created a jQuery version of PhpMyCoder's answer:

$('form').submit(function( e ) {    
    if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
        //Prevent default and display error
        alert("File is wrong type or over 10Mb in size!");
        e.preventDefault();
    }
});

function get_extension(filename) {
    return filename.split('.').pop().toLowerCase();
}

How can I make an EXE file from a Python program?

Not on the freehackers list is gui2exe which can be used to build standalone Windows executables, Linux applications and Mac OS application bundles and plugins starting from Python scripts.

Find commit by hash SHA in Git

There are two ways to do this.

1. providing the SHA of the commit you want to see to git log

git log -p a2c25061

Where -p is short for patch

2. use git show

git show a2c25061

The output for both commands will be:

  • the commit
  • the author
  • the date
  • the commit message
  • the patch information

Refresh (reload) a page once using jQuery?

Use:

<html>
    <head>
        <title>Reload (Refresh) Page Using Jquery</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#reload').click(function() {
                    window.location.reload();
                });
            });
        </script>
    </head>
    <body>
        <button id="reload" >Reload (Refresh) Page Using</button>
    </body>
</html>

Get the content of a sharepoint folder with Excel VBA

I spent some time on this very problem - I was trying to verify a file existed before opening it.

Eventually, I came up with a solution using XML and SOAP - use the EnumerateFolder method and pull in an XML response with the folder's contents.

I blogged about it here.

How to Convert double to int in C?

main() {
    double a;
    a=3669.0;
    int b;
    b=a;
    printf("b is %d",b);
  
}

output is :b is 3669

when you write b=a; then its automatically converted in int

see on-line compiler result : 

http://ideone.com/60T5b


This is called Implicit Type Conversion Read more here https://www.geeksforgeeks.org/implicit-type-conversion-in-c-with-examples/

How to convert a char array to a string?

The string class has a constructor that takes a NULL-terminated C-string:

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

// or
str = arr;

PL/SQL block problem: No data found error

Might be worth checking online for the errata section for your book.

There's an example of handling this exception here http://www.dba-oracle.com/sf_ora_01403_no_data_found.htm

How to split a list by comma not space

Set IFS to ,:

sorin@sorin:~$ IFS=',' ;for i in `echo "Hello,World,Questions,Answers,bash shell,script"`; do echo $i; done
Hello
World
Questions
Answers
bash shell
script
sorin@sorin:~$ 

How to add label in chart.js for pie chart

Rachel's solution is working fine, although you need to use the third party script from raw.githubusercontent.com

By now there is a feature they show on the landing page when advertisng the "modular" script. You can see a legend there with this structure:

<div class="labeled-chart-container">
    <div class="canvas-holder">
        <canvas id="modular-doughnut" width="250" height="250" style="width: 250px; height: 250px;"></canvas>
    </div>

<ul class="doughnut-legend">
    <li><span style="background-color:#5B90BF"></span>Core</li>
    <li><span style="background-color:#96b5b4"></span>Bar</li>
    <li><span style="background-color:#a3be8c"></span>Doughnut</li>
    <li><span style="background-color:#ab7967"></span>Radar</li>
    <li><span style="background-color:#d08770"></span>Line</li>
    <li><span style="background-color:#b48ead"></span>Polar Area</li>
</ul>
</div>

To achieve this they use the chart configuration option legendTemplate

legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"

You can find the doumentation here on chartjs.org This works for all the charts although it is not part of the global chart configuration.

Then they create the legend and add it to the DOM like this:

var legend = myPie.generateLegend();
$("#legend").html(legend);

Sample See also my JSFiddle sample

Can an abstract class have a constructor?

You would define a constructor in an abstract class if you are in one of these situations:

  • you want to perform some initialization (to fields of the abstract class) before the instantiation of a subclass actually takes place
  • you have defined final fields in the abstract class but you did not initialize them in the declaration itself; in this case, you MUST have a constructor to initialize these fields

Note that:

  • you may define more than one constructor (with different arguments)
  • you can (should?) define all your constructors protected (making them public is pointless anyway)
  • your subclass constructor(s) can call one constructor of the abstract class; it may even have to call it (if there is no no-arg constructor in the abstract class)

In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).

window.close and self.close do not close the window in Chrome

Many people are still trying to find a way to close the Chrome browser using javascript. The following method only works when you use Chrome as APP launcher - kiosk for example!

I have tested the following:

I'm using the following extension: Close Kiosk

I'm following the usage instructions and it seems to work just fine (make sure you clear the cache while doing the tests). The javascript I use is (attached to click event):

window.location.href = '/closekiosk';

I hope that helps somebody, as it's the only working solution I have found.

Note: It seems the extension runs in background and adds a Chrome tray icon. It has the following option checked: "Let Chrome run in background" (or similar text). You may need to play with it, until it work for you. I unchecked it and now it works just fine!

Swift - Integer conversion to Hours/Minutes/Seconds

Here is a more structured/flexible approach: (Swift 3)

struct StopWatch {

    var totalSeconds: Int

    var years: Int {
        return totalSeconds / 31536000
    }

    var days: Int {
        return (totalSeconds % 31536000) / 86400
    }

    var hours: Int {
        return (totalSeconds % 86400) / 3600
    }

    var minutes: Int {
        return (totalSeconds % 3600) / 60
    }

    var seconds: Int {
        return totalSeconds % 60
    }

    //simplified to what OP wanted
    var hoursMinutesAndSeconds: (hours: Int, minutes: Int, seconds: Int) {
        return (hours, minutes, seconds)
    }
}

let watch = StopWatch(totalSeconds: 27005 + 31536000 + 86400)
print(watch.years) // Prints 1
print(watch.days) // Prints 1
print(watch.hours) // Prints 7
print(watch.minutes) // Prints 30
print(watch.seconds) // Prints 5
print(watch.hoursMinutesAndSeconds) // Prints (7, 30, 5)

Having an approach like this allows the adding of convenience parsing like this:

extension StopWatch {

    var simpleTimeString: String {
        let hoursText = timeText(from: hours)
        let minutesText = timeText(from: minutes)
        let secondsText = timeText(from: seconds)
        return "\(hoursText):\(minutesText):\(secondsText)"
    }

    private func timeText(from number: Int) -> String {
        return number < 10 ? "0\(number)" : "\(number)"
    }
}
print(watch.simpleTimeString) // Prints 07:30:05

It should be noted that purely Integer based approaches don't take leap day/seconds into account. If the use case is dealing with real dates/times Date and Calendar should be used.

What is the best way to know if all the variables in a Class are null?

"Best" is such a subjective term :-)

I would just use the method of checking each individual variable. If your class already has a lot of these, the increase in size is not going to be that much if you do something like:

public Boolean anyUnset() {
    if (  id == null) return true;
    if (name == null) return true;
    return false;
}

Provided you keep everything in the same order, code changes (and automated checking with a script if you're paranoid) will be relatively painless.

Alternatively (assuming they're all strings), you could basically put these values into a map of some sort (eg, HashMap) and just keep a list of the key names for that list. That way, you could iterate through the list of keys, checking that the values are set correctly.

Clear icon inside input text

If you want it like Google, then you should know that the "X" isn't actually inside the <input> -- they're next to each other with the outer container styled to appear like the text box.

HTML:

<form>
    <span class="x-input">
        <input type="text" class="x-input-text" />
        <input type="reset" />
    </span>
</form>

CSS:

.x-input {
    border: 1px solid #ccc;
}

.x-input input.x-input-text {
    border: 0;
    outline: 0;
}

Example: http://jsfiddle.net/VTvNX/

Changing CSS Values with Javascript

Ok, it sounds like you want to change the global CSS so which will effictively change all elements of a peticular style at once. I've recently learned how to do this myself from a Shawn Olson tutorial. You can directly reference his code here.

Here is the summary:

You can retrieve the stylesheets via document.styleSheets. This will actually return an array of all the stylesheets in your page, but you can tell which one you are on via the document.styleSheets[styleIndex].href property. Once you have found the stylesheet you want to edit, you need to get the array of rules. This is called "rules" in IE and "cssRules" in most other browsers. The way to tell what CSSRule you are on is by the selectorText property. The working code looks something like this:

var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
var selector = rule.selectorText;  //maybe '#tId'
var value = rule.value;            //both selectorText and value are settable.

Let me know how this works for ya, and please comment if you see any errors.

Postgres FOR LOOP

I just ran into this question and, while it is old, I figured I'd add an answer for the archives. The OP asked about for loops, but their goal was to gather a random sample of rows from the table. For that task, Postgres 9.5+ offers the TABLESAMPLE clause on WHERE. Here's a good rundown:

https://www.2ndquadrant.com/en/blog/tablesample-in-postgresql-9-5-2/

I tend to use Bernoulli as it's row-based rather than page-based, but the original question is about a specific row count. For that, there's a built-in extension:

https://www.postgresql.org/docs/current/tsm-system-rows.html

CREATE EXTENSION tsm_system_rows;

Then you can grab whatever number of rows you want:

select * from playtime tablesample system_rows (15);

Can angularjs routes have optional parameter values?

Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl

You can use a function to generate the template string:

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

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id;   }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

Responsive table handling in Twitter Bootstrap

One option that is available is fooTable. Works great on a Responsive website and allows you to set multiple breakpoints... fooTable Link

How can I see the raw SQL queries Django is running?

I've made a small snippet you can use:

from django.conf import settings
from django.db import connection


def sql_echo(method, *args, **kwargs):
    settings.DEBUG = True
    result = method(*args, **kwargs)
    for query in connection.queries:
        print(query)
    return result


# HOW TO USE EXAMPLE:
# 
# result = sql_echo(my_method, 'whatever', show=True)

It takes as parameters function (contains sql queryies) to inspect and args, kwargs needed to call that function. As the result it returns what function returns and prints SQL queries in a console.

How to free memory in Java?

If you really want to allocate and free a block of memory you can do this with direct ByteBuffers. There is even a non-portable way to free the memory.

However, as has been suggested, just because you have to free memory in C, doesn't mean it a good idea to have to do this.

If you feel you really have a good use case for free(), please include it in the question so we can see what you are rtying to do, it is quite likely there is a better way.

Escaping a forward slash in a regular expression

If the delimiter is /, you will need to escape.

What is the difference between class and instance methods?

Class methods can't change or know the value of any instance variable. That should be the criteria for knowing if an instance method can be a class method.

Using IF ELSE in Oracle

You can use Decode as well:

SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
      AND A.ITEM_KEY = b.item_key
      AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
                         and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item

How to replace list item in best way

I don't if it is best or not but you can use it also

List<string> data = new List<string>
(new string[]   { "Computer", "A", "B", "Computer", "B", "A" });
int[] indexes = Enumerable.Range(0, data.Count).Where
                 (i => data[i] == "Computer").ToArray();
Array.ForEach(indexes, i => data[i] = "Calculator");

Creating object with dynamic keys

In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.

The syntax is:

var obj = {
  [myKey]: value,
}

If applied to the OP's scenario, it would turn into:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    return {
      [this.attr('name')]: this.attr('value'),
    };
  }) 

  callback(null, inputs);
}

Note: A transpiler is still required for browser compatiblity.

Using Babel or Google's traceur, it is possible to use this syntax today.


In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.

To use a "dynamic" key, you have to use bracket notation:

var obj = {};
obj[myKey] = value;

In your case:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    var key   = this.attr('name')
     ,  value = this.attr('value')
     ,  ret   = {};

     ret[key] = value;
     return ret;
  }) 

  callback(null, inputs);
}

How to check if an element does NOT have a specific class?

Select element (or group of elements) having class "abc", not having class "xyz":

    $('.abc:not(".xyz")')

When selecting regular CSS you can use .abc:not(.xyz).

zsh compinit: insecure directories

Send a y character to the input stream of the script using compinit, in order to automatically answer the Ignore insecure directories and files and continue [y] or abort compinit [n]? question

echo "y" > source <GOOGLECLOUDSDK>/completion.zsh.inc

The solution is useful when

  • you can't make ownership/access changes to the folders
  • when you can't use the -u option to remove the warning (probably because you don't explicitly call 'compinit' yourself, but it's called by a script you call)

Remark: It doesn't fix the problem and only hides the warning (as opposed to others answers here which involve removing 'group write access' or 'change ownership to root').

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

Well I've tried everything I found on the internet and none of them worked. Calling System.gc() only drags down the speed of app. Recycling bitmaps in onDestroy didn't work for me too.

The only thing that works now is to have a static list of all the bitmap so that the bitmaps survive after a restart. And just use the saved bitmaps instead of creating new ones every time the activity if restarted.

In my case the code looks like this:

private static BitmapDrawable currentBGDrawable;

if (new File(uriString).exists()) {
    if (!uriString.equals(currentBGUri)) {
        freeBackground();
        bg = BitmapFactory.decodeFile(uriString);

        currentBGUri = uriString;
        bgDrawable = new BitmapDrawable(bg);
        currentBGDrawable = bgDrawable;
    } else {
        bgDrawable = currentBGDrawable;
    }
}

React Native: Getting the position of an element

I had a similar problem and solved it by combining the answers above

class FeedPost extends React.Component {
  constructor(props) {
    ...
    this.handleLayoutChange = this.handleLayoutChange.bind(this);
  }


handleLayoutChange() {
    this.feedPost.measure( (fx, fy, width, height, px, py) => {
      console.log('Component width is: ' + width)
      console.log('Component height is: ' + height)
      console.log('X offset to page: ' + px)
      console.log('Y offset to page: ' + py)
    })
  }

  render {
    return(
      <View onLayout={(event) => {this.handleLayoutChange(event) }} 
      ref={view => { this.feedPost = view; }} >
...

Now I can see the position of my feedPost element in the logs:

08-24 11:15:36.838  3727 27838 I ReactNativeJS: Component width is: 156
08-24 11:15:36.838  3727 27838 I ReactNativeJS: Component height is: 206
08-24 11:15:36.838  3727 27838 I ReactNativeJS: X offset to page: 188
08-24 11:15:36.838  3727 27838 I ReactNativeJS: Y offset to page: 870

What is a user agent stylesheet?

I have a solution. Check this:

Error

<link href="assets/css/bootstrap.min.css" rel="text/css" type="stylesheet">

Correct

<link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">

fetch from origin with deleted remote branches?

You need to do the following

git fetch -p

This will update the local database of remote branches.

Editing legend (text) labels in ggplot

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

An example with your data:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

this results in:

enter image description here

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

Python - How to concatenate to a string in a for loop?

endstring = ''
for s in list:
    endstring += s

Why is the time complexity of both DFS and BFS O( V + E )

Time complexity is O(E+V) instead of O(2E+V) because if the time complexity is n^2+2n+7 then it is written as O(n^2).

Hence, O(2E+V) is written as O(E+V)

because difference between n^2 and n matters but not between n and 2n.

Need help rounding to 2 decimal places

The System.Math.Round method uses the Double structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:

Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)

Result: 0.58

Using lambda expressions for event handlers

No performance implications that I'm aware of or have ever run into, as far as I know its just "syntactic sugar" and compiles down to the same thing as using delegate syntax, etc.

User Control - Custom Properties

Just add public properties to the user control.

You can add [Category("MyCategory")] and [Description("A property that controls the wossname")] attributes to make it nicer, but as long as it's a public property it should show up in the property panel.

How to convert interface{} to string?

You need to add type assertion .(string). It is necessary because the map is of type map[string]interface{}:

host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)

Latest version of Docopt returns Opts object that has methods for conversion:

host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port

Sending email from Command-line via outlook without having to click send

You can use cURL and CRON to run .php files at set times.

Here's an example of what cURL needs to run the .php file:

curl http://localhost/myscript.php

Then setup the CRON job to run the above cURL:

nano -w /var/spool/cron/root
or
crontab -e

Followed by:

01 * * * * /usr/bin/curl http://www.yoursite.com/script.php

For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/

For more info about cURL: What is cURL in PHP?

For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800

Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )

NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.

Best of luck with the automatic PHP running :-)

What exactly is RESTful programming?

REST is an architectural style which is based on web-standards and the HTTP protocol (introduced in 2000).

In a REST based architecture, everything is a resource(Users, Orders, Comments). A resource is accessed via a common interface based on the HTTP standard methods(GET, PUT, PATCH, DELETE etc).

In a REST based architecture you have a REST server which provides access to the resources. A REST client can access and modify the REST resources.

Every resource should support the HTTP common operations. Resources are identified by global IDs (which are typically URIs).

REST allows that resources have different representations, e.g., text, XML, JSON etc. The REST client can ask for a specific representation via the HTTP protocol (content negotiation).

HTTP methods:

The PUT, GET, POST and DELETE methods are typical used in REST based architectures. The following table gives an explanation of these operations.

  • GET defines a reading access of the resource without side-effects. The resource is never changed via a GET request, e.g., the request has no side effects (idempotent).
  • PUT creates a new resource. It must also be idempotent.
  • DELETE removes the resources. The operations are idempotent. They can get repeated without leading to different results.
  • POST updates an existing resource or creates a new resource.

What Java FTP client library should I use?

Apache commons-nets get updates more frequently recently, while Enterprise DT library seems to update even more frequently.

How to determine the current shell I'm working on

Provided that your /bin/sh supports the POSIX standard and your system has the lsof command installed - a possible alternative to lsof could in this case be pid2path - you can also use (or adapt) the following script that prints full paths:

#!/bin/sh
# cat /usr/local/bin/cursh
set -eu
pid="$$"

set -- sh bash zsh ksh ash dash csh tcsh pdksh mksh fish psh rc scsh bournesh wish Wish login

unset echo env sed ps lsof awk getconf

# getconf _POSIX_VERSION  # reliable test for availability of POSIX system?
PATH="`PATH=/usr/bin:/bin:/usr/sbin:/sbin getconf PATH`"
[ $? -ne 0 ] && { echo "'getconf PATH' failed"; exit 1; }
export PATH

cmd="lsof"
env -i PATH="${PATH}" type "$cmd" 1>/dev/null 2>&1 || { echo "$cmd not found"; exit 1; }

awkstr="`echo "$@" | sed 's/\([^ ]\{1,\}\)/|\/\1/g; s/ /$/g' | sed 's/^|//; s/$/$/'`"

ppid="`env -i PATH="${PATH}" ps -p $pid -o ppid=`"
[ "${ppid}"X = ""X ] && { echo "no ppid found"; exit 1; }

lsofstr="`lsof -p $ppid`" || 
   { printf "%s\n" "lsof failed" "try: sudo lsof -p \`ps -p \$\$ -o ppid=\`"; exit 1; }

printf "%s\n" "${lsofstr}" | 
   LC_ALL=C awk -v var="${awkstr}" '$NF ~ var {print $NF}'

"Can't find Project or Library" for standard VBA functions

I have seen errors on standard functions if there was a reference to a totally different library missing.

In the VBA editor launch the Compile command from the menu and then check the References dialog to see if there is anything missing and if so try to add these libraries.

In general it seems to be good practice to compile the complete VBA code and then saving the document before distribution.

Draw path between two points using Google Maps Android API v2

Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }


        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

GetPathFromLocation.java

public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}

DirectionPointListener

public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}

Now draw path using below code in your Activity

private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }

OutPut

enter image description here

I hope this can help you!

Thank You.

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

A solution that helped me: Go to Tools > NuGet Package Manager > Manage NuGet Packaged for Solution... > Browse > Search for System.IO.Compression.ZipFile and install it

UITextField border color

Import the following class:

#import <QuartzCore/QuartzCore.h> 

//Code for setting the grey color for the border of the text field

[[textField layer] setBorderColor:[[UIColor colorWithRed:171.0/255.0
                                                   green:171.0/255.0
                                                    blue:171.0/255.0
                                                   alpha:1.0] CGColor]];

Replace 171.0 with the respective color number as required.

Get list of data-* attributes using javascript / jQuery

Actually, if you're working with jQuery, as of version 1.4.3 1.4.4 (because of the bug as mentioned in the comments below), data-* attributes are supported through .data():

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.

Note that strings are left intact while JavaScript values are converted to their associated value (this includes booleans, numbers, objects, arrays, and null). The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

The jQuery.fn.data function will return all of the data- attribute inside an object as key-value pairs, with the key being the part of the attribute name after data- and the value being the value of that attribute after being converted following the rules stated above.

I've also created a simple demo if that doesn't convince you: http://jsfiddle.net/yijiang/WVfSg/

how to take user input in Array using java?

It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.

The simplest example is if you're bundling an executable - in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application's main method.

Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet/doPost method of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.

If it's a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.

Basically, reading input as arrays is quite easy, once you have worked out a way to get input. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.

How to pass the password to su/sudo/ssh without overriding the TTY?

I had the same problem. dialog script to create directory on remote pc. dialog with ssh is easy. I use sshpass (previously installed).

   dialog --inputbox "Enter IP" 8 78 2> /tmp/ip

   IP=$(cat /tmp/ip)


   dialog --inputbox "Please enter username" 8 78 2> /tmp/user

   US=$(cat /tmp/user)


   dialog --passwordbox "enter password for \"$US\" 8 78 2> /tmp/pass

   PASSWORD = $(cat /tmp/pass)


   sshpass -p "$PASSWORD" ssh $US@$IP mkdir -p /home/$US/TARGET-FOLDER


   rm /tmp/ip

   rm /tmp/user

   rm /tmp/pass

greetings from germany

titus

Assert that a method was called in a Python unit test

I'm not aware of anything built-in. It's pretty simple to implement:

class assertMethodIsCalled(object):
    def __init__(self, obj, method):
        self.obj = obj
        self.method = method

    def called(self, *args, **kwargs):
        self.method_called = True
        self.orig_method(*args, **kwargs)

    def __enter__(self):
        self.orig_method = getattr(self.obj, self.method)
        setattr(self.obj, self.method, self.called)
        self.method_called = False

    def __exit__(self, exc_type, exc_value, traceback):
        assert getattr(self.obj, self.method) == self.called,
            "method %s was modified during assertMethodIsCalled" % self.method

        setattr(self.obj, self.method, self.orig_method)

        # If an exception was thrown within the block, we've already failed.
        if traceback is None:
            assert self.method_called,
                "method %s of %s was not called" % (self.method, self.obj)

class test(object):
    def a(self):
        print "test"
    def b(self):
        self.a()

obj = test()
with assertMethodIsCalled(obj, "a"):
    obj.b()

This requires that the object itself won't modify self.b, which is almost always true.

HTML image not showing in Gmail

Google only allows images which are coming from trusted source .

So I solved this issue by hosting my images in google drive and using its url as source for my images.

Example: with: http://drive.google.com/uc?export=view&id=FILEID'>

to form URL please refer here.

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

What is the difference between instanceof and Class.isAssignableFrom(...)?

Talking in terms of performance "2" (with JMH):

class A{}
class B extends A{}

public class InstanceOfTest {

public static final Object a = new A();
public static final Object b = new B();

@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public boolean testInstanceOf()
{
    return b instanceof A;
}

@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public boolean testIsInstance()
{
    return A.class.isInstance(b);
}

@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public boolean testIsAssignableFrom()
{
    return A.class.isAssignableFrom(b.getClass());
}

public static void main(String[] args) throws RunnerException {
    Options opt = new OptionsBuilder()
            .include(InstanceOfTest.class.getSimpleName())
            .warmupIterations(5)
            .measurementIterations(5)
            .forks(1)
            .build();

    new Runner(opt).run();
}
}

It gives:

Benchmark                            Mode  Cnt  Score   Error  Units
InstanceOfTest.testInstanceOf        avgt    5  1,972 ? 0,002  ns/op
InstanceOfTest.testIsAssignableFrom  avgt    5  1,991 ? 0,004  ns/op
InstanceOfTest.testIsInstance        avgt    5  1,972 ? 0,003  ns/op

So that we can conclude: instanceof as fast as isInstance() and isAssignableFrom() not far away (+0.9% executon time). So no real difference whatever you choose

Git submodule head 'reference is not a tree' error

Assuming the submodule's repository does contain a commit you want to use (unlike the commit that is referenced from current state of the super-project), there are two ways to do it.

The first requires you to already know the commit from the submodule that you want to use. It works from the “inside, out” by directly adjusting the submodule then updating the super-project. The second works from the “outside, in” by finding the super-project's commit that modified the submodule and then reseting the super-project's index to refer to a different submodule commit.

Inside, Out

If you already know which commit you want the submodule to use, cd to the submodule, check out the commit you want, then git add and git commit it back in the super-project.

Example:

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

Oops, someone made a super-project commit that refers to an unpublished commit in the submodule sub. Somehow, we already know that we want the submodule to be at commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c. Go there and check it out directly.

Checkout in the Submodule

$ cd sub
$ git checkout 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
Note: moving to '5d5a3ee314476701a20f2c6ec4a53f88d651df6c' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
  git checkout -b <new_branch_name>
HEAD is now at 5d5a3ee... quux
$ cd ..

Since we are checking out a commit, this produces a detached HEAD in the submodule. If you want to make sure that the submodule is using a branch, then use git checkout -b newbranch <commit> to create and checkout a branch at the commit or checkout the branch that you want (e.g. one with the desired commit at the tip).

Update the Super-project

A checkout in the submodule is reflected in the super-project as a change to the working tree. So we need to stage the change in the super-project's index and verify the results.

$ git add sub

Check the Results

$ git submodule update
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The submodule update was silent because the submodule is already at the specified commit. The first diff shows that the index and worktree are the same. The third diff shows that the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.


Outside, In

If you are not sure which commit you should use from the submodule, you can look at the history in the superproject to guide you. You can also manage the reset directly from the super-project.

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

This is the same situation as above. But this time we will focus on fixing it from the super-project instead of dipping into the submodule.

Find the Super-project's Errant Commit

$ git log --oneline -p -- sub
ce5d37c local change in sub
diff --git a/sub b/sub
index 5d5a3ee..e47c0a1 160000
--- a/sub
+++ b/sub
@@ -1 +1 @@
-Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
+Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
bca4663 added sub
diff --git a/sub b/sub
new file mode 160000
index 0000000..5d5a3ee
--- /dev/null
+++ b/sub
@@ -0,0 +1 @@
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

OK, it looks like it went bad in ce5d37c, so we will restore the submodule from its parent (ce5d37c~).

Alternatively, you can take the submodule's commit from the patch text (5d5a3ee314476701a20f2c6ec4a53f88d651df6c) and use the above “inside, out” process instead.

Checkout in the Super-project

$ git checkout ce5d37c~ -- sub

This reset the submodule entry for sub to what it was at commit ce5d37c~ in the super-project.

Update the Submodule

$ git submodule update
Submodule path 'sub': checked out '5d5a3ee314476701a20f2c6ec4a53f88d651df6c'

The submodule update went OK (it indicates a detached HEAD).

Check the Results

$ git diff ce5d37c~ -- sub
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The first diff shows that sub is now the same in ce5d37c~. The second diff shows that the index and worktree are the same. The third diff shows the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

How to calculate the median of an array?

The Arrays class in Java has a static sort function, which you can invoke with Arrays.sort(numArray).

Arrays.sort(numArray);
double median;
if (numArray.length % 2 == 0)
    median = ((double)numArray[numArray.length/2] + (double)numArray[numArray.length/2 - 1])/2;
else
    median = (double) numArray[numArray.length/2];

If you can decode JWT, how are they secure?

You can go to jwt.io, paste your token and read the contents. This is jarring for a lot of people initially.

The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.

The logical question is what is the motivation for not concerning itself with encrypted contents?

  1. The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure (is not transmitted via HTTP, only via HTTPS) and httpOnly (can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.

  2. This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).

  3. JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.

It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

For:

  • Windows, 64 bit
  • SQL Server (tested with SQL Server 2017 and it should work for all versions):

Option 1: Command Prompt

sqlcmd -s, -W -Q "set nocount on; select * from [DATABASE].[dbo].[TABLENAME]" | findstr /v /c:"-" /b > "c:\dirname\file.csv"

Where:

  • [DATABASE].[dbo].[TABLENAME] is table to write.
  • c:\dirname\file.csv is file to write to (surrounded in quotes to handle a path with spaces).
  • Output .csv file includes headers.

Note: I tend to avoid bcp: it is legacy, it predates sqlcmd by a decade, and it never seems to work without causing a whole raft of headaches.

Option 2: Within SQL Script

-- Export table [DATABASE].[dbo].[TABLENAME] to .csv file c:\dirname\file.csv
exec master..xp_cmdshell 'sqlcmd -s, -W -Q "set nocount on; select * from [DATABASE].[dbo].[TABLENAME]" | findstr /v /c:"-" /b > "c:\dirname\file.csv"'

Troubleshoooting: must enable xp_cmdshell within MSSQL.

Sample Output

File: file.csv:

ID,Name,Height
1,Bob,192
2,Jane,184
3,Harry,186

Speed

As fast as theoretically possible: same speed as bcp, and many times faster than manually exporting from SSMS.

Parameter Explanation (optional - can ignore)

In sqlcmd:

  • -s, puts a comma between each column.
  • -W eliminates padding either side of the values.
  • set nocount on eliminates a garbage line at the end of the query.

For findstr:

  • All this does is remove the second line underline underneath the header, e.g. --- ----- ---- ---- ----- --.
  • /v /c:"-" matches any line that starts with "-".
  • /b returns all other lines.

Importing into other programs

In Excel:

  • Can directly open the file in Excel.

In Python:

import pandas as pd
df_raw = pd.read_csv("c:\dirname\file.csv")

Numpy array dimensions

rows = a.shape[0] # 2 
cols = a.shape[1] # 2
a.shape #(2,2)
a.size # rows * cols = 4

Replace a string in shell script using a variable

echo $LINE | sed -e 's/12345678/'$replace'/g'

you can still use single quotes, but you have to "open" them when you want the variable expanded at the right place. otherwise the string is taken "literally" (as @paxdiablo correctly stated, his answer is correct as well)

Represent space and tab in XML tag

New, expanded answer to an old, commonly asked question...

Whitespace in XML Component Names

Summary: Whitespace characters are not permitted in XML element or attribute names.

Here are the main Unicode code points related to whitespace:

  • #x0009 CHARACTER TABULATION
  • #x0020 SPACE
  • #x000A LINE FEED (LF)
  • #x000D CARRIAGE RETURN (CR)
  • #x00A0 NO-BREAK SPACE
  • [#x2002-#x200A] EN SPACE through HAIR SPACE
  • #x205F MEDIUM MATHEMATICAL SPACE
  • #x3000 IDEOGRAPHIC SPACE

None of these code points are permitted by the W3C XML BNF for XML names:

NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] |
                  [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] |
                  [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] |
                  [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] |
                  [#x10000-#xEFFFF]
NameChar      ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] |
                  [#x203F-#x2040]
Name          ::= NameStartChar (NameChar)*

Whitespace in XML Content (Not Component Names)

Summary: Whitespace characters are, of course, permitted in XML content.

All of the above whitespace codepoints are permitted in XML content by the W3C XML BNF for Char:

Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
/* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */

Unicode code points can be inserted as character references. Both decimal &#decimal; and hexadecimal &#xhex; forms are supported.

How to set the allowed url length for a nginx request (error code: 414, uri too large)

From: http://nginx.org/r/large_client_header_buffers

Syntax: large_client_header_buffers number size ;
Default: large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

so you need to change the size parameter at the end of that line to something bigger for your needs.

Query Mongodb on month, day, year... of a datetime

how about storing the month in its own property since you need to query for it? less elegant than $where, but likely to perform better since it can be indexed.

How to split a line into words separated by one or more spaces in bash?

The -a option of read will allow you to split a line read in by the characters contained in $IFS.

Choice between vector::resize() and vector::reserve()

resize() not only allocates memory, it also creates as many instances as the desired size which you pass to resize() as argument. But reserve() only allocates memory, it doesn't create instances. That is,

std::vector<int> v1;
v1.resize(1000); //allocation + instance creation
cout <<(v1.size() == 1000)<< endl;   //prints 1
cout <<(v1.capacity()==1000)<< endl; //prints 1

std::vector<int> v2;
v2.reserve(1000); //only allocation
cout <<(v2.size() == 1000)<< endl;   //prints 0
cout <<(v2.capacity()==1000)<< endl; //prints 1

Output (online demo):

1
1
0
1

So resize() may not be desirable, if you don't want the default-created objects. It will be slow as well. Besides, if you push_back() new elements to it, the size() of the vector will further increase by allocating new memory (which also means moving the existing elements to the newly allocated memory space). If you have used reserve() at the start to ensure there is already enough allocated memory, the size() of the vector will increase when you push_back() to it, but it will not allocate new memory again until it runs out of the space you reserved for it.

Catch an exception thrown by an async void method

It's somewhat weird to read but yes, the exception will bubble up to the calling code - but only if you await or Wait() the call to Foo.

public async Task Foo()
{
    var x = await DoSomethingAsync();
}

public async void DoFoo()
{
    try
    {
        await Foo();
    }
    catch (ProtocolException ex)
    {
          // The exception will be caught because you've awaited
          // the call in an async method.
    }
}

//or//

public void DoFoo()
{
    try
    {
        Foo().Wait();
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught because you've
             waited for the completion of the call. */
    }
} 

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. - https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Note that using Wait() may cause your application to block, if .Net decides to execute your method synchronously.

This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.

How to select all textareas and textboxes using jQuery?

Password boxes are also textboxes, so if you need them too:

$("input[type='text'], textarea, input[type='password']").css({width: "90%"});

and while file-input is a bit different, you may want to include them too (eg. for visual consistency):

$("input[type='text'], textarea, input[type='password'], input[type='file']").css({width: "90%"});

How to call a View Controller programmatically?

Swift

This gets a view controller from the storyboard and presents it.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "secondViewControllerId") as! SecondViewController
self.present(secondViewController, animated: true, completion: nil)

Change the storyboard name, view controller name, and view controller id as appropriate.

How do I generate a list with a specified increment step?

Executing seq(1, 10, 1) does what 1:10 does. You can change the last parameter of seq, i.e. by, to be the step of whatever size you like.

> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability 
> [1]  0  2  4  6  8 10

bash script read all the files in directory

To write it with a while loop you can do:

ls -f /var | while read -r file; do cmd $file; done

The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)

Margin while printing html page

I also recommend pt versus cm or mm as it's more precise. Also, I cannot get @page to work in Chrome (version 30.0.1599.69 m) It ignores anything I put for the margins, large or small. But, you can get it to work with body margins on the document, weird.

How to type a new line character in SQL Server Management Studio

I had trouble initially (don't know why) but I finally got the following to work with SSMS for SQL Server 2008.

Insert ALT-13 then ALT-10 where desired in your text in a varchar type column (music symbol and square appear and save when you leave the row). Initially you'll get a warning(!) to the left of the row after leaving it. Just re-excecute your SELECT statement. The symbols and warning will disappear but the CR/LF is saved. You must include ALT-13 if you want the text displayed properly in HTML. To quickly determine if this worked, copy the saved text from SSMS to Notepad.

Alternatively, if you can't get this to work, you can do the same thing starting with an nvarchar column. However the symbols will be saved as text so you must convert the column to varchar when you're done to convert the symbols to CR/LFs.

If you want to copy & paste text from another source (another row or table, HTML, Notepad, etc.) and not have your text truncated at the first CR, I found that the solution (Programmer's Notepad) referred to at the following link works with SSMS for SQL Server 2008 using varchar & nvarchar column types.

http://dbaspot.com/sqlserver-programming/409451-how-i-enter-linefeed-when-modifying-text-field-2.html#post1523145

The author of the post (dbaspot) mentions something about creating SQL queries - not sure what he means. Just follow the intructions about Programmer's Notepad and you can copy & paste text to and from SSMS and retain the LFs both ways (using Programmer's Notepad, not Notepad). To have the text display properly in HTML you must add CRs to the text copied to SSMS. The best way to do this is by executing an UPDATE statement using the REPLACE function to add CRs as follows:

UPDATE table_name
SET column_name = REPLACE(column_name , CHAR(10), CHAR(13) + CHAR(10)).

Email Address Validation for ASP.NET

Preventing XSS is a different issue from validating input.

Regarding XSS: You should not try to check input for XSS or related exploits. You should prevent XSS exploits, SQL injection and so on by escaping correctly when inserting strings into a different language where some characters are "magic", eg, when inserting strings in HTML or SQL. For example a name like O'Reilly is perfectly valid input, but could cause a crash or worse if inserted unescaped into SQL. You cannot prevent that kind of problems by validating input.

Validation of user input makes sense to prevent missing or malformed data, eg. a user writing "asdf" in the zip-code field and so on. Wrt. e-mail adresses, the syntax is so complex though, that it doesnt provide much benefit to validate it using a regex. Just check that it contains a "@".

Changing nav-bar color after scrolling?

Slight variation to the above answers, but with Vanilla JS:

var nav = document.querySelector('nav'); // Identify target

window.addEventListener('scroll', function(event) { // To listen for event
    event.preventDefault();

    if (window.scrollY <= 150) { // Just an example
        nav.style.backgroundColor = '#000'; // or default color
    } else {
        nav.style.backgroundColor = 'transparent';
    }
});

How to add empty spaces into MD markdown readme on GitHub?

As a workaround, you can use a code block to render the code literally. Just surround your text with triple backticks ```. It will look like this:

2018-07-20 Wrote this answer Can format it without &nbsp; Also don't need <br /> for new line

Note that using <pre> and <code> you get slightly different behaviour: &nbsp and <br /> will be parsed rather than inserted literally.

<pre>:

2018-07-20 Wrote this answer
           Can format it without  
    Also don't need 
for new line

<code>: 2018-07-20 Wrote this answer Can format it without   Also don't need
for new line

Why is width: 100% not working on div {display: table-cell}?

Just add min-height:100% and min-width:100% and it will work. I had the same problem. You don't need a 3th wrapper

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

How to find elements with 'value=x'?

If the value is hardcoded in the source of the page using the value attribute then you can

$('#attached_docs :input[value="123"]').remove();

If you want to target elements that have a value of 123, which was set by the user or programmatically then use EDIT works both ways ..

or

$('#attached_docs :input').filter(function(){return this.value=='123'}).remove();

demo http://jsfiddle.net/gaby/RcwXh/2/

C++ vector of char array

FFWD to 2019. Although this code worketh in 2011 too.

// g++ prog.cc -Wall -std=c++11
#include <iostream>
#include <vector>

 using namespace std;

 template<size_t N>
    inline 
      constexpr /* compile time */
      array<char,N> string_literal_to_array ( char const (&charrar)[N] )
 {
    return std::to_array( charrar) ;
 }

 template<size_t N>
    inline 
      /* run time */
      vector<char> string_literal_to_vector ( char const (&charrar)[N] )
 {
    return { charrar, charrar + N };
 }


int main()
{
   constexpr auto arr = string_literal_to_array("Compile Time");
   auto cv = string_literal_to_vector ("Run Time") ;
   return 42;
}

Advice: try optimizing the use of std::string. For char buffering std::array<char,N> is the fastest, std::vector<char> is faster.

https://wandbox.org/permlink/wcasstoY56MWbHqd

How do you truncate all tables in a database using TSQL?

It is much easier (and possibly even faster) to script out your database, then just drop and create it from the script.

creating list of objects in Javascript

Going off of tbradley22's answer, but using .map instead:

var a = ["car", "bike", "scooter"];
a.map(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    return singleObj;
});

Python: Append item to list N times

Itertools repeat combined with list extend.

from itertools import repeat
l = []
l.extend(repeat(x, 100))

How can I get the DateTime for the start of the week?

You could use the excellent Umbrella library:

using nVentive.Umbrella.Extensions.Calendar;
DateTime beginning = DateTime.Now.BeginningOfWeek();

However, they do seem to have stored Monday as the first day of the week (see the property nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn), so that previous localized solution is a bit better. Unfortunate.

Edit: looking closer at the question, it looks like Umbrella might actually work for that too:

// Or DateTime.Now.PreviousDay(DayOfWeek.Monday)
DateTime monday = DateTime.Now.PreviousMonday(); 
DateTime sunday = DateTime.Now.PreviousSunday();

Although it's worth noting that if you ask for the previous Monday on a Monday, it'll give you seven days back. But this is also true if you use BeginningOfWeek, which seems like a bug :(.

How to find and replace string?

Do we really need a Boost library for seemingly such a simple task?

To replace all occurences of a substring use this function:

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

Output:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

How to configure log4j with a properties file

Since JVM arguments are eventually passed to your java program as system variables, you can use this code at the beginning of your execution point to edit the property and have log4j read the property you just set in system properties

try {
        System.setProperty("log4j.configuration", new File(System.getProperty("user.dir")+File.separator+"conf"+File.separator+"log4j.properties").toURI().toURL().toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

C++ Double Address Operator? (&&)

&& is new in C++11. int&& a means "a" is an r-value reference. && is normally only used to declare a parameter of a function. And it only takes a r-value expression. If you don't know what an r-value is, the simple explanation is that it doesn't have a memory address. E.g. the number 6, and character 'v' are both r-values. int a, a is an l-value, however (a+2) is an r-value. For example:

void foo(int&& a)
{
    //Some magical code...
}

int main()
{
    int b;
    foo(b); //Error. An rValue reference cannot be pointed to a lValue.
    foo(5); //Compiles with no error.
    foo(b+3); //Compiles with no error.

    int&& c = b; //Error. An rValue reference cannot be pointed to a lValue.
    int&& d = 5; //Compiles with no error.
}

Hope that is informative.

Oracle SqlPlus - saving output in a file but don't show on screen

Try This:

sqlplus -s ${ORA_CONN_STR} <<EOF >/dev/null

How to reset AUTO_INCREMENT in MySQL?

You can also use the syntax TRUNCATE table like this : TRUNCATE TABLE table_name

BEWARE!! TRUNCATE TABLE your_table will delete everything in your your_table!!

How could I put a border on my grid control in WPF?

This is a later answer that works for me, if it may be of use to anyone in the future. I wanted a simple border around all four sides of the grid and I achieved it like so...

<DataGrid x:Name="dgDisplay" Margin="5" BorderBrush="#1266a7" BorderThickness="1"...

flutter corner radius with transparent background

If both containers are siblings and the bottom container has rounded corners and the top container is dynamic then you will have to use the stack widget

Stack(
 children: [
   /*your_widget_1*/,
  /*your_widget_2*/,
 ],
);

Using `date` command to get previous, current and next month

the following will do:

date -d "$(date +%Y-%m-1) -1 month" +%-m
date -d "$(date +%Y-%m-1) 0 month" +%-m
date -d "$(date +%Y-%m-1) 1 month" +%-m

or as you need:

LAST_MONTH=`date -d "$(date +%Y-%m-1) -1 month" +%-m`
NEXT_MONTH=`date -d "$(date +%Y-%m-1) 1 month" +%-m`
THIS_MONTH=`date -d "$(date +%Y-%m-1) 0 month" +%-m`

you asked for output like 9,10,11, so I used the %-m

%m (without -) will produce output like 09,... (leading zero)

this also works for more/less than 12 months:

date -d "$(date +%Y-%m-1) -13 month" +%-m

just try

date -d "$(date +%Y-%m-1) -13 month"

to see full result

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

If you still get too many authentication failures errors:

nano ~/.ssh/config

And paste:

Host bitbucket_james
    HostName bitbucket.org
    User james
    Port 22
    IdentitiesOnly=yes
    IdentityFile=~/.ssh/id_rsa_bitbucket_james

And most important - you should bitbucket_james alias instead of bitbucket.org when you set up your remote URL:

git remote set-url origin git@bitbucket_james:repo_owner_user/repo_name.git

How to start an application without waiting in a batch file?

I'm making a guess here, but your start invocation probably looks like this:

start "\Foo\Bar\Path with spaces in it\program.exe"

This will open a new console window, using “\Foo\Bar\Path with spaces in it\program.exe” as its title.

If you use start with something that is (or needs to be) surrounded by quotes, you need to put empty quotes as the first argument:

start "" "\Foo\Bar\Path with spaces in it\program.exe"

This is because start interprets the first quoted argument it finds as the window title for a new console window.

What is the best way to repeatedly execute a function every x seconds?

This seems much simpler than accepted solution - does it have shortcomings I'm not considering? Came here looking for some dead-simple copy pasta.

import threading, time

def print_every_n_seconds(n=2):
    while True:
        print(time.ctime())
        time.sleep(n)
    
thread = threading.Thread(target=print_every_n_seconds, daemon=True)
thread.start()

Which asynchronously outputs.

#Tue Oct 16 17:29:40 2018
#Tue Oct 16 17:29:42 2018
#Tue Oct 16 17:29:44 2018

This does have drift. If the task being run takes appreciable amount of time, then the interval becomes 2 seconds + task time, so if you need precise scheduling then this is not for you.**

Note the daemon=True flag means this thread won't block the app from shutting down. For example, had issue where pytest would hang indefinitely after running tests waiting for this thead to cease.

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

This error is encountered when the primary key of a table is updated but it is referenced by a foreign key from another table and the update specific is set to No action. The No action is the default option.

If this is your case and No action is set on the update operation you can change the foreign-key definition to Cascade.

Right click your foreign key and select Modify. In the Foreign key relationships dialog under the INSERT and UPDATE specifics set the UPDATE rule on Cascade:

enter image description here

You can also set the rule using T-SQL:

ALTER TABLE YourTable
DROP Constraint Your_FK
GO

ALTER TABLE YourTable
ADD CONSTRAINT [New_FK_Constraint]
FOREIGN KEY (YourColumn) REFERENCES ReferencedTable(YourColumn)
ON DELETE CASCADE ON UPDATE CASCADE
GO 

Hope this helps

Regex to get the words after matching string

You're almost there. Use the following regex (with multi-line option enabled)

\bObject Name:\s+(.*)$

The complete match would be

Object Name:   D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log

while the captured group one would contain

D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log

If you want to capture the file path directly use

(?m)(?<=\bObject Name:).*$

Toggle visibility property of div

According to the jQuery docs, calling toggle() without parameters will toggle visibility.

$('#play-pause').click(function(){
   $('#video-over').toggle();
});

http://jsfiddle.net/Q47ya/

Android Gradle Apache HttpClient does not exist?

Perfect Answer by Jinu and Daniel

Adding to this I solved the Issue by Using This, if your compileSdkVersion is 19(IN MY CASE)

compile ('org.apache.httpcomponents:httpmime:4.3'){
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile ('org.apache.httpcomponents:httpcore:4.4.1'){
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile 'commons-io:commons-io:1.3.2'

else if your compileSdkVersion is 23 then use

android {
useLibrary 'org.apache.http.legacy'
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    }
}

Dynamically add data to a javascript map

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> namesList = Arrays.asList(names);

or

String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> temp = Arrays.asList(names);         

Above Statement adds the wrapper on the input array. So the methods like add & remove will not be applicable on list reference object 'namesList'.

If you try to add an element in the existing array/list then you will get "Exception in thread "main" java.lang.UnsupportedOperationException".

The above operation is readonly or viewonly.
We can not perform add or remove operation in list object. But

String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.ArrayList<String> list1 = new ArrayList<>(Arrays.asList(names));

or

String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> listObject = Arrays.asList(names);
java.util.ArrayList<String> list1 = new ArrayList<>(listObject);

In above statement you have created a concrete instance of an ArrayList class and passed a list as a parameter.

In this case method add & remove will work properly as both methods are from ArrayList class so here we won't get any UnSupportedOperationException.
Changes made in Arraylist object (method add or remove an element in/from an arraylist) will get not reflect in to original java.util.List object.

String names[] = new String[] {
    "Avinash",
    "Amol",
    "John",
    "Peter"
};

java.util.List < String > listObject = Arrays.asList(names);
java.util.ArrayList < String > list1 = new ArrayList < > (listObject);
for (String string: list1) {
    System.out.print("   " + string);
}
list1.add("Alex"); //Added without any exception
list1.remove("Avinash"); //Added without any exception will not make any changes in original list in this case temp object.


for (String string: list1) {
    System.out.print("   " + string);
}
String existingNames[] = new String[] {
    "Avinash",
    "Amol",
    "John",
    "Peter"
};
java.util.List < String > namesList = Arrays.asList(names);
namesList.add("Bob"); // UnsupportedOperationException occur
namesList.remove("Avinash"); //UnsupportedOperationException

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

A slight practical perspective to look into memory through id and gc.

>>> b = a = ['hell', 'word']
>>> c = ['hell', 'word']

>>> id(a), id(b), id(c)
(4424020872, 4424020872, 4423979272) 
     |           |
      -----------

>>> id(a[0]), id(b[0]), id(c[0])
(4424018328, 4424018328, 4424018328) # all referring to same 'hell'
     |           |           |
      -----------------------

>>> id(a[0][0]), id(b[0][0]), id(c[0][0])
(4422785208, 4422785208, 4422785208) # all referring to same 'h'
     |           |           |
      -----------------------

>>> a[0] += 'o'
>>> a,b,c
(['hello', 'word'], ['hello', 'word'], ['hell', 'word'])  # b changed too
>>> id(a[0]), id(b[0]), id(c[0])
(4424018384, 4424018384, 4424018328) # augmented assignment changed a[0],b[0]
     |           |
      -----------

>>> b = a = ['hell', 'word']
>>> id(a[0]), id(b[0]), id(c[0])
(4424018328, 4424018328, 4424018328) # the same hell
     |           |           |
      -----------------------

>>> import gc
>>> gc.get_referrers(a[0]) 
[['hell', 'word'], ['hell', 'word']]  # one copy belong to a,b, the another for c
>>> gc.get_referrers(('hell'))
[['hell', 'word'], ['hell', 'word'], ('hell', None)] # ('hello', None) 

Powershell import-module doesn't find modules

I experienced the same error and tried numerous things before I succeeded. The solution was to prepend the path of the script to the relative path of the module like this:

// Note that .Path will only be available during script-execution
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

Import-Module $ScriptPath\Modules\Builder.psm1

Btw you should take a look at http://msdn.microsoft.com/en-us/library/dd878284(v=vs.85).aspx which states:

Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command. This feature works on any module in a directory that this included in the value of the PSModulePath environment variable ($env:PSModulePath)

Open JQuery Datepicker by clicking on an image w/ no input field

Having a hidden input field leads to problems with datepicker dialog positioning (dialog is horizontally centered). You could alter the dialog's margin, but there's a better way.

Just create an input field and "hide" it by setting it's opacity to 0 and making it 1px wide. Also position it near (or under) the button, or where ever you want the datepicker to appear.

Then attach the datepicker to the "hidden" input field and show it when user presses the button.

HTML:

<button id="date-button">Show Calendar</button>
<input type="text" name="date-field" id="date-field" value="">

CSS:

#date-button {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    height 30px;
}

#date-field {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 1px;
    height: 32px; // height of the button + a little margin
    opacity: 0;
}

JS:

$(function() {
   $('#date-field').datepicker();

   $('#date-button').on('click', function() {
      $('#date-field').datepicker('show');
   });
});

Note: not tested with all browsers.

Netbeans how to set command line arguments in Java

  1. Create the Java code that can receive an argument as a command line argument.

    class TestCode{
        public static void main(String args[]){
            System.out.println("first argument is: "+args[0]);
        }
    }
    
  2. Run the program without arguments (press F6).

  3. In the Output window, at the bottom, click the double yellow arrow (or the yellow button) to open a Run dialog.

  4. If the argument you need to pass is testArgument, then here in this window pass the argument as application.args=testArgument.

This will give the output as follows in the same Output window:

first argument is: testArgument

For Maven, the instructions are similar, but change the exec.args property instead:

exec.args=-classpath %classpath package.ClassName PARAM1 PARAM2 PARAM3

Note: Use single quotes for string parameters that contain spaces.

How to compare character ignoring case in primitive types

You can't actually do the job quite right with toLowerCase, either on a string or in a character. The problem is that there are variant glyphs in either upper or lower case, and depending on whether you uppercase or lowercase your glyphs may or may not be preserved. It's not even clear what you mean when you say that two variants of a lower-case glyph are compared ignoring case: are they or are they not the same? (Note that there are also mixed-case glyphs: \u01c5, \u01c8, \u01cb, \u01f2 or ?, ?, ?, ?, but any method suggested here will work on those as long as they should count as the same as their fully upper or full lower case variants.)

There is an additional problem with using Char: there are some 80 code points not representable with a single Char that are upper/lower case variants (40 of each), at least as detected by Java's code point upper/lower casing. You therefore need to get the code points and change the case on these.

But code points don't help with the variant glyphs.

Anyway, here's a complete list of the glyphs that are problematic due to variants, showing how they fare against 6 variant methods:

  1. Character toLowerCase
  2. Character toUpperCase
  3. String toLowerCase
  4. String toUpperCase
  5. String equalsIgnoreCase
  6. Character toLowerCase(toUpperCase) (or vice versa)

For these methods, S means that the variants are treated the same as each other, D means the variants are treated as different from each other.

Behavior     Unicode                             Glyphs
===========  ==================================  =========
1 2 3 4 5 6  Upper  Lower  Var Up Var Lo Vr Lo2  U L u l l2
- - - - - -  ------ ------ ------ ------ ------  - - - - -
D D D D S S  \u0049 \u0069 \u0130 \u0131         I i I i   
S D S D S S  \u004b \u006b \u212a                K k K     
D S D S S S  \u0053 \u0073        \u017f         S s   ?   
D S D S S S  \u039c \u03bc        \u00b5         ? µ   µ   
S D S D S S  \u00c5 \u00e5 \u212b                Å å Å     
D S D S S S  \u0399 \u03b9        \u0345 \u1fbe  ? ?   ? ? 
D S D S S S  \u0392 \u03b2        \u03d0         ? ß   ?   
D S D S S S  \u0395 \u03b5        \u03f5         ? e   ?   
D D D D S S  \u0398 \u03b8 \u03f4 \u03d1         T ? ? ?   
D S D S S S  \u039a \u03ba        \u03f0         ? ?   ?   
D S D S S S  \u03a0 \u03c0        \u03d6         ? p   ?   
D S D S S S  \u03a1 \u03c1        \u03f1         ? ?   ?   
D S D S S S  \u03a3 \u03c3        \u03c2         S s   ?   
D S D S S S  \u03a6 \u03c6        \u03d5         F f   ?   
S D S D S S  \u03a9 \u03c9 \u2126                O ? ?     
D S D S S S  \u1e60 \u1e61        \u1e9b         ? ?   ?   

Complicating this still further is that there is no way to get the Turkish I's right (i.e. the dotted versions are different than the undotted versions) unless you know you're in Turkish; none of these methods give correct behavior and cannot unless you know the locale (i.e. non-Turkish: i and I are the same ignoring case; Turkish, not).

Overall, using toUpperCase gives you the closest approximation, since you have only five uppercase variants (or four, not counting Turkish).

You can also try to specifically intercept those five troublesome cases and call toUpperCase(toLowerCase(c)) on them alone. If you choose your guards carefully (just toUpperCase if c < 0x130 || c > 0x212B, then work through the other alternatives) you can get only a ~20% speed penalty for characters in the low range (as compared to ~4x if you convert single characters to strings and equalsIgnoreCase them) and only about a 2x penalty if you have a lot in the danger zone. You still have the locale problem with dotted I, but otherwise you're in decent shape. Of course if you can use equalsIgnoreCase on a larger string, you're better off doing that.

Here is sample Scala code that does the job:

def elevateCase(c: Char): Char = {
  if (c < 0x130 || c > 0x212B) Character.toUpperCase(c)
  else if (c == 0x130 || c == 0x3F4 || c == 0x2126 || c >= 0x212A)
    Character.toUpperCase(Character.toLowerCase(c))
  else Character.toUpperCase(c)
}

beyond top level package error in relative import

This is very tricky in Python.

I'll first comment on why you're having that problem and then I will mention two possible solutions.

  • What's going on?

You must take this paragraph from the Python documentation into consideration:

Note that relative imports are based on the name of the current module. Since the name of the main module is always "main", modules intended for use as the main module of a Python application must always use absolute imports.

And also the following from PEP 328:

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Relative imports work from the filename (__name__ attribute), which can take two values:

  1. It's the filename, preceded by the folder strucutre, separated by dots. For eg: package.test_A.test Here Python knows the parent directories: before test comes test_A and then package. So you can use the dot notation for relative import.
#  package.test_A/test.py
from ..A import foo

You can then have like a root file in the root directory which calls test.py:

#  root.py
from package.test_A import test
  1. When you run the module (test.py) directly, it becomes the entry point to the program , so __name__ == __main__. The filename has no indication of the directory structure, so Python doesn't know how to go up in the directory. For Python, test.py becomes the top-level script, there is nothing above it. That's why you cannot use relative import.

  • Possible Solutions

A) One way to solve this is to have a root file (in the root directory) which calls the modules/packages, like this:

enter image description here

  • root.py imports test.py. (entry point, __name__ == __main__).
  • test.py (relative) imports foo.py.
  • foo.py says the module has been imported.

The output is:

package.A.foo has been imported
Module's name is:  package.test_A.test

B) If you want to execute the code as a module and not as a top-level script, you can try this from the command line:

python -m package.test_A.test

Any suggestions are welcomed.

You should also check: Relative imports for the billionth time , specially BrenBarn's answer.

Remove an item from array using UnderscoreJS

By Using underscore.js

var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];

var resultArr = _.reject(arr,{id:3});

console.log(resultArr);

The result will be :: [{id:1name:'a'},{id:2,name:'c'}]

Chrome javascript debugger breakpoints don't do anything?

So, in addition to Adam Rackis' answer, if you have errors in your javascript file above the breakpoint, you won't reach it regardless if you flag it, or put in debugger;.

Here's an example:

if (nonExistentVar === "something") {
  console.log("this won't happen as the above errors out");
}
debugger;
console.log("this won't print either")

How to deal with page breaks when printing a large HTML table

The accepted answer did not work for me in all browsers, but following css did work for me:

tr    
{ 
  display: table-row-group;
  page-break-inside:avoid; 
  page-break-after:auto;
}

The html structure was:

<table>
  <thead>
    <tr></tr>
  </thead>
  <tbody>
    <tr></tr>
    <tr></tr>
    ...
  </tbody>
</table>

In my case, there were some additional issues with the thead tr, but this resolved the original issue of keeping the table rows from breaking.

Because of the header issues, I ultimately ended up with:

#theTable td *
{
  page-break-inside:avoid;
}

This didn't prevent rows from breaking; just each cell's content.

How to merge many PDF files into a single one?

You can also use Ghostscript to merge different PDFs. You can even use it to merge a mix of PDFs, PostScript (PS) and EPS into one single output PDF file:

gs \
  -o merged.pdf \
  -sDEVICE=pdfwrite \
  -dPDFSETTINGS=/prepress \
   input_1.pdf \
   input_2.pdf \
   input_3.eps \
   input_4.ps \
   input_5.pdf

However, I agree with other answers: for your use case of merging PDF file types only, pdftk may be the best (and certainly fastest) option.

Update:
If processing time is not the main concern, but if the main concern is file size (or a fine-grained control over certain features of the output file), then the Ghostscript way certainly offers more power to you. To highlight a few of the differences:

  • Ghostscript can 'consolidate' the fonts of the input files which leads to a smaller file size of the output. It also can re-sample images, or scale all pages to a different size, or achieve a controlled color conversion from RGB to CMYK (or vice versa) should you need this (but that will require more CLI options than outlined in above command).
  • pdftk will just concatenate each file, and will not convert any colors. If each of your 16 input PDFs contains 5 subsetted fonts, the resulting output will contain 80 subsetted fonts. The resulting PDF's size is (nearly exactly) the sum of the input file bytes.

javascript: detect scroll end

if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight)
{
//your code here
}

I too searched it and even after checking all comments here and more, this is the solution to check if reached the bottom or not.

Securely storing passwords for use in python script

Know the master key yourself. Don't hard code it.

Use py-bcrypt (bcrypt), powerful hashing technique to generate a password yourself.

Basically you can do this (an idea...)

import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)

save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.

This is basically how login should work these days.

Space between Column's children in Flutter

There are many ways of doing it, I'm listing a few here.

  1. Use Container and give some height:

    Column(
      children: <Widget>[
        Widget1(),
        Container(height: 10), // set height
        Widget2(),
      ],
    )
    
  2. Use Spacer

    Column(
      children: <Widget>[
        Widget1(),
        Spacer(), // use Spacer
        Widget2(),
      ],
    )
    
  3. Use Expanded

    Column(
      children: <Widget>[
        Widget1(),
        Expanded(child: SizedBox()), // use Expanded
        Widget2(),
      ],
    )
    
  4. Use mainAxisAlignment

    Column(
      mainAxisAlignment: MainAxisAlignment.spaceAround, // mainAxisAlignment
      children: <Widget>[
        Widget1(),
        Widget2(),
      ],
    )
    
  5. Use Wrap

    Wrap(
      direction: Axis.vertical, // make sure to set this
      spacing: 20, // set your spacing
      children: <Widget>[
        Widget1(),
        Widget2(),
      ],
    )
    

Calling a javascript function in another js file

Use cache if your server allows it to improve speed.

var extern =(url)=> {           // load extern javascript
    let scr = $.extend({}, {
        dataType: 'script',
        cache: true,
        url: url
    });
    return $.ajax(scr);
}
function ext(file, func) {
    extern(file).done(func);    // calls a function from an extern javascript file
}

And then use it like this:

ext('somefile.js',()=>              
    myFunc(args)
);  

Optionally, make a prototype of it to have it more flexible. So that you don't have to define the file every time, if you call a function or if you want to fetch code from multiple files.

What is the difference between HTML tags and elements?

HTML tags vs. elements vs. attributes

HTML elements

An element in HTML represents some kind of structure or semantics and generally consists of a start tag, content, and an end tag. The following is a paragraph element:

<p>
This is the content of the paragraph element.
</p>

HTML tags

Tags are used to mark up the start and end of an HTML element.

<p></p>

HTML attributes

An attribute defines a property for an element, consists of an attribute/value pair, and appears within the element’s start tag. An element’s start tag may contain any number of space separated attribute/value pairs.

The most popular misuse of the term “tag” is referring to alt attributes as “alt tags”. There is no such thing in HTML. Alt is an attribute, not a tag.

<img src="foobar.gif" alt="A foo can be balanced on a bar by placing its fubar on the bar's foobar.">

Source: 456bereastreet.com: HTML tags vs. elements vs. attributes

An existing connection was forcibly closed by the remote host - WCF

After pulling my hair out for like 6 hours of this completely useless error, my problem ended up being that my data transfer objects were too complex. Start with uber simple properties like public long Id { get; set;} that's it... nothing fancy.

Android EditText delete(backspace) key event

I sent 2 days to find a solution and I figured out a working one :) (on soft keys)

public TextWatcher textWatcher = new TextWatcher() {
@Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {   } 

@Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (count == 0) {
        //Put your code here.
        //Runs when delete/backspace pressed on soft key (tested on htc m8)
        //You can use EditText.getText().length() to make if statements here
        }
    }

@Override
    public void afterTextChanged(Editable s) {
    }
}

After add the textwatcher to your EditText:

yourEditText.addTextChangedListener(textWatcher);

I hope it works on another android devices too (samsung, LG, etc).

What is the difference between :focus and :active?

:active       Adds a style to an element that is activated
:focus        Adds a style to an element that has keyboard input focus
:hover        Adds a style to an element when you mouse over it
:lang         Adds a style to an element with a specific lang attribute
:link         Adds a style to an unvisited link
:visited      Adds a style to a visited link

Source: CSS Pseudo-classes

Filling a List with all enum values in Java

List<Something> result = new ArrayList<Something>(all);

EnumSet is a Java Collection, as it implements the Set interface:

public interface Set<E> extends Collection<E> 

So anything you can do with a Collection you can do with an EnumSet.

What is the most efficient/quickest way to loop through rows in VBA (excel)?

For Each is much faster than for I=1 to X, for some reason. Just try to go through the same dictionary,


once with for each Dkey in dDict,


and once with for Dkey = lbound(dDict.keys) to ubound(dDict.keys)

=>You will notice a huge difference, even though you are going through the same construct.

Better way of getting time in milliseconds in javascript?

I know this is a pretty old thread, but to keep things up to date and more relevant, you can use the more accurate performance.now() functionality to get finer grain timing in javascript.

window.performance = window.performance || {};
performance.now = (function() {
    return performance.now       ||
        performance.mozNow    ||
        performance.msNow     ||
        performance.oNow      ||
        performance.webkitNow ||            
        Date.now  /*none found - fallback to browser default */
})();

DISTINCT for only one column

For Access, you can use the SQL Select query I present here:

For example you have this table:

CLIENTE|| NOMBRES || MAIL

888 || T800 ARNOLD || [email protected]

123 || JOHN CONNOR || [email protected]

125 || SARAH CONNOR ||[email protected]

And you need to select only distinct mails. You can do it with this:

SQL SELECT:

SELECT MAX(p.CLIENTE) AS ID_CLIENTE
, (SELECT TOP 1 x.NOMBRES 
    FROM Rep_Pre_Ene_MUESTRA AS x 
    WHERE x.MAIL=p.MAIL 
     AND x.CLIENTE=(SELECT MAX(l.CLIENTE) FROM Rep_Pre_Ene_MUESTRA AS l WHERE x.MAIL=l.MAIL)) AS NOMBRE, 
p.MAIL
FROM Rep_Pre_Ene_MUESTRA AS p
GROUP BY p.MAIL;

You can use this to select the maximum ID, the correspondent name to that maximum ID , you can add any other attribute that way. Then at the end you put the distinct column to filter and you only group it with that last distinct column.

This will bring you the maximum ID with the correspondent data, you can use min or any other functions and you replicate that function to the sub-queries.

This select will return:

CLIENTE|| NOMBRES || MAIL

888 || T800 ARNOLD || [email protected]

125 || SARAH CONNOR ||[email protected]

Remember to index the columns you select and the distinct column must have not numeric data all in upper case or in lower case, or else it won't work. This will work with only one registered mail as well. Happy coding!!!

How to push files to an emulator instance using Android Studio

Update (May 2020): Android studio have new tool called Device File Explorer. You can access it in two way:

  1. By clicking on Device File Explorer icon in right bottom corner of android studio window.
  2. If you could not find its icon, inside Android Studio press shift button twice. Quick search window will appear, then type Device File in it and Device File Explorer will appear in search result and you can click it. open Device File Explorer

Then you can navigate to folder which you want to push your file in it. Right click on that folder and select upload(or press Ctrl+Shift+O). Select file you want to upload and it will upload file to desired location.

enter image description here

Push file using adb.exe:

In Android 6.0+, you should use same process but your android application cannot access files which pushed inside SDCARD using DDMS File Explorer. It is the same if you try commands like this:

adb push myfile.txt /mnt/sdcard/myfile.txt

If you face EACCES (Permission denied) exception when you try to read file inside your application, it means you have no access to files inside external storage, since it requires a dangerous permission.

For this situation, you need to request granting access manually using new permission system in Android 6.0 and upper version. For details you can have a look in android tutorial and this link.

Solution for old android studio version:

If you want to do it using graphical interface you can follow this inside android studio menus:

Tools --> Android --> Android Device Monitor

enter image description here

Afterward, Android Device Monitor(DDMS) window will open and you can upload files using File Explorer. You can select an address like /mnt/sdcard and then push your file into sdcard. enter image description here

How do I print the key-value pairs of a dictionary in python

In addition to ways already mentioned.. can use 'viewitems', 'viewkeys', 'viewvalues'

>>> d = {320: 1, 321: 0, 322: 3}
>>> list(d.viewitems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.viewkeys())
[320, 321, 322]
>>> list(d.viewvalues())
[1, 0, 3]

Or

>>> list(d.iteritems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.iterkeys())
[320, 321, 322]
>>> list(d.itervalues())
[1, 0, 3]

or using itemgetter

>>> from operator import itemgetter
>>> map(itemgetter(0), dd.items())     ####  for keys
['323', '332']
>>> map(itemgetter(1), dd.items())     ####  for values
['3323', 232]

How can I combine multiple rows into a comma-delimited list in Oracle?

SELECT REPLACE(REPLACE
((SELECT     TOP (100) PERCENT country_name + ', ' AS CountryName
FROM         country_name
ORDER BY country_name FOR XML PATH('')), 
'&<CountryName>', ''), '&<CountryName>', '') AS CountryNames

Counting number of characters in a file through shell script

awk only

awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)c++}END{print "total chars:"c}' file

shell only

var=$(<file)
echo ${#var}

Ruby(1.9+)

ruby -0777 -ne 'print $_.size' file

react native get TextInput value

If you set the text state, why not use that directly?

_handlePress(event) {
  var username=this.state.text;

Of course the variable naming could be more descriptive than 'text' but your call.

How to add a touch event to a UIView?

Gesture Recognizers

There are a number of commonly used touch events (or gestures) that you can be notified of when you add a Gesture Recognizer to your view. They following gesture types are supported by default:

  • UITapGestureRecognizer Tap (touching the screen briefly one or more times)
  • UILongPressGestureRecognizer Long touch (touching the screen for a long time)
  • UIPanGestureRecognizer Pan (moving your finger across the screen)
  • UISwipeGestureRecognizer Swipe (moving finger quickly)
  • UIPinchGestureRecognizer Pinch (moving two fingers together or apart - usually to zoom)
  • UIRotationGestureRecognizer Rotate (moving two fingers in a circular direction)

In addition to these, you can also make your own custom gesture recognizer.

Adding a Gesture in the Interface Builder

Drag a gesture recognizer from the object library onto your view.

enter image description here

Control drag from the gesture in the Document Outline to your View Controller code in order to make an Outlet and an Action.

enter image description here

This should be set by default, but also make sure that User Action Enabled is set to true for your view.

enter image description here

Adding a Gesture Programmatically

To add a gesture programmatically, you (1) create a gesture recognizer, (2) add it to a view, and (3) make a method that is called when the gesture is recognized.

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var myView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1. create a gesture recognizer (tap gesture)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
        
        // 2. add the gesture recognizer to a view
        myView.addGestureRecognizer(tapGesture)
    }
    
    // 3. this method is called when a tap is recognized
    @objc func handleTap(sender: UITapGestureRecognizer) {
        print("tap")
    }
}

Notes

  • The sender parameter is optional. If you don't need a reference to the gesture then you can leave it out. If you do so, though, remove the (sender:) after the action method name.
  • The naming of the handleTap method was arbitrary. Name it whatever you want using action: #selector(someMethodName(sender:)).

More Examples

You can study the gesture recognizers that I added to these views to see how they work.

enter image description here

Here is the code for that project:

import UIKit
class ViewController: UIViewController {
    
    @IBOutlet weak var tapView: UIView!
    @IBOutlet weak var doubleTapView: UIView!
    @IBOutlet weak var longPressView: UIView!
    @IBOutlet weak var panView: UIView!
    @IBOutlet weak var swipeView: UIView!
    @IBOutlet weak var pinchView: UIView!
    @IBOutlet weak var rotateView: UIView!
    @IBOutlet weak var label: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Tap
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tapView.addGestureRecognizer(tapGesture)
        
        // Double Tap
        let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
        doubleTapGesture.numberOfTapsRequired = 2
        doubleTapView.addGestureRecognizer(doubleTapGesture)
        
        // Long Press
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gesture:)))
        longPressView.addGestureRecognizer(longPressGesture)
        
        // Pan
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:)))
        panView.addGestureRecognizer(panGesture)
        
        // Swipe (right and left)
        let swipeRightGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
        let swipeLeftGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
        swipeRightGesture.direction = UISwipeGestureRecognizerDirection.right
        swipeLeftGesture.direction = UISwipeGestureRecognizerDirection.left
        swipeView.addGestureRecognizer(swipeRightGesture)
        swipeView.addGestureRecognizer(swipeLeftGesture)
        
        // Pinch
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(gesture:)))
        pinchView.addGestureRecognizer(pinchGesture)
        
        // Rotate
        let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(handleRotate(gesture:)))
        rotateView.addGestureRecognizer(rotateGesture)
        
    }
    
    // Tap action
    @objc func handleTap() {
        label.text = "Tap recognized"
        
        // example task: change background color
        if tapView.backgroundColor == UIColor.blue {
            tapView.backgroundColor = UIColor.red
        } else {
            tapView.backgroundColor = UIColor.blue
        }
        
    }
    
    // Double tap action
    @objc func handleDoubleTap() {
        label.text = "Double tap recognized"
        
        // example task: change background color
        if doubleTapView.backgroundColor == UIColor.yellow {
            doubleTapView.backgroundColor = UIColor.green
        } else {
            doubleTapView.backgroundColor = UIColor.yellow
        }
    }
    
    // Long press action
    @objc func handleLongPress(gesture: UILongPressGestureRecognizer) {
        label.text = "Long press recognized"
        
        // example task: show an alert
        if gesture.state == UIGestureRecognizerState.began {
            let alert = UIAlertController(title: "Long Press", message: "Can I help you?", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
    
    // Pan action
    @objc func handlePan(gesture: UIPanGestureRecognizer) {
        label.text = "Pan recognized"
        
        // example task: drag view
        let location = gesture.location(in: view) // root view
        panView.center = location
    }
    
    // Swipe action
    @objc func handleSwipe(gesture: UISwipeGestureRecognizer) {
        label.text = "Swipe recognized"
        
        // example task: animate view off screen
        let originalLocation = swipeView.center
        if gesture.direction == UISwipeGestureRecognizerDirection.right {
            UIView.animate(withDuration: 0.5, animations: {
                self.swipeView.center.x += self.view.bounds.width
            }, completion: { (value: Bool) in
                self.swipeView.center = originalLocation
            })
        } else if gesture.direction == UISwipeGestureRecognizerDirection.left {
            UIView.animate(withDuration: 0.5, animations: {
                self.swipeView.center.x -= self.view.bounds.width
            }, completion: { (value: Bool) in
                self.swipeView.center = originalLocation
            })
        }
    }
    
    // Pinch action
    @objc func handlePinch(gesture: UIPinchGestureRecognizer) {
        label.text = "Pinch recognized"
        
        if gesture.state == UIGestureRecognizerState.changed {
            let transform = CGAffineTransform(scaleX: gesture.scale, y: gesture.scale)
            pinchView.transform = transform
        }
    }
    
    // Rotate action
    @objc func handleRotate(gesture: UIRotationGestureRecognizer) {
        label.text = "Rotate recognized"
        
        if gesture.state == UIGestureRecognizerState.changed {
            let transform = CGAffineTransform(rotationAngle: gesture.rotation)
            rotateView.transform = transform
        }
    }
}

Notes

  • You can add multiple gesture recognizers to a single view. For the sake of simplicity, though, I didn't do that (except for the swipe gesture). If you need to for your project, you should read the gesture recognizer documentation. It is fairly understandable and helpful.
  • Known issues with my examples above: (1) Pan view resets its frame on next gesture event. (2) Swipe view comes from the wrong direction on the first swipe. (These bugs in my examples should not affect your understanding of how Gestures Recognizers work, though.)

Dynamically add event listener

Here's my workaround:

I created a library with Angular 6. I added a common component commonlib-header which is used like this in an external application.

Note the serviceReference which is the class (injected in the component constructor(public serviceReference: MyService) that uses the commonlib-header) that holds the stringFunctionName method:

<commonlib-header
    [logo]="{ src: 'assets/img/logo.svg', alt: 'Logo', href: '#' }"
    [buttons]="[{ index: 0, innerHtml: 'Button', class: 'btn btn-primary', onClick: [serviceReference, 'stringFunctionName', ['arg1','arg2','arg3']] }]">
    </common-header>

The library component is programmed like this. The dynamic event is added in the onClick(fn: any) method:

export class HeaderComponent implements OnInit {

 _buttons: Array<NavItem> = []

 @Input()
  set buttons(buttons: Array<any>) {
    buttons.forEach(navItem => {
      let _navItem = new NavItem(navItem.href, navItem.innerHtml)

      _navItem.class = navItem.class

      _navItem.onClick = navItem.onClick // this is the array from the component @Input properties above

      this._buttons[navItem.index] = _navItem
    })
  }

  constructor() {}

  ngOnInit() {}

  onClick(fn: any){
    let ref = fn[0]
    let fnName = fn[1]
    let args = fn[2]

    ref[fnName].apply(ref, args)
  }

The reusable header.component.html:

<div class="topbar-right">
  <button *ngFor="let btn of _buttons"
    class="{{ btn.class }}"
    (click)="onClick(btn.onClick)"
    [innerHTML]="btn.innerHtml | keepHtml"></button>
</div>

Is it possible to run CUDA on AMD GPUs?

Nope, you can't use CUDA for that. CUDA is limited to NVIDIA hardware. OpenCL would be the best alternative.

Khronos itself has a list of resources. As does the StreamComputing.eu website. For your AMD specific resources, you might want to have a look at AMD's APP SDK page.

Note that at this time there are several initiatives to translate/cross-compile CUDA to different languages and APIs. One such an example is HIP. Note however that this still does not mean that CUDA runs on AMD GPUs.

Read all contacts' phone numbers in android

     package com.example.readcontacts;

        import java.util.ArrayList;

        import android.app.Activity; import android.app.ProgressDialog;
        import android.content.ContentResolver; import
        android.database.Cursor; import android.net.Uri; import
        android.os.Bundle; import android.os.Handler; import
        android.provider.ContactsContract; import android.view.View; import
        android.widget.AdapterView; import
        android.widget.AdapterView.OnItemClickListener; import
        android.widget.ArrayAdapter; import android.widget.ListView; import
        android.widget.Toast;

        public class MainActivity extends Activity {    private ListView
        mListView;  private ProgressDialog pDialog;     private Handler
        updateBarHandler;

            ArrayList<String> contactList;  Cursor cursor;  int counter;    
            @Override   public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                pDialog = new ProgressDialog(this);         pDialog.setMessage("Reading
        contacts...");      pDialog.setCancelable(false);       pDialog.show();

                mListView = (ListView) findViewById(R.id.list);         updateBarHandler
        =new Handler();
                        // Since reading contacts takes more time, let's run it on a separate thread.       new Thread(new Runnable() {

                    @Override           public void run() {
                        getContacts();          }       }).start();

                // Set onclicklistener to the list item.
                mListView.setOnItemClickListener(new OnItemClickListener() {

                    @Override           public void onItemClick(AdapterView<?> parent, View
        view,
                            int position, long id) {
                        //TODO Do whatever you want with the list data
                        Toast.makeText(getApplicationContext(), "item clicked : \n"+contactList.get(position), Toast.LENGTH_SHORT).show();          }
                });     }

            public void getContacts() {


                contactList = new ArrayList<String>();

                String phoneNumber = null;      String email = null;

                Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;        String
        _ID = ContactsContract.Contacts._ID;        String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;       String HAS_PHONE_NUMBER =
        ContactsContract.Contacts.HAS_PHONE_NUMBER;

                Uri PhoneCONTENT_URI =
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI;         String
        Phone_CONTACT_ID =
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID;      String NUMBER =
        ContactsContract.CommonDataKinds.Phone.NUMBER;

                Uri EmailCONTENT_URI = 
        ContactsContract.CommonDataKinds.Email.CONTENT_URI;         String
        EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
                String DATA = ContactsContract.CommonDataKinds.Email.DATA;

                StringBuffer output;

                ContentResolver contentResolver = getContentResolver();

                cursor = contentResolver.query(CONTENT_URI, null,null, null,
        null);  

                // Iterate every contact in the phone       if (cursor.getCount() > 0)
        {

                    counter = 0;            while (cursor.moveToNext()) {
                        output = new StringBuffer();

                        // Update the progress message
                        updateBarHandler.post(new Runnable() {
                            public void run() {
                                pDialog.setMessage("Reading contacts : "+ counter++ +"/"+cursor.getCount());
                            }
                        });

                        String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
                        String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));

                        int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(
        HAS_PHONE_NUMBER )));

                        if (hasPhoneNumber > 0) {

                            output.append("\n First Name:" + name);

                            //This is to read multiple phone numbers associated with the same contact
                            Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);

                            while (phoneCursor.moveToNext()) {
                                phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                                output.append("\n Phone number:" + phoneNumber);

                            }

                            phoneCursor.close();

                            // Read every email id associated with the contact
                            Cursor emailCursor = contentResolver.query(EmailCONTENT_URI,    null, EmailCONTACT_ID+ " =
        ?", new String[] { contact_id }, null);

                            while (emailCursor.moveToNext()) {

                                email = emailCursor.getString(emailCursor.getColumnIndex(DATA));

                                output.append("\n Email:" + email);

                            }

                            emailCursor.close();
                        }

                        // Add the contact to the ArrayList
                        contactList.add(output.toString());             }

                    // ListView has to be updated using a ui thread
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item,
        R.id.text1, contactList);
                            mListView.setAdapter(adapter);          
                        }           });

                    // Dismiss the progressbar after 500 millisecondds
                    updateBarHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            pDialog.cancel();               
                        }           }, 500);        }

            }

        }

List item

java.net.BindException: Address already in use: JVM_Bind <null>:80

C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\conf

Your Port ID in Server.xml File in Source folder is 8080. change the Port Number to 8081...etc

Parse (split) a string in C++ using string delimiter (standard C++)

If you do not want to modify the string (as in the answer by Vincenzo Pii) and want to output the last token as well, you may want to use this approach:

inline std::vector<std::string> splitString( const std::string &s, const std::string &delimiter ){
    std::vector<std::string> ret;
    size_t start = 0;
    size_t end = 0;
    size_t len = 0;
    std::string token;
    do{ end = s.find(delimiter,start); 
        len = end - start;
        token = s.substr(start, len);
        ret.emplace_back( token );
        start += len + delimiter.length();
        std::cout << token << std::endl;
    }while ( end != std::string::npos );
    return ret;
}

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

Javascript seconds to minutes and seconds

  function formatSeconds(s: number) {
    let minutes = ~~(s / 60);
    let seconds = ~~(s % 60);
    return minutes + ':' + seconds;
  }

How to allow Cross domain request in apache2

I had a lot of trouble getting this to work. Dummy me, don't forget that old page - even for sub-requests - gets cached in your browser. Maybe obvious, but clear your browsers cache. After that, one can also use Header set Cache-Control "no-store" This was helpful to me while testing.

Count number of times value appears in particular column in MySQL

select email, count(*) as c FROM orders GROUP BY email

How to filter array when object key value is in array

Fastest way (will take extra memory):

var empid=[1,4,5]
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] ;

var empIdObj={};

empid.forEach(function(element) {
empIdObj[element]=true;
});

var filteredArray=[];

records.forEach(function(element) {
if(empIdObj[element.empid])
    filteredArray.push(element)
});

laravel collection to array

Use collect($comments_collection).

Else, try json_encode($comments_collection) to convert to json.

Relationship between hashCode and equals method in Java

According to the doc, the default implementation of hashCode will return some integer that differ for every object

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation
technique is not required by the JavaTM programming language.)

However some time you want the hash code to be the same for different object that have the same meaning. For example

Student s1 = new Student("John", 18);
Student s2 = new Student("John", 18);
s1.hashCode() != s2.hashCode(); // With the default implementation of hashCode

This kind of problem will be occur if you use a hash data structure in the collection framework such as HashTable, HashSet. Especially with collection such as HashSet you will end up having duplicate element and violate the Set contract.

resource error in android studio after update: No Resource Found

First of all,

Try to check your SDK folder, for me, it was mydocuments/appdata/sdk.... etc. So basically my sdk folder was not fully downloaded, the source of this problem mainly. You have to either use another fully downloaded android sdk(including Tools section and extras that you really need) or use the eclipse sdk that you may downloaded earlier for your Eclipse android developments. Then build->clean your project once again.

Worth to try.

How to see the changes in a Git commit?

If you just want to see the changes in the latest commit, simply git show will give you that.

Specifying java version in maven - differences between properties and compiler plugin

None of the solutions above worked for me straight away. So I followed these steps:

  1. Add in pom.xml:
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>
  1. Go to Project Properties > Java Build Path, then remove the JRE System Library pointing to JRE1.5.

  2. Force updated the project.

Making text background transparent but not text itself

box-shadow: inset 1px 2000px rgba(208, 208, 208, 0.54);

CSS transition fade in

CSS Keyframes support is pretty good these days:

_x000D_
_x000D_
.fade-in {_x000D_
 opacity: 1;_x000D_
 animation-name: fadeInOpacity;_x000D_
 animation-iteration-count: 1;_x000D_
 animation-timing-function: ease-in;_x000D_
 animation-duration: 2s;_x000D_
}_x000D_
_x000D_
@keyframes fadeInOpacity {_x000D_
 0% {_x000D_
  opacity: 0;_x000D_
 }_x000D_
 100% {_x000D_
  opacity: 1;_x000D_
 }_x000D_
}
_x000D_
<h1 class="fade-in">Fade Me Down Scotty</h1>
_x000D_
_x000D_
_x000D_

Can we convert a byte array into an InputStream in Java?

If you use Robert Harder's Base64 utility, then you can do:

InputStream is = new Base64.InputStream(cph);

Or with sun's JRE, you can do:

InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)

However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.

There are other Stack Overflow questions about Base64 decoding, such as this one.

How do I define a method in Razor?

MyModelVm.cs

public class MyModelVm
{
    public HttpStatusCode StatusCode { get; set; }
}

Index.cshtml

@model MyNamespace.MyModelVm
@functions
{
    string GetErrorMessage()
    {
        var isNotFound = Model.StatusCode == HttpStatusCode.NotFound;
        string errorMessage;
        if (isNotFound)
        {
            errorMessage = Resources.NotFoundMessage;
        }
        else
        {
            errorMessage = Resources.GeneralErrorMessage
        }

        return errorMessage;
    }
}

<div>
    @GetErrorMessage()
</div>