Programs & Examples On #Data storage

Best way to store data locally in .NET (C#)

I have done several "stand alone" apps that have a local data store. I think the best thing to use would be SQL Server Compact Edition (formerly known as SQLAnywhere).

It's lightweight and free. Additionally, you can stick to writing a data access layer that is reusable in other projects plus if the app ever needs to scale to something bigger like full blown SQL server, you only need to change the connection string.

How to add percent sign to NSString

The escape code for a percent sign is "%%", so your code would look like this

[NSString stringWithFormat:@"%d%%", someDigit];

Also, all the other format specifiers can be found at Conceptual Strings Articles

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

The following code may help you:

$("#svgEuropa [id='stallwanger.it.dev_shape_DEU']").on("click",function(){
    alert($(this).attr("id"));
});

Source

CSS body background image fixed to full screen even when zooming in/out

Use Directly like this

.bg-div{
     background: url(../img/beach.jpg) no-repeat fixed 100% 100%;
}

or call CSS separately like

.bg-div{
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

How to add a Try/Catch to SQL Stored Procedure

See TRY...CATCH (Transact-SQL)

 CREATE PROCEDURE [dbo].[PL_GEN_PROVN_NO1]        
       @GAD_COMP_CODE  VARCHAR(2) =NULL, 
       @@voucher_no numeric =null output 
       AS         
   BEGIN  

     begin try 
         -- your proc code
     end try

     begin catch
          -- what you want to do in catch
     end catch    
  END -- proc end

How do you find the current user in a Windows environment?

This is the main difference between username variable and whoami command:

C:\Users\user.name>echo %username%
user.name

C:\Users\user.name>whoami
domain\user.name

DOMAIN = bios name of the domain (not fqdn)

Conda environments not showing up in Jupyter Notebook

I encountered this problem when using vscode server. In the conda environment named "base", I installed the 1.2.0 version of opennmt-py, but I want to run jupyter notebook in the conda environment "opennmt2", which contains code using opennmt-py 2.0. I solved the problem by reinstalling jupyter in conda(opennmt2).

conda install jupyter

After reinstalling, executing jupyter notebook in the opennmt2 environment will execute the newly installed jupyter

where jupyter 
/root/miniconda3/envs/opennmt2/bin/jupyter
/root/miniconda3/bin/jupyter

How to remove special characters from a string?

This will replace all the characters except alphanumeric

replaceAll("[^A-Za-z0-9]","");

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

I have also faced the similar problem with the following details Java 1.8.0_121, Spark spark-1.6.1-bin-hadoop2.6, Windows 10 and Eclipse Oxygen.When I ran my WordCount.java in Eclipse using HADOOP_HOME as a system variable as mentioned in the previous post, it did not work, what worked for me is -

System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR");

PATH/TO/THE/DIR/bin=winutils.exe whether you run within Eclipse as a Java application or by spark-submit from cmd using

spark-submit --class groupid.artifactid.classname --master local[2] /path to the jar file created using maven /path to a demo test file /path to output directory command

Example: Go to the bin location of Spark/home/location/bin and execute the spark-submit as mentioned,

D:\BigData\spark-2.3.0-bin-hadoop2.7\bin>spark-submit --class com.bigdata.abdus.sparkdemo.WordCount --master local[1] D:\BigData\spark-quickstart\target\spark-quickstart-0.0.1-SNAPSHOT.jar D:\BigData\spark-quickstart\wordcount.txt

CSS grid wrapping

You may be looking for auto-fill:

grid-template-columns: repeat(auto-fill, 186px);

Demo: http://codepen.io/alanbuchanan/pen/wJRMox

To use up the available space more efficiently, you could use minmax, and pass in auto as the second argument:

grid-template-columns: repeat(auto-fill, minmax(186px, auto));

Demo: http://codepen.io/alanbuchanan/pen/jBXWLR

If you don't want the empty columns, you could use auto-fit instead of auto-fill.

Why is printing "B" dramatically slower than printing "#"?

Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.

  1. First Matrix: O and # = 6.03 seconds
  2. Second Matrix: O and B = 50.97 seconds

Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("B");
        }
        if(j%100==0){               //Adding a line break in second loop      
            System.out.println();
        }                    
    }
    System.out.println("");                
}

Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

NetBeans Editor Settings

Best programming based games

A game in which you have to graphically construct and train artificial neural networks in order to control a bug is Bug Brain.

Bug Brain screen shot http://www.infionline.net/~wtnewton/oldcomp/bugbrain.jpg

Font size of TextView in Android application changes on changing font size from native settings

Also note that if the textSize is set in code, calling textView.setTextSize(X) interprets the number (X) as SP. Use setTextSize(TypedValue.COMPLEX_UNIT_DIP, X) to set values in dp.

HTML: Changing colors of specific words in a string of text

Tailor this code however you like to fit your needs, you can select text? in the paragraph to be what font or style you need!:

<head>
<style>
p{ color:#ff0000;font-family: "Times New Roman", Times, serif;} 
font{color:#000fff;background:#000000;font-size:225%;}
b{color:green;}
</style>
</head>
<body>
<p>This is your <b>text. <font>Type</font></strong></b>what you like</p>
</body>

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

Try this query

SELECT v.VehicleId, v.Name, ll.LocationList
FROM Vehicles v 
LEFT JOIN 
    (SELECT 
     DISTINCT
        VehicleId,
        REPLACE(
            REPLACE(
                REPLACE(
                    (
                        SELECT City as c 
                        FROM Locations x 
                        WHERE x.VehicleID = l.VehicleID FOR XML PATH('')
                    ),    
                    '</c><c>',', '
                 ),
             '<c>',''
            ),
        '</c>', ''
        ) AS LocationList
    FROM Locations l
) ll ON ll.VehicleId = v.VehicleId

How do I declare an array variable in VBA?

The Array index only accepts a long value.

You declared iCounter as an integer. You should declare it as a long.

How to open spss data files in excel?

I tried the below and it worked well,

Install Dimensions Data Model and OLE DB Access

and follow the below steps in excel

Data->Get External Data ->From Other sources -> From Data Connection Wizard -> Other/Advanced-> SPSS MR DM-2 OLE DB Provider-> Metadata type as SPSS File(SAV)-> SPSS data file in Metadata Location->Finish

CSS full screen div with text in the middle

text-align: center will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0; (you will probably also have to give the span a display: block property)

Difference between xcopy and robocopy

The most important difference is that robocopy will (usually) retry when an error occurs, while xcopy will not. In most cases, that makes robocopy far more suitable for use in a script.

Addendum: for completeness, there is one known edge case issue with robocopy; it may silently fail to copy files or directories whose names contain invalid UTF-16 sequences. If that's a problem for you, you may need to look at third-party tools, or write your own.

How do I correct the character encoding of a file?

In sublime text editor, file -> reopen with encoding -> choose the correct encoding.

Generally, the encoding is auto-detected, but if not, you can use the above method.

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

SELECT DISTINCT will always be the same, or faster, than a GROUP BY. On some systems (i.e. Oracle), it might be optimized to be the same as DISTINCT for most queries. On others (such as SQL Server), it can be considerably faster.

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

Python loop counter in a for loop

I'll sometimes do this:

def draw_menu(options, selected_index):
    for i in range(len(options)):
        if i == selected_index:
            print " [*] %s" % options[i]
        else:
            print " [ ] %s" % options[i]

Though I tend to avoid this if it means I'll be saying options[i] more than a couple of times.

java.lang.ClassCastException

A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example

Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;

This works because an apple 'is a' fruit. However if we reverse this.

Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;

This will throw a ClasCastException because a Fruit is not (always) an Apple.

It is good practice to guard any explicit casts with an instanceof check first:

if (myApple instanceof Fruit) {
  Fruit myFruit = (Fruit)myApple;
}

UITableview: How to Disable Selection for Some Rows but Not Others

I agree with Bryan's answer

if I do

cell.isUserInteractionEnabled = false 

then the subviews within the cell won't be user interacted.

On the other site, setting

cell.selectionStyle = .none

will trigger the didSelect method despite not updating the selection color.

Using willSelectRowAt is the way I solved my problem. Example:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {

    if indexPath.section == 0{

        if indexPath.row == 0{
            return nil
        }

    }
    else if indexPath.section == 1{

        if indexPath.row == 0{
            return nil
        }

    }

    return indexPath

}

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I had the same problem. Just after enabling Internet Virtualization from BIOS. After that let the system boot and install HAXM once again. Now emulator will run faster than before and HAXM will work. Enjoy!!

How to detect window.print() finish

Tested IE, FF, Chrome and works in all.

    setTimeout(function () { window.print(); }, 500);
    window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }

Multiple actions were found that match the request in Web Api

This is the answer for everyone who knows everything is correct and has checked 50 times.....

Make sure you are not repeatedly looking at RouteConfig.cs.

The file you want to edit is named WebApiConfig.cs

Also, it should probably look exactly like this:

using System.Web.Http;

namespace My.Epic.Website
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
          config.MapHttpAttributeRoutes();

          // api/Country/WithStates
          config.Routes.MapHttpRoute(
            name: "ControllerAndActionOnly",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { },
            constraints: new { action = @"^[a-zA-Z]+([\s][a-zA-Z]+)*$" });

          config.Routes.MapHttpRoute(
            name: "DefaultActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
          );
    }
    }
}

I could have saved myself about 3 hours.

How can I make a CSS glass/blur effect work for an overlay?

This will do the blur overlay over the content:

.blur {
  display: block;
  bottom: 0;
  left: 0;
  position: fixed;
  right: 0;
  top: 0;
  -webkit-backdrop-filter: blur(15px);
  backdrop-filter: blur(15px);
  background-color: rgba(0, 0, 0, 0.5);
}

can not find module "@angular/material"

Found this post: "Breaking changes" in angular 9. All modules must be imported separately. Also a fine module available there, thanks to @jeff-gilliland: https://stackoverflow.com/a/60111086/824622

What is the difference between `git merge` and `git merge --no-ff`?

Other answers indicate perfectly well that --no-ff results in a merge commit. This retains historical information about the feature branch which is useful since feature branches are regularly cleaned up and deleted.

This answer may provide context for when to use or not to use --no-ff.

Merging from feature into the main branch: use --no-ff

Worked example:

$ git checkout -b NewFeature
[work...work...work]
$ git commit -am  "New feature complete!"
$ git checkout main
$ git merge --no-ff NewFeature
$ git push origin main
$ git branch -d NewFeature

Merging changes from main into feature branch: leave off --no-ff

Worked example:

$ git checkout -b NewFeature
[work...work...work]
[New changes made for HotFix in the main branch! Lets get them...]
$ git commit -am  "New feature in progress"
$ git pull origin main
[shortcut for "git fetch origin main", "git merge origin main"]

How to make a progress bar

Basically its this: You have three files: Your long running PHP script, a progress bar controlled by Javascript (@SapphireSun gives an option), and a progress script. The hard part is the Progress Script; your long script must be able to report its progress without direct communication to your progress script. This can be in the form of session id's mapped to progress meters, a database, or check of whats not finished.

The process is simple:

  1. Execute your script and zero out progress bar
  2. Using AJAX, query your progress script
  3. Progress script must somehow check on progress
  4. Change the progress bar to reflect the value
  5. Clean up when finished

get enum name from enum value

If you want something more efficient in runtime condition, you can have a map that contains every possible choice of the enum by their value. But it'll be juste slower at initialisation of the JVM.

import java.util.HashMap;
import java.util.Map;

/**
 * Example of enum with a getter that need a value in parameter, and that return the Choice/Instance 
 * of the enum which has the same value.
 * The value of each choice can be random.
 */
public enum MyEnum {
    /** a random choice */
    Choice1(4),
    /** a nother one */
    Choice2(2),
    /** another one again */
    Choice3(9);
    /** a map that contains every choices of the enum ordered by their value. */
    private static final Map<Integer, MyEnum> MY_MAP = new HashMap<Integer, MyEnum>();
    static {
        // populating the map
        for (MyEnum myEnum : values()) {
            MY_MAP.put(myEnum.getValue(), myEnum);
        }
    }
    /** the value of the choice */
    private int value;

    /**
     * constructor
     * @param value the value
     */
    private MyEnum(int value) {
        this.value = value;
    }

    /**
     * getter of the value
     * @return int
     */
    public int getValue() {
        return value;
    }

    /**
     * Return one of the choice of the enum by its value.
     * May return null if there is no choice for this value.
     * @param value value
     * @return MyEnum
     */
    public static MyEnum getByValue(int value) {
        return MY_MAP.get(value);
    }

    /**
     * {@inheritDoc}
     * @see java.lang.Enum#toString()
     */
    public String toString() {
        return name() + "=" + value;
    }

    /**
     * Exemple of how to use this class.
     * @param args args
     */
    public static void main(String[] args) {
        MyEnum enum1 = MyEnum.Choice1;
        System.out.println("enum1==>" + String.valueOf(enum1));
        MyEnum enum2GotByValue = MyEnum.getByValue(enum1.getValue());
        System.out.println("enum2GotByValue==>" + String.valueOf(enum2GotByValue));
        MyEnum enum3Unknown = MyEnum.getByValue(4);
        System.out.println("enum3Unknown==>" + String.valueOf(enum3Unknown));
    }
}

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

CSS background-image not working

The code below works. Replace the text within the single quotes with your image name. If it is in the same folder, if not add ../foldername/'yourimagename' I hope that helps.

NOTE:

use of the single quotes by most of the programmers is not advised but I use it and it works. Also, if you would write a PHP you would appreciate what it can do i.e. add the background image automatically from the variable etc.

<html>
<head>
<style type="text/css">
.btn-pTool{
margin:0;
padding:0;
background-image: url('your name of the field');
height:100px;
width:200px;
display:block;
}

.btn-pToolName{
    text-align: center; 
    width: 26px; 
    height: 190px; 
    display: block; 
    color: #fff; 
    text-decoration: none;  
    font-family: Arial, Helvetica, sans-serif;  
    font-weight: bold; 
    font-size: 1em; 
    line-height: 32px; 
    }
    </style>
    </head>
    <body>
    <div class="pToolContainer">
    <span class="btn-pTool"><a class="btn-pToolName" href="#">Test text</a></span>
    <div class="pToolSlidePanel">Test text</div>
    </div>
    </body>
    </html>

How can I know if Object is String type object?

Use the instanceof syntax.

Like so:

Object foo = "";

if( foo instanceof String ) {
  // do something String related to foo
}

How to use ImageBackground to set background image for screen in react-native

Here is a link to the RN docs: https://facebook.github.io/react-native/docs/images

A common feature request from developers familiar with the web is background-image. To handle this use case, you can use the <ImageBackground> component, which has the same props as <Image>, and add whatever children to it you would like to layer on top of it.

You might not want to use <ImageBackground> in some cases, since the implementation is very simple. Refer to <ImageBackground>'s source code for more insight, and create your own custom component when needed.

return (
  <ImageBackground source={require('./image.png')} style={{width: '100%', height: '100%'}}>
    <Text>Inside</Text>
  </ImageBackground>
);

Note that you must specify some width and height style attributes.

Note also that the file path is relative to the directory the component is in.

Is there any "font smoothing" in Google Chrome?

Ok you can use this simply

-webkit-text-stroke-width: .7px;
-webkit-text-stroke-color: #34343b;
-webkit-font-smoothing:antialiased;

Make sure your text color and upper text-stroke-width must me same and that's it.

How to solve privileges issues when restore PostgreSQL Database

Some of the answers have already provided various approaches related to getting rid of the create extension and comment on extensions. For me, the following command line seemed to work and be the simplest approach to solve the problem:

cat /tmp/backup.sql.gz | gunzip - | \
  grep -v -E '(CREATE\ EXTENSION|COMMENT\ ON)' |  \
    psql --set ON_ERROR_STOP=on -U db_user -h localhost my_db

Some notes

  • The first line is just uncompressing my backup and you may need to adjust accordingly.
  • The second line is using grep to get rid of offending lines.
  • the third line is my psql command; you may need to adjust as you normally would use psql for restore.

How to initialize const member variable in a class?

Another solution is

class T1
{
    enum
    {
        t = 100
    };

    public:
    T1();
};

So t is initialised to 100 and it cannot be changed and it is private.

How do you divide each element in a list by an int?

The idiomatic way would be to use list comprehension:

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [x / myInt for x in myList]

or, if you need to maintain the reference to the original list:

myList[:] = [x / myInt for x in myList]

Returning Promises from Vuex actions

Just for an information on a closed topic: you don’t have to create a promise, axios returns one itself:

Ref: https://forum.vuejs.org/t/how-to-resolve-a-promise-object-in-a-vuex-action-and-redirect-to-another-route/18254/4

Example:

    export const loginForm = ({ commit }, data) => {
      return axios
        .post('http://localhost:8000/api/login', data)
        .then((response) => {
          commit('logUserIn', response.data);
        })
        .catch((error) => {
          commit('unAuthorisedUser', { error:error.response.data });
        })
    }

Another example:

    addEmployee({ commit, state }) {       
      return insertEmployee(state.employee)
        .then(result => {
          commit('setEmployee', result.data);
          return result.data; // resolve 
        })
        .catch(err => {           
          throw err.response.data; // reject
        })
    }

Another example with async-await

    async getUser({ commit }) {
        try {
            const currentUser = await axios.get('/user/current')
            commit('setUser', currentUser)
            return currentUser
        } catch (err) {
            commit('setUser', null)
            throw 'Unable to fetch current user'
        }
    },

Format LocalDateTime with Timezone in Java8

The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime). Despite the often misleading name such classes like LocalDateTime or LocalTime have NO timezone information or offset.

You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.

Solution:

Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime (which contains an offset but not a timezone including DST-rules) or ZonedDateTime. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds is supported in OffsetDateTime and ZonedDateTime, but not in LocalDateTime.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);

The conversion of the varchar value overflowed an int column

Thanks Ravi and other users .... Nevertheless I have got the solution

SELECT @phoneNumber=
CASE 
  WHEN  ISNULL(rdg2.nPhoneNumber  ,'0') in ('0','-',NULL)
THEN ISNULL(rdg2.nMobileNumber, '0') 
  WHEN ISNULL(rdg2.nMobileNumber, '0')  in ('0','-',NULL)
THEN '0'
  ELSE ISNULL(rdg2.nPhoneNumber  ,'0')
END 
FROM tblReservation_Details_Guest  rdg2 
WHERE nReservationID=@nReservationID

Just need to put '0' instead of 0

How can I scroll a web page using selenium webdriver in python?

You can use send_keys to simulate a PAGE_DOWN key press (which normally scroll the page):

from selenium.webdriver.common.keys import Keys
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.PAGE_DOWN)

Converting a string to a date in DB2

Based on your own answer, I'm guessing that your column has data formatted like this:

'DD/MM/YYYY HH:MI:SS'

The actual separators between Day/Month/Year don't matter, nor does anything that comes after the year.

You don't say what version of DB2 you are using or what platform it's running on, so I'm going to assume that it's on Linux, UNIX or Windows.

Almost any recent version of DB2 for Linux/UNIX/Windows (8.2 or later, possibly even older versions), you can do this using the TRANSLATE function:

select 
   date(translate('GHIJ-DE-AB',column_with_date,'ABCDEFGHIJ'))
from
   yourtable

With this solution it doesn't matter what comes after the date in your column.

In DB2 9.7, you can also use the TO_DATE function (similar to Oracle's TO_DATE):

date(to_date(column_with_date,'DD-MM-YYYY HH:MI:SS'))

This requires your data match the formatting string; it's easier to understand when looking at it, but not as flexible as the TRANSLATE option.

how to return a char array from a function in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
    int n,k=0;
    char *ch1;
    ch1=(char*)malloc((j-i+1)*1);
    n=j-i+1;

    while(k<n)
    {
        ch1[k]=ch[i];
        i++;k++;
    }

    return (char *)ch1;
}

int main()
{
    int i=0,j=2;
    char s[]="String";
    char *test;

    test=substring(i,j,s);
    printf("%s",test);
    free(test); //free the test 
    return 0;
}

This will compile fine without any warning

  1. #include stdlib.h
  2. pass test=substring(i,j,s);
  3. remove m as it is unused
  4. either declare char substring(int i,int j,char *ch) or define it before main

Removing duplicates in the lists

Try using sets:

import sets
t = sets.Set(['a', 'b', 'c', 'd'])
t1 = sets.Set(['a', 'b', 'c'])

print t | t1
print t - t1

Get current URL with jQuery?

This is a more complicated issue than many may think. Several browsers support built-in JavaScript location objects and associated parameters/methods accessible through window.location or document.location. However, different flavors of Internet Explorer (6,7) don't support these methods in the same way, (window.location.href? window.location.replace() not supported) so you have to access them differently by writing conditional code all the time to hand-hold Internet Explorer.

So, if you have jQuery available and loaded, you might as well use jQuery (location), as the others mentioned because it resolves these issues. If however, you are doing-for an example-some client-side geolocation redirection via JavaScript (that is, using Google Maps API and location object methods), then you may not want to load the entire jQuery library and write your conditional code that checks every version of Internet Explorer/Firefox/etc.

Internet Explorer makes the front-end coding cat unhappy, but jQuery is a plate of milk.

When does a process get SIGABRT (signal 6)?

In my case, it was due to an input in an array at an index equal to the length of the array.

string x[5];

for(int i=1; i<=5; i++){

    cin>>x[i];

}

x[5] is being accessed which is not present.

getDate with Jquery Datepicker

You can format the jquery date with this line:

moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");

http://momentjs.com

Jquery show/hide table rows

The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:

    var black = $('.black');
    var white = $('.white');

The selector will find every element classed under black or white. Button functions stay as stated above:

    $('#showBlackButton').click(function() {
           black.show();
           white.hide();
    });

    $('#showWhiteButton').click(function() {
           white.show();
           black.hide();
    });

How to install SQL Server Management Studio 2008 component only

SQL Server Management Studio 2008 R2 Express commandline:

The answer by dyslexicanaboko hits the crucial point, but this one is even simpler and suited for command line (unattended scenarios):

(tried out with SQL Server 2008 R2 Express, one instance installed and having downloaded SQLManagementStudio_x64_ENU.exe)

As pointed out in this thread often enough, it is better to use the original SQL server setup (e.g. SQL Express with Tools), if possible, but there are some scenarios, where you want to add SSMS at a SQL derivative without that tools, afterwards:

I´ve already put it in a batch syntax here:

@echo off
"%~dp0SQLManagementStudio_x64_ENU.exe" /Q /ACTION="Install" /FEATURES="SSMS" /IACCEPTSQLSERVERLICENSETERMS

Remarks:

  1. For 2008 without R2 it should be enough to omit the /IACCEPTSQLSERVERLICENSETERMS flag, i guess.

  2. The /INDICATEPROGRESS parameter is useless here, the whole command takes a number of minutes and is 100% silent without any acknowledgement. Just look at the start menu, if the command is ready, if it has succeeded.

  3. This should work for the "ADV_SSMS" Feature (instead of "SSMS") too, which is the management studio extended variant (profiling, reporting, tuning, etc.)

Generate random string/characters in JavaScript

Assuming you use underscorejs it's possible to elegantly generate random string in just two lines:

var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var random = _.sample(possible, 5).join('');

How to convert milliseconds into human readable form?

You should use the datetime functions of whatever language you're using, but, just for fun here's the code:

int milliseconds = someNumber;

int seconds = milliseconds / 1000;

int minutes = seconds / 60;

seconds %= 60;

int hours = minutes / 60;

minutes %= 60;

int days = hours / 24;

hours %= 24;

Height equal to dynamic width (CSS fluid layout)

Extremely simple method jsfiddle

HTML

<div id="container">
    <div id="element">
        some text
    </div>
</div>

CSS

#container {
    width: 50%; /* desired width */
}

#element {
    height: 0;
    padding-bottom: 100%;
}

Which mime type should I use for mp3

I had a problem with mime types and where making tests for few file types. It looks like each browser sends it's variation of a mime type for a specific file. I was trying to upload mp3 and zip files with open source php class, that what I have found:

  • Firefox (mp3): audio/mpeg
  • Firefox (zip): application/zip
  • Chrome (mp3): audio/mp3
  • Chrome (zip): application/octet-stream
  • Opera (mp3): audio/mp3
  • Opera (zip): application/octet-stream
  • IE (mp3): audio/mpeg
  • IE (zip): application/x-zip-compressed

So if you need several file types to upload, you better make some tests so that every browser could upload a file and pass mime type check.

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Here is part of a line in my code that brought the warning up in NetBeans:

$page = (!empty($_GET['p'])) 

After much research and seeing how there are about a bazillion ways to filter this array, I found one that was simple. And my code works and NetBeans is happy:

$p = filter_input(INPUT_GET, 'p');
$page = (!empty($p))

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There a small difference when u use rgba(255,255,255,a),background color becomes more and more lighter as the value of 'a' increase from 0.0 to 1.0. Where as when use rgba(0,0,0,a), the background color becomes more and more darker as the value of 'a' increases from 0.0 to 1.0. Having said that, its clear that both (255,255,255,0) and (0,0,0,0) make background transparent. (255,255,255,1) would make the background completely white where as (0,0,0,1) would make background completely black.

How to set thousands separator in Java?

public String formatStr(float val) {
 return String.format(Locale.CANADA, "%,.2f", val);
}

formatStr(2524.2) // 2,254.20



assignment operator overloading in c++

it's right way to use operator overloading now you get your object by reference avoiding value copying.

How to timeout a thread

Indeed rather use ExecutorService instead of Timer, here's an SSCCE:

package com.stackoverflow.q2275443;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Test {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new Task());

        try {
            System.out.println("Started..");
            System.out.println(future.get(3, TimeUnit.SECONDS));
            System.out.println("Finished!");
        } catch (TimeoutException e) {
            future.cancel(true);
            System.out.println("Terminated!");
        }

        executor.shutdownNow();
    }
}

class Task implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
        return "Ready!";
    }
}

Play a bit with the timeout argument in Future#get() method, e.g. increase it to 5 and you'll see that the thread finishes. You can intercept the timeout in the catch (TimeoutException e) block.

Update: to clarify a conceptual misunderstanding, the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep(). Inside your long running task, you should be checking if the thread is not interrupted as follows:

while (!Thread.interrupted()) {
    // Do your long running task here.
}

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

You should see if your tables has any data on the rows. If "yes" then you should truncate the table(s) or else you can make them to have the same number of data at tblDomare.PersNR to tblBana.BanNR and vise-verse.

MySQL combine two columns and add into a new column

Add new column to your table and perfrom the query:

UPDATE tbl SET combined = CONCAT(zipcode, ' - ', city, ', ', state)

how to set the query timeout from SQL connection string

You can only set the connection timeout on the connection string, the timeout for your query would normally be on the command timeout. (Assuming we are talking .net here, I can't really tell from your question).

However the command timeout has no effect when the command is executed against a context connection (a SqlConnection opened with "context connection=true" in the connection string).

Version of Apache installed on a Debian machine

Try apachectl -V:

$ apachectl -V
Server version: Apache/2.2.9 (Unix)
Server built:   Sep 18 2008 21:54:05
Server's Module Magic Number: 20051115:15
Server loaded:  APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
... etc ...

If it does not work for you, run the command with sudo.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

//Abstract factory - Provides interface to create factory of related products
interface PizzaIngredientsFactory{    
   public Dough createDough(); //Will return you family of Dough
   public Clam createClam();   //Will return you family of Clam
   public Sauce createSauce(); //Will return you family of Sauce
}

class NYPizzaIngredientsFactory implements PizzaIngredientsFactory{

   @Override
   public Dough createDough(){
      //create the concrete dough instance that NY uses
      return doughInstance;
   }

   //override other methods
} 

The text book definitions are already provided by other answers. I thought I would provide an example of it too.

So here the PizzaIngredientsFactory is an abstract factory as it provides methods to create family of related products.

Note that each method in the Abstract factory is an Factory method in itself. Like createDough() is in itself a factory method whose concrete implementations will be provided by subclasses like NYPizzaIngredientsFactory. So using this each different location can create instances of concrete ingredients that belong to their location.

Factory Method

Provides instance of concrete implementation

In the example:
- createDough() - provides concrete implementation for dough. So this is a factory method

Abstract Factory

Provides interface to create family of related objects

In the example:
- PizzaIngredientsFactory is an abstract factory as it allows to create a related set of objects like Dough, Clams, Sauce. For creating each family of objects it provides a factory method.

Example from Head First design patterns

What does %>% function mean in R?

The R packages dplyr and sf import the operator %>% from the R package magrittr.

Help is available by using the following command:

?'%>%'

Of course the package must be loaded before by using e.g.

library(sf)

The documentation of the magrittr forward-pipe operator gives a good example: When functions require only one argument, x %>% f is equivalent to f(x)

Purpose of installing Twitter Bootstrap through npm?

If you NPM those modules you can serve them using static redirect.

First install the packages:

npm install jquery
npm install bootstrap

Then on the server.js:

var express = require('express');
var app = express();

// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www')); // redirect root
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap

Then, finally, at the .html:

<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>

I would not serve pages directly from the folder where your server.js file is (which is usually the same as node_modules) as proposed by timetowonder, that way people can access your server.js file.

Of course you can simply download and copy & paste on your folder, but with NPM you can simply update when needed... easier, I think.

link_to image tag. how to add class to a tag

Best will be:

link_to image_tag("Search.png", :border => 0, :alt => '', :title => ''), pages_search_path, :class => 'dock-item'

How do I write a Python dictionary to a csv file?

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

Ruby optional parameters

It is possible :) Just change definition

def ldap_get ( base_dn, filter, scope=LDAP::LDAP_SCOPE_SUBTREE, attrs=nil )

to

def ldap_get ( base_dn, filter, *param_array, attrs=nil )
scope = param_array.first || LDAP::LDAP_SCOPE_SUBTREE

scope will be now in array on its first place. When you provide 3 arguments, then you will have assigned base_dn, filter and attrs and param_array will be [] When 4 and more arguments then param_array will be [argument1, or_more, and_more]

Downside is... it is unclear solution, really ugly. This is to answer that it is possible to ommit argument in the middle of function call in ruby :)

Another thing you have to do is to rewrite default value of scope.

Disable hover effects on mobile browsers

You can use js. It should work as expected.

_x000D_
_x000D_
function myFunction(){
    var x = document.getElementById("DIV");
  x.style.backgroundColor="red";
  x.style.cursor="pointer";
  x.style.color="white"
}
function my2Function(){
    var x = document.getElementById("DIV");
  x.style.backgroundColor="white";
  x.style.color="red"
}
_x000D_
.mydiv {
  background-color: white;
  color: red;
}
_x000D_
<div class = "mydiv" id="DIV" onmouseover="myFunction()" onmouseleave="my2Function()">
  hi
</div>
_x000D_
_x000D_
_x000D_

How to place div in top right hand corner of page

Try css:

.topcorner{
    position:absolute;
    top:10px;
    right: 10px;
 }

you can play with the top and right properties.

If you want to float the div even when you scroll down, just change position:absolute; to position:fixed;.

Hope it helps.

How to know if a DateTime is between a DateRange in C#

I’ve found the following library to be the most helpful when doing any kind of date math. I’m still amazed nothing like this is part of the .Net framework.

http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

In my case, the AllowHtml attribute was not working when combined with the OutputCache action filter. This answer solved the problem for me. Hope this helps someone.

Convert an NSURL to an NSString

Swift update:

var myUrlStr : String = myUrl.absoluteString

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

GlobalConfiguration class is part of Microsoft.AspNet.WebApi.WebHost nuget package...Have you upgraded this package to Web API 2?

Body of Http.DELETE request in Angular2

If you use Angular 6 we can put body in http.request method.

Reference from github

You can try this, for me it works.

import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {

  constructor(
    private http: HttpClient
  ) {
    http.request('delete', url, {body: body}).subscribe();
  }
}

How to print Unicode character in C++?

I needed to show the string in UI as well as save that to an xml configuration file. The above specified format is good for string in c++, I would add we can have the xml compatible string for the special character by replacing "\u" by "&#x" and adding a ";" at the end.

For example : C++ : "\u0444" --> XML : "&#x0444;"

How to add a default include path for GCC in Linux?

just a note: CPLUS_INCLUDE_PATH and C_INCLUDE_PATH are not the equivalent of LD_LIBRARY_PATH. LD_LIBRARY_PATH serves the ld (the dynamic linker at runtime) whereas the equivalent of the former two that serves your C/C++ compiler with the location of libraries is LIBRARY_PATH.

MySQL vs MongoDB 1000 reads

Here is a little research that explored RDBMS vs NoSQL using MySQL vs Mongo, the conclusions were inline with @Sean Reilly's response. In short, the benefit comes from the design, not some raw speed difference. Conclusion on page 35-36:

RDBMS vs NoSQL: Performance and Scaling Comparison

The project tested, analysed and compared the performance and scalability of the two database types. The experiments done included running different numbers and types of queries, some more complex than others, in order to analyse how the databases scaled with increased load. The most important factor in this case was the query type used as MongoDB could handle more complex queries faster due mainly to its simpler schema at the sacrifice of data duplication meaning that a NoSQL database may contain large amounts of data duplicates. Although a schema directly migrated from the RDBMS could be used this would eliminate the advantage of MongoDB’s underlying data representation of subdocuments which allowed the use of less queries towards the database as tables were combined. Despite the performance gain which MongoDB had over MySQL in these complex queries, when the benchmark modelled the MySQL query similarly to the MongoDB complex query by using nested SELECTs MySQL performed best although at higher numbers of connections the two behaved similarly. The last type of query benchmarked which was the complex query containing two JOINS and and a subquery showed the advantage MongoDB has over MySQL due to its use of subdocuments. This advantage comes at the cost of data duplication which causes an increase in the database size. If such queries are typical in an application then it is important to consider NoSQL databases as alternatives while taking in account the cost in storage and memory size resulting from the larger database size.

Using Git, show all commits that are in one branch, but not the other(s)

To show the commits in oldbranch but not in newbranch:

git log newbranch..oldbranch

To show the diff by these commits (note there are three dots):

git diff newbranch...oldbranch

Here is the doc with a diagram illustration https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection#Commit-Ranges

How to get the Parent's parent directory in Powershell?

In PowerShell 3, $PsScriptRoot or for your question of two parents up,

$dir = ls "$PsScriptRoot\..\.."

When would you use the different git merge strategies?

I'm not familiar with resolve, but I've used the others:

Recursive

Recursive is the default for non-fast-forward merges. We're all familiar with that one.

Octopus

I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.

An octopus branch merges multiple heads in one commit as long as it can do it cleanly.

For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).

A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):

series of recursive merges

However, a single octopus merge would look like this:

commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...

octopus merge

Ours

Ours == I want to pull in another head, but throw away all of the changes that head introduces.

This keeps the history of a branch without any of the effects of the branch.

(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours)

Subtree

Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

I had the same error when tried to run my tests in a JSF project.

I´m using Eclipse IDE (kepler). So, I did "project > clean" and then ran the tests again of the same project.

It worked!

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Follow these steps to run your application on the device connected. 1. Change directories to the root of your Android project and execute: ant debug 2. Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute: adb install bin/<*your app name*>-debug.apk On your device, locate <*your app name*> and open it.

Refer Running App

How to validate an Email in PHP?

This is old post but I will share one my solution because noone mention here one problem before.

New email address can contain UTF-8 characters or special domain names like .live, .news etc.

Also I find that some email address can be on Cyrilic and on all cases standard regex or filter_var() will fail.

That's why I made an solution for it:

function valid_email($email) 
{
    if(is_array($email) || is_numeric($email) || is_bool($email) || is_float($email) || is_file($email) || is_dir($email) || is_int($email))
        return false;
    else
    {
        $email=trim(strtolower($email));
        if(filter_var($email, FILTER_VALIDATE_EMAIL)!==false) return $email;
        else
        {
            $pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
            return (preg_match($pattern, $email) === 1) ? $email : false;
        }
    }
}

This function work perfectly for all cases and email formats.

Remove scrollbar from iframe

Add this in your css to hide both scroll bar

iframe 
{
  overflow-x:hidden;
  overflow-Y:hidden;
}

Check whether a string contains a substring

Another possibility is to use regular expressions which is what Perl is famous for:

if ($mystring =~ /s1\.domain\.com/) {
   print qq("$mystring" contains "s1.domain.com"\n);
}

The backslashes are needed because a . can match any character. You can get around this by using the \Q and \E operators.

my $substring = "s1.domain.com";
    if ($mystring =~ /\Q$substring\E/) {
   print qq("$mystring" contains "$substring"\n);
}

Or, you can do as eugene y stated and use the index function. Just a word of warning: Index returns a -1 when it can't find a match instead of an undef or 0.

Thus, this is an error:

my $substring = "s1.domain.com";
if (not index($mystring, $substr)) {
    print qq("$mystring" doesn't contains "$substring"\n";
} 

This will be wrong if s1.domain.com is at the beginning of your string. I've personally been burned on this more than once.

Error in finding last used cell in Excel with VBA

Find Last Row in a Column OR a Table Column(ListObject) by range

Finding the last row requires:

  1. Specifying several parameters (table name, column inside table relative to first column, worksheet, range).
  2. May require switching between methods. e.g. if the range is a Table (List Object) or not. Using the wrong search type will return wrong results.

This proposed solution is more general, requires only the range ,less chance of typos and is short (just calling MyLastRow function).

Sub test()
Dim rng As Range
Dim Result As Long
Set rng = Worksheets(1).Range("D4")
Result = MyLastRow(rng)
End Sub
    Function MyLastRow(FirstRow As Range) As Long
    Dim WS As Worksheet
    Dim TableName As String
    Dim ColNumber As Long
    Dim LastRow As Long
    Dim FirstColumnTable As Long
    Dim ColNumberTable As Long
    Set WS = FirstRow.Worksheet
    TableName = GetTableName(FirstRow)
    ColNumber = FirstRow.Column
    
    ''If the table (ListObject) does not start in column "A" we need to calculate the 
    ''first Column table and how many Columns from its beginning the Column is located.
    If TableName <> vbNullString Then
     FirstColumnTable = WS.ListObjects(TableName).ListColumns(1).Range.Column
     ColNumberTable = ColNumber - FirstColumnTable + 1
    End If 

    If TableName = vbNullString Then
    LastRow = WS.Cells(WS.Rows.Count, ColNumber).End(xlUp).Row
    Else
    LastRow = WS.ListObjects(TableName).ListColumns(ColNumberTable).Range.Find( _
               What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End If
    MyLastRow = LastRow
    End Function
    
    ''Get Table Name by Cell Range
    Function GetTableName(CellRange As Range) As String
        If CellRange.ListObject Is Nothing Then
            GetTableName = vbNullString
        Else
            GetTableName = CellRange.ListObject.Name
        End If
    End Function

Gradle finds wrong JAVA_HOME even though it's correctly set

Try installing latest version of gradle,

sudo add-apt-repository ppa:cwchien/gradle

sudo apt-get update

sudo apt-get install gradle

If we install from ubuntu repo, it will install the old version , (for me it was gradle 1.4). In older version, it sets java home from gradle as export JAVA_HOME=/usr/lib/jvm/default-java. Latest version don't have this issue.

Create view with primary key?

You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also. Applications requiring a primary key may accept the view as it is the case with Lightswitch.

How to replace a char in string with an Empty character in C#.NET

If you want to replace a char in a string with an empty char that means you want to remove that char from a string, read the answer of R. Martinho Fernandes.

Here is an exemple of how to remove a char from a string (replace with an "Empty char"):

    public static string RemoveCharFromString(string input, char charItem)
    {
        int indexOfChar = input.IndexOf(charItem);
        if (indexOfChar >= 0)
        {
            input = input.Remove(indexOfChar, 1);
        }
        return input;
    }

or this version that removes all recurrences of a char in a string :

    public static string RemoveCharFromString(string input, char charItem)
    {
        int indexOfChar = input.IndexOf(charItem);
        if (indexOfChar < 0)
        {
            return input;
        }
        return RemoveCharFromString(input.Remove(indexOfChar, 1), charItem);
    }

Using async/await with a forEach loop

Instead of Promise.all in conjunction with Array.prototype.map (which does not guarantee the order in which the Promises are resolved), I use Array.prototype.reduce, starting with a resolved Promise:

async function printFiles () {
  const files = await getFilePaths();

  await files.reduce(async (promise, file) => {
    // This line will wait for the last async function to finish.
    // The first iteration uses an already resolved Promise
    // so, it will immediately continue.
    await promise;
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }, Promise.resolve());
}

How to use opencv in using Gradle?

If you don't want to use JavaCV this works for me...

Step 1- Download the Resources

Download OpenCV Android SDK from http://opencv.org/downloads.html

Step 2 - Copying the OpenCV binaries into your APK

Copy libopencv_info.so & libopencv_java.so from

OpenCV-2.?.?-android-sdk -> sdk -> native -> libs -> armeabi-v7a

to

Project Root -> Your Project -> lib - > armeabi-v7a

Zip the lib folder up and rename that zip to whatever-v7a.jar.

Copy this .jar file and place it in here in your project

Project Root -> Your Project -> libs

Add this line to your projects build.gradle in the dependencies section

compile files('libs/whatever-v7a.jar')

When you compile now you will probably see your .apk is about 4mb bigger.

(Repeat for "armeabi" if you want to support ARMv6 too, likely not needed anymore.)

Step 3 - Adding the java sdk to your project

Copy the java folder from here

OpenCV-2.?.?-android-sdk -> sdk

to

Project Root -> Your Project -> libs (Same place as your .jar file);

(You can rename the 'java' folder name to 'OpenCV')

In this freshly copied folder add a typical build.gradle file; I used this:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.+'
    }
}

apply plugin: 'android-library'

repositories {
    mavenCentral();
}

android {
    compileSdkVersion 19
    buildToolsVersion "19"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 19
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
}

In your Project Root settings.gradle file change it too look something like this:

include ':Project Name:libs:OpenCV', ':Project Name'

In your Project Root -> Project Name -> build.gradle file in the dependencies section add this line:

compile project(':Project Name:libs:OpenCV')

Step 4 - Using OpenCV in your project

Rebuild and you should be able to import and start using OpenCV in your project.

import org.opencv.android.OpenCVLoader;
...
if (!OpenCVLoader.initDebug()) {}

I know this if a bit of hack but I figured I would post it anyway.

How to remove entry from $PATH on mac

On MAC OS X Leopard and higher

cd /etc/paths.d

There may be a text file in the above directory that contains the path you are trying to remove.

vim textfile //check and see what is in it when you are done looking type :q 
//:q just quits, no saves

If its the one you want to remove do this

rm textfile //remove it, delete it

Here is a link to a site that has more info on it, even though it illustrates 'adding' the path. However, you may gain some insight.

How to fix homebrew permissions?

try also executing this command

sudo chmod +t /tmp

How do I get list of methods in a Python class?

Say you want to know all methods associated with list class Just Type The following

 print (dir(list))

Above will give you all methods of list class

Maven command to determine which settings.xml file Maven is using

The M2_HOME environment variable for the global one. See Settings Reference:

The settings element in the settings.xml file contains elements used to define values which configure Maven execution in various ways, like the pom.xml, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information. There are two locations where a settings.xml file may live:

  • The Maven install: $M2_HOME/conf/settings.xml
  • A user's install: ${user.home}/.m2/settings.xml

Create instance of generic type in Java?

In Java 8 you can use the Supplier functional interface to achieve this pretty easily:

class SomeContainer<E> {
  private Supplier<E> supplier;

  SomeContainer(Supplier<E> supplier) {
    this.supplier = supplier;
  }

  E createContents() {
    return supplier.get();
  }
}

You would construct this class like this:

SomeContainer<String> stringContainer = new SomeContainer<>(String::new);

The syntax String::new on that line is a constructor reference.

If your constructor takes arguments you can use a lambda expression instead:

SomeContainer<BigInteger> bigIntegerContainer
    = new SomeContainer<>(() -> new BigInteger(1));

How to use CURL via a proxy?

root@APPLICATIOSERVER:/var/www/html# php connectiontest.php
61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#

Post declaring the proxy settings in the php script file issue has been fixed.

$proxy = '10.172.123.1:80';
curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port

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

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

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

Convert NSDate to String in iOS Swift

I always use this code while converting Date to String . (Swift 3)

extension Date
{
    func toString( dateFormat format  : String ) -> String
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }

}

and call like this . .

let today = Date()
today.toString(dateFormat: "dd-MM")

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

Create own colormap using matplotlib and plot color scale

This seems to work for me.

def make_Ramp( ramp_colors ): 
    from colour import Color
    from matplotlib.colors import LinearSegmentedColormap

    color_ramp = LinearSegmentedColormap.from_list( 'my_list', [ Color( c1 ).rgb for c1 in ramp_colors ] )
    plt.figure( figsize = (15,3))
    plt.imshow( [list(np.arange(0, len( ramp_colors ) , 0.1)) ] , interpolation='nearest', origin='lower', cmap= color_ramp )
    plt.xticks([])
    plt.yticks([])
    return color_ramp

custom_ramp = make_Ramp( ['#754a28','#893584','#68ad45','#0080a5' ] ) 

custom color ramp

Sending GET request with Authentication headers using restTemplate

You can use postForObject with an HttpEntity. It would look like this:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+accessToken);

HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String result = restTemplate.postForObject(url, entity, String.class);

In a GET request, you'd usually not send a body (it's allowed, but it doesn't serve any purpose). The way to add headers without wiring the RestTemplate differently is to use the exchange or execute methods directly. The get shorthands don't support header modification.

The asymmetry is a bit weird on a first glance, perhaps this is going to be fixed in future versions of Spring.

Given URL is not allowed by the Application configuration Facebook application error

sometimes you need to check your code (the part of redirect)

$helper = new FacebookRedirectLoginHelper('https://apps.facebook.com/xxx');
$auth_url = $helper->getLoginUrl(array('email', 'publish_actions'));
echo "<script>window.top.location.href='".$auth_url."'</script>";

if any changes happens there (for example, the name of your application "https://apps.facebook.com/xxx" in relation the application settings in facebook, you will get the above error

How to append the output to a file?

Use >> to append:

command >> file

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

The steps you took are not appropriate because the cell you want formatted is not the trigger cell (presumably won't normally be blank). In your case you want formatting to apply to one set of cells according to the status of various other cells. I suggest with data layout as shown in the image (and with thanks to @xQbert for a start on a suitable formula) you select ColumnA and:

HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::

=AND(LEN(E1)*LEN(F1)*LEN(G1)*LEN(H1)=0,NOT(ISBLANK(A1)))

Format..., select formatting, OK, OK.

SO22487695 example

where I have filled yellow the cells that are triggering the red fill result.

Injecting $scope into an angular service function()

Instead of trying to modify the $scope within the service, you can implement a $watch within your controller to watch a property on your service for changes and then update a property on the $scope. Here is an example you might try in a controller:

angular.module('cfd')
    .controller('MyController', ['$scope', 'StudentService', function ($scope, StudentService) {

        $scope.students = null;

        (function () {
            $scope.$watch(function () {
                return StudentService.students;
            }, function (newVal, oldVal) {
                if ( newValue !== oldValue ) {
                    $scope.students = newVal;
                }
            });
        }());
    }]);

One thing to note is that within your service, in order for the students property to be visible, it needs to be on the Service object or this like so:

this.students = $http.get(path).then(function (resp) {
  return resp.data;
});

The entity type <type> is not part of the model for the current context

Put this in your custom DbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Estate>().ToTable("Estate");
}

If your tables are not created on startup, this is why. You need to tell the DbContext about them in the OnModelCreating method override.

You can either do custom per-entity mappings here, or separate them out into separate EntityTypeConfiguration<T> classes.

PHP $_POST not working?

try this
html code

  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
          <input type="text" name="firstname">
          <input type="submit" name="submit" value="Submit">
        </form>

php code:

if(isset($_POST['Submit'])){
$firstname=isset($_POST['firstname'])?$_post['firstname']:"";
echo $firstname;

}

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

If your are using gmail.

  • 1-logon to your account

    2- browse this link

    3- Allow less secure apps: ON

Enjoy....

Does my application "contain encryption"?

I had a lab with App Review team (WWDC20).

My questions were:

  1. My app is making calls through HTTPS only. Should I select Yes or No?
  2. Should I send report to the US government if my app available in Germany only (doesn't available in the USA)?

Answers:

  1. If you just use HTTPS you can select No

  2. The answer on the second question was unclear. Helpful link Looks like yes if you're using custom encryption.

How to use the command update-alternatives --config java

There are many other binaries that need to be linked so I think it's much better to try something like sudo update-alternatives --all and choosing the right alternatives for everything else besides java and javac.

Ignoring SSL certificate in Apache HttpClient 4.3

class ApacheHttpClient {

    /***
     * This is a https get request that bypasses certificate checking and hostname verifier.
     * It uses basis authentication method.
     * It is tested with Apache httpclient-4.4.
     * It dumps the contents of a https page on the console output.
     * It is very similar to http get request, but with the additional customization of
     *   - credential provider, and
     *   - SSLConnectionSocketFactory to bypass certification checking and hostname verifier.
     * @param path String
     * @param username String
     * @param password String
     * @throws IOException
     */
    public void get(String path, String username, String password) throws IOException {
        final CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCredentialsProvider(createCredsProvider(username, password))
                .setSSLSocketFactory(createGenerousSSLSocketFactory())
                .build();

        final CloseableHttpResponse response = httpClient.execute(new HttpGet(path));
        try {
            HttpEntity entity = response.getEntity();
            if (entity == null)
                return;
            System.out.println(EntityUtils.toString(entity));
        } finally {
            response.close();
            httpClient.close();
        }
    }

    private CredentialsProvider createCredsProvider(String username, String password) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));
        return credsProvider;
    }

    /***
     * 
     * @return SSLConnectionSocketFactory that bypass certificate check and bypass HostnameVerifier
     */
    private SSLConnectionSocketFactory createGenerousSSLSocketFactory() {
        SSLContext sslContext;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{createGenerousTrustManager()}, new SecureRandom());
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    }

    private X509TrustManager createGenerousTrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
    }
}

htaccess redirect all pages to single page

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
RewriteRule ^(.*)$ "http://www.thenewdomain.com/" [R=301,L]

How to rename uploaded file before saving it into a directory?

You can Try this,

$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

What is the purpose of "&&" in a shell command?

See the example:

mkdir test && echo "Something" > test/file

Shell will try to create directory test and then, only if it was successfull will try create file inside it.

So you may interrupt a sequence of steps if one of them failed.

Cannot bulk load because the file could not be opened. Operating System Error Code 3

It's probably a permissions issue but you need to make sure to try these steps to troubleshoot:

  • Put the file on a local drive and see if the job works (you don't necessarily need RDP access if you can map a drive letter on your local workstation to a directory on the database server)
  • Put the file on a remote directory that doesn't require username and password (allows Everyone to read) and use the UNC path (\server\directory\file.csv)
  • Configure the SQL job to run as your own username
  • Configure the SQL job to run as sa and add the net use and net use /delete commands before and after

Remember to undo any changes (especially running as sa). If nothing else works, you can try to change the bulk load into a scheduled task, running on the database server or another server that has bcp installed.

How to use EOF to run through a text file in C?

I would suggest you to use fseek-ftell functions.

FILE *stream = fopen("example.txt", "r");

if(!stream) {
    puts("I/O error.\n");
    return;
}

fseek(stream, 0, SEEK_END);
long size = ftell(stream);
fseek(stream, 0, SEEK_SET);

while(1) {

    if(ftell(stream) == size) {
        break;
    }

    /* INSERT ROUTINE */

}

fclose(stream);

How to get span tag inside a div in jQuery and assign a text?

function Errormessage(txt) {
    $("#message").fadeIn("slow");
    $("#message span:first").text(txt);
    // find the span inside the div and assign a text
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
    });
}

Count number of iterations in a foreach loop

count($Contents);

or

sizeof($Contents);

How to use parameters with HttpPost

You can also use this approach in case you want to pass some http parameters and send a json request:

(note: I have added in some extra code just incase it helps any other future readers)

public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {

    //add the http parameters you wish to pass
    List<NameValuePair> postParameters = new ArrayList<>();
    postParameters.add(new BasicNameValuePair("param1", "param1_value"));
    postParameters.add(new BasicNameValuePair("param2", "param2_value"));

    //Build the server URI together with the parameters you wish to pass
    URIBuilder uriBuilder = new URIBuilder("http://google.ug");
    uriBuilder.addParameters(postParameters);

    HttpPost postRequest = new HttpPost(uriBuilder.build());
    postRequest.setHeader("Content-Type", "application/json");

    //this is your JSON string you are sending as a request
    String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";

    //pass the json string request in the entity
    HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
    postRequest.setEntity(entity);

    //create a socketfactory in order to use an http connection manager
    PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);

    connManager.setMaxTotal(20);
    connManager.setDefaultMaxPerRoute(20);

    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setSocketTimeout(HttpClientPool.connTimeout)
            .setConnectTimeout(HttpClientPool.connTimeout)
            .setConnectionRequestTimeout(HttpClientPool.readTimeout)
            .build();

    // Build the http client.
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(connManager)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();

    CloseableHttpResponse response = httpclient.execute(postRequest);

    //Read the response
    String responseString = "";

    int statusCode = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();

    HttpEntity responseHttpEntity = response.getEntity();

    InputStream content = responseHttpEntity.getContent();

    BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
    String line;

    while ((line = buffer.readLine()) != null) {
        responseString += line;
    }

    //release all resources held by the responseHttpEntity
    EntityUtils.consume(responseHttpEntity);

    //close the stream
    response.close();

    // Close the connection manager.
    connManager.close();
}

Chrome doesn't delete session cookies

I just had the same problem with a cookie which was set to expire on "Browsing session end".

Unfortunately it did not so I played a bit with the settings of the browser.

Turned out that the feature that remembers the opened tabs when the browser is closed was the root of the problem. (The feature is named "On startup" - "Continue where I left off". At least on the current version of Chrome).

This also happens with Opera and Firefox.

Replace an element into a specific position of a vector

You can do that using at. You can try out the following simple example:

const size_t N = 20;
std::vector<int> vec(N);
try {
    vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
    std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);

Notice that method at returns an allocator_type::reference, which is that case is a int&. Using at is equivalent to assigning values like vec[i]=....


There is a difference between at and insert as it can be understood with the following example:

const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
    vec[i] = i + 1;
}

vec.insert(vec.begin()+2, 10);

If we now print out vec we will get:

1 2 10 3 4 5 0 0 0

If, instead, we did vec.at(2) = 10, or vec[2]=10, we would get

1 2 10 4 5 0 0 0

a page can have only one server-side form tag

Does your page contain these

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
</asp:content>

tags, and are all your controls inside these? You should only have the Form tags in the MasterPage.


Here are some of my understanding and suggestion:

Html element can be put in the body of html pages and html page does support multiple elements, however they can not be nested each other, you can find the detailed description from the W3C html specification:

The FORM element

http://www.w3.org/MarkUp/html3/forms.html

And as for ASP.NET web form page, it is based on a single server-side form element which contains all the controls inside it, so generally we do not recommend that we put multiple elements. However, this is still supported in ASP.NET page(master page) and I think the problem in your master page should be caused by the unsupported nested element, and multiple in the same level should be ok. e.g:

In addition, if what you want to do through multiple forms is just make our page posting to multiple pages, I think you can consider using the new feature for cross-page posting in ASP.NET 2.0. This can help us use button controls to postback to different pages without having multpile forms on the page:

Cross-Page Posting in ASP.NET Web Pages

http://msdn2.microsoft.com/en-us/lib...39(VS.80).aspx

http://msdn2.microsoft.com/en-us/lib...40(VS.80).aspx

Postgresql SELECT if string contains

I personally prefer the simpler syntax of the ~ operator.

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' ~ tag_name;

Worth reading through Difference between LIKE and ~ in Postgres to understand the difference. `

How do I configure HikariCP in my Spring Boot app in my application.properties files?

I came across HikariCP and I was amazed by the benchmarks and I wanted to try it instead of my default choice C3P0 and to my surprise I struggled to get the configurations right probably because the configurations differ based on what combination of tech stack you are using.

I have setup Spring Boot project with JPA, Web, Security starters (Using Spring Initializer) to use PostgreSQL as a database with HikariCP as connection pooling.
I have used Gradle as build tool and I would like to share what worked for me for the following assumptions:

  1. Spring Boot Starter JPA (Web & Security - optional)
  2. Gradle build too
  3. PostgreSQL running and setup with a database (i.e. schema, user, db)

You need the following build.gradle if you are using Gradle or equivalent pom.xml if you are using maven

buildscript {
    ext {
        springBootVersion = '1.5.8.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

group = 'com'
version = '1.0'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-aop')

    // Exclude the tomcat-jdbc since it's used as default for connection pooling
    // This can also be achieved by setting the spring.datasource.type to HikariCP 
    // datasource see application.properties below
    compile('org.springframework.boot:spring-boot-starter-data-jpa') {
        exclude group: 'org.apache.tomcat', module: 'tomcat-jdbc'
    }
    compile('org.springframework.boot:spring-boot-starter-security')
    compile('org.springframework.boot:spring-boot-starter-web')
    runtime('org.postgresql:postgresql')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.springframework.security:spring-security-test')

    // Download HikariCP but, exclude hibernate-core to avoid version conflicts
    compile('com.zaxxer:HikariCP:2.5.1') {
        exclude group: 'org.hibernate', module: 'hibernate-core'
    }

    // Need this in order to get the HikariCPConnectionProvider
    compile('org.hibernate:hibernate-hikaricp:5.2.11.Final') {
        exclude group: 'com.zaxxer', module: 'HikariCP'
        exclude group: 'org.hibernate', module: 'hibernate-core'
    }
}

There are a bunch of excludes in the above build.gradle and that's because

  1. First exclude, instructs gradle that exclude the jdbc-tomcat connection pool when downloading the spring-boot-starter-data-jpa dependencies. This can be achieved by setting up the spring.datasource.type=com.zaxxer.hikari.HikariDataSource also but, I don't want an extra dependency if I don't need it
  2. Second exclude, instructs gradle to exclude hibernate-core when downloading com.zaxxer dependency and that's because hibernate-core is already downloaded by Spring Boot and we don't want to end up with different versions.
  3. Third exclude, instructs gradle to exclude hibernate-core when downloading hibernate-hikaricp module which is needed in order to make HikariCP use org.hibernate.hikaricp.internal.HikariCPConnectionProvider as connection provider instead of deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider

Once I figured out the build.gradle and what to keep and what to not, I was ready to copy/paste a datasource configuration into my application.properties and expected everything to work with flying colors but, not really and I stumbled upon the following issues

  • Spring boot failing to find out database details (i.e. url, driver) hence, not able to setup jpa and hibernate (because I didn't name the property key values right)
  • HikariCP falling back to com.zaxxer.hikari.hibernate.HikariConnectionProvider
  • After instructing Spring to use new connection-provider for when auto-configuring hibernate/jpa then HikariCP failed because it was looking for some key/value in the application.properties and was complaining about dataSource, dataSourceClassName, jdbcUrl. I had to debug into HikariConfig, HikariConfigurationUtil, HikariCPConnectionProvider and found out that HikariCP could not find the properties from application.properties because it was named differently.

Anyway, this is where I had to rely on trial and error and make sure that HikariCP is able to pick the properties (i.e. data source that's db details, as well as pooling properties) as well as Sping Boot behave as expected and I ended up with the following application.properties file.

server.contextPath=/
debug=true

# Spring data source needed for Spring boot to behave
# Pre Spring Boot v2.0.0.M6 without below Spring Boot defaults to tomcat-jdbc connection pool included 
# in spring-boot-starter-jdbc and as compiled dependency under spring-boot-starter-data-jpa
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:postgresql://localhost:5432/somedb
spring.datasource.username=dbuser
spring.datasource.password=dbpassword

# Hikari will use the above plus the following to setup connection pooling
spring.datasource.hikari.minimumIdle=5
spring.datasource.hikari.maximumPoolSize=20
spring.datasource.hikari.idleTimeout=30000
spring.datasource.hikari.poolName=SpringBootJPAHikariCP
spring.datasource.hikari.maxLifetime=2000000
spring.datasource.hikari.connectionTimeout=30000

# Without below HikariCP uses deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider
# Surprisingly enough below ConnectionProvider is in hibernate-hikaricp dependency and not hibernate-core
# So you need to pull that dependency but, make sure to exclude it's transitive dependencies or you will end up 
# with different versions of hibernate-core 
spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider

# JPA specific configs
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql=true
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.jpa.properties.hibernate.default_schema=dbschema
spring.jpa.properties.hibernate.search.autoregister_listeners=false
spring.jpa.properties.hibernate.bytecode.use_reflection_optimizer=false

# Enable logging to verify that HikariCP is used, the second entry is specific to HikariCP
logging.level.org.hibernate.SQL=DEBUG
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE 

As shown above the configurations are divided into categories based on following naming patterns

  • spring.datasource.x (Spring auto-configure will pick these, so will HikariCP)
  • spring.datasource.hikari.x (HikariCP picks these to setup the pool, make a note of the camelCase field names)
  • spring.jpa.hibernate.connection.provider_class (Instructs Spring to use new HibernateConnectionProvider)
  • spring.jpa.properties.hibernate.x (Used by Spring to auto-configure JPA, make a note of the field names with underscores)

It's hard to come across a tutorial or post or some resource that shows how the above properties file is used and how the properties should be named. Well, there you have it.

Throwing the above application.properties with build.gradle (or at least similar) into a Spring Boot JPA project version (1.5.8) should work like a charm and connect to your pre-configured database (i.e. in my case it's PostgreSQL that both HikariCP & Spring figure out from the spring.datasource.url on which database driver to use).

I did not see the need to create a DataSource bean and that's because Spring Boot is capable of doing everything for me just by looking into application.properties and that's neat.

The article in HikariCP's github wiki shows how to setup Spring Boot with JPA but, lacks explanation and details.

The above two file is also availble as a public gist https://gist.github.com/rhamedy/b3cb936061cc03acdfe21358b86a5bc6

What is the difference between public, protected, package-private and private in Java?

The most misunderstood access modifier in Java is protected. We know that it's similar to the default modifier with one exception in which subclasses can see it. But how? Here is an example which hopefully clarifies the confusion:

  • Assume that we have 2 classes; Father and Son, each in its own package:

    package fatherpackage;
    
    public class Father
    {
    
    }
    
    -------------------------------------------
    
    package sonpackage;
    
    public class Son extends Father
    {
    
    }
    
  • Let's add a protected method foo() to Father.

    package fatherpackage;
    
    public class Father
    {
        protected void foo(){}
    }
    
  • The method foo() can be called in 4 contexts:

    1. Inside a class that is located in the same package where foo() is defined (fatherpackage):

      package fatherpackage;
      
      public class SomeClass
      {
          public void someMethod(Father f, Son s)
          {
              f.foo();
              s.foo();
          }
      }
      
    2. Inside a subclass, on the current instance via this or super:

      package sonpackage;
      
      public class Son extends Father
      {
          public void sonMethod()
          {
              this.foo();
              super.foo();
          }
      }
      
    3. On an reference whose type is the same class:

      package fatherpackage;
      
      public class Father
      {
          public void fatherMethod(Father f)
          {
              f.foo(); // valid even if foo() is private
          }
      }
      
      -------------------------------------------
      
      package sonpackage;
      
      public class Son extends Father
      {
          public void sonMethod(Son s)
          {
              s.foo();
          }
      }
      
    4. On an reference whose type is the parent class and it is inside the package where foo() is defined (fatherpackage) [This can be included inside context no. 1]:

      package fatherpackage;
      
      public class Son extends Father
      {
          public void sonMethod(Father f)
          {
              f.foo();
          }
      }
      
  • The following situations are not valid.

    1. On an reference whose type is the parent class and it is outside the package where foo() is defined (fatherpackage):

      package sonpackage;
      
      public class Son extends Father
      {
          public void sonMethod(Father f)
          {
              f.foo(); // compilation error
          }
      }
      
    2. A non-subclass inside a package of a subclass (A subclass inherits the protected members from its parent, and it makes them private to non-subclasses):

      package sonpackage;
      
      public class SomeClass
      {
          public void someMethod(Son s) throws Exception
          {
              s.foo(); // compilation error
          }
      }
      

How to write MySQL query where A contains ( "a" or "b" )

I user for searching the size of motorcycle :

For example : Data = "Tire cycle size 70 / 90 - 16"

i can search with "70 90 16"

$searchTerms = preg_split("/[\s,-\/?!]+/", $itemName);

foreach ($searchTerms as $term) {
        $term = trim($term);
            if (!empty($term)) {
            $searchTermBits[] = "name LIKE '%$term%'";
            }
        }

$query = "SELECT * FROM item WHERE " .implode(' AND ', $searchTermBits);

Failed to start mongod.service: Unit mongod.service not found

For Ubuntu 16.04.5, it is noticed that MongoDB installations does not auto enable the mongod.service file after installation in my case after I have installed on several servers, so we need to enable it like below:

Issue below to check whether mongod is enabled

systemctl list-unit-files --type=service

If it shows as "disabled", then you need to enable it.

sudo systemctl enable mongod.service

If we want to see whether mongod.service file exists in case this file is missing, check in

ls /lib/systemd/system

You will see a file

/lib/systemd/system/mongod.service

Windows command to convert Unix line endings?

I cloned my git project using the git bash on windows. All the files then had LF endings. Our repository has CRLF endings as default.

I deleted the project, and then cloned it again using the Windows Command Prompt. The CRLF endings were intact then. In my case, if I had changed the endings for the project, then it would've resulted in a huge commit and would've caused trouble for my teammates. So, did it this way. Hope this helps somebody.

How to open an Excel file in C#?

It's easier to help you if you say what's wrong as well, or what fails when you run it.

But from a quick glance you've confused a few things.

The following doesn't work because of a couple of issues.

if (Directory("C:\\csharp\\error report1.xls") = "")

What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.

What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).

What you should do (for this line at least) is the following

FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
    // Create the xl file here
}
else
{
    // Open file here
}

As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.

How can I kill a process by name instead of PID?

The default kill command accepts command names as an alternative to PID. See kill (1). An often occurring trouble is that bash provides its own kill which accepts job numbers, like kill %1, but not command names. This hinders the default command. If the former functionality is more useful to you than the latter, you can disable the bash version by calling

enable -n kill

For more info see kill and enable entries in bash (1).

Which concurrent Queue implementation should I use in Java?

Your question title mentions Blocking Queues. However, ConcurrentLinkedQueue is not a blocking queue.

The BlockingQueues are ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, and SynchronousQueue.

Some of these are clearly not fit for your purpose (DelayQueue, PriorityBlockingQueue, and SynchronousQueue). LinkedBlockingQueue and LinkedBlockingDeque are identical, except that the latter is a double-ended Queue (it implements the Deque interface).

Since ArrayBlockingQueue is only useful if you want to limit the number of elements, I'd stick to LinkedBlockingQueue.

Call to undefined method mysqli_stmt::get_result

I realize that it's been a while since there has been any new activity on this question. But, as other posters have commented - get_result() is now only available in PHP by installing the MySQL native driver (mysqlnd), and in some cases, it may not be possible or desirable to install mysqlnd. So, I thought it would be helpful to post this answer with info on how get the functionality that get_result() offers - without using get_result().

get_result() is/was often combined with fetch_array() to loop through a result set and store the values from each row of the result set in a numerically-indexed or associative array. For example, the code below uses get_result() with fetch_array() to loop through a result set, storing the values from each row in the numerically-indexed $data[] array:

$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);                 
$stmt->bind_param('i', $c);                                             
$stmt->execute();
$result = $stmt->get_result();       
while($data = $result->fetch_array(MYSQLI_NUM)) {
   print $data[0] . ', ' . $data[1] . "<BR>\n"; 
}

However, if get_result() is not available (because mysqlnd is not installed), then this leads to the problem of how to store the values from each row of a result set in an array, without using get_result(). Or, how to migrate legacy code that uses get_result() to run without it (e.g. using bind_result() instead) - while impacting the rest of the code as little as possible.

It turns out that storing the values from each row in a numerically-indexed array is not so straight-forward using bind_result(). bind_result() expects a list of scalar variables (not an array). So, it takes some doing to make it store the values from each row of the result set in an array.

Of course, the code could easily be modified as follows:

$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);                 
$stmt->bind_param('i', $c);                                             
$stmt->execute();
$stmt->bind_result($data[0], $data[1]);
while ($stmt->fetch()) {
   print $data[0] . ', ' . $data[1] . "<BR>\n"; 
}

But, this requires us to explicitly list $data[0], $data[1], etc. individually in the call to bind_result(), which is not ideal. We want a solution that doesn't require us to have to explicitly list $data[0], $data[1], ... $data[N-1] (where N is the number of fields in the select statement) in the call to bind_results(). If we're migrating a legacy application that has a large number of queries, and each query may contain a different number of fields in the select clause, the migration will be very labor intensive and prone to error if we use a solution like the one above.

Ideally, we want a snippet of 'drop-in replacement' code - to replace just the line containing the get_result() function and the while() loop on the next line. The replacement code should have the same function as the code that it's replacing, without affecting any of the lines before, or any of the lines after - including the lines inside the while() loop. Ideally we want the replacement code to be as compact as possible, and we don't want to have to taylor the replacement code based on the number of fields in the select clause of the query.

Searching on the internet, I found a number of solutions that use bind_param() with call_user_func_array() (for example, Dynamically bind mysqli_stmt parameters and then bind result (PHP)), but most solutions that I found eventually lead to the results being stored in an associative array, not a numerically-indexed array, and many of these solutions were not as compact as I would like and/or were not suited as 'drop-in replacements'. However, from the examples that I found, I was able to cobble together this solution, which fits the bill:

$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);                 
$stmt->bind_param('i', $c);                                             
$stmt->execute();
$data=array();
for ($i=0;$i<$mysqli->field_count;$i++) { 
    $var = $i;
    $$var = null; 
    $data[$var] = &$$var; 
}
call_user_func_array(array($stmt,'bind_result'), $data);
while ($stmt->fetch()) {
   print $data[0] . ', ' . $data[1] . "<BR>\n"; 
}

Of course, the for() loop can be collapsed into one line to make it more compact.

I hope this helps anyone who is looking for a solution using bind_result() to store the values from each row in a numerically-indexed array and/or looking for a way to migrate legacy code using get_result(). Comments welcome.

jquery mobile background image

my experience:

in some situations the background image url have to be put separately for all page parts - I use:

var bgImageUrl = "url(../thirdparty/icons/android-circuit.jpg)";

...

$('#indexa').live('pageinit', function() {

   $("#indexa").css("background-image",bgImageUrl);
   $("#contenta").css("background-image",bgImageUrl);
   $("#footera").css("background-image",bgImageUrl);
   ...
}

where "indexa" is the id of the whole page, and the "contenta" and "footera" are id-s of the content and footer respectively.

This works for sure in PhoneGap + jQuery Mobile

Allow docker container to connect to a local/host postgres database

Simple Solution for mac:

The newest version of docker (18.03) offers a built in port forwarding solution. Inside your docker container simply have the db host set to host.docker.internal. This will be forwarded to the host the docker container is running on.

Documentation for this is here: https://docs.docker.com/docker-for-mac/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host

Java null check why use == instead of .equals()

According to sources it doesn't matter what to use for default method implementation:

public boolean equals(Object object) {
    return this == object;
}

But you can't be sure about equals in custom class.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.

That is neither a good idea in terms of peformance nor in terms of fail-safety.

Don't poach on the Connection-Pool's territory

There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.

So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.

If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).

Conclusion:

  • Don't reuse connections or any ADO.NET objects at all.
  • Don't make them static/shared(in VB.NET)
  • Always create, open(in case of Connections), use, close and dispose them where you need them(f.e. in a method)
  • use the using-statement to dispose and close(in case of Connections) implicitely

That's true not only for Connections(although most noticable). Every object implementing IDisposable should be disposed(simplest by using-statement), all the more in the System.Data.SqlClient namespace.

All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.


Edit: Here's a possible implementation of your retrievePromotion-method:

public Promotion retrievePromotion(int promotionID)
{
    Promotion promo = null;
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
        using (var da = new SqlDataAdapter(queryString, connection))
        {
            // you could also use a SqlDataReader instead
            // note that a DataTable does not need to be disposed since it does not implement IDisposable
            var tblPromotion = new DataTable();
            // avoid SQL-Injection
            da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
            da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
            try
            {
                connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise 
                da.Fill(tblPromotion);
                if (tblPromotion.Rows.Count != 0)
                {
                    var promoRow = tblPromotion.Rows[0];
                    promo = new Promotion()
                    {
                        promotionID    = promotionID,
                        promotionTitle = promoRow.Field<String>("PromotionTitle"),
                        promotionUrl   = promoRow.Field<String>("PromotionURL")
                    };
                }
            }
            catch (Exception ex)
            {
                // log this exception or throw it up the StackTrace
                // we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
                throw;
            }
        }
    }
    return promo;
}

What are the use cases for selecting CHAR over VARCHAR in SQL?

There are performance benefits, but here is one that has not been mentioned: row migration. With char, you reserve the entire space in advance.So let's says you have a char(1000), and you store 10 characters, you will use up all 1000 charaters of space. In a varchar2(1000), you will only use 10 characters. The problem comes when you modify the data. Let's say you update the column to now contain 900 characters. It is possible that the space to expand the varchar is not available in the current block. In that case, the DB engine must migrate the row to another block, and make a pointer in the original block to the new row in the new block. To read this data, the DB engine will now have to read 2 blocks.
No one can equivocally say that varchar or char are better. There is a space for time tradeoff, and consideration of whether the data will be updated, especially if there is a good chance that it will grow.

javac is not recognized as an internal or external command, operable program or batch file

Run the following from the command prompt: set Path="C:\Program Files\Java\jdk1.7.0_09\bin" or set PATH="C:\Program Files\Java\jdk1.7.0_09\bin"

I have tried this and it works well.

NULL vs nullptr (Why was it replaced?)

You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:

This problem falls into the following categories:

  • Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types.

  • Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.

  • Make C++ easier to teach and learn.

Servlet for serving static content

I've had good results with FileServlet, as it supports pretty much all of HTTP (etags, chunking, etc.).

How to create an empty array in PHP with predefined size?

There is also array_pad. You can use it like this:

$data = array_pad($data,$number_of_items,0);

For initializing with zeros the $number_of_items positions of the array $data.

HTTP Error 500.19 and error code : 0x80070021

In my case, there were rules for IIS URL Rewrite module but I didn't have that module installed. You should check your web.config if there are any modules included but not installed.

Should CSS always preceed Javascript?

I think this wont be true for all the cases. Because css will download parallel but js cant. Consider for the same case,

Instead of having single css, take 2 or 3 css files and try it out these ways,

1) css..css..js 2) css..js..css 3) js..css..css

I'm sure css..css..js will give better result than all others.

AngularJS view not updating on model change

As Ajay beniwal mentioned above you need to use Apply to start digestion.

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

app.controller('TestCtrl', function ($scope) {
   $scope.testValue = 0;

    setInterval(function() {
        console.log($scope.testValue++);
        $scope.$apply() 
    }, 500);
});

Insert multiple lines into a file after specified pattern using shell script

Using GNU sed:

sed "/cdef/aline1\nline2\nline3\nline4" input.txt

If you started with:

abcd
accd
cdef
line
web

this would produce:

abcd
accd
cdef
line1
line2
line3
line4
line
web

If you want to save the changes to the file in-place, say:

sed -i "/cdef/aline1\nline2\nline3\nline4" input.txt

How to find the Center Coordinate of Rectangle?

We can calculate using mid point of line formula,

centre (x,y) =  new Point((boundRect.tl().x+boundRect.br().x)/2,(boundRect.tl().y+boundRect.br().y)/2)

Storing files in SQL Server

There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.

There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)

The article is definitely worth a read.

Is null check needed before calling instanceof?

No, a null check is not needed before using instanceof.

The expression x instanceof SomeClass is false if x is null.

From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":

"At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false."

So if the operand is null, the result is false.

Activity restart on rotation Android

 onConfigurationChanged is called when the screen rotates. 
 (onCreate is no longer called when screen rotates due to manifest, see:  
 android:configChanges)

What part of the manifest tells it "don't call onCreate()"?

Also, Google's docs say to avoid using android:configChanges (except as a last resort).... But then the alternate methods they suggest all DO use android:configChanges.

It has been my experience that the emulator ALWAYS calls onCreate() upon rotation.
But the 1-2 devices that I run the same code on... do not. (Not sure why there would be any difference.)

How to set selectedIndex of select element using display text?

You can use the HTMLOptionsCollection.namedItem() That means that you have to define your select options to have a name attribute and have the value of the displayed text. e.g California

Create zip file and ignore directory structure

Using -j won't work along with the -r option.
So the work-around for it can be this:

cd path/to/parent/dir/;
zip -r complete/path/to/name.zip ./* ;
cd -;

Or in-line version

cd path/to/parent/dir/ && zip -r complete/path/to/name.zip ./* && cd -

you can direct the output to /dev/null if you don't want the cd - output to appear on screen

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Add an = at the beginning. That makes it a function rather than an entry.

byte[] to hex string

I thought I should provide an answer. From my test this method is the fastest

public static class Helper
{
    public static string[] HexTbl = Enumerable.Range(0, 256).Select(v => v.ToString("X2")).ToArray();
    public static string ToHex(this IEnumerable<byte> array)
    {
        StringBuilder s = new StringBuilder();
        foreach (var v in array)
            s.Append(HexTbl[v]);
        return s.ToString();
    }
    public static string ToHex(this byte[] array)
    {
        StringBuilder s = new StringBuilder(array.Length*2);
        foreach (var v in array)
            s.Append(HexTbl[v]);
        return s.ToString();
    }
}

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

For those who on a mac with the same issue and installed npm via homebrew:

brew uninstall npm

then

brew install npm

Works for me on osx (10.9.1)

EDIT: You may need to brew update before installing npm. You can also do a brew upgrade after updating homebrew. Also it might be helpful to run brew doctor if you run into any other issues.

How can I submit form on button click when using preventDefault()?

Ok, first e.preventDefault(); it's not a Jquery element, it's a method of javascript, now what it's true it's if you add this method you avoid the submit the event, now what you could do it's send the form by ajax something like this

$('#subscription_order_form').submit(function(e){
    $.ajax({
     url: $(this).attr('action'),
     data : $(this).serialize(),
     success : function (data){

      }
   });
    e.preventDefault();
});

Attaching click to anchor tag in angular

<a href="#" (click)="onGoToPage2()">Go to page 2</a>

Does the join order matter in SQL?

Oracle optimizer chooses join order of tables for inner join. Optimizer chooses the join order of tables only in simple FROM clauses . U can check the oracle documentation in their website. And for the left, right outer join the most voted answer is right. The optimizer chooses the optimal join order as well as the optimal index for each table. The join order can affect which index is the best choice. The optimizer can choose an index as the access path for a table if it is the inner table, but not if it is the outer table (and there are no further qualifications).

The optimizer chooses the join order of tables only in simple FROM clauses. Most joins using the JOIN keyword are flattened into simple joins, so the optimizer chooses their join order.

The optimizer does not choose the join order for outer joins; it uses the order specified in the statement.

When selecting a join order, the optimizer takes into account: The size of each table The indexes available on each table Whether an index on a table is useful in a particular join order The number of rows and pages to be scanned for each table in each join order

Correct way to pause a Python program

I have had a similar question and I was using signal:

import signal

def signal_handler(signal_number, frame):
    print "Proceed ..."

signal.signal(signal.SIGINT, signal_handler)
signal.pause()

So you register a handler for the signal SIGINT and pause waiting for any signal. Now from outside your program (e.g. in bash), you can run kill -2 <python_pid>, which will send signal 2 (i.e. SIGINT) to your python program. Your program will call your registered handler and proceed running.

Creating a static class with no instances

You could use a classmethod or staticmethod

class Paul(object):
    elems = []

    @classmethod
    def addelem(cls, e):
        cls.elems.append(e)

    @staticmethod
    def addelem2(e):
        Paul.elems.append(e)

Paul.addelem(1)
Paul.addelem2(2)

print(Paul.elems)

classmethod has advantage that it would work with sub classes, if you really wanted that functionality.

module is certainly best though.

Where do I put image files, css, js, etc. in Codeigniter?

I'm using the latest version of CodeIgniter 3.1.0. The folder structure of it is:

  • system
  • application
  • user_guide
  • assets
    • images
    • js
    • css

That's where you should put the images, css and js files inside the assets folder.

Set Google Maps Container DIV width and height 100%

Better late than never! I made mine a class:

.map
{
    position:absolute;
    top:64px;
    width:1100px;
    height:735px;
    overflow:hidden;
    border:1px solid rgb(211,211,211);
    border-radius:3px;
}

and then

<div id="map" class="map"></div>

How to write a multidimensional array to a text file?

There exist special libraries to do just that. (Plus wrappers for python)

hope this helps

javascript object max size limit

There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.

The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.

To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.

Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:

var items = $.map(keys, function(item, i) {
  var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
  return
    '{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
    '" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
});
var jsonObj =
  '{"code":"' + code + '",'+
  '"defaultfile":"' + defaultfile + '",'+
  '"filename":"' + currentFile + '",'+
  '"lstResDef":[' + items.join(',') + ']}';

How to get city name from latitude and longitude coordinates in Google Maps?

You can use this if you have a list:

Address address = list.get(0);
String cityname = address.getLocality();

How do I reformat HTML code using Sublime Text 2?

I'm using tidy together with custom build system to prettify HTML.

I have HTMLTidy.sublime-build in my Packages/User/ directory:

{
  "cmd": ["tidy", "-config", "$packages/User/tidy_config.cfg", "$file"]
}

and tidy_config.cfg file in the same directory:

indent: auto
tab-size: 4
show-warnings: no
write-back: yes
quiet: yes
indent-cdata: yes
tidy-mark: no
wrap: 0

And just select build system and press ctrl+b or cmd+b to reformat file content. One minor issue with that is that ST2 does not automatically reload the file so to see the results you have to switch to some other file and back (or to other application and back).

On Mac I've used macports to install tidy, on Windows you'd have to download it yourself and specify working directory in the build system, where tidy is located:

"working_dir": "c:\\HTMLTidy\\"

or add it to the PATH.

http to https through .htaccess

None of these worked for me, except for this. My site was hosted in https://www.asmallorange.com

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Usage of unicode() and encode() functions in Python

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

What's the best way to set a single pixel in an HTML5 canvas?

Fast and handy

Following class implements fast method described in this article and contains all you need: readPixel, putPixel, get width/height. Class update canvas after calling refresh() method. Example solve simple case of 2d wave equation

_x000D_
_x000D_
class Screen{
  constructor(canvasSelector) {
    this.canvas = document.querySelector(canvasSelector);
    this.width  = this.canvas.width;
    this.height = this.canvas.height;
    this.ctx = this.canvas.getContext('2d');
    this.imageData = this.ctx.getImageData(0, 0, this.width, this.height);
    this.buf = new ArrayBuffer(this.imageData.data.length);
    this.buf8 = new Uint8ClampedArray(this.buf);
    this.data = new Uint32Array(this.buf);  
  }
  
  // r,g,b,a - red, gren, blue, alpha components in range 0-255
  putPixel(x,y,r,g,b,a=255) {
    this.data[y * this.width + x] = (a<<24) | (b<<16) | (g<<8) | r;
  }
  
  readPixel(x,y) {
    let p= this.data[y * this.width + x]
    return [p&0xff, p>>8&0xff, p>>16&0xff, p>>>24];
  }

  refresh() {
    this.imageData.data.set(this.buf8);
    this.ctx.putImageData(this.imageData, 0, 0);
  }
}




// --------
// TEST
// --------

let s= new Screen('#canvas');                // initialise

function draw() {

  for (var y = 1; y < s.height-1; ++y) {
    for (var x = 1; x < s.width-1; ++x) {      
      let a = [[1,0],[-1,0],[0,1],[0,-1]].reduce((a,[xp,yp])=> 
        a+= s.readPixel(x+xp,y+yp)[0]        // read pixel
      ,0);
      let v= a/1.99446-tmp[x][y];
      tmp[x][y]=v<0 ? 0:v;
    }
  }

  for (var y = 1; y < s.height-1; ++y) {
    for (var x = 1; x < s.width-1; ++x) {  
      let v=tmp[x][y];
      tmp[x][y]= s.readPixel(x,y)[0];        // read pixel
      s.putPixel(x,y, v,0,0);                // put pixel
    }
  }

  s.refresh(); 
  frame++;
  window.requestAnimationFrame(draw)
}

// temporary 2d buffer ()for solving wave equation)
let tmp = [...Array(s.width)].map(x => Array(s.height).fill(0));

function move(e) { s.putPixel(e.x-10, e.y-10, 255,255,255);}

draw();
_x000D_
<canvas id="canvas" height="150" width="512" onmousemove="move(event)"></canvas>
<div>Move mouse on black square</div>
_x000D_
_x000D_
_x000D_

TextView Marquee not working

These attributes must be included in the textview tag in order to allow scrolling.

Everything else is optional.

android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="fill_parent"
android:ellipsize="marquee"

How do I select the parent form based on which submit button is clicked?

To get the form that the submit is inside why not just

this.form

Easiest & quickest path to the result.

Java: notify() vs. notifyAll() all over again

Short summary:

Always prefer notifyAll() over notify() unless you have a massively parallel application where a large number of threads all do the same thing.

Explanation:

notify() [...] wakes up a single thread. Because notify() doesn't allow you to specify the thread that is woken up, it is useful only in massively parallel applications — that is, programs with a large number of threads, all doing similar chores. In such an application, you don't care which thread gets woken up.

source: https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

Compare notify() with notifyAll() in the above described situation: a massively parallel application where threads are doing the same thing. If you call notifyAll() in that case, notifyAll() will induce the waking up (i.e. scheduling) of a huge number of threads, many of them unnecessarily (since only one thread can actually proceed, namely the thread which will be granted the monitor for the object wait(), notify(), or notifyAll() was called on), therefore wasting computing resources.

Thus, if you don't have an application where a huge number of threads do the same thing concurrently, prefer notifyAll() over notify(). Why? Because, as other users have already answered in this forum, notify()

wakes up a single thread that is waiting on this object's monitor. [...] The choice is arbitrary and occurs at the discretion of the implementation.

source: Java SE8 API (https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notify--)

Imagine you have a producer consumer application where consumers are ready (i.e. wait() ing) to consume, producers are ready (i.e. wait() ing) to produce and the queue of items (to be produced / consumed) is empty. In that case, notify() might wake up only consumers and never producers because the choice who is waken up is arbitrary. The producer consumer cycle wouldn't make any progress although producers and consumers are ready to produce and consume, respectively. Instead, a consumer is woken up (i.e. leaving the wait() status), doesn't take an item out of the queue because it's empty, and notify() s another consumer to proceed.

In contrast, notifyAll() awakens both producers and consumers. The choice who is scheduled depends on the scheduler. Of course, depending on the scheduler's implementation, the scheduler might also only schedule consumers (e.g. if you assign consumer threads a very high priority). However, the assumption here is that the danger of the scheduler scheduling only consumers is lower than the danger of the JVM only waking up consumers because any reasonably implemented scheduler doesn't make just arbitrary decisions. Rather, most scheduler implementations make at least some effort to prevent starvation.

How can I clear the NuGet package cache using the command line?

You can use PowerShell too (same as me).

For example:

rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg

Or 'quiet' mode (without error messages):

rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg 2> $null

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

for (const field in this.formErrors) {
  if (this.formErrors.hasOwnProperty(field)) {
for (const key in control.errors) {
  if (control.errors.hasOwnProperty(key)) {

Is there any way I can define a variable in LaTeX?

If you want to use \newcommand, you can also include \usepackage{xspace} and define command by \newcommand{\newCommandName}{text to insert\xspace}. This can allow you to just use \newCommandName rather than \newCommandName{}.

For more detail, http://www.math.tamu.edu/~harold.boas/courses/math696/why-macros.html

Returning JSON from PHP to JavaScript?

You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.

It looks like :

<?php
// Include the json class
include('includes/json.php');

// Then create the PHP-Json Object to suits your needs

// Set a variable ; var name = {}
$Json = new json('var', 'name'); 
// Fire a callback ; callback({});
$Json = new json('callback', 'name'); 
// Just send a raw JSON ; {}
$Json = new json();

// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';

// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);

// Finally, send the JSON.

$Json->send();
?>

Maven: Failed to read artifact descriptor

I had a similar problem. In my case, the version of testng in my .m2/repositories folder was corrupt, but when I deleted it & did a maven update again, everything worked fine.

Vue.js—Difference between v-model and v-bind

v-model
it is two way data binding, it is used to bind html input element when you change input value then bounded data will be change.

v-model is used only for HTML input elements

ex: <input type="text" v-model="name" > 

v-bind
it is one way data binding,means you can only bind data to input element but can't change bounded data changing input element. v-bind is used to bind html attribute
ex:
<input type="text" v-bind:class="abc" v-bind:value="">

<a v-bind:href="home/abc" > click me </a>

How do I test a website using XAMPP?

Make a new folder inside htdocs and access it in browser.Like this or this. Always start Apache when you start working or check whether it has started (in Control panel of xampp).

Span inside anchor or anchor inside span or doesn't matter?

SPAN is a GENERIC inline container. It does not matter whether an a is inside span or span is inside a as both are inline elements. Feel free to do whatever seems logically correct to you.

How to utilize date add function in Google spreadsheet?

You can use the DATE(Year;Month;Day) to make operations on date:

Examples:

=DATE(2013;3;8 + 30) give the result...  7 april 2013 !
=DATE(2013;3 + 15; 8) give the result... 8 june 2014 !

It's very surprising but it works...

MySQL WHERE: how to write "!=" or "not equals"?

You may be using old version of Mysql but surely you can use

 DELETE FROM konta WHERE taken <> ''

But there are many other options available. You can try the following ones

DELETE * from konta WHERE strcmp(taken, '') <> 0;

DELETE * from konta where NOT (taken = '');

Twitter Bootstrap alert message close and open again

Based on the other answers and changing data-dismiss to data-hide, this example handles opening the alert from a link and allows the alert to be opened and closed repeatedly

$('a.show_alert').click(function() {
    var $theAlert = $('.my_alert'); /* class on the alert */
    $theAlert.css('display','block');
   // set up the close event when the alert opens
   $theAlert.find('a[data-hide]').click(function() {
     $(this).parent().hide(); /* hide the alert */
   });
});

Vertical Alignment of text in a table cell

valign="top" should do the work.

_x000D_
_x000D_
<tr>_x000D_
  <td valign="top">Description</td>_x000D_
</tr>
_x000D_
_x000D_
_x000D_

Need a good hex editor for Linux

Personally, I use Emacs with hexl-mod.

Emacs is able to work with really huge files. You can use search/replace value easily. Finally, you can use 'ediff' to do some diffs.

Disable LESS-CSS Overwriting calc()

Example for escaped string with variable:

@some-variable-height: 10px;

...

div {
    height: ~"calc(100vh - "@some-variable-height~")";
}

compiles to

div {
    height: calc(100vh - 10px );
}

How do I hide the PHP explode delimiter from submitted form results?

Instead of adding the line breaks with nl2br() and then removing the line breaks with explode(), try using the line break character '\r' or '\n' or '\r\n'.

<?php     $options= file_get_contents("employees.txt");     $options=explode("\n",$options);        // try \r as well.      foreach ($options as $singleOption){         echo "<option value='".$singleOption."'>".$singleOption."</option>";     }   ?> 

This could also fix the issue if the problem was due to Google Spreadsheets reading the line breaks.

Are Git forks actually Git clones?

I keep hearing people say they're forking code in git. Git "fork" sounds suspiciously like git "clone" plus some (meaningless) psychological willingness to forgo future merges. There is no fork command in git, right?

"Forking" is a concept, not a command specifically supported by any version control system.

The simplest kind of forking is synonymous with branching. Every time you create a branch, regardless of your VCS, you've "forked". These forks are usually pretty easy to merge back together.

The kind of fork you're talking about, where a separate party takes a complete copy of the code and walks away, necessarily happens outside the VCS in a centralized system like Subversion. A distributed VCS like Git has much better support for forking the entire codebase and effectively starting a new project.

Git (not GitHub) natively supports "forking" an entire repo (ie, cloning it) in a couple of ways:

  • when you clone, a remote called origin is created for you
  • by default all the branches in the clone will track their origin equivalents
  • fetching and merging changes from the original project you forked from is trivially easy

Git makes contributing changes back to the source of the fork as simple as asking someone from the original project to pull from you, or requesting write access to push changes back yourself. This is the part that GitHub makes easier, and standardizes.

Any angst over Github extending git in this direction? Or any rumors of git absorbing the functionality?

There is no angst because your assumption is wrong. GitHub "extends" the forking functionality of Git with a nice GUI and a standardized way of issuing pull requests, but it doesn't add the functionality to Git. The concept of full-repo-forking is baked right into distributed version control at a fundamental level. You could abandon GitHub at any point and still continue to push/pull projects you've "forked".

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

In some cases (like poorly designed iterators), the class needs to keep a count or some other incidental value, that doesn't really affect the major "state" of the class. This is most often where I see mutable used. Without mutable, you'd be forced to sacrifice the entire const-ness of your design.

It feels like a hack most of the time to me as well. Useful in a very very few situations.

How do I log a Python error with debug information?

Quoting

What if your application does logging some other way – not using the logging module?

Now, traceback could be used here.

import traceback

def log_traceback(ex, ex_traceback=None):
    if ex_traceback is None:
        ex_traceback = ex.__traceback__
    tb_lines = [ line.rstrip('\n') for line in
                 traceback.format_exception(ex.__class__, ex, ex_traceback)]
    exception_logger.log(tb_lines)
  • Use it in Python 2:

    try:
        # your function call is here
    except Exception as ex:
        _, _, ex_traceback = sys.exc_info()
        log_traceback(ex, ex_traceback)
    
  • Use it in Python 3:

    try:
        x = get_number()
    except Exception as ex:
        log_traceback(ex)
    

Refreshing data in RecyclerView and keeping its scroll position

1- You need to save scroll position like this

rvProduct.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                recyclerViewState = rvProduct.getLayoutManager().onSaveInstanceState(); // save recycleView state
            }
        });

2- And after you call notifyDataSetChanged then onRestoreInstanceState like this example

productsByBrandAdapter.addData(productCompareList);
productsByBrandAdapter.notifyDataSetChanged();
rvProduct.getLayoutManager().onRestoreInstanceState(recyclerViewState); // restore recycleView state

File Not Found when running PHP with Nginx

For me, problem was Typo in location path.

Maybe first thing to check out for this kind of problem

Is path to project.