Programs & Examples On #Database mirroring

Class constructor type in typescript?

How can I declare a class type, so that I ensure the object is a constructor of a general class?

A Constructor type could be defined as:

 type AConstructorTypeOf<T> = new (...args:any[]) => T;

 class A { ... }

 function factory(Ctor: AConstructorTypeOf<A>){
   return new Ctor();
 }

const aInstance = factory(A);

Compare two Byte Arrays? (Java)

Check out the static java.util.Arrays.equals() family of methods. There's one that does exactly what you want.

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

You could use a regex, yes, but a simple string.Replace() will probably suffice.

 myString = myString.Replace("\r\n", string.Empty);

How to place a JButton at a desired location in a JFrame using Java

Following line should be called before you add your component

pnlButton.setLayout(null);

Above will set your content panel to use absolute layout. This means you'd always have to set your component's bounds explicitly by using setBounds method.

In general I wouldn't recommend using absolute layout.

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

This worked for me:

I simply cd "C:\the_path_of_the_project_where_package.json_is"

before I ran "npm start"

Use python requests to download CSV

You can update the accepted answer with the iter_lines method of requests if the file is very large

import csv
import requests

CSV_URL = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'

with requests.Session() as s:
    download = s.get(CSV_URL)

    line_iterator = (x.decode('utf-8') for x in download.iter_lines(decode_unicode=True))

    cr = csv.reader(line_iterator, delimiter=',')
    my_list = list(cr)
    for row in my_list:
        print(row)

Download files in laravel using Response::download

If you want to use the JavaScript download functionality then you can also do

 <a onclick=“window.open(‘info.pdf) class="btn btn-large pull-right"><i class="icon-download-alt"> </i> Download Brochure </a>

Also remember to paste the info.pdf file in your public directory of your project

maxReceivedMessageSize and maxBufferSize in app.config

The currently accepted answer is incorrect. It is NOT required to set maxBufferSize and maxReceivedMessageSize on the client and the server binding. It depends!

If your request is too large (i.e., method parameters of the service operation are memory intensive) set the properties on the server-side, if the response is too large (i.e., the method return value of the service operation is memory intensive) set the values on the client-side.

For the difference between maxBufferSize and maxReceivedMessageSize see MaxBufferSize property?.

How can I get a file's size in C++?

Using standard library:

Assuming that your implementation meaningfully supports SEEK_END:

fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file

Linux/POSIX:

You can use stat (if you know the filename), or fstat (if you have the file descriptor).

Here is an example for stat:

#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;

Win32:

You can use GetFileSize or GetFileSizeEx.

Disable HttpClient logging

It took far too long to find this out, but JWebUnit comes bundled with the Logback logging component, so it won't even use log4j.properties or commons-logging.properties.

Instead, create a file called logback.xml and place it in your source code folder (in my case, src):

<configuration debug="false">
  <!-- definition of appender STDOUT -->
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
    </encoder>
  </appender>

  <root level="ERROR">
    <!-- appender referenced after it is defined -->
    <appender-ref ref="STDOUT"/>
  </root> 
</configuration>

Logback looks to still be under development and the API seems to still be changing, so this code sample may fail in the future. See also this StackOverflow question.

Set Content-Type to application/json in jsp file

Try this piece of code, it should work too

<%
    //response.setContentType("Content-Type", "application/json"); // this will fail compilation
    response.setContentType("application/json"); //fixed
%>

Using querySelectorAll to retrieve direct children

I would like to add that you can extend the compatibility of :scope by just assigning a temporary attribute to the current node.

let node = [...];
let result;

node.setAttribute("foo", "");
result = window.document.querySelectorAll("[foo] > .bar");
// And, of course, you can also use other combinators.
result = window.document.querySelectorAll("[foo] + .bar");
result = window.document.querySelectorAll("[foo] ~ .bar");
node.removeAttribute("foo");

Using quotation marks inside quotation marks

When you have several words like this which you want to concatenate in a string, I recommend using format or f-strings which increase readability dramatically (in my opinion).

To give an example:

s = "a word that needs quotation marks"
s2 = "another word"

Now you can do

print('"{}" and "{}"'.format(s, s2))

which will print

"a word that needs quotation marks" and "another word"

As of Python 3.6 you can use:

print(f'"{s}" and "{s2}"')

yielding the same output.

Python socket receive - incoming packets always have a different size

I know this is old, but I hope this helps someone.

Using regular python sockets I found that you can send and receive information in packets using sendto and recvfrom

# tcp_echo_server.py
import socket

ADDRESS = ''
PORT = 54321

connections = []
host = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host.setblocking(0)
host.bind((ADDRESS, PORT))
host.listen(10)  # 10 is how many clients it accepts

def close_socket(connection):
    try:
        connection.shutdown(socket.SHUT_RDWR)
    except:
        pass
    try:
        connection.close()
    except:
        pass

def read():
    for i in reversed(range(len(connections))):
        try:
            data, sender = connections[i][0].recvfrom(1500)
            return data
        except (BlockingIOError, socket.timeout, OSError):
            pass
        except (ConnectionResetError, ConnectionAbortedError):
            close_socket(connections[i][0])
            connections.pop(i)
    return b''  # return empty if no data found

def write(data):
    for i in reversed(range(len(connections))):
        try:
            connections[i][0].sendto(data, connections[i][1])
        except (BlockingIOError, socket.timeout, OSError):
            pass
        except (ConnectionResetError, ConnectionAbortedError):
            close_socket(connections[i][0])
            connections.pop(i)

# Run the main loop
while True:
    try:
        con, addr = host.accept()
        connections.append((con, addr))
    except BlockingIOError:
        pass

    data = read()
    if data != b'':
        print(data)
        write(b'ECHO: ' + data)
        if data == b"exit":
            break

# Close the sockets
for i in reversed(range(len(connections))):
    close_socket(connections[i][0])
    connections.pop(i)
close_socket(host)

The client is similar

# tcp_client.py
import socket

ADDRESS = "localhost"
PORT = 54321

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ADDRESS, PORT))
s.setblocking(0)

def close_socket(connection):
    try:
        connection.shutdown(socket.SHUT_RDWR)
    except:
        pass
    try:
        connection.close()
    except:
        pass

def read():
    """Read data and return the read bytes."""
    try:
        data, sender = s.recvfrom(1500)
        return data
    except (BlockingIOError, socket.timeout, AttributeError, OSError):
        return b''
    except (ConnectionResetError, ConnectionAbortedError, AttributeError):
        close_socket(s)
        return b''

def write(data):
    try:
        s.sendto(data, (ADDRESS, PORT))
    except (ConnectionResetError, ConnectionAbortedError):
        close_socket(s)

while True:
    msg = input("Enter a message: ")
    write(msg.encode('utf-8'))

    data = read()
    if data != b"":
        print("Message Received:", data)

    if msg == "exit":
        break

close_socket(s)

React - How to get parameter value from query string?

export class ClassName extends Component{
      constructor(props){
        super(props);
        this.state = {
          id:parseInt(props.match.params.id,10)
        }
    }
     render(){
        return(
          //Code
          {this.state.id}
        );
}

Is there a way to reduce the size of the git folder?

Don't know if it will shrink it, but after I run git clean, I often do git repack -ad as well, which reduces the number of pack files.

Angularjs simple file download causes router to redirect

If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.

I hope it, will be helpfull.

HTML :

<a href="#" class="btn btn-default" file-name="'fileName.extension'"  ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>

DIRECTIVE :

directive('fileDownload',function(){
    return{
        restrict:'A',
        scope:{
            fileDownload:'=',
            fileName:'=',
        },

        link:function(scope,elem,atrs){


            scope.$watch('fileDownload',function(newValue, oldValue){

                if(newValue!=undefined && newValue!=null){
                    console.debug('Downloading a new file'); 
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    var isBlink = (isChrome || isOpera) && !!window.CSS;

                    if(isFirefox || isIE || isChrome){
                        if(isChrome){
                            console.log('Manage Google Chrome download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var downloadLink = angular.element('<a></a>');//create a new  <a> tag element
                            downloadLink.attr('href',fileURL);
                            downloadLink.attr('download',scope.fileName);
                            downloadLink.attr('target','_self');
                            downloadLink[0].click();//call click function
                            url.revokeObjectURL(fileURL);//revoke the object from URL
                        }
                        if(isIE){
                            console.log('Manage IE download>10');
                            window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName); 
                        }
                        if(isFirefox){
                            console.log('Manage Mozilla Firefox download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var a=elem[0];//recover the <a> tag from directive
                            a.href=fileURL;
                            a.download=scope.fileName;
                            a.target='_self';
                            a.click();//we call click function
                        }


                    }else{
                        alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
                    }
                }
            });

        }
    }
})

IN CONTROLLER:

$scope.myBlobObject=undefined;
$scope.getFile=function(){
        console.log('download started, you can show a wating animation');
        serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
        .then(function(data){//is important that the data was returned as Aray Buffer
                console.log('Stream download complete, stop animation!');
                $scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        },function(fail){
                console.log('Download Error, stop animation and show error message');
                                    $scope.myBlobObject=[];
                                });
                            }; 

IN SERVICE:

function getStream(params){
                 console.log("RUNNING");
                 var deferred = $q.defer();

                 $http({
                     url:'../downloadURL/',
                     method:"PUT",//you can use also GET or POST
                     data:params,
                     headers:{'Content-type': 'application/json'},
                     responseType : 'arraybuffer',//THIS IS IMPORTANT
                    })
                    .success(function (data) {
                        console.debug("SUCCESS");
                        deferred.resolve(data);
                    }).error(function (data) {
                         console.error("ERROR");
                         deferred.reject(data);
                    });

                 return deferred.promise;
                };

BACKEND(on SPRING):

@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
        @RequestBody Map<String,String> spParams
        ) throws IOException {
        OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}

How do I set the colour of a label (coloured text) in Java?

You can set the color of a JLabel by altering the foreground category:

JLabel title = new JLabel("I love stackoverflow!", JLabel.CENTER);

title.setForeground(Color.white);

As far as I know, the simplest way to create the two-color label you want is to simply make two labels, and make sure they get placed next to each other in the proper order.

Iterate keys in a C++ map

Here's an example of how to do it using Boost's transform_iterator

#include <iostream>
#include <map>
#include <iterator>
#include "boost/iterator/transform_iterator.hpp"

using std::map;
typedef std::string Key;
typedef std::string Val;

map<Key,Val>::key_type get_key(map<Key,Val>::value_type aPair) {
  return aPair.first;
}

typedef map<Key,Val>::key_type (*get_key_t)(map<Key,Val>::value_type);
typedef map<Key,Val>::iterator map_iterator;
typedef boost::transform_iterator<get_key_t, map_iterator> mapkey_iterator;

int main() {
  map<Key,Val> m;
  m["a"]="A";
  m["b"]="B";
  m["c"]="C";

  // iterate over the map's (key,val) pairs as usual
  for(map_iterator i = m.begin(); i != m.end(); i++) {
    std::cout << i->first << " " << i->second << std::endl;
  }

  // iterate over the keys using the transformed iterators
  mapkey_iterator keybegin(m.begin(), get_key);
  mapkey_iterator keyend(m.end(), get_key);
  for(mapkey_iterator i = keybegin; i != keyend; i++) {
    std::cout << *i << std::endl;
  }
}

Changing the resolution of a VNC session in linux

Found out that the vnc4server (4.1.1) shipped with Ubuntu (10.04) is patched to also support changing the resolution on the fly via xrandr. Unfortunately the feature was hard to find because it is undocumented. So here it is...

Start the server with multiple 'geometry' instances, like:

vnc4server -geometry 1280x1024 -geometry 800x600

From a terminal in a vncviewer (with: 'allow dymanic desktop resizing' enabled) use xrandr to view the available modes:

xrandr

to change the resulution, for example use:

xrandr -s 800x600

Thats it.

Convert SQL Server result set into string

The answer from brad.v is incorrect! It won't give you a concatenated string.

Here's the correct code, almost like brad.v's but with one important change:

DECLARE @results VarChar(1000)
  SELECT @results = CASE
     WHEN @results IS NULL THEN CONVERT( VarChar(20), [StudentId])
     ELSE @results + ', ' + CONVERT( VarChar(20), [StudentId])
  END
FROM Student WHERE condition = abc;

See the difference? :) brad.v please fix your answer, I can't do anything to correct it or comment on it 'cause my reputation here is zero. I guess I can remove mine after you fix yours. Thanks!

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

As mentioned here (in French), this can happen when you have two versions of R installed on your computer. Uninstall the oldest one, then try your package installation again! It worked fine for me.

How to list installed packages from a given repo using yum

Try

yum list installed | grep reponame

On one of my servers:

yum list installed | grep remi
ImageMagick2.x86_64                       6.6.5.10-1.el5.remi          installed
memcache.x86_64                          1.4.5-2.el5.remi             installed
mysql.x86_64                              5.1.54-1.el5.remi            installed
mysql-devel.x86_64                        5.1.54-1.el5.remi            installed
mysql-libs.x86_64                         5.1.54-1.el5.remi            installed
mysql-server.x86_64                       5.1.54-1.el5.remi            installed
mysqlclient15.x86_64                      5.0.67-1.el5.remi            installed
php.x86_64                                5.3.5-1.el5.remi             installed
php-cli.x86_64                            5.3.5-1.el5.remi             installed
php-common.x86_64                         5.3.5-1.el5.remi             installed
php-domxml-php4-php5.noarch               1.21.2-1.el5.remi            installed
php-fpm.x86_64                            5.3.5-1.el5.remi             installed
php-gd.x86_64                             5.3.5-1.el5.remi             installed
php-mbstring.x86_64                       5.3.5-1.el5.remi             installed
php-mcrypt.x86_64                         5.3.5-1.el5.remi             installed
php-mysql.x86_64                          5.3.5-1.el5.remi             installed
php-pdo.x86_64                            5.3.5-1.el5.remi             installed
php-pear.noarch                           1:1.9.1-6.el5.remi           installed
php-pecl-apc.x86_64                       3.1.6-1.el5.remi             installed
php-pecl-imagick.x86_64                   3.0.1-1.el5.remi.1           installed
php-pecl-memcache.x86_64                  3.0.5-1.el5.remi             installed
php-pecl-xdebug.x86_64                    2.1.0-1.el5.remi             installed
php-soap.x86_64                           5.3.5-1.el5.remi             installed
php-xml.x86_64                            5.3.5-1.el5.remi             installed
remi-release.noarch                       5-8.el5.remi                 installed

It works.

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

How to trigger a phone call when clicking a link in a web page on mobile phone

Essentially, use an <a> element with an href attr pointing to the phone number prefixed by tel:. Note that pluses can be used to specify country code, and hyphens can be included simply for human eyes.

MDN Web Docs

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Creating_a_phone_link

The HTML <a> element (or anchor element), along with its href attribute, creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.

[…]

Offering phone links is helpful for users viewing web documents and laptops connected to phones.

<a href="tel:+491570156">+49 157 0156</a>

IETF Documents

https://tools.ietf.org/html/rfc3966

The tel URI for Telephone Numbers

The "tel" URI has the following syntax:

telephone-uri = "tel:" telephone-subscriber

[…]

Examples

tel:+1-201-555-0123: This URI points to a phone number in the United States. The hyphens are included to make the number more human readable; they separate country, area code and subscriber number.

tel:7042;phone-context=example.com: The URI describes a local phone number valid within the context "example.com".

tel:863-1234;phone-context=+1-914-555: The URI describes a local phone number that is valid within a particular phone prefix.

StringStream in C#

You have a number of options:

One is to not use streams, but use the TextWriter

   void Print(TextWriter writer) 
   {
   }

   void Main() 
  {
    var textWriter = new StringWriter();
    Print(writer);
    string myString = textWriter.ToString();
   }

It's likely that TextWriter is the appropriate level of abstraction for your print function. Streams are aimed at writing binary data, while TextWriter works at a higher abstraction level, specifically geared towards outputting strings.

If your motivation is that you also want your Print function to write to files, you can get a text writer from a filestream as well.

void Print(TextWriter writer) 
{
}

void PrintToFile(string filePath) 
{
     using(var textWriter = new StreamWriter(filePath))
     {
         Print(writer);
     }
}

If you REALLY want a stream you can look at MemoryStream.

How to use Elasticsearch with MongoDB?

Since mongo-connector now appears dead, my company decided to build a tool for using Mongo change streams to output to Elasticsearch.

Our initial results look promising. You can check it out at https://github.com/electionsexperts/mongo-stream. We're still early in development, and would welcome suggestions or contributions.

Pass parameter to EventHandler

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

Getting the object's property name

Use Object.keys():

_x000D_
_x000D_
var myObject = { a: 'c', b: 'a', c: 'b' };_x000D_
var keyNames = Object.keys(myObject);_x000D_
console.log(keyNames); // Outputs ["a","b","c"]
_x000D_
_x000D_
_x000D_

Object.keys() gives you an array of property names belonging to the input object.

The APR based Apache Tomcat Native library was not found on the java.library.path

Regarding the original question asked in the title ...

  • sudo apt-get install libtcnative-1

  • or if you are on RHEL Linux yum install tomcat-native

The documentation states you need http://tomcat.apache.org/native-doc/

  • sudo apt-get install libapr1.0-dev libssl-dev
  • or RHEL yum install apr-devel openssl-devel

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

How to combine two vectors into a data frame

Here's a simple function. It generates a data frame and automatically uses the names of the vectors as values for the first column.

myfunc <- function(a, b, names = NULL) {
  setNames(data.frame(c(rep(deparse(substitute(a)), length(a)), 
                        rep(deparse(substitute(b)), length(b))), c(a, b)), names)
}

An example:

x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"

myfunc(x, y, c(x_name, y_name))

  cond rating
1    x      1
2    x      2
3    x      3
4    y    100
5    y    200
6    y    300

Elegant way to create empty pandas DataFrame with NaN of type float

Hope this can help!

 pd.DataFrame(np.nan, index = np.arange(<num_rows>), columns = ['A'])

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

You can do a variety of things. What I would do is this.

Create an array on scope that will be your data structure for the phone numbers.

$scope.telephone = '';
$scope.numbers = [];

Then in your html I would have this

<input type="text" ng-model="telephone">
<button ng-click="submitNumber()">Submit</button>

Then when your user clicks submit, run submitNumber(), which pushes the new telephone number into the numbers array.

$scope.submitNumber = function(){
  $scope.numbers.push($scope.telephone);
}

System.web.mvc missing

MVC 5

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Stack 5\Packages\ Microsoft.AspNet.Mvc.5.0.0\lib\net45\System.Web.Mvc.dll

MVC 4

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Web.Mvc.dll

MVC 3

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll

MVC 2

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dll

Where can I find System.Web.MVC dll in a system where MVC 3 is installed?

NullInjectorError: No provider for AngularFirestore

Weird thing for me was that I had the provider:[], but the HTML tag that uses the provider was what was causing the error. I'm referring to the red box below: enter image description here

It turns out I had two classes in different components with the same "employee-list.component.ts" filename and so the project compiled fine, but the references were all messed up.

How can I plot separate Pandas DataFrames as subplots?

You can see e.gs. in the documentation demonstrating joris answer. Also from the documentation, you could also set subplots=True and layout=(,) within the pandas plot function:

df.plot(subplots=True, layout=(1,2))

You could also use fig.add_subplot() which takes subplot grid parameters such as 221, 222, 223, 224, etc. as described in the post here. Nice examples of plot on pandas data frame, including subplots, can be seen in this ipython notebook.

Create aar file in Android Studio

just like user hcpl said but if you want to not worry about the version of the library you can do this:

dependencies {
    compile(name:'mylibrary', ext:'aar')
}

as its kind of annoying to have to update the version everytime. Also it makes the not worrying about the name space easier this way.

What does the "at" (@) symbol do in Python?

Decorators were added in Python to make function and method wrapping (a function that receives a function and returns an enhanced one) easier to read and understand. The original use case was to be able to define the methods as class methods or static methods on the head of their definition. Without the decorator syntax, it would require a rather sparse and repetitive definition:

class WithoutDecorators:
def some_static_method():
    print("this is static method")
some_static_method = staticmethod(some_static_method)

def some_class_method(cls):
    print("this is class method")
some_class_method = classmethod(some_class_method)

If the decorator syntax is used for the same purpose, the code is shorter and easier to understand:

class WithDecorators:
    @staticmethod
    def some_static_method():
        print("this is static method")

    @classmethod
    def some_class_method(cls):
        print("this is class method")

General syntax and possible implementations

The decorator is generally a named object ( lambda expressions are not allowed) that accepts a single argument when called (it will be the decorated function) and returns another callable object. "Callable" is used here instead of "function" with premeditation. While decorators are often discussed in the scope of methods and functions, they are not limited to them. In fact, anything that is callable (any object that implements the _call__ method is considered callable), can be used as a decorator and often objects returned by them are not simple functions but more instances of more complex classes implementing their own __call_ method.

The decorator syntax is simply only a syntactic sugar. Consider the following decorator usage:

@some_decorator
def decorated_function():
    pass

This can always be replaced by an explicit decorator call and function reassignment:

def decorated_function():
    pass
decorated_function = some_decorator(decorated_function)

However, the latter is less readable and also very hard to understand if multiple decorators are used on a single function. Decorators can be used in multiple different ways as shown below:

As a function

There are many ways to write custom decorators, but the simplest way is to write a function that returns a subfunction that wraps the original function call.

The generic patterns is as follows:

def mydecorator(function):
    def wrapped(*args, **kwargs):
        # do some stuff before the original
        # function gets called
        result = function(*args, **kwargs)
        # do some stuff after function call and
        # return the result
        return result
    # return wrapper as a decorated function
    return wrapped

As a class

While decorators almost always can be implemented using functions, there are some situations when using user-defined classes is a better option. This is often true when the decorator needs complex parametrization or it depends on a specific state.

The generic pattern for a nonparametrized decorator as a class is as follows:

class DecoratorAsClass:
    def __init__(self, function):
        self.function = function

    def __call__(self, *args, **kwargs):
        # do some stuff before the original
        # function gets called
        result = self.function(*args, **kwargs)
        # do some stuff after function call and
        # return the result
        return result

Parametrizing decorators

In real code, there is often a need to use decorators that can be parametrized. When the function is used as a decorator, then the solution is simple—a second level of wrapping has to be used. Here is a simple example of the decorator that repeats the execution of a decorated function the specified number of times every time it is called:

def repeat(number=3):
"""Cause decorated function to be repeated a number of times.

Last value of original function call is returned as a result
:param number: number of repetitions, 3 if not specified
"""
def actual_decorator(function):
    def wrapper(*args, **kwargs):
        result = None
        for _ in range(number):
            result = function(*args, **kwargs)
        return result
    return wrapper
return actual_decorator

The decorator defined this way can accept parameters:

>>> @repeat(2)
... def foo():
...     print("foo")
...
>>> foo()
foo
foo

Note that even if the parametrized decorator has default values for its arguments, the parentheses after its name is required. The correct way to use the preceding decorator with default arguments is as follows:

>>> @repeat()
... def bar():
...     print("bar")
...
>>> bar()
bar
bar
bar

Finally lets see decorators with Properties.

Properties

The properties provide a built-in descriptor type that knows how to link an attribute to a set of methods. A property takes four optional arguments: fget , fset , fdel , and doc . The last one can be provided to define a docstring that is linked to the attribute as if it were a method. Here is an example of a Rectangle class that can be controlled either by direct access to attributes that store two corner points or by using the width , and height properties:

class Rectangle:
    def __init__(self, x1, y1, x2, y2):
        self.x1, self.y1 = x1, y1
        self.x2, self.y2 = x2, y2

    def _width_get(self):
        return self.x2 - self.x1

    def _width_set(self, value):
        self.x2 = self.x1 + value

    def _height_get(self):
        return self.y2 - self.y1

    def _height_set(self, value):
        self.y2 = self.y1 + value

    width = property(
        _width_get, _width_set,
        doc="rectangle width measured from left"
    )
    height = property(
        _height_get, _height_set,
        doc="rectangle height measured from top"
    )

    def __repr__(self):
        return "{}({}, {}, {}, {})".format(
            self.__class__.__name__,
            self.x1, self.y1, self.x2, self.y2
    )

The best syntax for creating properties is using property as a decorator. This will reduce the number of method signatures inside of the class and make code more readable and maintainable. With decorators the above class becomes:

class Rectangle:
    def __init__(self, x1, y1, x2, y2):
        self.x1, self.y1 = x1, y1
        self.x2, self.y2 = x2, y2

    @property
    def width(self):
        """rectangle height measured from top"""
        return self.x2 - self.x1

    @width.setter
    def width(self, value):
        self.x2 = self.x1 + value

    @property
    def height(self):
        """rectangle height measured from top"""
        return self.y2 - self.y1

    @height.setter
    def height(self, value):
        self.y2 = self.y1 + value

if else condition in blade file (laravel 5.3)

I think you are putting one too many curly brackets. Try this

 @if($user->status=='waiting')
            <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
            @else
            <td>{!! $user->status !!}</td>
        @endif

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

python ValueError: invalid literal for float()

I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.

In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.

I was getting the error:

> '     0.00'
> 3 0 fast loop, delta =  10.0 weight =  0.0 
> '     0.00'
> 1 800 fast loop, delta = 10.0 weight =  0.0 
> '     0.00'
> 6 0 fast loop, delta =  10.0 weight =  0.0
> '     0\x00.0' 
> Traceback (most recent call last):
>   File "measure_weight_speed.py", line 172, in start
>     valueScale = float(answer_string) 
>     ValueError: invalid literal for float(): 0

After some research I wrote few lines of code that work in my case.

replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)

The answers in these posts helped:

  1. How to get rid of \x00 in my array of bytes?
  2. Invalid literal for float(): 0.000001, how to fix error?

copy-item With Alternate Credentials

The newer verion of PowerShell handles this and the MS Documentation has a great example of copying a file with different credentials here

$Session = New-PSSession -ComputerName "Server02" -Credential "Contoso\User01"
Copy-Item "D:\Folder002\" -Destination "C:\Folder002_Copy\" -ToSession $Session

Get a list of dates between two dates

We had a similar problem with BIRT reports in that we wanted to report on those days that had no data. Since there were no entries for those dates, the easiest solution for us was to create a simple table that stored all dates and use that to get ranges or join to get zero values for that date.

We have a job that runs every month to ensure that the table is populated 5 years out into the future. The table is created thus:

create table all_dates (
    dt date primary key
);

No doubt there are magical tricky ways to do this with different DBMS' but we always opt for the simplest solution. The storage requirements for the table are minimal and it makes the queries so much simpler and portable. This sort of solution is almost always better from a performance point-of-view since it doesn't require per-row calculations on the data.

The other option (and we've used this before) is to ensure there's an entry in the table for every date. We swept the table periodically and added zero entries for dates and/or times that didn't exist. This may not be an option in your case, it depends on the data stored.

If you really think it's a hassle to keep the all_dates table populated, a stored procedure is the way to go which will return a dataset containing those dates. This will almost certainly be slower since you have to calculate the range every time it's called rather than just pulling pre-calculated data from a table.

But, to be honest, you could populate the table out for 1000 years without any serious data storage problems - 365,000 16-byte (for example) dates plus an index duplicating the date plus 20% overhead for safety, I'd roughly estimate at about 14M [365,000 * 16 * 2 * 1.2 = 14,016,000 bytes]), a minuscule table in the scheme of things.

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

Just another case here. I had this error from Managed Debugging Assistant on the first time deserializing a XML file into objects under VS2010/.NET 4. A DLL containing classes for the objects is generated in a post-build event (usual Microsoft style stuff). Worked very well for several projects in same solution, problem appeared when doing that in one more of the projects. Error text:

BindingFailure was detected Message: The assembly with display name MyProjectName.XmlSerializers' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.FileLoadException: Could not load file or assembly MyProjectName.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Since some answers here suggested a platform mismatch, I noticed that 3 projects and the solution had "mixed platforms" configuration selected, and 3 projects were compiled for x86 instead of AnyCPU. I have no platform-specific code (though some vendor-provided DLLs rely on a few x86 libraries). I replaced all occurrences of x86 into AnyCPU with this:

for a in $( egrep '(x86|AnyCPU)' */*.csproj *.sln -l  ) ; do echo $a ; sed -i 's/x86/AnyCPU/' $a ; done

Then the project would build but all options to run or debug code would be greyed out. Restarting VS would not help.

I reverted with git the references to the x86-library, just in case, but kept AnyCPU for all the code I compile.

Following F5 or Start Debugging Button is Greyed Out for Winform application? I unloaded and reloaded the starting project (it was also the one where the initial problem appeared in the first place).

After that, everything fell back into place: the program works without the initial error.

See http://www.catb.org/jargon/html/R/rain-dance.html , http://www.catb.org/jargon/html/V/voodoo-programming.html or http://www.catb.org/jargon/html/I/incantation.html and links there.

How to hide close button in WPF window?

This won't get rid of the close button, but it will stop someone closing the window.

Put this in your code behind file:

protected override void OnClosing(CancelEventArgs e)
{
   base.OnClosing(e);
   e.Cancel = true;
}

How to split one string into multiple variables in bash shell?

If you know it's going to be just two fields, you can skip the extra subprocesses like this:

var1=${STR%-*}
var2=${STR#*-}

What does this do? ${STR%-*} deletes the shortest substring of $STR that matches the pattern -* starting from the end of the string. ${STR#*-} does the same, but with the *- pattern and starting from the beginning of the string. They each have counterparts %% and ## which find the longest anchored pattern match. If anyone has a helpful mnemonic to remember which does which, let me know! I always have to try both to remember.

Getting a slice of keys from a map

This is an old question, but here's my two cents. PeterSO's answer is slightly more concise, but slightly less efficient. You already know how big it's going to be so you don't even need to use append:

keys := make([]int, len(mymap))

i := 0
for k := range mymap {
    keys[i] = k
    i++
}

In most situations it probably won't make much of a difference, but it's not much more work, and in my tests (using a map with 1,000,000 random int64 keys and then generating the array of keys ten times with each method), it was about 20% faster to assign members of the array directly than to use append.

Although setting the capacity eliminates reallocations, append still has to do extra work to check if you've reached capacity on each append.

Signed versus Unsigned Integers

  1. Yes, unsigned integer can store large value.
  2. No, there are different ways to show positive and negative values.
  3. Yes, signed integer can contain both positive and negative values.

Implement Stack using Two Queues

import java.util.LinkedList;
import java.util.Queue;


public class StackQueue {

    static Queue<Integer> Q1 = new LinkedList<Integer>();
    static Queue<Integer> Q2 = new LinkedList<Integer>();
    public static void main(String args[]) {



        push(24);
        push(34);
        push(4);
        push(10);
        push(1);
        push(43);
        push(21);
        System.out.println("Popped element is  "+pop());
        System.out.println("Popped element is  "+pop());
        System.out.println("Popped element is  "+pop());


    }

    public static void push(int data) {

        Q1.add(data);

    }

    public static int pop() {

        if(Q1.isEmpty()) {
        System.out.println("Cannot pop elements ,  Stack is Empty !!"); 
        return -1;
        }
        else
        {
        while(Q1.size() > 1) {
            Q2.add(Q1.remove());
        }
        int element = Q1.remove();
        Queue<Integer> temp = new LinkedList<Integer>();
        temp = Q1;
        Q1 = Q2;
        Q2 = temp;
        return element;
        }
    }
}

SQL Query for Selecting Multiple Records

I strongly recommend using lowercase field|column names, it will make your life easier.

Let's assume you have a table called users with the following definition and records:

id|firstname|lastname|username             |password
1 |joe      |doe     |[email protected]   |1234
2 |jane     |doe     |[email protected]  |12345
3 |johnny   |doe     |[email protected]|123456

let's say you want to get all records from table users, then you do:

SELECT * FROM users;

Now let's assume you want to select all records from table users, but you're interested only in the fields id, firstname and lastname, thus ignoring username and password:

SELECT id, firstname, lastname FROM users;

Now we get at the point where you want to retrieve records based on condition(s), what you need to do is to add the WHERE clause, let's say we want to select from users only those that have username = [email protected] and password = 1234, what you do is:

SELECT * FROM users
WHERE ( ( username = '[email protected]' ) AND ( password = '1234' ) );

But what if you need only the id of a record with username = [email protected] and password = 1234? then you do:

SELECT id FROM users
WHERE ( ( username = '[email protected]' ) AND ( password = '1234' ) );

Now to get to your question, as others before me answered you can use the IN clause:

SELECT * FROM users
WHERE ( id IN (1,2,..,n) );

or, if you wish to limit to a list of records between id 20 and id 40, then you can easily write:

SELECT * FROM users
WHERE ( ( id >= 20 ) AND ( id <= 40 ) );

I hope this gives a better understanding.

get launchable activity name of package from adb

You don't need root to pull the apk files from /data/app. Sure, you might not have permissions to list the contents of that directory, but you can find the file locations of APKs with:

adb shell pm list packages -f

Then you can use adb pull:

adb pull <APK path from previous command>

and then aapt to get the information you want:

aapt dump badging <pulledfile.apk>

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

Add multiple items to a list

Code check:

This is offtopic here but the people over at CodeReview are more than happy to help you.

I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.

Lists:

As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List.

Lists are very straightforward to use but take a look at the related documentation anyway.

A very simple example to keep multiple bikes in a list:

List<Motorbike> bikes = new List<Motorbike>();

bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });

And to iterate over the list you can use the foreach statement:

foreach(var bike in bikes) {
     Console.WriteLine(bike.make);
}

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<

Very simple question that you can solved it easily ,

Please follow my step : change < to ( and >; to );

Just use: (

     );

enter code here

` CREATE TABLE information (
-> id INT(11) NOT NULL AUTO_INCREMENT,
-> name VARCHAR(30) NOT NULL,
-> age INT(10) NOT NULL,
-> salary INT(100) NOT NULL,
-> address VARCHAR(100) NOT NULL,
-> PRIMARY KEY(id)
-> );`

How do I activate a specific workbook and a specific sheet?

Dim Wb As Excel.Workbook
Set Wb = Workbooks.Open(file_path)
Wb.Sheets("Sheet1").Cells(2,24).Value = 24
Wb.Close

To know the sheets name to refer in Wb.Sheets("sheetname") you can use the following :

Dim sht as Worksheet    
For Each sht In tempWB.Sheets
    Debug.Print sht.Name
Next sht

ImportError: cannot import name NUMPY_MKL

yes,Just reinstall numpy,it works.

Recommended Fonts for Programming?

Verdana - Once I realised that I didn't HAVE to use a mono-spaced font ;-)

Create list of single item repeated N times

Itertools has a function just for that:

import itertools
it = itertools.repeat(e,n)

Of course itertools gives you a iterator instead of a list. [e] * n gives you a list, but, depending on what you will do with those sequences, the itertools variant can be much more efficient.

What is the easiest way to clear a database from the CLI with manage.py in Django?

If you don't care about data:

Best way would be to drop the database and run syncdb again. Or you can run:

For Django >= 1.5

python manage.py flush

For Django < 1.5

python manage.py reset appname

(you can add --no-input to the end of the command for it to skip the interactive prompt.)

If you do care about data:

From the docs:

syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.

If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.

https://docs.djangoproject.com/en/dev/ref/django-admin/

Reference: FAQ - https://docs.djangoproject.com/en/dev/faq/models/#if-i-make-changes-to-a-model-how-do-i-update-the-database

People also recommend South ( http://south.aeracode.org/docs/about.html#key-features ), but I haven't tried it.

iOS detect if user is on an iPad

Why so complicated? This is how I do it...

Swift 4:

var iPad : Bool {
    return UIDevice.current.model.contains("iPad")
}

This way you can just say if iPad {}

Counting the Number of keywords in a dictionary in python

Some modifications were made on posted answer UnderWaterKremlin to make it python3 proof. A surprising result below as answer.

System specs:

  • python =3.7.4,
  • conda = 4.8.0
  • 3.6Ghz, 8 core, 16gb.
import timeit

d = {x: x**2 for x in range(1000)}
#print (d)
print (len(d))
# 1000

print (len(d.keys()))
# 1000

print (timeit.timeit('len({x: x**2 for x in range(1000)})', number=100000))        # 1

print (timeit.timeit('len({x: x**2 for x in range(1000)}.keys())', number=100000)) # 2

Result:

1) = 37.0100378

2) = 37.002148899999995

So it seems that len(d.keys()) is currently faster than just using len().

MySQL LIKE IN()?

Flip operands

'a,b,c' like '%'||field||'%'

Relative imports in Python 3

I had a similar problem: I needed a Linux service and cgi plugin which use common constants to cooperate. The 'natural' way to do this is to place them in the init.py of the package, but I cannot start the cgi plugin with the -m parameter.

My final solution was similar to Solution #2 above:

import sys
import pathlib as p
import importlib

pp = p.Path(sys.argv[0])
pack = pp.resolve().parent

pkg = importlib.import_module('__init__', package=str(pack))

The disadvantage is that you must prefix the constants (or common functions) with pkg:

print(pkg.Glob)

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

css to make bootstrap navbar transparent

There is no need for all this mess.

You can make the navbar transparent by not writing navbar-defaultor navbar-inverse

<nav class="navbar">  //Don't add navbar-default to the class

  //

</nav>

How to download and save an image in Android

Edit as of 30.12.2015 - The Ultimate Guide to image downloading


last major update: Mar 31 2016


TL;DR a.k.a. stop talking, just give me the code!!

Skip to the bottom of this post, copy the BasicImageDownloader (javadoc version here) into your project, implement the OnImageLoaderListener interface and you're done.

Note: though the BasicImageDownloader handles possible errors and will prevent your app from crashing in case anything goes wrong, it will not perform any post-processing (e.g. downsizing) on the downloaded Bitmaps.


Since this post has received quite a lot of attention, I have decided to completely rework it to prevent the folks from using deprecated technologies, bad programming practices or just doing silly things - like looking for "hacks" to run network on the main thread or accept all SSL certs.

I've created a demo project named "Image Downloader" that demonstrates how to download (and save) an image using my own downloader implementation, the Android's built-in DownloadManager as well as some popular open-source libraries. You can view the complete source code or download the project on GitHub.

Note: I have not adjusted the permission management for SDK 23+ (Marshmallow) yet, thus the project is targeting SDK 22 (Lollipop).

In my conclusion at the end of this post I will share my humble opinion about the proper use-case for each particular way of image downloading I've mentioned.

Let's start with an own implementation (you can find the code at the end of the post). First of all, this is a BasicImageDownloader and that's it. All it does is connecting to the given url, reading the data and trying to decode it as a Bitmap, triggering the OnImageLoaderListener interface callbacks when appropriate. The advantage of this approach - it is simple and you have a clear overview of what's going on. A good way to go if all you need is downloading/displaying and saving some images, whilst you don't care about maintaining a memory/disk cache.

Note: in case of large images, you might need to scale them down.

--

Android DownloadManager is a way to let the system handle the download for you. It's actually capable of downloading any kind of files, not just images. You may let your download happen silently and invisible to the user, or you can enable the user to see the download in the notification area. You can also register a BroadcastReceiver to get notified after you download is complete. The setup is pretty much straightforward, refer to the linked project for sample code.

Using the DownloadManager is generally not a good idea if you also want to display the image, since you'd need to read and decode the saved file instead of just setting the downloaded Bitmap into an ImageView. The DownloadManager also does not provide any API for you app to track the download progress.

--

Now the introduction of the great stuff - the libraries. They can do much more than just downloading and displaying images, including: creating and managing the memory/disk cache, resizing images, transforming them and more.

I will start with Volley, a powerful library created by Google and covered by the official documentation. While being a general-purpose networking library not specializing on images, Volley features quite a powerful API for managing images.

You will need to implement a Singleton class for managing Volley requests and you are good to go.

You might want to replace your ImageView with Volley's NetworkImageView, so the download basically becomes a one-liner:

((NetworkImageView) findViewById(R.id.myNIV)).setImageUrl(url, MySingleton.getInstance(this).getImageLoader());

If you need more control, this is what it looks like to create an ImageRequest with Volley:

     ImageRequest imgRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
             @Override
             public void onResponse(Bitmap response) {
                    //do stuff
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.ARGB_8888, 
             new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {
                   //do stuff
                }
            });

It is worth mentioning that Volley features an excellent error handling mechanism by providing the VolleyError class that helps you to determine the exact cause of an error. If your app does a lot of networking and managing images isn't its main purpose, then Volley it a perfect fit for you.

--

Square's Picasso is a well-known library which will do all of the image loading stuff for you. Just displaying an image using Picasso is as simple as:

 Picasso.with(myContext)
       .load(url)
       .into(myImageView); 

By default, Picasso manages the disk/memory cache so you don't need to worry about that. For more control you can implement the Target interface and use it to load your image into - this will provide callbacks similar to the Volley example. Check the demo project for examples.

Picasso also lets you apply transformations to the downloaded image and there are even other libraries around that extend those API. Also works very well in a RecyclerView/ListView/GridView.

--

Universal Image Loader is an another very popular library serving the purpose of image management. It uses its own ImageLoader that (once initialized) has a global instance which can be used to download images in a single line of code:

  ImageLoader.getInstance().displayImage(url, myImageView);

If you want to track the download progress or access the downloaded Bitmap:

 ImageLoader.getInstance().displayImage(url, myImageView, opts, 
 new ImageLoadingListener() {
     @Override
     public void onLoadingStarted(String imageUri, View view) {
                     //do stuff
                }

      @Override
      public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                   //do stuff
                }

      @Override
      public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                   //do stuff
                }

      @Override
      public void onLoadingCancelled(String imageUri, View view) {
                   //do stuff
                }
            }, new ImageLoadingProgressListener() {
      @Override
      public void onProgressUpdate(String imageUri, View view, int current, int total) {
                   //do stuff
                }
            });

The opts argument in this example is a DisplayImageOptions object. Refer to the demo project to learn more.

Similar to Volley, UIL provides the FailReason class that enables you to check what went wrong on download failure. By default, UIL maintains a memory/disk cache if you don't explicitly tell it not to do so.

Note: the author has mentioned that he is no longer maintaining the project as of Nov 27th, 2015. But since there are many contributors, we can hope that the Universal Image Loader will live on.

--

Facebook's Fresco is the newest and (IMO) the most advanced library that takes image management to a new level: from keeping Bitmaps off the java heap (prior to Lollipop) to supporting animated formats and progressive JPEG streaming.

To learn more about ideas and techniques behind Fresco, refer to this post.

The basic usage is quite simple. Note that you'll need to call Fresco.initialize(Context); only once, preferable in the Application class. Initializing Fresco more than once may lead to unpredictable behavior and OOM errors.

Fresco uses Drawees to display images, you can think of them as of ImageViews:

    <com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/drawee"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    fresco:fadeDuration="500"
    fresco:actualImageScaleType="centerCrop"
    fresco:placeholderImage="@drawable/placeholder_grey"
    fresco:failureImage="@drawable/error_orange"
    fresco:placeholderImageScaleType="fitCenter"
    fresco:failureImageScaleType="centerInside"
    fresco:retryImageScaleType="centerCrop"
    fresco:progressBarImageScaleType="centerInside"
    fresco:progressBarAutoRotateInterval="1000"
    fresco:roundAsCircle="false" />

As you can see, a lot of stuff (including transformation options) gets already defined in XML, so all you need to do to display an image is a one-liner:

 mDrawee.setImageURI(Uri.parse(url));

Fresco provides an extended customization API, which, under circumstances, can be quite complex and requires the user to read the docs carefully (yes, sometimes you need to RTFM).

I have included examples for progressive JPEG's and animated images into the sample project.


Conclusion - "I have learned about the great stuff, what should I use now?"

Note that the following text reflects my personal opinion and should not be taken as a postulate.

  • If you only need to download/save/display some images, don't plan to use them in a Recycler-/Grid-/ListView and don't need a whole bunch of images to be display-ready, the BasicImageDownloader should fit your needs.
  • If your app saves images (or other files) as a result of a user or an automated action and you don't need the images to be displayed often, use the Android DownloadManager.
  • In case your app does a lot of networking, transmits/receives JSON data, works with images, but those are not the main purpose of the app, go with Volley.
  • Your app is image/media-focused, you'd like to apply some transformations to images and don't want to bother with complex API: use Picasso (Note: does not provide any API to track the intermediate download status) or Universal Image Loader
  • If your app is all about images, you need advanced features like displaying animated formats and you are ready to read the docs, go with Fresco.

In case you missed that, the Github link for the demo project.


And here's the BasicImageDownloader.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;

public class BasicImageDownloader {

    private OnImageLoaderListener mImageLoaderListener;
    private Set<String> mUrlsInProgress = new HashSet<>();
    private final String TAG = this.getClass().getSimpleName();

    public BasicImageDownloader(@NonNull OnImageLoaderListener listener) {
        this.mImageLoaderListener = listener;
    }

    public interface OnImageLoaderListener {
        void onError(ImageError error);      
        void onProgressChange(int percent);
        void onComplete(Bitmap result);
    }


    public void download(@NonNull final String imageUrl, final boolean displayProgress) {
        if (mUrlsInProgress.contains(imageUrl)) {
            Log.w(TAG, "a download for this url is already running, " +
                    "no further download will be started");
            return;
        }

        new AsyncTask<Void, Integer, Bitmap>() {

            private ImageError error;

            @Override
            protected void onPreExecute() {
                mUrlsInProgress.add(imageUrl);
                Log.d(TAG, "starting download");
            }

            @Override
            protected void onCancelled() {
                mUrlsInProgress.remove(imageUrl);
                mImageLoaderListener.onError(error);
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                mImageLoaderListener.onProgressChange(values[0]);
            }

        @Override
        protected Bitmap doInBackground(Void... params) {
            Bitmap bitmap = null;
            HttpURLConnection connection = null;
            InputStream is = null;
            ByteArrayOutputStream out = null;
            try {
                connection = (HttpURLConnection) new URL(imageUrl).openConnection();
                if (displayProgress) {
                    connection.connect();
                    final int length = connection.getContentLength();
                    if (length <= 0) {
                        error = new ImageError("Invalid content length. The URL is probably not pointing to a file")
                                .setErrorCode(ImageError.ERROR_INVALID_FILE);
                        this.cancel(true);
                    }
                    is = new BufferedInputStream(connection.getInputStream(), 8192);
                    out = new ByteArrayOutputStream();
                    byte bytes[] = new byte[8192];
                    int count;
                    long read = 0;
                    while ((count = is.read(bytes)) != -1) {
                        read += count;
                        out.write(bytes, 0, count);
                        publishProgress((int) ((read * 100) / length));
                    }
                    bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size());
                } else {
                    is = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                }
            } catch (Throwable e) {
                if (!this.isCancelled()) {
                    error = new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION);
                    this.cancel(true);
                }
            } finally {
                try {
                    if (connection != null)
                        connection.disconnect();
                    if (out != null) {
                        out.flush();
                        out.close();
                    }
                    if (is != null)
                        is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return bitmap;
        }

            @Override
            protected void onPostExecute(Bitmap result) {
                if (result == null) {
                    Log.e(TAG, "factory returned a null result");
                    mImageLoaderListener.onError(new ImageError("downloaded file could not be decoded as bitmap")
                            .setErrorCode(ImageError.ERROR_DECODE_FAILED));
                } else {
                    Log.d(TAG, "download complete, " + result.getByteCount() +
                            " bytes transferred");
                    mImageLoaderListener.onComplete(result);
                }
                mUrlsInProgress.remove(imageUrl);
                System.gc();
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    public interface OnBitmapSaveListener {
        void onBitmapSaved();
        void onBitmapSaveError(ImageError error);
    }


    public static void writeToDisk(@NonNull final File imageFile, @NonNull final Bitmap image,
                               @NonNull final OnBitmapSaveListener listener,
                               @NonNull final Bitmap.CompressFormat format, boolean shouldOverwrite) {

    if (imageFile.isDirectory()) {
        listener.onBitmapSaveError(new ImageError("the specified path points to a directory, " +
                "should be a file").setErrorCode(ImageError.ERROR_IS_DIRECTORY));
        return;
    }

    if (imageFile.exists()) {
        if (!shouldOverwrite) {
            listener.onBitmapSaveError(new ImageError("file already exists, " +
                    "write operation cancelled").setErrorCode(ImageError.ERROR_FILE_EXISTS));
            return;
        } else if (!imageFile.delete()) {
            listener.onBitmapSaveError(new ImageError("could not delete existing file, " +
                    "most likely the write permission was denied")
                    .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
            return;
        }
    }

    File parent = imageFile.getParentFile();
    if (!parent.exists() && !parent.mkdirs()) {
        listener.onBitmapSaveError(new ImageError("could not create parent directory")
                .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
        return;
    }

    try {
        if (!imageFile.createNewFile()) {
            listener.onBitmapSaveError(new ImageError("could not create file")
                    .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
            return;
        }
    } catch (IOException e) {
        listener.onBitmapSaveError(new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION));
        return;
    }

    new AsyncTask<Void, Void, Void>() {

        private ImageError error;

        @Override
        protected Void doInBackground(Void... params) {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(imageFile);
                image.compress(format, 100, fos);
            } catch (IOException e) {
                error = new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION);
                this.cancel(true);
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onCancelled() {
            listener.onBitmapSaveError(error);
        }

        @Override
        protected void onPostExecute(Void result) {
            listener.onBitmapSaved();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  }

public static Bitmap readFromDisk(@NonNull File imageFile) {
    if (!imageFile.exists() || imageFile.isDirectory()) return null;
    return BitmapFactory.decodeFile(imageFile.getAbsolutePath());
}

public interface OnImageReadListener {
    void onImageRead(Bitmap bitmap);
    void onReadFailed();
}

public static void readFromDiskAsync(@NonNull File imageFile, @NonNull final OnImageReadListener listener) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            return BitmapFactory.decodeFile(params[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null)
                listener.onImageRead(bitmap);
            else
                listener.onReadFailed();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imageFile.getAbsolutePath());
}

    public static final class ImageError extends Throwable {

        private int errorCode;
        public static final int ERROR_GENERAL_EXCEPTION = -1;
        public static final int ERROR_INVALID_FILE = 0;
        public static final int ERROR_DECODE_FAILED = 1;
        public static final int ERROR_FILE_EXISTS = 2;
        public static final int ERROR_PERMISSION_DENIED = 3;
        public static final int ERROR_IS_DIRECTORY = 4;


        public ImageError(@NonNull String message) {
            super(message);
        }

        public ImageError(@NonNull Throwable error) {
            super(error.getMessage(), error.getCause());
            this.setStackTrace(error.getStackTrace());
        }

        public ImageError setErrorCode(int code) {
            this.errorCode = code;
            return this;
        }

        public int getErrorCode() {
            return errorCode;
        }
      }
   }

round value to 2 decimals javascript

Just multiply the number by 100, round, and divide the resulting number by 100.

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I faced this issue when I integrated spring boot with spring mvc. I solved it by just adding these dependencies.

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>

Where are logs located?

  • Ensure debug mode is on - either add APP_DEBUG=true to .env file or set an environment variable

  • Log files are in storage/logs folder. laravel.log is the default filename. If there is a permission issue with the log folder, Laravel just halts. So if your endpoint generally works - permissions are not an issue.

  • In case your calls don't even reach Laravel or aren't caused by code issues - check web server's log files (check your Apache/nginx config files to see the paths).

  • If you use PHP-FPM, check its log files as well (you can see the path to log file in PHP-FPM pool config).

Convert time span value to format "hh:mm Am/Pm" using C#

You can try this:

   string timeexample= string.Format("{0:hh:mm:ss tt}", DateTime.Now);

you can remove hh or mm or ss or tt according your need where hh is hour in 12 hr formate, mm is minutes,ss is seconds,and tt is AM/PM.

What is the equivalent of the C# 'var' keyword in Java?

Lombok supports var but it's still classified as experimental:

import lombok.experimental.var;

var number = 1; // Inferred type: int
number = 2; // Legal reassign since var is not final
number = "Hi"; // Compilation error since a string cannot be assigned to an int variable
System.out.println(number);

Here is a pitfall to avoid when trying to use it in IntelliJ IDEA. It appears to work as expected though including auto completion and everything. Until there is a "non-hacky" solution (e.g. due to JEP 286: Local-Variable Type Inference), this might be your best bet right now.

Note that val is support by Lombok as well without modifying or creating a lombok.config.

could not extract ResultSet in hibernate

For MySql take in mind that it's not a good idea to write camelcase. For example if the schema is like that:

CREATE TABLE IF NOT EXISTS `task`(
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `teaching_hours` DECIMAL(5,2) DEFAULT NULL,
    `isActive` BOOLEAN DEFAULT FALSE,
    `is_validated` BOOLEAN DEFAULT FALSE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You must be very careful cause isActive column will translate to isactive. So in your Entity class is should be like this:

 @Basic
 @Column(name = "isactive", nullable = true)
 public boolean isActive() {
     return isActive;
 }
 public void setActive(boolean active) {
     isActive = active;
 }

That was my problem at least that got me your error

This has nothing to do with MySql which is case insensitive, but rather is a naming strategy that spring will use to translate your tables. For more refer to this post

How do you specify a debugger program in Code::Blocks 12.11?

Click on settings in top tool bar;

Click on debugger;

In tree, highlight "gdb/cdb debugger" by clicking it

Click "create configuration"

Click default configuration, a dialogue will appear to the right for "executable path" with a button to the right.

Click on that button and it will bring up the file that codeblocks is installed in. Just keep clicking until you create the path to the gdb.exe (it sort of finds itself).

How do I send a cross-domain POST request via JavaScript?

Should be possible with a YQL custom table + JS XHR, take a look at: http://developer.yahoo.com/yql/guide/index.html

I use it to do some client side (js) html scraping, works fine (I have a full audio player, with search on internet/playlists/lyrics/last fm informations, all client js + YQL)

Append to the end of a Char array in C++

You should have enough space for array1 array and use something like strcat to contact array1 to array2:

char array1[BIG_ENOUGH];
char array2[X];
/* ......             */
/* check array bounds */
/* ......             */

strcat(array1, array2);

Get value of Span Text

You need to change your code as below:

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

javascript regular expression to check for IP addresses

Simple Method

const invalidIp = ipAddress
   .split(".")
   .map(ip => Number(ip) >= 0 && Number(ip) <= 255)
   .includes(false);

if(invalidIp){
 // IP address is invalid
 // throw error here
}

I want to multiply two columns in a pandas DataFrame and add the result into a new column

If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:

In [22]: orders_df['C'] = orders_df.Action.apply(
               lambda x: (1 if x == 'Sell' else -1))

In [23]: orders_df   # New column C represents the sign of the transaction
Out[23]:
   Prices  Amount Action  C
0       3      57   Sell  1
1      89      42   Sell  1
2      45      70    Buy -1
3       6      43   Sell  1
4      60      47   Sell  1
5      19      16    Buy -1
6      56      89   Sell  1
7       3      28    Buy -1
8      56      69   Sell  1
9      90      49    Buy -1

Now we have eliminated the need for the if statement. Using DataFrame.apply(), we also do away with the for loop. As Hayden noted, vectorized operations are always faster.

In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C

In [25]: orders_df   # The resulting dataframe
Out[25]:
   Prices  Amount Action  C  Value
0       3      57   Sell  1    171
1      89      42   Sell  1   3738
2      45      70    Buy -1  -3150
3       6      43   Sell  1    258
4      60      47   Sell  1   2820
5      19      16    Buy -1   -304
6      56      89   Sell  1   4984
7       3      28    Buy -1    -84
8      56      69   Sell  1   3864
9      90      49    Buy -1  -4410

This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.

Running an executable in Mac Terminal

Unix will only run commands if they are available on the system path, as you can view by the $PATH variable

echo $PATH

Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such

./my-exec

Where my-exec is the name of your program.

Format bytes to kilobytes, megabytes, gigabytes

function byte_format($size) {
    $bytes = array( ' KB', ' MB', ' GB', ' TB' );
    foreach ($bytes as $val) {
        if (1024 <= $size) {
            $size = $size / 1024;
            continue;
        }
        break;
    }
    return round( $size, 1 ) . $val;
}

Image re-size to 50% of original size in HTML

The percentage setting does not take into account the original image size. From w3schools :

In HTML 4.01, the width could be defined in pixels or in % of the containing element. In HTML5, the value must be in pixels.

Also, good practice advice from the same source :

Tip: Downsizing a large image with the height and width attributes forces a user to download the large image (even if it looks small on the page). To avoid this, rescale the image with a program before using it on a page.

Why shouldn't I use "Hungarian Notation"?

I've always thought that a prefix or two in the right place wouldn't hurt. I think if I can impart something useful, like "Hey this is an interface, don't count on specific behaviour" right there, as in IEnumerable, I oughtta do it. Comment can clutter things up much more than just a one or two character symbol.

Error when deploying an artifact in Nexus

I had this exact problem today and the problem was that the version I was trying to release:perform was already in the Nexus repo.

In my case this was likely due to a network disconnect during an earlier invocation of release:perform. Even though I lost my connection, it appears the release succeeded.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

This problem is caused by URLSession has two dataTask methods

open func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask
open func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask

The first one has URLRequest as parameter, and the second one has URL as parameter, so we need to specify which type to call, for example, I want to call the second method

let task = URLSession.shared.dataTask(with: url! as URL) {
    data, response, error in
    // Handler
}

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Paths specified with a . are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js but not if you run node folder/app.js. The only exception to this is require('./file') and that is only possible because require exists per-module and thus knows what module it is being called from.

To make a path relative to the script, you must use the __dirname variable.

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

path.join(__dirname, 'path', 'to', 'file')

How to detect online/offline event cross-browser?

Since recently, navigator.onLine shows the same on all major browsers, and is thus useable.

if (navigator.onLine) {
  // do things that need connection
} else {
  // do things that don't need connection
}

The oldest versions that support this in the right way are: Firefox 41, IE 9, Chrome 14 and Safari 5.

Currently this will represent almost the whole spectrum of users, but you should always check what the users of your page have of capabilities.

Previous to FF 41, it would only show false if the user put the browser manually in offline mode. In IE 8, the property was on the body, instead of window.

source: caniuse

How to calculate the difference between two dates using PHP?

I don't know if you are using a PHP framework or not, but a lot of PHP frameworks have date/time libraries and helpers to help keep you from reinventing the wheel.

For example CodeIgniter has the timespan() function. Simply input two Unix timestamps and it will automatically generate a result like this:

1 Year, 10 Months, 2 Weeks, 5 Days, 10 Hours, 16 Minutes

http://codeigniter.com/user_guide/helpers/date_helper.html

How to store printStackTrace into a string

Something along the lines of

StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
return errors.toString();

Ought to be what you need.

Relevant documentation:

How to set the height of table header in UITableView?

You can create a UIView with the desired height (the width should be that of the UITableView), and inside it you can place a UIImageView with the picture of the proper dimensions: they won't stretch automatically.

You can also give margin above and below the inner UIImageView, by giving a higher height to the container view.

Additionally, you can assign a Translation transform in order to place the image in the middle of its container header view, for example.

How to get my project path?

Your program has no knowledge of where your VS project is, so see get path for my .exe and go ../.. to get your project's path.

TypeError: Can't convert 'int' object to str implicitly

def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
    print("Your SP balance is now 0.")
    attributeConfirmation()
elif strength < 0:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif strength > balance:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
    print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
    print("That is an invalid input. Restarting attribute selection.")
    attributeSelection()

How to mute an html5 video player using jQuery

If you don't want to jQuery, here's the vanilla JavaScript:

///Mute
var video = document.getElementById("your-video-id");
video.muted= true;

//Unmute
var video = document.getElementById("your-video-id");
video.muted= false;

It will work for audio too, just put the element's id and it will work (and change the var name if you want, to 'media' or something suited for both audio/video as you like).

Java: JSON -> Protobuf & back conversion

We are currently using protobuf-java-format to convert our Protobuf messages (anything subclass of Message) into a JSON format to send over our web API.

Simply do:

  JsonFormat.printToString(protoMessage)

How to check if an integer is in a given range?

If you are confident that numbers are stored in 2's complement form:

return  ((x-low) <= (high-low));

A more general and safer solution would be:

return ((x-high)*(x-low) <= 0);

setting textColor in TextView in layout/main.xml main layout file not referencing colors.xml file. (It wants a #RRGGBB instead of @color/text_color)

You have a typo in your xml; it should be:

android:textColor="@color/text_color"

that's "@color" without the 's'.

Replace an element into a specific position of a vector

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

Upgrade version of Pandas

Add your C:\WinPython-64bit-3.4.4.1\python_***\Scripts folder to your system PATH variable by doing the following:

  1. Select Start, select Control Panel. double click System, and select the Advanced tab.
  2. Click Environment Variables. ...

  3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. ...

  4. Reopen Command prompt window

Is it possible to use jQuery to read meta tags

I just tried this, and this could be a jQuery version-specific error, but

$("meta[property=twitter:image]").attr("content");

resulted in the following syntax error for me:

Error: Syntax error, unrecognized expression: meta[property=twitter:image]

Apparently it doesn't like the colon. I was able to fix it by using double and single quotes like this:

$("meta[property='twitter:image']").attr("content");

(jQuery version 1.8.3 -- sorry, I would have made this a comment to @Danilo, but it won't let me comment yet)

How is the AND/OR operator represented as in Regular Expressions?

Or you can use this:

^(?:part[12]|(part)1,\12)$

.htaccess not working apache

Most probably, AllowOverride is set to None. in Directory section of apache2.conf located in /etc/apache2 folder

Try setting it to AllowOverride All

How can I view a git log of just one user's commits?

Show n number of logs for x user in colour by adding this little snippet in your .bashrc file.

gitlog() {
    if [ "$1" ] && [ "$2" ]; then
       git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order -n "$1" --author="$2"
    elif [ "$1" ]; then
       git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order -n "$1"
    else
        git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order
    fi
}

alias l=gitlog

To show the last 10 commits by Frank:

l 10 frank

To show the last 20 commits by anyone:

l 20

How to change column order in a table using sql query in sql server 2005?

alter table name modify columnname int(5) first; will bring the column to first alter table name modify columnname int(5) after (tablename);

How do I measure execution time of a command on the Windows command line?

This is a one-liner which avoids delayed expansion, which could disturb certain commands:

cmd /E /C "prompt $T$$ & echo.%TIME%$ & COMMAND_TO_MEASURE & for %Z in (.) do rem/ "

The output is something like:

14:30:27.58$
...
14:32:43.17$ rem/ 

For long-term tests replace $T by $D, $T and %TIME% by %DATE%, %TIME% to include the date.

To use this inside of a batch file, replace %Z by %%Z.


Update

Here is an improved one-liner (without delayed expansion too):

cmd /E /C "prompt $D, $T$$ & (for %# in (.) do rem/ ) & COMMAND_TO_MEASURE & for %# in (.) do prompt"

The output looks similar to this:

2015/09/01, 14:30:27.58$ rem/ 
...
2015/09/01, 14:32:43.17$ prompt

This approach does not include the process of instancing a new cmd in the result, nor does it include the prompt command(s).

Installing PHP Zip Extension

If you use php5.6 then execute this:

sudo apt-get install php5.6-zip

Does C have a "foreach" loop construct?

There is no foreach in C.

You can use a for loop to loop through the data but the length needs to be know or the data needs to be terminated by a know value (eg. null).

char* nullTerm;
nullTerm = "Loop through my characters";

for(;nullTerm != NULL;nullTerm++)
{
    //nullTerm will now point to the next character.
}

How do I request and receive user input in a .bat and use it to run a certain program?

I have improved batch file with yes or no prompt. If user enter any character except y and n , then it will again prompt user for valid input. It Works for me.

    @echo off

    :ConfirmBox 
        set /P c= Are you sure want to contine (y/n)?

    if /I "%c%" EQU "Y" (
    goto :FnYes 
    ) else if /I "%c%" EQU "N" ( 
    goto :FnNo
    ) else ( 
    goto :InValid 
    )


:FnYes
     echo You have entered Y
     goto :END

:FnNo
     echo You have entered N
     goto :END

:InValid
     echo Invalid selection. Enter Y or N
     goto :ConfirmBox

:END
    pause
    exit  

/I in if condition will validate both lowercase and uppercase characters.

limit text length in php and provide 'Read more' link

Another method: insert the following in your theme's function.php file.

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_trim_excerpt');

function custom_trim_excerpt($text) { // Fakes an excerpt if needed
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = x;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
array_push($words, '...');
$text = implode(' ', $words);
}
}
return $text;
}

You can use this.

Disable and later enable all table indexes in Oracle

If you're on Oracle 11g, you may also want to check out dbms_index_utl.

Internal and external fragmentation

External fragmentation
Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous so it can not be used.

External fragmentation

Internal fragmentation
Memory block assigned to process is bigger. Some portion of memory is left unused as it can not be used by another process.

Internal fragmentation

Get Return Value from Stored procedure in asp.net

you can try this.Add the parameter as output direction and after executing the query get the output parameter value.

  SqlParameter parmOUT = new SqlParameter("@return", SqlDbType.Int);
  parmOUT.Direction = ParameterDirection.Output;
  cmd.Parameters.Add(parmOUT);
  cmd.ExecuteNonQuery();
  int returnVALUE = (int)cmd.Parameters["@return"].Value;

Remove empty lines in a text file via grep

grep '^..' my_file

example

THIS

IS

THE

FILE

EOF_MYFILE

it gives as output only lines with at least 2 characters.

THIS
IS
THE
FILE
EOF_MYFILE

See also the results with grep '^' my_file outputs

THIS

IS

THE

FILE

EOF_MYFILE

and also with grep '^.' my_file outputs

THIS
IS
THE
FILE
EOF_MYFILE

json_encode/json_decode - returns stdClass instead of Array in PHP

Take a closer look at the second parameter of json_decode($json, $assoc, $depth) at https://secure.php.net/json_decode

What is the string concatenation operator in Oracle?

DECLARE
     a      VARCHAR2(30);
     b      VARCHAR2(30);
     c      VARCHAR2(30);
 BEGIN
      a  := ' Abc '; 
      b  := ' def ';
      c  := a || b;
 DBMS_OUTPUT.PUT_LINE(c);  
   END;

output:: Abc def

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

It's a surprisingly little-known feature of C++ (as evidenced by the fact that no-one has given this as an answer yet), but it actually has special syntax for value-initializing an array:

new int[10]();

Note that you must use the empty parentheses — you cannot, for example, use (0) or anything else (which is why this is only useful for value initialization).

This is explicitly permitted by ISO C++03 5.3.4[expr.new]/15, which says:

A new-expression that creates an object of type T initializes that object as follows:

...

  • If the new-initializer is of the form (), the item is value-initialized (8.5);

and does not restrict the types for which this is allowed, whereas the (expression-list) form is explicitly restricted by further rules in the same section such that it does not allow array types.

Set position / size of UI element as percentage of screen size

I think what you want is to set the android:layout_weight,

http://developer.android.com/resources/tutorials/views/hello-linearlayout.html

something like this (I'm just putting text views above and below as placeholders):

  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="68"/>
    <Gallery 
        android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="0dp"

        android:layout_weight="16"
    />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="16"/>

  </LinearLayout>

Div Scrollbar - Any way to style it?

This one does well its scrolling job. It's very easy to understand, just really few lines of code, well written and totally readable.

Post form data using HttpWebRequest

Use this code:

internal void SomeFunction() {
    Dictionary<string, string> formField = new Dictionary<string, string>();
    
    formField.Add("Name", "Henry");
    formField.Add("Age", "21");
    
    string body = GetBodyStringFromDictionary(formField);
    // output : Name=Henry&Age=21
}

internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
    string body = string.Empty;
    foreach (var pair in formField)
    {
        body += $"{pair.Key}={pair.Value}&";   
    }

    // delete last "&"
    body = body.Substring(0, body.Length - 1);

    return body;
}

how to call scalar function in sql server 2008

For Scalar Function Syntax is

Select dbo.Function_Name(parameter_name)

Select dbo.Department_Employee_Count('HR')

Using Get-childitem to get a list of files modified in the last 3 days

Here's a minor update to the solution provided by Dave Sexton. Many times you need multiple filters. The Filter parameter can only take a single string whereas the -Include parameter can take a string array. if you have a large file tree it also makes sense to only get the date to compare with once, not for each file. Here's my updated version:

$compareDate = (Get-Date).AddDays(-3)    
@(Get-ChildItem -Path c:\pstbak\*.* -Filter '*.pst','*.mdb' -Recurse | Where-Object { $_.LastWriteTime -gt $compareDate}).Count

Import MySQL database into a MS SQL Server

Run:

mysqldump -u root -p your_target_DB --compatible=mssql > MSSQL_Compatible_Data.sql

Do you want to see a process bar?

pv mysqldump -u root -p your_target_DB --compatible=mssql > MSSQL_Compatible_Data.sql

How to use XPath preceding-sibling correctly

You don't need to go level up and use .. since all buttons are on the same level:

//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']

How to import an excel file in to a MySQL database

Below is another method to import spreadsheet data into a MySQL database that doesn't rely on any extra software. Let's assume you want to import your Excel table into the sales table of a MySQL database named mydatabase.

  1. Select the relevant cells:

    enter image description here

  2. Paste into Mr. Data Converter and select the output as MySQL:

    enter image description here

  3. Change the table name and column definitions to fit your requirements in the generated output:

CREATE TABLE sales (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  Country VARCHAR(255),
  Amount INT,
  Qty FLOAT
);
INSERT INTO sales
  (Country,Amount,Qty)
VALUES
  ('America',93,0.60),
  ('Greece',9377,0.80),
  ('Australia',9375,0.80);
  1. If you're using MySQL Workbench or already logged into mysql from the command line, then you can execute the generated SQL statements from step 3 directly. Otherwise, paste the code into a text file (e.g., import.sql) and execute this command from a Unix shell:

    mysql mydatabase < import.sql

    Other ways to import from a SQL file can be found in this Stack Overflow answer.

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

After 2 hrs of net surfing Finally For me the problem was fixed by creating a folder pip, with a file: pip.ini in C:\Users<username>\AppData\Roaming\ e.g:

C:\Users\<username>\AppData\Roaming\pip\pip.ini

Inside it I wrote:

[global]
trusted-host = pypi.python.org
pypi.org
files.pythonhosted.org

I restarted python, and then pip permanently trusted these sites, and used them to download packages from.

If you can't find the AppData Folder on windows, write %appdata% in file explorer and it should appear.

Source : pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

How to search for a string in cell array in MATLAB?

Since 2011a, the recommended way is:

booleanIndex = strcmp('KU', strs)

If you want to get the integer index (which you often don't need), you can use:

integerIndex = find(booleanIndex);

strfind is deprecated, so try not to use it.

How can I remove text within parentheses with a regex?

If a path may contain parentheses then the r'\(.*?\)' regex is not enough:

import os, re

def remove_parenthesized_chunks(path, safeext=True, safedir=True):
    dirpath, basename = os.path.split(path) if safedir else ('', path)
    name, ext = os.path.splitext(basename) if safeext else (basename, '')
    name = re.sub(r'\(.*?\)', '', name)
    return os.path.join(dirpath, name+ext)

By default the function preserves parenthesized chunks in directory and extention parts of the path.

Example:

>>> f = remove_parenthesized_chunks
>>> f("Example_file_(extra_descriptor).ext")
'Example_file_.ext'
>>> path = r"c:\dir_(important)\example(extra).ext(untouchable)"
>>> f(path)
'c:\\dir_(important)\\example.ext(untouchable)'
>>> f(path, safeext=False)
'c:\\dir_(important)\\example.ext'
>>> f(path, safedir=False)
'c:\\dir_\\example.ext(untouchable)'
>>> f(path, False, False)
'c:\\dir_\\example.ext'
>>> f(r"c:\(extra)\example(extra).ext", safedir=False)
'c:\\\\example.ext'

How should I edit an Entity Framework connection string?

If you remove the connection string from the app.config file, re-running the entity Data Model wizard will guide you to build a new connection.

How to jump back to NERDTree from file in tab?

NERDTree opens up in another window. That split view you're seeing? They're called windows in vim parlance. All the window commands start with CTRL-W. To move from adjacent windows that are left and right of one another, you can change focus to the window to the left of your current window with CTRL-w h, and move focus to the right with CTRL-w l. Likewise, CTRL-w j and CTRL-w k will move you between horizontally split windows (i.e., one window is above the other). There's a lot more you can do with windows as described here.

You can also use the :NERDTreeToggle command to make your tree open and close. I usually bind that do t.

How to get current url in view in asp.net core 1.0

You can use the extension method of Request:

Request.GetDisplayUrl()

How can I get the number of days between 2 dates in Oracle 11g?

This will work i have tested myself.
It gives difference between sysdate and date fetched from column admitdate

  TABLE SCHEMA:
    CREATE TABLE "ADMIN"."DUESTESTING" 
    (   
  "TOTAL" NUMBER(*,0), 
"DUES" NUMBER(*,0), 
"ADMITDATE" TIMESTAMP (6), 
"DISCHARGEDATE" TIMESTAMP (6)
    )

EXAMPLE:
select TO_NUMBER(trunc(sysdate) - to_date(to_char(admitdate, 'yyyy-mm-dd'),'yyyy-mm-dd')) from admin.duestesting where total=300

Git undo changes in some files

Yes;

git commit FILE

will commit just FILE. Then you can use

git reset --hard

to undo local changes in other files.

There may be other ways too that I don't know about...

edit: or, as NicDumZ said, git-checkout just the files you want to undo the changes on (the best solution depends on wether there are more files to commit or more files to undo :-)

Darkening an image with CSS (In any shape)

I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!

style

.wrapper{background-image:url(silhouette.png);} 
.original{opacity:0.7:}
.original:hover{opacity:1}

<div class="wrapper">
  <div class="img">
    <img src="original.png">
  </div>
</div>

How to increase buffer size in Oracle SQL Developer to view all records?

Select Tools > Preferences > Database / Advanced

There is an input field for Sql Array Fetch Size but it only allows setting a max of 500 rows.

How can I read the contents of an URL with Python?

You can use requests and beautifulsoup libraries to read data on a website. Just install these two libraries and type the following code.

import requests
import bs4
help(requests)
help(bs4)

You will get all the information you need about the library.

Error running android: Gradle project sync failed. Please fix your project and try again

Just ignore the error and try running the project anyway. It will fail, but this time you will get a link in the error description. Clicking the link will trigger the automatic update/download of the outdated/missing component.

In my scenario, the project failed to launch two times, each time another API/SDK component being the culprit.

In my case I was just trying to launch a sample project I downloaded, having no clue what API level was being targeted or where to look for this information.

How to launch Windows Scheduler by command-line?

You might want to have look at simple command line scheduler "at":


C:\Documents and Settings\mahendra.patil>at/?

The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command.

AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE]
    [ /EVERY:date[,...] | /NEXT:date[,...]] "command"

\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is omitted.

id Is an identification number assigned to a scheduled command.

/delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are canceled.

/yes Used with cancel all jobs command when no further confirmation is desired.

time Specifies the time when command is to run.

/interactive Allows the job to interact with the desktop of the user who is logged on at the time the job runs.

/every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day of the month is assumed.

/next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, the current day of the month is assumed.

"command" Is the Windows NT command, or batch program to be run.

Unable to find velocity template resources

Just a simple velocity standalone app based on maven structure. Here is the code snippet written in Scala to render the template helloworld.vm in

${basedir}/src/main/resources folder:

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

References with text in LaTeX

I think you can do this with the hyperref package, although I've not tried it myself. From the relevant LaTeX Wikibook section:

The hyperref package introduces another useful command; \autoref{}. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command \autoref{sec:intro} would create a hyperlink to the \label{sec:intro} command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining \typeautorefname to the prefix you want, as in:

\def\subsectionautorefname{section}

How do I instantiate a JAXBElement<String> object?

I don't know why you think there's no constructor. See the API.

How to show two figures using matplotlib?

Alternatively, I would suggest turning interactive on in the beginning and at the very last plot, turn it off. All will show up, but they will not disappear as your program will stay around until you close the figures.

import matplotlib.pyplot as plt
from matplotlib import interactive

plt.figure(1)
... code to make figure (1)

interactive(True)
plt.show()

plt.figure(2)
... code to make figure (2)

plt.show()

plt.figure(3)
... code to make figure (3)

interactive(False)
plt.show()

How to make a WPF window be on top of all other windows of my app (not system wide)?

This is what helped me:

Window selector = new Window ();
selector.Show();
selector.Activate();
selector.Topmost = true;

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

PYTHONPATH only affects import statements, not the top-level Python interpreter's lookup of python files given as arguments.

Needing PYTHONPATH to be set is not a great idea - as with anything dependent on environment variables, replicating things consistently across different machines gets tricky. Better is to use Python 'packages' which can be installed (using 'pip', or distutils) in system-dependent paths which Python already knows about.

Have a read of https://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/ - 'The Hitchhiker's Guide to Packaging', and also http://docs.python.org/3/tutorial/modules.html - which explains PYTHONPATH and packages at a lower level.

Using SELECT result in another SELECT

You are missing table NewScores, so it can't be found. Just join this table.

If you really want to avoid joining it directly you can replace NewScores.NetScore with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}

Setting equal heights for div's with jQuery

Answer to your specific question

Your code was checking all columns within any container, what you need to do is:

  • Loop through each container
    • Get the heights of each column within that container
    • Find the highest one
    • Apply that height to every column in that container before moving on to the next one.

Note: Try to provide an example jsfiddle of your issue, it enables us to more easily help you and understand the issue, you get to see the working solution straight away and it encourages quicker responses.

Quick (Rough) Example

_x000D_
_x000D_
$(document).ready(function(){_x000D_
_x000D_
    // Select and loop the container element of the elements you want to equalise_x000D_
    $('.container').each(function(){  _x000D_
      _x000D_
      // Cache the highest_x000D_
      var highestBox = 0;_x000D_
      _x000D_
      // Select and loop the elements you want to equalise_x000D_
      $('.column', this).each(function(){_x000D_
        _x000D_
        // If this box is higher than the cached highest then store it_x000D_
        if($(this).height() > highestBox) {_x000D_
          highestBox = $(this).height(); _x000D_
        }_x000D_
      _x000D_
      });  _x000D_
            _x000D_
      // Set the height of all those children to whichever was highest _x000D_
      $('.column',this).height(highestBox);_x000D_
                    _x000D_
    }); _x000D_
_x000D_
});
_x000D_
.container { border 1px solid red; }_x000D_
.column { border: 1px solid blue; float:left; width: 30%; text-align:center; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
    <div class="column">This is<br />the highest<br />column</div>_x000D_
    <div class="column">One line</div>_x000D_
    <div class="column">Two<br />lines</div>_x000D_
</div>_x000D_
<div class="container">_x000D_
    <div class="column">One line</div>_x000D_
    <div class="column">Two<br>lines</div>_x000D_
    <div class="column">One line</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Library!

Here's a library i found that looks promising if you want some more clever equalisation controls

http://brm.io/jquery-match-height-demo/



Addressing @Mem's question

Question: Will $(document).ready() work if you have images that need to load which in turn modify the heights of the containers?


Equalising heights after image load

If you are loading images, you will find that this solution doesn't always work. This is because document.ready is fired at the earliest possible time, which means it does not wait for external resources to be loaded in (such as images).

When your images finally load, they may distort the heights of their containers after the equalisation script has run, causing it too appear not too work.


Solving equalising heights with images

  1. Bind to image loading events

This is the best solution (at the time of writing) and involves binding to the img.load event. All you have to do is get a count of how many img's there are $('img').length and then for each load, -1 from that count until you hit zero, then fire the equaliser.

The caveat here is load may not fire in all browsers if the image is in the cache. Look around google/github, there should be a solution script out there. At the time of writing i found waitForImages from Alexander Dickson (untested, this is not an endorsement).

  1. Another more reliable solution is the window.load event. This should generally always work. However, if you check the docs out, you'll notice this event fires after ALL external resources are loaded. This means if your images are loaded but there's some javascript waiting to download it won't fire until that completes.

If you load the majority of your externals asyncronously and are clever with minimising, compressing and spreading the load you probably wont have any issues with this method, however a suddenly slow CDN (happens all the time) could cause issues.

In both cases, you could take a dumb approach and apply fallback timers. Have the equalise script run automatically after a set few seconds just in case the event doesn't fire or something is slow out of your control. It's not fool proof, but in reality you'll satisfy 99% of your visitors with this fallback if you tune the timer correctly.



Years later this is still getting upvotes, with flexbox widely supported these days you may want to consider just plain CSS for this, unless there's a specific reason you are using JS for it

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  border: 2px dashed red;_x000D_
  margin: 10px 0;_x000D_
}_x000D_
_x000D_
.container > .column { _x000D_
 padding: 10px;_x000D_
}_x000D_
_x000D_
.container.fill-width {_x000D_
  justify-content: stretch;_x000D_
}_x000D_
_x000D_
.container.fill-width>.column {_x000D_
  flex-grow: 1_x000D_
}_x000D_
_x000D_
.container>.column:nth-child(1) {_x000D_
  background: yellow;_x000D_
}_x000D_
_x000D_
.container>.column:nth-child(2) {_x000D_
  background: blue;_x000D_
}_x000D_
_x000D_
.container>.column:nth-child(3) {_x000D_
  background: green;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="column">Some<br>text</div>_x000D_
  <div class="column">Some<br>more<br>text<br>here</div>_x000D_
  <div class="column">One line</div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="column">Some<br>more<br>even<br>longer<br>text<br>here</div>_x000D_
  <div class="column">Some<br>text</div>_x000D_
  <div class="column">One line</div>_x000D_
</div>_x000D_
<div class="container fill-width">_x000D_
  <div class="column">Some<br>more<br>text<br>here</div>_x000D_
  <div class="column">Some<br>text</div>_x000D_
  <div class="column">One line</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is there a way to get the XPath in Google Chrome?

Slightly OT, but perhaps useful: On Mac Chrome, although you cannot copy the xpath out of the search box in the Dev tools panel (instead, copy grabs the node as HTML), you can drag and drop the text into an external editor.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

One more variant with foreign keys support and in one statement:

 SELECT
        obj.name
        ,'CREATE TABLE [' + obj.name + '] (' + LEFT(cols.list, LEN(cols.list) - 1 ) + ')'
        + ISNULL(' ' + refs.list, '')
    FROM sysobjects obj
    CROSS APPLY (
        SELECT 
            CHAR(10)
            + ' [' + column_name + '] '
            + data_type
            + CASE data_type
                WHEN 'sql_variant' THEN ''
                WHEN 'text' THEN ''
                WHEN 'ntext' THEN ''
                WHEN 'xml' THEN ''
                WHEN 'decimal' THEN '(' + CAST(numeric_precision as VARCHAR) + ', ' + CAST(numeric_scale as VARCHAR) + ')'
                ELSE COALESCE('(' + CASE WHEN character_maximum_length = -1 THEN 'MAX' ELSE CAST(character_maximum_length as VARCHAR) END + ')', '')
            END
            + ' '
            + case when exists ( -- Identity skip
            select id from syscolumns
            where object_name(id) = obj.name
            and name = column_name
            and columnproperty(id,name,'IsIdentity') = 1 
            ) then
            'IDENTITY(' + 
            cast(ident_seed(obj.name) as varchar) + ',' + 
            cast(ident_incr(obj.name) as varchar) + ')'
            else ''
            end + ' '
            + CASE WHEN IS_NULLABLE = 'No' THEN 'NOT ' ELSE '' END
            + 'NULL'
            + CASE WHEN information_schema.columns.column_default IS NOT NULL THEN ' DEFAULT ' + information_schema.columns.column_default ELSE '' END
            + ','
        FROM
            INFORMATION_SCHEMA.COLUMNS
        WHERE table_name = obj.name
        ORDER BY ordinal_position
        FOR XML PATH('')
    ) cols (list)
    CROSS APPLY(
        SELECT
            CHAR(10) + 'ALTER TABLE ' + obj.name + '_noident_temp ADD ' + LEFT(alt, LEN(alt)-1)
        FROM(
            SELECT
                CHAR(10)
                + ' CONSTRAINT ' + tc.constraint_name
                + ' ' + tc.constraint_type + ' (' + LEFT(c.list, LEN(c.list)-1) + ')'
                + COALESCE(CHAR(10) + r.list, ', ')
            FROM
                information_schema.table_constraints tc
                CROSS APPLY(
                    SELECT
                        '[' + kcu.column_name + '], '
                    FROM
                        information_schema.key_column_usage kcu
                    WHERE
                        kcu.constraint_name = tc.constraint_name
                    ORDER BY
                        kcu.ordinal_position
                    FOR XML PATH('')
                ) c (list)
                OUTER APPLY(
                    -- // http://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema
                    SELECT
                        '  REFERENCES [' + kcu1.constraint_schema + '].' + '[' + kcu2.table_name + ']' + '(' + kcu2.column_name + '), '
                    FROM information_schema.referential_constraints as rc
                        JOIN information_schema.key_column_usage as kcu1 ON (kcu1.constraint_catalog = rc.constraint_catalog AND kcu1.constraint_schema = rc.constraint_schema AND kcu1.constraint_name = rc.constraint_name)
                        JOIN information_schema.key_column_usage as kcu2 ON (kcu2.constraint_catalog = rc.unique_constraint_catalog AND kcu2.constraint_schema = rc.unique_constraint_schema AND kcu2.constraint_name = rc.unique_constraint_name AND kcu2.ordinal_position = KCU1.ordinal_position)
                    WHERE
                        kcu1.constraint_catalog = tc.constraint_catalog AND kcu1.constraint_schema = tc.constraint_schema AND kcu1.constraint_name = tc.constraint_name
                ) r (list)
            WHERE tc.table_name = obj.name
            FOR XML PATH('')
        ) a (alt)
    ) refs (list)
    WHERE
        xtype = 'U'
    AND name NOT IN ('dtproperties')
    AND obj.name = 'your_table_name'

You could try in is sqlfiddle: http://sqlfiddle.com/#!6/e3b66/3/0

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

Using multiple delimiters in awk

The delimiter can be a regular expression.

awk -F'[/=]' '{print $3 "\t" $5 "\t" $8}' file

Produces:

tc0001   tomcat7.1    demo.example.com  
tc0001   tomcat7.2    quest.example.com  
tc0001   tomcat7.5    www.example.com

What's the use of ob_start() in php?

The accepted answer here describes what ob_start() does - not why it is used (which was the question asked).

As stated elsewhere ob_start() creates a buffer which output is written to.

But nobody has mentioned that it is possible to stack multiple buffers within PHP. See ob_get_level().

As to the why....

  1. Sending HTML to the browser in larger chunks gives a performance benefit from a reduced network overhead.

  2. Passing the data out of PHP in larger chunks gives a performance and capacity benefit by reducing the number of context switches required

  3. Passing larger chunks of data to mod_gzip/mod_deflate gives a performance benefit in that the compression can be more efficient.

  4. buffering the output means that you can still manipulate the HTTP headers later in the code

  5. explicitly flushing the buffer after outputting the [head]....[/head] can allow the browser to begin marshaling other resources for the page before HTML stream completes.

  6. Capturing the output in a buffer means that it can redirected to other functions such as email, or copied to a file as a cached representation of the content

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

Never faced this problem before (not worked much on email, I avoid it like the plague) but you could try declaring the bullet with the unicode code point (different notation for CSS than for HTML): content: '\2022'. (you need to use the hex number, not the 8226 decimal one)

Then, in case you use something that picks up those characters and HTML-encodes them into entities (which won't work for CSS strings), I guess it will ignore that.

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

HTML5 Video Autoplay not working correctly

Chrome does not allow autoplay if the video is not muted. Try using this:

<video width="440px" loop="true" autoplay="autoplay" controls muted>
  <source src="http://www.tuscorlloyds.com/CorporateVideo.mp4" type="video/mp4" />
  <source src="http://www.tuscorlloyds.com/CorporateVideo.ogv" type="video/ogv" />
  <source src="http://www.tuscorlloyds.com/CorporateVideo.webm" type="video/webm" />
</video>

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

You can use this

if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) 
    {
        // for iOS 8
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

        [application registerForRemoteNotifications];
    }
    else
    {
        // for iOS < 8
        [application registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
    }

    // RESET THE BADGE COUNT 
    application.applicationIconBadgeNumber = 0;

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Should I use pt or px?

Here you've got a very detailed explanation of their differences

http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/

The jist of it (from source)

Pixels are fixed-size units that are used in screen media (i.e. to be read on the computer screen). Pixel stands for "picture element" and as you know, one pixel is one little "square" on your screen. Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.

How to get the file path from URI?

Here is the answer to the question here

Actually we have to get it from the sharable ContentProvider of Camera Application.

EDIT . Copying answer that worked for me

private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;

}

Generic Interface

Here's one suggestion:

public interface Service<T,U> {
    T executeService(U... args);
}

public class MyService implements Service<String, Integer> {
    @Override
    public String executeService(Integer... args) {
        // do stuff
        return null;
    }
}

Because of type erasure any class will only be able to implement one of these. This eliminates the redundant method at least.

It's not an unreasonable interface that you're proposing but I'm not 100% sure of what value it adds either. You might just want to use the standard Callable interface. It doesn't support arguments but that part of the interface has the least value (imho).

Create component to specific module with Angular-CLI

I am having the similar issues with multiple modules in application. A component can be created to any module so before creating a component we have to specify the name of the particular module.

'ng generate component newCompName --module= specify name of module'

Collision Detection between two images in Java

You don't want to have the collision check code inside the painting code. The painting needs to be fast. Collision can go in the game loop. Therefore you need an internal representation of the objects independent of their sprites.

How to get the last value of an ArrayList

How about this.. Somewhere in your class...

List<E> list = new ArrayList<E>();
private int i = -1;
    public void addObjToList(E elt){
        i++;
        list.add(elt);
    }


    public E getObjFromList(){
        if(i == -1){ 
            //If list is empty handle the way you would like to... I am returning a null object
            return null; // or throw an exception
        }

        E object = list.get(i);
        list.remove(i); //Optional - makes list work like a stack
        i--;            //Optional - makes list work like a stack
        return object;
    }

Proper way of checking if row exists in table in PL/SQL block

I wouldn't push regular code into an exception block. Just check whether any rows exist that meet your condition, and proceed from there:

declare
  any_rows_found number;
begin
  select count(*)
  into   any_rows_found
  from   my_table
  where  rownum = 1 and
         ... other conditions ...

  if any_rows_found = 1 then
    ...
  else
    ...
  end if;

Python Script Uploading files via FTP

To avoid getting the encryption error you can also try out below commands

ftp = ftplib.FTP_TLS("ftps.dummy.com")
ftp.login("username", "password")
ftp.prot_p()
file = open("filename", "rb")
ftp.storbinary("STOR filename", file)
file.close()
ftp.close()

ftp.prot_p() ensure that your connections are encrypted

Adding timestamp to a filename with mv in BASH

I use this command for simple rotate a file:

mv output.log `date +%F`-output.log

In local folder I have 2019-09-25-output.log

How should I make my VBA code compatible with 64-bit Windows?

Office 2007 is 32 bit only so there is no issue there. Your problems arise only with Office 64 bit which has both 32 and 64 bit versions.

You cannot hope to support users with 64 bit Office 2010 when you only have Office 2007. The solution is to upgrade.

If the only Declare that you have is that ShellExecute then you won't have much to do once you get hold of 64 bit Office, but it's not really viable to support users when you can't run the program that you ship! Just think what you would do you do when they report a bug?

How to Correctly Use Lists in R?

why do these two different operators, [ ], and [[ ]], return the same result?

x = list(1, 2, 3, 4)
  1. [ ] provides sub setting operation. In general sub set of any object will have the same type as the original object. Therefore, x[1] provides a list. Similarly x[1:2] is a subset of original list, therefore it is a list. Ex.

    x[1:2]
    
    [[1]] [1] 1
    
    [[2]] [1] 2
    
  2. [[ ]] is for extracting an element from the list. x[[1]] is valid and extract the first element from the list. x[[1:2]] is not valid as [[ ]] does not provide sub setting like [ ].

     x[[2]] [1] 2 
    
    > x[[2:3]] Error in x[[2:3]] : subscript out of bounds
    

What are the rules for casting pointers in C?

I suspect you need a more general answer:

There are no rules on casting pointers in C! The language lets you cast any pointer to any other pointer without comment.

But the thing is: There is no data conversion or whatever done! Its solely your own responsibilty that the system does not misinterpret the data after the cast - which would generally be the case, leading to runtime error.

So when casting its totally up to you to take care that if data is used from a casted pointer the data is compatible!

C is optimized for performance, so it lacks runtime reflexivity of pointers/references. But that has a price - you as a programmer have to take better care of what you are doing. You have to know on your self if what you want to do is "legal"

What is difference between cacerts and keystore?

'cacerts' is a truststore. A trust store is used to authenticate peers. A keystore is used to authenticate yourself.

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

First prevent default actions on your entire document as usual:

$(document).bind('touchmove', function(e){
  e.preventDefault();           
});

Then stop your class of elements from propagating to the document level. This stops it from reaching the function above and thus e.preventDefault() is not initiated:

$('.scrollable').bind('touchmove', function(e){
  e.stopPropagation();
});

This system seems to be more natural and less intensive than calculating the class on all touch moves. Use .on() rather than .bind() for dynamically generated elements.

Also consider these meta tags to prevent unfortunate things from happening while using your scrollable div:

<meta content='True' name='HandheldFriendly' />
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />

Check if a JavaScript string is a URL

Rely on a library: https://www.npmjs.com/package/valid-url

import { isWebUri } from 'valid-url';
// ...
if (!isWebUri(url)) {
    return "Not a valid url.";
}

Length of string in bash

UTF-8 string length

In addition to fedorqui's correct answer, I would like to show the difference between string length and byte length:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
LANG=$oLang LC_ALL=$oLcAll
printf "%s is %d char len, but %d bytes len.\n" "${myvar}" $chrlen $bytlen

will render:

Généralités is 11 char len, but 14 bytes len.

you could even have a look at stored chars:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
printf -v myreal "%q" "$myvar"
LANG=$oLang LC_ALL=$oLcAll
printf "%s has %d chars, %d bytes: (%s).\n" "${myvar}" $chrlen $bytlen "$myreal"

will answer:

Généralités has 11 chars, 14 bytes: ($'G\303\251n\303\251ralit\303\251s').

Nota: According to Isabell Cowan's comment, I've added setting to $LC_ALL along with $LANG.

Length of an argument

Argument work same as regular variables

strLen() {
    local bytlen sreal oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    printf -v sreal %q "$1"
    LANG=$oLang LC_ALL=$oLcAll
    printf "String '%s' is %d bytes, but %d chars len: %s.\n" "$1" $bytlen ${#1} "$sreal"
}

will work as

strLen théorème
String 'théorème' is 10 bytes, but 8 chars len: $'th\303\251or\303\250me'

Useful printf correction tool:

If you:

for string in Généralités Language Théorème Février  "Left: ?" "Yin Yang ?";do
    printf " - %-14s is %2d char length\n" "'$string'"  ${#string}
done

 - 'Généralités' is 11 char length
 - 'Language'     is  8 char length
 - 'Théorème'   is  8 char length
 - 'Février'     is  7 char length
 - 'Left: ?'    is  7 char length
 - 'Yin Yang ?' is 10 char length

Not really pretty... For this, there is a little function:

strU8DiffLen () { 
    local bytlen oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    LANG=$oLang LC_ALL=$oLcAll
    return $(( bytlen - ${#1} ))
}

Then now:

for string in Généralités Language Théorème Février  "Left: ?" "Yin Yang ?";do
    strU8DiffLen "$string"
    printf " - %-$((14+$?))s is %2d chars length, but uses %2d bytes\n" \
        "'$string'" ${#string} $((${#string}+$?))
  done 

 - 'Généralités'  is 11 chars length, but uses 14 bytes
 - 'Language'     is  8 chars length, but uses  8 bytes
 - 'Théorème'     is  8 chars length, but uses 10 bytes
 - 'Février'      is  7 chars length, but uses  8 bytes
 - 'Left: ?'      is  7 chars length, but uses  9 bytes
 - 'Yin Yang ?'   is 10 chars length, but uses 12 bytes

Unfortunely, this is not perfect!

But there left some strange UTF-8 behaviour, like double-spaced chars, zero spaced chars, reverse deplacement and other that could not be as simple...

Have a look at diffU8test.sh or diffU8test.sh.txt for more limitations.

If statement within Where clause

CASE might help you out:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
                        WHEN status_flag = STATUS_INACTIVE THEN 'T'
                        ELSE null END)
   AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
                               WHEN source_flag = SOURCE_USER THEN 'users'
                               ELSE null END)
   AND t.first_name LIKE firstname
   AND t.last_name LIKE lastname
   AND t.employid LIKE employeeid;

The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.

How to create an instance of System.IO.Stream stream

Stream stream = new MemoryStream();

you can use MemoryStream

Reference: MemoryStream

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

Setup: 32-bit Windows 7

Context: Installed a PCI-GPIB driver that I was unable to communicate through due to the aforementioned issue.

Short Answer: Reinstall the driver.

Long Answer: I also used Dependency Walker, which identified several missing dependency modules. Immediately, I thought that it must have been a botched driver installation. I didn't want to check and restore each missing file.

The fact that I was unable to find the uninstaller under Programs and Features of the Control Panel is another indicator of bad installation. I had to manually delete a couple of *.dll in \system32 and registry keys to allow for driver re-installation.

Issue fixed.

The unexpected part was that not all dependency modules were resolved. Nevertheless, the *.dll of interest can now be referenced.

Which HTML Parser is the best?

Self plug: I have just released a new Java HTML parser: jsoup. I mention it here because I think it will do what you are after.

Its party trick is a CSS selector syntax to find elements, e.g.:

String html = "<html><head><title>First parse</title></head>"
  + "<body><p>Parsed HTML into a doc.</p></body></html>";
Document doc = Jsoup.parse(html);
Elements links = doc.select("a");
Element head = doc.select("head").first();

See the Selector javadoc for more info.

This is a new project, so any ideas for improvement are very welcome!

Bold & Non-Bold Text In A Single UILabel?

That's easy to do in Interface Builder:

1) make UILabel Attributed in Attributes Inspector

Bold Example Step 1

2) select part of phrase you want to make bold

Bold Example Step 2

3) change its font (or bold typeface of the same font) in font selector

Bold Example Step 3

That's all!

Refresh Fragment at reload

For example with TabLayout: just implement OnTabSelectedListener. To reload the page, you may use implement SwipeRefreshLayout.OnRefreshListener i.e. public class YourFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

the onRefresh() method will be @Override from the interface i.e.:

@Override
public void onRefresh() {
 loadData();
}

Here's the layout:

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tablayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryLighter"
    app:tabGravity="fill"
    app:tabIndicatorColor="@color/white"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/colorTextPrimary"
    app:tabTextColor="@color/colorTextDisable" />

Code in your activity

TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout); tabLayout.setupWithViewPager(viewPager);

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tab.getPosition() == 0) {
                yourFragment1.onRefresh();
            } else if (tab.getPosition() == 1) {
                yourFragment2.onRefresh();
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

Setting up SSL on a local xampp/apache server

You can enable SSL on XAMPP by creating self signed certificates and then installing those certificates. Type the below commands to generate and move the certificates to ssl folders.

openssl genrsa -des3 -out server.key 1024

openssl req -new -key server.key -out server.csr

cp server.key server.key.org

openssl rsa -in server.key.org -out server.key

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

cp server.crt /opt/lampp/etc/ssl.crt/domainname.crt

cp server.key /opt/lampp/etc/ssl.key/domainname.key

(Use sudo with each command if you are not the super user)

Now, Check that mod_ssl is enabled in [XAMPP_HOME]/etc/httpd.conf:

LoadModule ssl_module modules/mod_ssl.so

Add a virtual host, in this example "localhost.domainname.com" by editing [XAMPP_HOME]/etc/extra/httpd-ssl.conf as follows:

<virtualhost 127.0.1.4:443>
    ServerName localhost.domainname.com
    ServerAlias localhost.domainname.com *.localhost.domainname.com
    ServerAdmin admin@localhost

    DocumentRoot "/opt/lampp/htdocs/"

    DirectoryIndex index.php

    ErrorLog /opt/lampp/logs/domainname.local.error.log
    CustomLog /opt/lampp/logs/domainname.local.access.log combined

    SSLEngine on
    SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
    SSLCertificateFile /opt/lampp/etc/ssl.crt/domainname.crt
    SSLCertificateKeyFile /opt/lampp/etc/ssl.key/domainname.key

    <directory /opt/lampp/htdocs/>
            Options Indexes FollowSymLinks
            AllowOverride All
            Order allow,deny
            Allow from all
    </directory>
    BrowserMatch ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
</virtualhost>

Add the following entry to /etc/hosts:

127.0.1.4 localhost.domainname.com

Now, try installing the certificate/ try importing certificate to browser. I have checked this and this worked on Ubuntu.

How do you fadeIn and animate at the same time?

$('.tooltip').animate({ opacity: 1, top: "-10px" }, 'slow');

However, this doesn't appear to work on display: none elements (as fadeIn does). So, you might need to put this beforehand:

$('.tooltip').css('display', 'block');
$('.tooltip').animate({ opacity: 0 }, 0);

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

As a general rule (i.e. in vanilla kernels), fork/clone failures with ENOMEM occur specifically because of either an honest to God out-of-memory condition (dup_mm, dup_task_struct, alloc_pid, mpol_dup, mm_init etc. croak), or because security_vm_enough_memory_mm failed you while enforcing the overcommit policy.

Start by checking the vmsize of the process that failed to fork, at the time of the fork attempt, and then compare to the amount of free memory (physical and swap) as it relates to the overcommit policy (plug the numbers in.)

In your particular case, note that Virtuozzo has additional checks in overcommit enforcement. Moreover, I'm not sure how much control you truly have, from within your container, over swap and overcommit configuration (in order to influence the outcome of the enforcement.)

Now, in order to actually move forward I'd say you're left with two options:

  • switch to a larger instance, or
  • put some coding effort into more effectively controlling your script's memory footprint

NOTE that the coding effort may be all for naught if it turns out that it's not you, but some other guy collocated in a different instance on the same server as you running amock.

Memory-wise, we already know that subprocess.Popen uses fork/clone under the hood, meaning that every time you call it you're requesting once more as much memory as Python is already eating up, i.e. in the hundreds of additional MB, all in order to then exec a puny 10kB executable such as free or ps. In the case of an unfavourable overcommit policy, you'll soon see ENOMEM.

Alternatives to fork that do not have this parent page tables etc. copy problem are vfork and posix_spawn. But if you do not feel like rewriting chunks of subprocess.Popen in terms of vfork/posix_spawn, consider using suprocess.Popen only once, at the beginning of your script (when Python's memory footprint is minimal), to spawn a shell script that then runs free/ps/sleep and whatever else in a loop parallel to your script; poll the script's output or read it synchronously, possibly from a separate thread if you have other stuff to take care of asynchronously -- do your data crunching in Python but leave the forking to the subordinate process.

HOWEVER, in your particular case you can skip invoking ps and free altogether; that information is readily available to you in Python directly from procfs, whether you choose to access it yourself or via existing libraries and/or packages. If ps and free were the only utilities you were running, then you can do away with subprocess.Popen completely.

Finally, whatever you do as far as subprocess.Popen is concerned, if your script leaks memory you will still hit the wall eventually. Keep an eye on it, and check for memory leaks.

Setting user agent of a java URLConnection

Off hand, setting the http.agent system property to "" might do the trick (I don't have the code in front of me).

You might get away with:

 System.setProperty("http.agent", "");

but that might require a race between you and initialisation of the URL protocol handler, if it caches the value at startup (actually, I don't think it does).

The property can also be set through JNLP files (available to applets from 6u10) and on the command line:

-Dhttp.agent=

Or for wrapper commands:

-J-Dhttp.agent=

How to use new PasswordEncoder from Spring Security

I had a similar issue. I needed to keep the legacy encrypted passwords (Base64/SHA-1/Random salt Encoded) as users will not want to change their passwords or re-register. However I wanted to use the BCrypt encoder moving forward too.

My solution was to write a bespoke decoder that checks to see which encryption method was used first before matching (BCrypted ones start with $).

To get around the salt issue, I pass into the decoder a concatenated String of salt + encrypted password via my modified user object.

Decoder

@Component
public class LegacyEncoder implements PasswordEncoder {

    private static final String BCRYP_TYPE = "$";
    private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {

    return BCRYPT.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

    if (encodedPassword.startsWith(BCRYP_TYPE)) {
        return BCRYPT.matches(rawPassword, encodedPassword);
    }

    return sha1SaltMatch(rawPassword, encodedPassword);
    }

    @SneakyThrows
    private boolean sha1SaltMatch(CharSequence rawPassword, String encodedPassword) {

    String[] saltHash = encodedPassword.split(User.SPLIT_CHAR);

    // Legacy code from old system   
    byte[] b64salt = Base64.getDecoder().decode(saltHash[0].getBytes());
    byte[] validHash = Base64.getDecoder().decode(saltHash[1]);
    byte[] checkHash = Utility.getHash(5, rawPassword.toString(), b64salt);

    return Arrays.equals(checkHash, validHash);
    }

}

User Object

public class User implements UserDetails {

    public static final String SPLIT_CHAR = ":";

    @Id
    @Column(name = "user_id", nullable = false)
    private Integer userId;

    @Column(nullable = false, length = 60)
    private String password;

    @Column(nullable = true, length = 32)
    private String salt;

.
.

    @PostLoad
    private void init() {

    username = emailAddress; //To comply with UserDetails
    password = salt == null ? password : salt + SPLIT_CHAR + password;
    }        

You can also add a hook to re-encode the password in the new BCrypt format and replace it. Thus phasing out the old method.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

The problem is certainly the this binding while rending the button with onClick handler. The solution is to use arrow function while calling action handler while rendering. Like this: onClick={ () => this.handleButtonChange(false) }

Field 'id' doesn't have a default value?

This is caused by MySQL having a strict mode set which won’t allow INSERT or UPDATE commands with empty fields where the schema doesn’t have a default value set.

There are a couple of fixes for this.

First ‘fix’ is to assign a default value to your schema. This can be done with a simple ALTER command:

ALTER TABLE `details` CHANGE COLUMN `delivery_address_id` `delivery_address_id` INT(11) NOT NULL DEFAULT 0 ;

However, this may need doing for many tables in your database schema which will become tedious very quickly. The second fix is to remove sql_mode STRICT_TRANS_TABLES on the mysql server.

If you are using a brew installed MySQL you should edit the my.cnf file in the MySQL directory. Change the sql_mode at the bottom:

#sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
sql_mode=NO_ENGINE_SUBSTITUTION

Save the file and restart Mysql.

Source: https://www.euperia.com/development/mysql-fix-field-doesnt-default-value/1509

How can I show/hide a specific alert with twitter bootstrap?

I use this alert

<div class="alert alert-error hidden" id="successfulSave">
  <span>
    <p>Success! Result Saved.</p>
  </span>
</div>

repeatedly on a page each time a user updates a result successfully:

$('#successfulSave').removeClass('hidden');

to re-hide it, I call

$('#successfulSave').addClass('hidden');

How to use delimiter for csv in python

ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??

if i am then please try this,

import csv

with open(r"C:\\test.csv", "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["a","b"])

you have to set the delimiter = ","

How to insert array of data into mysql using php

I would avoid to do a query for each entry.

if(is_array($EMailArr)){

    $sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ";

    $valuesArr = array();
    foreach($EMailArr as $row){

        $R_ID = (int) $row['R_ID'];
        $email = mysql_real_escape_string( $row['email'] );
        $name = mysql_real_escape_string( $row['name'] );

        $valuesArr[] = "('$R_ID', '$email', '$name')";
    }

    $sql .= implode(',', $valuesArr);

    mysql_query($sql) or exit(mysql_error()); 
}

copy db file with adb pull results in 'permission denied' error

This is a bit late, but installing adbd Insecure worked for me. It makes adb run in root mode on production ("secure") devices, which is what you likely have.

A paid version is also available on Google Play if you want to support the developer.

How to instantiate a javascript class in another js file?

// Create Customer class as follows:
export default class Customer {}

// Import the class 
// no need for .js extension in path cos gets inferred automatically
import Customer from './path/to/Customer'; 
// or
const Customer = require('./path/to/Customer') 

// Use the class
var customer = new Customer();
var name = customer.getName();

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

This is a known bug, you can work it around with a hack:

Open up site-packages/requests/packages/urllib3/connectionpool.py (or otherwise just make a local copy of requests inside your own project), and change the block that says:

def connect(self):
    # Add certificate verification
    sock = socket.create_connection((self.host, self.port), self.timeout)

    # Wrap socket using verification with the root certs in
    # trusted_root_certs
    self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,
                                cert_reqs=self.cert_reqs,
                                ca_certs=self.ca_certs,
                                server_hostname=self.host,
                                ssl_version=self.ssl_version)

to:

def connect(self):
    # Add certificate verification
    sock = socket.create_connection((self.host, self.port), self.timeout)

    # Wrap socket using verification with the root certs in
    # trusted_root_certs
    self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,
                                cert_reqs=self.cert_reqs,
                                ca_certs=self.ca_certs,
                                server_hostname=self.host,
                                ssl_version=ssl.PROTOCOL_TLSv1)

Otherwise, I suppose there's an override somewhere which is less hacky, but I couldn't find one with a few glances.

NOTE: On a sidenote, requests from PIP (1.0.4) on a MacOS just works with the URL you provided.

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

[Updated to adapt to modern pandas, which has isnull as a method of DataFrames..]

You can use isnull and any to build a boolean Series and use that to index into your frame:

>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False
>>> df.isnull().any(axis=1)
0    False
1     True
2     True
3    False
4    False
dtype: bool
>>> df[df.isnull().any(axis=1)]
   0   1   2
1  0 NaN   0
2  0   0 NaN

[For older pandas:]

You could use the function isnull instead of the method:

In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])

In [57]: df
Out[57]: 
   0   1   2
0  0   1   2
1  0 NaN   0
2  0   0 NaN
3  0   1   2
4  0   1   2

In [58]: pd.isnull(df)
Out[58]: 
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False

In [59]: pd.isnull(df).any(axis=1)
Out[59]: 
0    False
1     True
2     True
3    False
4    False

leading to the rather compact:

In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]: 
   0   1   2
1  0 NaN   0
2  0   0 NaN

In which conda environment is Jupyter executing?

As mentioned in the comments, conda support for jupyter notebooks is needed to switch kernels. Seems like this support is now available through conda itself (rather than relying on pip). http://docs.continuum.io/anaconda/user-guide/tasks/use-jupyter-notebook-extensions/

conda install nb_conda

which brings three other handy extensions in addition to Notebook Conda Kernels.

TypeError: Missing 1 required positional argument: 'self'

You need to instantiate a class instance here.

Use

p = Pump()
p.getPumps()

Small example -

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

show all tags in git log

Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:

Make sure you study this thread, as overriding a signed tag is not as easy:

  • if you already pushed a tag, the git tag man page seriously advised against a simple git tag -f B to replace a tag name "A"
  • don't try to recreate a signed tag with git tag -f (see the thread extract below)

    (it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):

Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:

  • in the tag object itself as a contents of 'tag' header (you can see it in output of "git show <tag>" and also in output of "git cat-file -p <tag>", where <tag> is heavyweight tag, e.g. v1.6.3 in git.git repository),
  • and also is default name of tag reference (reference in "refs/tags/*" namespace) pointing to a tag object.
    Note that the tag reference (appropriate reference in the "refs/tags/*" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3', other can have in 'refs/tags/sub/v0.1.3' for example.

So when you create signed tag 'A', you have the following situation (assuming that it points at some commit)

  35805ce   <--- 5b7b4ead  <=== refs/tags/A
  (commit)       tag A
                 (tag)

Please also note that "git tag -f A A" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.

If you do "git tag -f -s A A": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of -s / -a / -m options is used to force annotated tag (creation of tag object), you will get the following situation

  35805ce   <--- 5b7b4ea  <--- ada8ddc  <=== refs/tags/A
  (commit)       tag A         tag A
                 (tag)         (tag)

Note also that "git show A" would show the whole chain down to the non-tag object...

Error: Java: invalid target release: 11 - IntelliJ IDEA

I Could say I had similar issue. My case: I switched from new version to old version of the project in workspace, try to run single junit which require recompil, recompilation error was thrown with invalid target.

From Projects settings (F4) in IntelliJ everything was looking good and java was set to 1.7. But when I try recompile from IDE error was thrown because of wrong target level. After checking I found that in one of the iml file language was set to JDK_11. After manual change to JDK_1_7 everything back to normal.

Worth to also manual check lang level in *iml files created by IDE.

How to check if the key pressed was an arrow key in Java KeyListener?

If you mean that you wanna attach this to your panel (Window that you are working with).

then you have to create an inner class that extend from IKeyListener interface and then add that method in to the class.

Then, attach that class to you panel by: this.addKeyListener(new subclass());

Python - How to convert JSON File to Dataframe

import pandas as pd
print(pd.json_normalize(your_json))

This will Normalize semi-structured JSON data into a flat table

Output

  FirstName LastName MiddleName password    username
      John     Mark      Lewis     2910  johnlewis2

Keras model.summary() result - Understanding the # of Parameters

Number of parameters is the amount of numbers that can be changed in the model. Mathematically this means number of dimensions of your optimization problem. For you as a programmer, each of this parameters is a floating point number, which typically takes 4 bytes of memory, allowing you to predict the size of this model once saved.

This formula for this number is different for each neural network layer type, but for Dense layer it is simple: each neuron has one bias parameter and one weight per input: N = n_neurons * ( n_inputs + 1).