Programs & Examples On #Vmware fusion

A software system for running virtual machines (a hypervisor) used to run Windows or other operating systems on a Macintosh under OSX.

Difference between fprintf, printf and sprintf?

printf("format", args) is used to print the data onto the standard output which is often a computer monitor.

sprintf(char *, "format", args) is like printf. Instead of displaying the formated string on the standard output i.e. a monitor, it stores the formated data in a string pointed to by the char pointer (the very first parameter). The string location is the only difference between printf and sprint syntax.

fprintf(FILE *fp, "format", args) is like printf again. Here, instead of displaying the data on the monitor, or saving it in some string, the formatted data is saved on a file which is pointed to by the file pointer which is used as the first parameter to fprintf. The file pointer is the only addition to the syntax of printf.

If stdout file is used as the first parameter in fprintf, its working is then considered equivalent to that of printf.

What's the difference between ".equals" and "=="?

The == operator compares if the objects are the same instance. The equals() oerator compares the state of the objects (e.g. if all attributes are equal). You can even override the equals() method to define yourself when an object is equal to another.

Git error: src refspec master does not match any

The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:

git push origin master

Which will create this new master branch for you. Little things like this are very confusing with git.

If this didn't fix your issue then it's probably a gitolite-related issue:

Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:

repo    phonegap                                                                                                                                                                           
    RW+     =   myusername otherusername                                                                                                                                               

repo    gitolite-admin                                                                                                                                                                         
    RW+     =   myusername                                                                                                                                                               

Please make sure you're setting your conf file correctly.

Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.

Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.

Static vs class functions/variables in Swift classes?

class vs static

class is used inside Reference Type(class):

  • computed property
  • method
  • can be overridden by subclass

static is used inside Reference Type and Value Type(class, enum):

  • computed property and stored property
  • method
  • cannot be changed by subclass
protocol MyProtocol {
//    class var protocolClassVariable : Int { get }//ERROR: Class properties are only allowed within classes
    static var protocolStaticVariable : Int { get }
    
//    class func protocolClassFunc()//ERROR: Class methods are only allowed within classes
    static func protocolStaticFunc()
}

struct ValueTypeStruct: MyProtocol {
    //MyProtocol implementation begin
    static var protocolStaticVariable: Int = 1
    
    static func protocolStaticFunc() {
        
    }
    //MyProtocol implementation end
    
//    class var classVariable = "classVariable"//ERROR: Class properties are only allowed within classes
    static var staticVariable = "staticVariable"

//    class func classFunc() {} //ERROR: Class methods are only allowed within classes
    static func staticFunc() {}
}

class ReferenceTypeClass: MyProtocol {
    //MyProtocol implementation begin
    static var protocolStaticVariable: Int = 2
    
    static func protocolStaticFunc() {
        
    }
    //MyProtocol implementation end
    
    var variable = "variable"

//    class var classStoredPropertyVariable = "classVariable"//ERROR: Class stored properties not supported in classes

    class var classComputedPropertyVariable: Int {
        get {
            return 1
        }
    }

    static var staticStoredPropertyVariable = "staticVariable"

    static var staticComputedPropertyVariable: Int {
        get {
            return 1
        }
    }

    class func classFunc() {}
    static func staticFunc() {}
}

final class FinalSubReferenceTypeClass: ReferenceTypeClass {
    override class var classComputedPropertyVariable: Int {
        get {
            return 2
        }
    }
    override class func classFunc() {}
}

//class SubFinalSubReferenceTypeClass: FinalSubReferenceTypeClass {}// ERROR: Inheritance from a final class

[Reference vs Value Type]

How to convert any Object to String?

"toString()" is Very useful method which returns a string representation of an object. The "toString()" method returns a string reperentation an object.It is recommended that all subclasses override this method.

Declaration: java.lang.Object.toString()

Since, you have not mentioned which object you want to convert, so I am just using any object in sample code.

Integer integerObject = 5;
String convertedStringObject = integerObject .toString();
System.out.println(convertedStringObject );

You can find the complete code here. You can test the code here.

Is there any native DLL export functions viewer?

dumpbin from the Visual Studio command prompt:

dumpbin /exports csp.dll

Example of output:

Microsoft (R) COFF/PE Dumper Version 10.00.30319.01
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file csp.dll

File Type: DLL

  Section contains the following exports for CSP.dll

    00000000 characteristics
    3B1D0B77 time date stamp Tue Jun 05 12:40:23 2001
        0.00 version
           1 ordinal base
          25 number of functions
          25 number of names

    ordinal hint RVA      name

          1    0 00001470 CPAcquireContext
          2    1 000014B0 CPCreateHash
          3    2 00001520 CPDecrypt
          4    3 000014B0 CPDeriveKey
          5    4 00001590 CPDestroyHash
          6    5 00001590 CPDestroyKey
          7    6 00001560 CPEncrypt
          8    7 00001520 CPExportKey
          9    8 00001490 CPGenKey
         10    9 000015B0 CPGenRandom
         11    A 000014D0 CPGetHashParam
         12    B 000014D0 CPGetKeyParam
         13    C 00001500 CPGetProvParam
         14    D 000015C0 CPGetUserKey
         15    E 00001580 CPHashData
         16    F 000014F0 CPHashSessionKey
         17   10 00001540 CPImportKey
         18   11 00001590 CPReleaseContext
         19   12 00001580 CPSetHashParam
         20   13 00001580 CPSetKeyParam
         21   14 000014F0 CPSetProvParam
         22   15 00001520 CPSignHash
         23   16 000015A0 CPVerifySignature
         24   17 00001060 DllRegisterServer
         25   18 00001000 DllUnregisterServer

  Summary

        1000 .data
        1000 .rdata
        1000 .reloc
        1000 .rsrc
        1000 .text

Jenkins pipeline if else not working

It requires a bit of rearranging, but when does a good job to replace conditionals above. Here's the example from above written using the declarative syntax. Note that test3 stage is now two different stages. One that runs on the master branch and one that runs on anything else.

stage ('Test 3: Master') {
    when { branch 'master' }
    steps { 
        echo 'I only execute on the master branch.' 
    }
}

stage ('Test 3: Dev') {
    when { not { branch 'master' } }
    steps {
        echo 'I execute on non-master branches.'
    }
}

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

So I'm a pretty critical person, and figure if I'm going to invest in a library, I'd better know what I'm getting myself into. I figure it's better to go heavy on the criticism and light on the flattery when scrutinizing; what's wrong with it has many more implications for the future than what's right. So I'm going to go overboard here a little bit to provide the kind of answer that would have helped me and I hope will help others who may journey down this path. Keep in mind that this is based on what little reviewing/testing I've done with these libs. Oh and I stole some of the positive description from Reed.

I'll mention up top that I went with GMTL despite it's idiosyncrasies because the Eigen2 unsafeness was too big of a downside. But I've recently learned that the next release of Eigen2 will contain defines that will shut off the alignment code, and make it safe. So I may switch over.

Update: I've switched to Eigen3. Despite it's idiosyncrasies, its scope and elegance are too hard to ignore, and the optimizations which make it unsafe can be turned off with a define.

Eigen2/Eigen3

Benefits: LGPL MPL2, Clean, well designed API, fairly easy to use. Seems to be well maintained with a vibrant community. Low memory overhead. High performance. Made for general linear algebra, but good geometric functionality available as well. All header lib, no linking required.

Idiocyncracies/downsides: (Some/all of these can be avoided by some defines that are available in the current development branch Eigen3)

  • Unsafe performance optimizations result in needing careful following of rules. Failure to follow rules causes crashes.
    • you simply cannot safely pass-by-value
    • use of Eigen types as members requires special allocator customization (or you crash)
    • use with stl container types and possibly other templates required special allocation customization (or you will crash)
    • certain compilers need special care to prevent crashes on function calls (GCC windows)

GMTL

Benefits: LGPL, Fairly Simple API, specifically designed for graphics engines. Includes many primitive types geared towards rendering (such as planes, AABB, quatenrions with multiple interpolation, etc) that aren't in any other packages. Very low memory overhead, quite fast, easy to use. All header based, no linking necessary.

Idiocyncracies/downsides:

  • API is quirky
    • what might be myVec.x() in another lib is only available via myVec[0] (Readability problem)
      • an array or stl::vector of points may cause you to do something like pointsList[0][0] to access the x component of the first point
    • in a naive attempt at optimization, removed cross(vec,vec) and replaced with makeCross(vec,vec,vec) when compiler eliminates unnecessary temps anyway
    • normal math operations don't return normal types unless you shut off some optimization features e.g.: vec1 - vec2 does not return a normal vector so length( vecA - vecB ) fails even though vecC = vecA - vecB works. You must wrap like: length( Vec( vecA - vecB ) )
    • operations on vectors are provided by external functions rather than members. This may require you to use the scope resolution everywhere since common symbol names may collide
    • you have to do
        length( makeCross( vecA, vecB ) )
      or
        gmtl::length( gmtl::makeCross( vecA, vecB ) )
      where otherwise you might try
        vecA.cross( vecB ).length()
  • not well maintained
    • still claimed as "beta"
    • documentation missing basic info like which headers are needed to use normal functionalty
      • Vec.h does not contain operations for Vectors, VecOps.h contains some, others are in Generate.h for example. cross(vec&,vec&,vec&) in VecOps.h, [make]cross(vec&,vec&) in Generate.h
  • immature/unstable API; still changing.
    • For example "cross" has moved from "VecOps.h" to "Generate.h", and then the name was changed to "makeCross". Documentation examples fail because still refer to old versions of functions that no-longer exist.

NT2

Can't tell because they seem to be more interested in the fractal image header of their web page than the content. Looks more like an academic project than a serious software project.

Latest release over 2 years ago.

Apparently no documentation in English though supposedly there is something in French somewhere.

Cant find a trace of a community around the project.

LAPACK & BLAS

Benefits: Old and mature.

Downsides:

  • old as dinosaurs with really crappy APIs

How to delete session cookie in Postman?

new version of postman app has the ability to do that programmatically in pre-request or tests scripts since 2019/08

see more examples here: Delete cookies programmatically · Issue #3312 · postmanlabs/postman-app-support

clear all cookies

const jar = pm.cookies.jar();

jar.clear(pm.request.url, function (error) {
  // error - <Error>
});

get all cookies

const jar = pm.cookies.jar();

jar.getAll('http://example.com', function (error, cookies) {
  // error - <Error>
  // cookies - <PostmanCookieList>
  // PostmanCookieList: https://www.postmanlabs.com/postman-collection/CookieList.html
});

get specific cookie

const jar = pm.cookies.jar();

jar.get('http://example.com', 'token', function (error, value) {
  // error - <Error>
  // value - <String>
});

sql insert into table with select case values

You need commas after end finishing the case statement. And, the "as" goes after the case statement, not inside it:

Insert into TblStuff(FullName, Address, City, Zip)
    Select (Case When Middle is Null Then Fname + LName
                 Else Fname +' ' + Middle + ' '+ Lname
            End)  as FullName,
           (Case When Address2 is Null Then Address1
                 else Address1 +', ' + Address2
            End)  as  Address,
           City as City,
           Zip as Zip
    from tblImport

Make browser window blink in task Bar

My "user interface" response is: Are you sure your users want their browsers flashing, or do you think that's what they want? If I were the one using your software, I know I'd be annoyed if these alerts happened very often and got in my way.

If you're sure you want to do it this way, use a javascript alert box. That's what Google Calendar does for event reminders, and they probably put some thought into it.

A web page really isn't the best medium for need-to-know alerts. If you're designing something along the lines of "ZOMG, the servers are down!" alerts, automated e-mails or SMS messages to the right people might do the trick.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How to search through all Git and Mercurial commits in the repository for a certain string?

Don't know about git, but in Mercurial I'd just pipe the output of hg log to some sed/perl/whatever script to search for whatever it is you're looking for. You can customize the output of hg log using a template or a style to make it easier to search on, if you wish.

This will include all named branches in the repo. Mercurial does not have something like dangling blobs afaik.

How to include quotes in a string

string str = @"""Hi, "" I am programmer";

OUTPUT - "Hi, " I am programmer

How get value from URL

Website URL:

http://www.example.com/?id=2

Code:

$id = intval($_GET['id']);
$results = mysql_query("SELECT * FROM next WHERE id=$id");    
while ($row = mysql_fetch_array($results))     
{       
    $url = $row['url'];
    echo $url; //Outputs: 2
}

How do you UDP multicast in Python?

Just another answer to explain some subtle points in the code of the other answers:

  • socket.INADDR_ANY - (Edited) In the context of IP_ADD_MEMBERSHIP, this doesn't really bind the socket to all interfaces but just choose the default interface where multicast is up (according to routing table)
  • Joining a multicast group isn't the same as binding a socket to a local interface address

see What does it mean to bind a multicast (UDP) socket? for more on how multicast works

Multicast receiver:

import socket
import struct
import argparse


def run(groups, port, iface=None, bind_group=None):
    # generally speaking you want to bind to one of the groups you joined in
    # this script,
    # but it is also possible to bind to group which is added by some other
    # programs (like another python program instance of this)

    # assert bind_group in groups + [None], \
    #     'bind group not in groups to join'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

    # allow reuse of socket (to allow another instance of python running this
    # script binding to the same ip/port)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.bind(('' if bind_group is None else bind_group, port))
    for group in groups:
        mreq = struct.pack(
            '4sl' if iface is None else '4s4s',
            socket.inet_aton(group),
            socket.INADDR_ANY if iface is None else socket.inet_aton(iface))

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    while True:
        print(sock.recv(10240))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=19900)
    parser.add_argument('--join-mcast-groups', default=[], nargs='*',
                        help='multicast groups (ip addrs) to listen to join')
    parser.add_argument(
        '--iface', default=None,
        help='local interface to use for listening to multicast data; '
        'if unspecified, any interface would be chosen')
    parser.add_argument(
        '--bind-group', default=None,
        help='multicast groups (ip addrs) to bind to for the udp socket; '
        'should be one of the multicast groups joined globally '
        '(not necessarily joined in this python program) '
        'in the interface specified by --iface. '
        'If unspecified, bind to 0.0.0.0 '
        '(all addresses (all multicast addresses) of that interface)')
    args = parser.parse_args()
    run(args.join_mcast_groups, args.port, args.iface, args.bind_group)

sample usage: (run the below in two consoles and choose your own --iface (must be same as the interface that receives the multicast data))

python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '224.1.1.1' '224.1.1.2' '224.1.1.3' --bind-group '224.1.1.2'

python3 multicast_recv.py --iface='192.168.56.102' --join-mcast-groups '224.1.1.4'

Multicast sender:

import socket
import argparse


def run(group, port):
    MULTICAST_TTL = 20
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
    sock.sendto(b'from multicast_send.py: ' +
                f'group: {group}, port: {port}'.encode(), (group, port))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--mcast-group', default='224.1.1.1')
    parser.add_argument('--port', default=19900)
    args = parser.parse_args()
    run(args.mcast_group, args.port)

sample usage: # assume the receiver binds to the below multicast group address and that some program requests to join that group. And to simplify the case, assume the receiver and the sender are under the same subnet

python3 multicast_send.py --mcast-group '224.1.1.2'

python3 multicast_send.py --mcast-group '224.1.1.4'

Run bash script as daemon

To run it as a full daemon from a shell, you'll need to use setsid and redirect its output. You can redirect the output to a logfile, or to /dev/null to discard it. Assuming your script is called myscript.sh, use the following command:

setsid myscript.sh >/dev/null 2>&1 < /dev/null &

This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first /dev/null with your /path/to/logfile.

You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).

Git submodule push

A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )

$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"

javascript createElement(), style problem

yourElement.setAttribute("style", "background-color:red; font-size:2em;");

Or you could write the element as pure HTML and use .innerHTML = [raw html code]... that's very ugly though.

In answer to your first question, first you use var myElement = createElement(...);, then you do document.body.appendChild(myElement);.

Array initialization syntax when not in a declaration

For those of you, who doesn't like this monstrous new AClass[] { ... } syntax, here's some sugar:

public AClass[] c(AClass... arr) { return arr; }

Use this little function as you like:

AClass[] array;
...
array = c(object1, object2);

Remove Primary Key in MySQL

To add primary key in the column.

ALTER TABLE table_name ADD PRIMARY KEY (column_name);

To remove primary key from the table.

ALTER TABLE table_name DROP PRIMARY KEY;

How to initialize an array of objects in Java

It is almost fine. Just have:

Player[] thePlayers = new Player[playerCount + 1];

And let the loop be:

for(int i = 0; i < thePlayers.length; i++)

And note that java convention dictates that names of methods and variables should start with lower-case.

Update: put your method within the class body.

In HTML I can make a checkmark with &#x2713; . Is there a corresponding X-mark?

Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use &check; for ✓ and &cross; for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.

As mentioned in the comments, &check; and &cross; are not supported in HTML4, so you may be better off using the more cryptic &#x2713; and &#x2717; if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.

Load different application.yml in SpringBoot Test

This might be considered one of the options. now if you wanted to load a yml file ( which did not get loaded by default on applying the above annotations) the trick is to use

@ContextConfiguration(classes= {...}, initializers={ConfigFileApplicationContextInitializer.class})

Here is a sample code

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@DirtiesContext
@ContextConfiguration(classes= {DataSourceTestConfig.class}, initializers = {ConfigFileApplicationContextInitializer.class})
public class CustomDateDeserializerTest {


    private ObjectMapper objMapper;

    @Before
    public void setUp() {
        objMapper = new ObjectMapper();

    }

    @Test
    public void test_dateDeserialization() {

    }
}

Again make sure that the setup config java file - here DataSourceTestConfig.java contains the following property values.

@Configuration
@ActiveProfiles("test")
@TestPropertySource(properties = { "spring.config.location=classpath:application-test.yml" })
public class DataSourceTestConfig implements EnvironmentAware {

    private Environment env;

    @Bean
    @Profile("test")
    public DataSource testDs() {
       HikariDataSource ds = new HikariDataSource();

        boolean isAutoCommitEnabled = env.getProperty("spring.datasource.hikari.auto-commit") != null ? Boolean.parseBoolean(env.getProperty("spring.datasource.hikari.auto-commit")):false;
        ds.setAutoCommit(isAutoCommitEnabled);
        // Connection test query is for legacy connections
        //ds.setConnectionInitSql(env.getProperty("spring.datasource.hikari.connection-test-query"));
        ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
        ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        long timeout = env.getProperty("spring.datasource.hikari.idleTimeout") != null ? Long.parseLong(env.getProperty("spring.datasource.hikari.idleTimeout")): 40000;
        ds.setIdleTimeout(timeout);
        long maxLifeTime = env.getProperty("spring.datasource.hikari.maxLifetime") != null ? Long.parseLong(env.getProperty("spring.datasource.hikari.maxLifetime")): 1800000 ;
        ds.setMaxLifetime(maxLifeTime);
        ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
        ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
        ds.setUsername(env.getProperty("spring.datasource.username"));
        ds.setPassword(env.getProperty("spring.datasource.password"));
        int poolSize = env.getProperty("spring.datasource.hikari.maximum-pool-size") != null ? Integer.parseInt(env.getProperty("spring.datasource.hikari.maximum-pool-size")): 10;
        ds.setMaximumPoolSize(poolSize);

        return ds;
    }

    @Bean
    @Profile("test")
    public JdbcTemplate testJdbctemplate() {
        return new JdbcTemplate(testDs());
    }

    @Bean
    @Profile("test")
    public NamedParameterJdbcTemplate testNamedTemplate() {
        return new NamedParameterJdbcTemplate(testDs());
    }

    @Override
    public void setEnvironment(Environment environment) {
        // TODO Auto-generated method stub
        this.env = environment;
    }
}

How can I generate a 6 digit unique number?

<?php
$file = 'count.txt';

//get the number from the file
$uniq = file_get_contents($file);

//add +1
$id = $uniq + 1 ;

// add that new value to text file again for next use
file_put_contents($file, $id);

// your unique id ready
echo $id;
?>

i hope this will work fine. i use the same technique in my website.

if block inside echo statement?

You will want to use the a ternary operator which acts as a shortened IF/Else statement:

echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';

Styling a disabled input with css only

Let's just say you have 3 buttons:

<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">

To style the disabled button you can use the following css:

input[type="button"]:disabled{
    color:#000;
}

This will only affect the button which is disabled.

To stop the color changing when hovering you can use this too:

input[type="button"]:disabled:hover{
    color:#000;
}

You can also avoid this by using a css-reset.

Error in file(file, "rt") : cannot open the connection

Error in file(file, "rt")

Created a .r file and saved it in Desktop together with a sample_10000.csv file.

Once trying to read it

heisenberg <- read.csv(file="sample_100000.csv")

was getting the same error as you

heisenberg <- read.csv(file="sample_10000") Error in file(file, "rt") : cannot open the connection In addition: Warning message: In file(file, "rt") : cannot open file 'sample_10000': No such file or directory


I knew at least two ways to fix this, one using the absolute path and the other changing the working directory.

Absolute path

I fixed it adding the absolute path to the file, more precisely

heisenberg <- read.csv(file="C:/Users/tiago/Desktop/sample_100000.csv")

Working directory

This error shows up because RStudio has a specific working directory defined which isn't necessarily the place the .r file is at.

So, to fix using this approach I've gone to Session > Set Working Directory > Chose Directory (CTRL + Shift + H) and selected Desktop, where the .csv file was at. That way running the following command also worked

heisenberg <- read.csv(file="sample_100000.csv")

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

I was playing around with C# code an I accidentally found the solution to your problem haha

This is the code for the Principal view:

`@model dynamic 
 @Html.Partial("_Partial", Model as IDictionary<string, object>)`

Then in the Partial view:

`@model dynamic 
 @if (Model != null) { 
   foreach (var item in Model) 
   { 
    <div>@item.text</div> 
   } 
  }`

It worked for me, I hope this will help you too!!

Convert a float64 to an int in Go

Correct rounding is likely desired.

Therefore math.Round() is your quick(!) friend. Approaches with fmt.Sprintf and strconv.Atois() were 2 orders of magnitude slower according to my tests with a matrix of float64 values that were intended to become correctly rounded int values.

package main
import (
    "fmt"
    "math"
)
func main() {
    var x float64 = 5.51
    var y float64 = 5.50
    var z float64 = 5.49
    fmt.Println(int(math.Round(x)))  // outputs "6"
    fmt.Println(int(math.Round(y)))  // outputs "6"
    fmt.Println(int(math.Round(z)))  // outputs "5"
}

math.Round() does return a float64 value but with int() applied afterwards, I couldn't find any mismatches so far.

Git Bash doesn't see my PATH

In my case It happened while installing heroku cli and git bash, Here is what i did to work.

got to this location

C:\Users\<username here>\AppData\Local

and delete the file in my case heroku folder. So I deleded folder and run cmd. It is working

cc1plus: error: unrecognized command line option "-std=c++11" with g++

you should try this

g++-4.4 -std=c++0x or g++-4.7 -std=c++0x

How to have image and text side by side

It's always worth grouping elements into sections that are relevant. In your case, a parent element that contains two columns;

  1. icon
  2. text.

http://jsfiddle.net/qMdfC/10/

HTML:

<div class='container2'>
    <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails' />

    <div class="text">
        <h4>Facebook</h4>
        <p>
            fine location, GPS, coarse location
            <span>0 mins ago</span>
        </p>
    </div>
</div>

CSS:

* {
    padding:0;
    margin:0;
}
.iconDetails {
    margin:0 2%;
    float:left;
    height:40px;
    width:40px;
}
.container2 {
    width:100%;
    height:auto;
    padding:1%;
}
.text {
    float:left;
}
.text h4, .text p {
    width:100%;
    float:left;
    font-size:0.6em;
}
.text p span {
    color:#666;
}

CUDA incompatible with my gcc version

This is happening because your current CUDA version doesn't support your current GCC version. You need to do the following:

  1. Find the supported GCC version (in my case 5 for CUDA 9)

    • CUDA 4.1: GCC 4.5
    • CUDA 5.0: GCC 4.6
    • CUDA 6.0: GCC 4.7
    • CUDA 7.0: GCC 4.8
    • CUDA 7.5: GCC 4.8
    • CUDA 8: GCC 5.3
    • CUDA 9: GCC 5.5
    • CUDA 9.2: GCC 7
    • CUDA 10.1: GCC 8
  2. Install the supported GCC version

    sudo apt-get install gcc-5
    sudo apt-get install g++-5
    
  3. Change the softlinks for GCC in the /usr/bin directory

    cd /usr/bin
    sudo rm gcc
    sudo rm g++
    sudo ln -s /usr/bin/gcc-5 gcc
    sudo ln -s /usr/bin/g++-5 g++
    
  4. Change the softlinks for GCC in the /usr/local/cuda-9.0/bin directory

    cd /usr/local/cuda-9.0/bin
    sudo rm gcc
    sudo rm g++
    sudo ln -s /usr/bin/gcc-5 gcc
    sudo ln -s /usr/bin/g++-5 g++
    
  5. Add -DCUDA_HOST_COMPILER=/usr/bin/gcc-5 to your setup.py file, used for compilation

    if torch.cuda.is_available() and CUDA_HOME is not None:
        extension = CUDAExtension
        sources += source_cuda
        define_macros += [("WITH_CUDA", None)]
        extra_compile_args["nvcc"] = [
            "-DCUDA_HAS_FP16=1",
            "-D__CUDA_NO_HALF_OPERATORS__",
            "-D__CUDA_NO_HALF_CONVERSIONS__",
            "-D__CUDA_NO_HALF2_OPERATORS__",
            "-DCUDA_HOST_COMPILER=/usr/bin/gcc-5"
        ]
    
  6. Remove the old build directory

    rm -rd build/
    
  7. Compile again by setting CUDAHOSTCXX=/usr/bin/gcc-5

    CUDAHOSTCXX=/usr/bin/gcc-5 python setup.py build develop
    

Note: If you still get the gcc: error trying to exec 'cc1plus': execvp: no such file or directory error after following these steps, try reinstalling the GCC like this and then compiling again:

sudo apt-get install --reinstall gcc-5
sudo apt-get install --reinstall g++-5

Credits: https://github.com/facebookresearch/maskrcnn-benchmark/issues/25#issuecomment-433382510

Convert generic List/Enumerable to DataTable?

 Dim counties As New List(Of County)
 Dim dtCounties As DataTable
 dtCounties = _combinedRefRepository.Get_Counties()
 If dtCounties.Rows.Count <> 0 Then
    For Each row As DataRow In dtCounties.Rows
      Dim county As New County
      county.CountyId = row.Item(0).ToString()
      county.CountyName = row.Item(1).ToString().ToUpper()
      counties.Add(county)
    Next
    dtCounties.Dispose()
 End If

Return a `struct` from a function in C

As far as I can remember, the first versions of C only allowed to return a value that could fit into a processor register, which means that you could only return a pointer to a struct. The same restriction applied to function arguments.

More recent versions allow to pass around larger data objects like structs. I think this feature was already common during the eighties or early nineties.

Arrays, however, can still be passed and returned only as pointers.

sudo: npm: command not found

I had to do the following:

  1. brew update
  2. brew uninstall node
  3. Visit https://nodejs.org/en/ download the file
  4. Install the downloaded file

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

You can give yourself permissions to fix this problem.

Right click on cacerts > choose properties > select Securit tab > Allow all permissions to all the Group and user names.

This worked for me.

How to display raw html code in PRE or something like it but without escaping it

Essentially the original question can be broken down in 2 parts:

  • Main objective/challenge: embedding(/transporting) a raw formatted code-snippet (any kind of code) in a web-page's markup (for simple copy/paste/edit due to no encoding/escaping)
  • correctly displaying/rendering that code-snippet (possibly edit it) in the browser

The short (but) ambiguous answer is: you can't, ...but you can (get very close).
(I know, that are 3 contradicting answers, so read on...)

(polyglot)(x)(ht)ml Markup-languages rely on wrapping (almost) everything between begin/opening and end/closing tags/character(sequences).
So, to embed any kind of raw code/snippet inside your markup-language, one will always have to escape/encode every instance (inside that snippet) that resembles the character(-sequence) that would close the wrapping 'container' element in the markup. (During this post I'll refer to this as rule no 1.)
Think of "some "data" here" or <i>..close italics with '</i>'-tag</i>, where it is obvious one should escape/encode (something in) </i and " (or change container's quote-character from " to ').

So, because of rule no 1, you can't 'just' embed 'any' unknown raw code-snippet inside markup.
Because, if one has to escape/encode even one character inside the raw snippet, then that snippet would no longer be the same original 'pure raw code' that anyone can copy/paste/edit in the document's markup without further thought. It would lead to malformed/illegal markup and Mojibake (mainly) because of entities.
Also, should that snippet contain such characters, you'd still need some javascript to 'translate' that character(sequence) from (and to) it's escaped/encoded representation to display the snippet correctly in the 'webpage' (for copy/paste/edit).

That brings us to (some of) the datatypes that markup-languages specify. These datatypes essentially define what are considered 'valid characters' and their meaning (per tag, property, etc.):

  • PCDATA (Parsed Character DATA): will expand entities and one must escape <, & (and > depending on markup language/version).
    Most tags like body, div, pre, etc, but also textarea (until HTML5) fall under this type.
    So not only do you need to encode all the container's closing character-sequences inside the snippet, you also have to encode all <, & (,>) characters (at minimum).
    Needless to say, encoding/escaping this many characters falls outside this objective's scope of embedding a raw snippet in the markup.
    '..But a textarea seems to work...', yes, either because of the browsers error-engine trying to make something out of it, or because HTML5:

  • RCDATA (Replaceable Character DATA): will not not treat tags inside the text as markup (but are still governed by rule 1), so one doesn't need to encode < (>). BUT entities are still expanded, so they and 'ambiguous ampersands' (&) need special care.
    The current HTML5 spec says the textarea is now a RCDATA field and (quote):

    The text in raw text and RCDATA elements must not contain any occurrences of the string "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

    Thus no matter what, textarea needs a hefty entity translation handler or it will eventually Mojibake on entities!

  • CDATA (Character Data) will not treat tags inside the text as markup and will not expand entities.
    So as long as the raw snippet code does not violate rule 1 (that one can't have the containers closing character(sequence) inside the snippet), this requires no other escaping/encoding.

Clearly this boils down to: how can we minimize the number of characters/character-sequences that still need to be encoded in the snippet's raw source and the number of times that character(sequence) might appear in an average snippet; something that is also of importance for the javascript that handles the translation of these characters (if they occur).

So what 'containers' have this CDATA context?

Most value properties of tags are CDATA, so one could (ab)use a hidden input's value property (proof of concept jsfiddle here).
However (conform rule 1) this creates an encoding/escape problem with nested quotes (" and ') in the raw snippet and one needs some javascript to get/translate and set the snippet in another (visible) element (or simply setting it as a text-area's value). Somehow this gave me problems with entities in FF (just like in a textarea). But it doesn't really matter, since the 'price' of having to escape/encode nested quotes is higher then a (HTML5) textarea (quotes are quite common in source code..).

What about trying to (ab)use <![CDATA[<tag>bla & bla</tag>]]>?
As Jukka points out in his extended answer, this would only work in (rare) 'real xhtml'.
I thought of using a script-tag (with or without such a CDATA wrapper inside the script-tag) together with a multi-line comment /* */ that wraps the raw snippet (script-tags can have an id and you can access them by count). But since this obviously introduces a escaping problem with */, ]]> and </script in the raw snippet, this doesn't seem like a solution either.

Please post other viable 'containers' in the comments to this answer.

By the way, encoding or counting the number of - characters and balancing them out inside a comment tag <!-- --> is just insane for this purpose (apart from rule 1).


That leaves us with Jukka K. Korpela's excellent answer: the <xmp> tag seems the best option!

The 'forgotten' <xmp> holds CDATA, is intended for this purpose AND is indeed still in the current HTML 5 spec (and has been at least since HTML3.2); exactly what we need! It's also widely supported, even in IE6 (that is.. until it suffers from the same regression as the scrolling table-body).
Note: as Jukka pointed out, this will not work in true xhtml or polyglot (that will treat it as a pre) and the xmp tag must still adhere to rule no 1. But that's the 'only' rule.

Consider the following markup:

<!-- ATTENTION: replace any occurrence of &lt;/xmp with </xmp -->
<xmp id="snippet-container">
<div>
    <div>this is an example div &amp; holds an xmp tag:<br />
        <xmp> 
<html><head>  <!-- indentation col 0!! -->
    <title>My Title</title>
</head><body>
    <p>hello world !!</p>
</body></html>
        &lt;/xmp>  <!-- note this encoded/escaped tag -->
    </div>
    This line is also part of the snippet
</div>
</xmp>

The above codeblok illustrates a raw piece of markup where <xmp id="snippet-container"> contains an (almost raw) code-snippet (containing div>div>xmp>html-document).
Notice the encoded closing tag in this markup? To comply with rule no 1, this was encoded/escaped).

So embedding/transporting the (sometimes almost) raw code is/seems solved.

What about displaying/rendering the snippet (and that encoded &lt;/xmp>)?

The browser will (or it should) render the snippet (the contents inside snippet-container) exactly the way you see it in the codeblock above (with some discrepancy amongst browsers whether or not the snippet starts with a blank line).
That includes the formatting/indentation, entities (like the string &amp;), full tags, comments AND the encoded closing tag &lt;/xmp> (just like it was encoded in the markup). And depending on browser(version) one could even try use the property contenteditable="true" to edit this snippet (all that without javascript enabled). Doing something like textarea.value=xmp.innerHTML is also a breeze.

So you can... if the snippet doesn't contain the containers closing character-sequence.

However, should a raw snippet contain the closing character-sequence </xmp (because it is an example of xmp itself or it contains some regex, etc), you must accept that you have to encode/escape that sequence in the raw snippet AND need a javascript handler to translate that encoding to display/render the encoded &lt;/xmp> like </xmp> inside a textarea (for editing/posting) or (for example) a pre just to correctly render the snippet's code (or so it seems).

A very rudimentary jsfiddle example of this here. Note that getting/embedding/displaying/retrieving-to-textarea worked perfect even in IE6. But setting the xmp's innerHTML revealed some interesting 'would-be-intelligent' behavior on IE's part. There is a more extensive note and workaround on that in the fiddle.

But now comes the important kicker (another reason why you only get very close): Just as an over-simplified example, imagine this rabbit-hole:

Intended raw code-snippet:

<!-- remember to translate between </xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Well, to comply with rule 1, we 'only' need to encode those </xmp[> \n\r\t\f\/] sequences, right?

So that gives us the following markup (using just a possible encoding):

<xmp id="container">
<!-- remember to translate between &lt;/xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
&lt;/xmp>
</xmp>

Hmm.. shalt I get my crystal ball or flip a coin? No, let the computer look at its system-clock and state that a derived number is 'random'. Yes, that should do it..

Using a regex like: xmp.innerHTML.replace(/&lt;(?=\/xmp[> \n\r\t\f\/])/gi, '<');, would translate 'back' to this:

<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Hmm.. seems this random generator is broken... Houston..?
Should you have missed the joke/problem, read again starting at the 'intended raw code-snippet'.

Wait, I know, we (also) need to encode .... to ....
Ok, rewind to 'intended raw code-snippet' and read again.
Somehow this all begins to smell like the famous hilarious-but-true rexgex-answer on SO, a good read for people fluent in mojibake.

Maybe someone knows a clever algorithm or solution to fix this problem, but I assume that the embedded raw code will get more and more obscure to the point where you'd be better of properly escaping/encoding just your <, & (and >), just like the rest of the world.

Conclusion: (using the xmp tag)

  • it can be done with known snippets that do not contain the container's closing character-sequence,
  • we can get very close to the original objective with known snippets that only use 'basic first-level' escaping/encoding so we don't fall in the rabbithole,
  • but ultimately it seems that one can't do this reliably in a 'production-environment' where people can/should copy/paste/edit 'any unknown' raw snippets while not knowing/understanding the implications/rules/rabbithole (depending on your implementation of handling/translating for rule 1 and the rabbit-hole).

Hope this helps!

PS: Whilst I would appreciate an upvote if you find this explanation useful, I kind of think Jukka's answer should be the accepted answer (should no better option/answer come along), since he was the one who remembered the xmp tag (that I forgot about over the years and got 'distracted' by the commonly advocated PCDATA elements like pre, textarea, etc.).
This answer originated in explaining why you can't do it (with any unknown raw snippet) and explain some obvious pitfalls that some other (now deleted) answers overlooked when advising a textarea for embedding/transport. I've expanded my existing explanation to also support and further explain Jukka's answer (since all that entity and *CDATA stuff is almost harder than code-pages).

what is Array.any? for javascript

Array has a length property :

[].length // 0
[0].length // 1
[4, 8, 15, 16, 23, 42].length // 6

Opening PDF String in new window with javascript

Based off other old answers:

escape() function is now deprecated,

Use encodeURI() or encodeURIComponent() instead.

Example that worked in my situation:

window.open("data:application/pdf," + encodeURI(pdfString)); 

Happy Coding!

Create a BufferedImage from file and make it TYPE_INT_ARGB

Create a BufferedImage from file and make it TYPE_INT_RGB

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );
            File f = new File("MyFile.png");
            int r = 5;
            int g = 25; 
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f); 
        }
        catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

This paints a big blue streak across the top.

If you want it ARGB, do it like this:

    try{
        BufferedImage img = new BufferedImage( 
            500, 500, BufferedImage.TYPE_INT_ARGB );
        File f = new File("MyFile.png");
        int r = 255;
        int g = 10;
        int b = 57;
        int alpha = 255;
        int col = (alpha << 24) | (r << 16) | (g << 8) | b;
        for(int x = 0; x < 500; x++){
            for(int y = 20; y < 30; y++){
                img.setRGB(x, y, col);
            }
        }
        ImageIO.write(img, "PNG", f);
    }
    catch(Exception e){
        e.printStackTrace();
    }

Open up MyFile.png, it has a red streak across the top.

Notepad++ Setting for Disabling Auto-open Previous Files

For versions 6.6+ you need to uncheck "Remember the current session for next launch" on Settings -> Preferences -> Backup.

this is it in 6.6+

For older versions you need to uncheck "Remember the current session for next launch" on Settings -> Preferences.

this is it

Add php variable inside echo statement as href link address?

you can either use

echo '<a href="'.$link_address.'">Link</a>';

or

echo "<a href=\"$link_address\">Link</a>';

if you use double quotes you can insert the variable into the string and it will be parsed.

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

For me, the HOST was set differently in tnsnames.ora and listener.ora. One was set to the full name of the computer and the other was set to IP address. I synchronized them to the full name of the computer and it worked. Don't forget to restart the oracle services.

I still don't understand exactly why this caused problem because I think IP address and computer name are ultimately same in my understanding.

Get MD5 hash of big files in Python

Below I've incorporated suggestion from comments. Thank you al!

python < 3.7

import hashlib

def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
    h = hash_factory()
    with open(filename,'rb') as f: 
        for chunk in iter(lambda: f.read(chunk_num_blocks*h.block_size), b''): 
            h.update(chunk)
    return h.digest()

python 3.8 and above

import hashlib

def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
    h = hash_factory()
    with open(filename,'rb') as f: 
        while chunk := f.read(chunk_num_blocks*h.block_size): 
            h.update(chunk)
    return h.digest()

original post

if you care about more pythonic (no 'while True') way of reading the file check this code:

import hashlib

def checksum_md5(filename):
    md5 = hashlib.md5()
    with open(filename,'rb') as f: 
        for chunk in iter(lambda: f.read(8192), b''): 
            md5.update(chunk)
    return md5.digest()

Note that the iter() func needs an empty byte string for the returned iterator to halt at EOF, since read() returns b'' (not just '').

Why are hexadecimal numbers prefixed with 0x?

The preceding 0 is used to indicate a number in base 2, 8, or 16.

In my opinion, 0x was chosen to indicate hex because 'x' sounds like hex.

Just my opinion, but I think it makes sense.

Good Day!

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

Save bitmap to location

// |==| Create a PNG File from Bitmap :

void devImjFylFnc(String pthAndFylTtlVar, Bitmap iptBmjVar)
{
    try
    {
        FileOutputStream fylBytWrtrVar = new FileOutputStream(pthAndFylTtlVar);
        iptBmjVar.compress(Bitmap.CompressFormat.PNG, 100, fylBytWrtrVar);
        fylBytWrtrVar.close();
    }
    catch (Exception errVar) { errVar.printStackTrace(); }
}

// |==| Get Bimap from File :

Bitmap getBmjFrmFylFnc(String pthAndFylTtlVar)
{
    return BitmapFactory.decodeFile(pthAndFylTtlVar);
}

How to send a JSON object using html form data

Get complete form data as array and json stringify it.

var formData = JSON.stringify($("#myForm").serializeArray());

You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.

$.ajax({
  type: "POST",
  url: "serverUrl",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"
});

Drop rows containing empty cells from a pandas DataFrame

If you don't care about the columns where the missing files are, considering that the dataframe has the name New and one wants to assign the new dataframe to the same variable, simply run

New = New.drop_duplicates()

If you specifically want to remove the rows for the empty values in the column Tenant this will do the work

New = New[New.Tenant != '']

This may also be used for removing rows with a specific value - just change the string to the value that one wants.

Note: If instead of an empty string one has NaN, then

New = New.dropna(subset=['Tenant'])

How can I specify my .keystore file with Spring Boot and Tomcat?

If you don't want to implement your connector customizer, you can build and import the library (https://github.com/ycavatars/spring-boot-https-kit) which provides predefined connector customizer. According to the README, you only have to create your keystore, configure connector.https.*, import the library and add @ComponentScan("org.ycavatars.sboot.kit"). Then you'll have HTTPS connection.

How to break out from a ruby block?

next and break seem to do the correct thing in this simplified example!

class Bar
  def self.do_things
      Foo.some_method(1..10) do |x|
            next if x == 2
            break if x == 9
            print "#{x} "
      end
  end
end

class Foo
    def self.some_method(targets, &block)
      targets.each do |target|
        begin
          r = yield(target)
        rescue  => x
          puts "rescue #{x}"
        end
     end
   end
end

Bar.do_things

output: 1 3 4 5 6 7 8

How do I change data-type of pandas data frame to string with a defined format?

I'm unable to reproduce your problem but have you tried converting it to an integer first?

image_name_data['id'] = image_name_data['id'].astype(int).astype('str')

Then, regarding your more general question you could use map (as in this answer). In your case:

image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)

Difference between "while" loop and "do while" loop

Probably wdlen starts with a value >=2, so in the second case the loop condition is initially false and the loop is never entered.

In the second case the loop body is executed before the wdlen<2 condition is checked for the first time, so the printf/scanf is executed at least once.

How to run a program automatically as admin on Windows 7 at startup?

schtasks /create /sc onlogon /tn MyProgram /rl highest /tr "exeFullPath"

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

How to add parameters to a HTTP GET request in Android?

If you have constant URL I recommend use simplified http-request built on apache http.

You can build your client as following:

private filan static HttpRequest<YourResponseType> httpRequest = 
                   HttpRequestBuilder.createGet(yourUri,YourResponseType)
                   .build();

public void send(){
    ResponseHendler<YourResponseType> rh = 
         httpRequest.execute(param1, value1, param2, value2);

    handler.ifSuccess(this::whenSuccess).otherwise(this::whenNotSuccess);
}

public void whenSuccess(ResponseHendler<YourResponseType> rh){
     rh.ifHasContent(content -> // your code);
}

public void whenSuccess(ResponseHendler<YourResponseType> rh){
   LOGGER.error("Status code: " + rh.getStatusCode() + ", Error msg: " + rh.getErrorText());
}

Note: There are many useful methods to manipulate your response.

Different ways of adding to Dictionary

Given the, most than probable similarities in performance, use whatever feel more correct and readable to the piece of code you're using.

I feel an operation that describes an addition, being the presence of the key already a really rare exception is best represented with the add. Semantically it makes more sense.

The dict[key] = value represents better a substitution. If I see that code I half expect the key to already be in the dictionary anyway.

How to implement 2D vector array?

We can easily use vector as 2d array. We use resize() method for this purpose. The code below can be helpful to understand this issue.

Code Snippet :

#include<bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    int row, col;
    cin>>row>>col;

    vector <vector<int>> v;
    v.resize(col,vector<int>(row));

    //v = {{1,2,3}, {4,5,6}, {7,8,9}}; 

    /** input from use **/
    for(int i=0; i<row; i++)
    {
       for(int j=0; j<col; j++)
       {
          cin>>v[i][j];
       }
    }

    for(int i=0;i<row; i++)
    {
       for(int j=0;j<col;j++)
       {
          cout<<v[i][j]<<" ";
       }
    }
    return 0;
}

JQuery - Call the jquery button click event based on name property

You can use the name property for that particular element. For example to set a border of 2px around an input element with name xyz, you can use;

$(function() {
    $("input[name = 'xyz']").css("border","2px solid red");
})

DEMO

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

This works for me on a similar issue where I failed to delete the user due to the reference. Thank you

@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH})

Get exit code for command in bash/ksh

There are several things wrong with your script.

Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).

It's good practice to surround your variable references with curly braces, too. Your code might look like:

#!/bin/sh
command="/bin/date -u"          #...Example Only

safeRunCommand() {
   cmnd="$@"                    #...insure whitespace passed and preserved
   $cmnd
   ERROR_CODE=$?                #...so we have it for the command we want
   if [ ${ERROR_CODE} != 0 ]; then
      printf "Error when executing command: '${command}'\n"
      exit ${ERROR_CODE}        #...consider 'return()' here
   fi
}

safeRunCommand $command
command="cp"
safeRunCommand $command

How to get current html page title with javascript

Like this :

jQuery(document).ready(function () {
    var title = jQuery(this).attr('title');
});

works for IE, Firefox and Chrome.

How do I encode/decode HTML entities in Ruby?

You can use htmlascii gem:

Htmlascii.convert string

Uploading/Displaying Images in MVC 4

Have a look at the following

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, 
                            new { enctype = "multipart/form-data" }))
{  
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 
}

your controller should have action method which would accept HttpPostedFileBase;

 public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (file != null)
        {
            string pic = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(
                                   Server.MapPath("~/images/profile"), pic); 
            // file is uploaded
            file.SaveAs(path);

            // save the image path path to the database or you can send image 
            // directly to database
            // in-case if you want to store byte[] ie. for DB
            using (MemoryStream ms = new MemoryStream()) 
            {
                 file.InputStream.CopyTo(ms);
                 byte[] array = ms.GetBuffer();
            }

        }
        // after successfully uploading redirect the user
        return RedirectToAction("actionname", "controller name");
    }

Update 1

In case you want to upload files using jQuery with asynchornously, then try this article.

the code to handle the server side (for multiple upload) is;

 try
    {
        HttpFileCollection hfc = HttpContext.Current.Request.Files;
        string path = "/content/files/contact/";

        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                string fileName = "";
                if (Request.Browser.Browser == "IE")
                {
                    fileName = Path.GetFileName(hpf.FileName);
                }
                else
                {
                    fileName = hpf.FileName;
                }
                string fullPathWithFileName = path + fileName;
                hpf.SaveAs(Server.MapPath(fullPathWithFileName));
            }
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }

this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.

UPDATE 2

Alternatively, you can try Async File Uploads in MVC 4.

Creating a daemon in Linux

A daemon is just a process in the background. If you want to start your program when the OS boots, on linux, you add your start command to /etc/rc.d/rc.local (run after all other scripts) or /etc/startup.sh

On windows, you make a service, register the service, and then set it to start automatically at boot in administration -> services panel.

Checking for a null object in C++

C++ references naturally can't be null, you don't need the check. The function can only be called by passing a reference to an existing object.

Parsing JSON with Unix tools

On the basis that some of the recommendations here (esp in the comments) suggested the use of Python, I was disappointed not to find an example.

So, here's a one liner to get a single value from some JSON data. It assumes that you are piping the data in (from somewhere) and so should be useful in a scripting context.

echo '{"hostname":"test","domainname":"example.com"}' | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["hostname"]'

Regex that matches integers in between whitespace or start/end of string only

You could use lookaround instead if all you want to match is whitespace:

(?<=\s|^)\d+(?=\s|$)

Java escape JSON String?

org.json.simple.JSONObject.escape() escapes quotes,, /, \r, \n, \b, \f, \t and other control characters.

import org.json.simple.JSONValue;
JSONValue.escape("test string");

Add pom.xml when using maven

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <scope>test</scope>
</dependency>

How to include a class in PHP

I suggest you also take a look at __autoload.
This will clean up the code of requires and includes.

How to calculate combination and permutation in R?

If you don't want your code to depend on other packages, you can always just write these functions:

perm = function(n, x) {
  factorial(n) / factorial(n-x)
}

comb = function(n, x) {
  factorial(n) / factorial(n-x) / factorial(x)
}

Java JTable getting the data of the selected row

http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html

You will find these methods in it:

getValueAt(int row, int column)
getSelectedRow()
getSelectedColumn()

Use a mix of these to achieve your result.

How to convert unsigned long to string

Try using sprintf:

unsigned long x=1000000;
char buffer[21];
sprintf(buffer,"%lu", x);

Edit:

Notice that you have to allocate a buffer in advance, and have no idea how long the numbers will actually be when you do so. I'm assuming 32bit longs, which can produce numbers as big as 10 digits.

See Carl Smotricz's answer for a better explanation of the issues involved.

How to concatenate string variables in Bash

Safer way:

a="AAAAAAAAAAAA"
b="BBBBBBBBBBBB"
c="CCCCCCCCCCCC"
d="DD DD"
s="${a}${b}${c}${d}"
echo "$s"
AAAAAAAAAAAABBBBBBBBBBBBCCCCCCCCCCCCDD DD

Strings containing spaces can become part of command, use "$XXX" and "${XXX}" to avoid these errors.

Plus take a look at other answer about +=

How to strip all non-alphabetic characters from string in SQL Server?

this way didn't work for me as i was trying to keep the Arabic letters i tried to replace the regular expression but also it didn't work. i wrote another method to work on ASCII level as it was my only choice and it worked.

 Create function [dbo].[RemoveNonAlphaCharacters] (@s varchar(4000)) returns varchar(4000)
   with schemabinding
begin
   if @s is null
      return null
   declare @s2 varchar(4000)
   set @s2 = ''
   declare @l int
   set @l = len(@s)
   declare @p int
   set @p = 1
   while @p <= @l begin
      declare @c int
      set @c = ascii(substring(@s, @p, 1))
      if @c between 48 and 57 or @c between 65 and 90 or @c between 97 and 122 or @c between 165 and 253 or @c between 32 and 33
         set @s2 = @s2 + char(@c)
      set @p = @p + 1
      end
   if len(@s2) = 0
      return null
   return @s2
   end

GO

Remove an item from an IEnumerable<T> collection

You can't remove IEnumerable<T> elements, but you can use the Enumerable.Skip Method

Datatable date sorting dd/mm/yyyy issue

I used in the rest call

**Date Variable is: Created **

var call = $.ajax({
            url: "../_api/Web/Lists/GetByTitle('NewUser')/items?$filter=(Created%20ge%20datetime'"+FromDate+"')%20and%20(Created%20le%20datetime'"+ToDate+"' and Title eq '"+epf+"' )&$top=5000",
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }

            });

  call.done(function (data,textStatus, jqXHR){
        $('#example').dataTable({
            "bDestroy": true,
            "bProcessing": true,
            "aaData": data.d.results,
            "aLengthMenu" : [
             [50,100],
             [50,100]
            ],
             dom: 'Bfrtip',
            buttons: [
                'copy', 'csv', 'excel'
            ],

            "aoColumnDefs": [{ "bVisible": false  }],
            "aoColumns": [
                { "mData": "ID" },
                { "mData": "Title" },
                { "mData": "EmployeeName" },
                { "mData": "Department1" },
                { "mData": "ServicingAt" },
                { "mData": "TestField" }, 
                { "mData": "BranchCode" },   
                { "mData": "Created" ,"render": function (data, type, row) {
        data = moment(data).format('DD MMM YYYY');
        return data;
    }

How can I send the "&" (ampersand) character via AJAX?

You could encode your string using Base64 encoding on the JavaScript side and then decoding it on the server side with PHP (?).

JavaScript (Docu)

var wysiwyg_clean = window.btoa( wysiwyg );

PHP (Docu):

var wysiwyg = base64_decode( $_POST['wysiwyg'] );

Initializing a member array in constructor initializer

C++98 doesn't provide a direct syntax for anything but zeroing (or for non-POD elements, value-initializing) the array. For that you just write C(): arr() {}.

I thing Roger Pate is wrong about the alleged limitations of C++0x aggregate initialization, but I'm too lazy to look it up or check it out, and it doesn't matter, does it? EDIT: Roger was talking about "C++03", I misread it as "C++0x". Sorry, Roger. ?

A C++98 workaround for your current code is to wrap the array in a struct and initialize it from a static constant of that type. The data has to reside somewhere anyway. Off the cuff it can look like this:

class C 
{
public:
    C() : arr( arrData ) {}

private:
     struct Arr{ int elem[3]; };
     Arr arr;
     static Arr const arrData;
};

C::Arr const C::arrData = {{1, 2, 3}};

String comparison in Objective-C

Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.

if ([category isEqualToString:@"Some String"])
{
    // Do stuff...
}

Best way to handle multiple constructors in Java

Several people have recommended adding a null check. Sometimes that's the right thing to do, but not always. Check out this excellent article showing why you'd skip it.

http://misko.hevery.com/2009/02/09/to-assert-or-not-to-assert/

How do I disable form resizing for users?

Change this property and try this at design time:

FormBorderStyle = FormBorderStyle.FixedDialog;

Designer view before the change:

Enter image description here

nginx 502 bad gateway

I executed my localhost and the page displayed the 502 bad gateway message. This helped me:

  1. Edit /etc/php5/fpm/pool.d/www.conf
  2. Change listen = /var/run/php5-fpm.sock to listen = 127.0.0.1:9000
  3. Ensure the location is set properly in nginx.conf.
  4. Run sudo service php5-fpm restart

Maybe it will help you.

Source from: http://wildlyinaccurate.com/solving-502-bad-gateway-with-nginx-php-fpm

How to use glyphicons in bootstrap 3.0

Bootstrap 3 requires span tag not i

<span class="glyphicon glyphicon-search"></span>`

How can I remove an element from a list, with lodash?

There are four ways to do this as I know

const array = [{id:1,name:'Jim'},{id:2,name:'Parker'}];
const toDelete = 1;

The first:

_.reject(array, {id:toDelete})

The second one is :

_.remove(array, {id:toDelete})

In this way the array will be mutated.

The third one is :

_.differenceBy(array,[{id:toDelete}],'id')
// If you can get remove item 
// _.differenceWith(array,[removeItem])

The last one is:

_.filter(array,({id})=>id!==toDelete)

I am learning lodash

Answer to make a record, so that I can find it later.

How do I change db schema to dbo

Move table from dbo schema to MySchema:

 ALTER SCHEMA MySchema TRANSFER dbo.MyTable


Move table from MySchema to dbo schema:

 ALTER SCHEMA dbo TRANSFER MySchema.MyTable

Maven Modules + Building a Single Specific Module

Any best practices here?

Use the Maven advanced reactor options, more specifically:

-pl, --projects
        Build specified reactor projects instead of all projects
-am, --also-make
        If project list is specified, also build projects required by the list

So just cd into the parent P directory and run:

mvn install -pl B -am

And this will build B and the modules required by B.

Note that you need to use a colon if you are referencing an artifactId which differs from the directory name:

mvn install -pl :B -am

As described here: https://stackoverflow.com/a/26439938/480894

PHP output showing little black diamonds with a question mark

Just Paste This Code In Starting to The Top of Page.

<?php
header("Content-Type: text/html; charset=ISO-8859-1");
?>

How do I get current URL in Selenium Webdriver 2 Python?

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

How can I reference a dll in the GAC from Visual Studio?

In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go

EDIT:

That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.

How do you round UP a number in Python?

My share

I have tested print(-(-101 // 5)) = 21 given example above.

Now for rounding up:

101 * 19% = 19.19

I can not use ** so I spread the multiply to division:

(-(-101 //(1/0.19))) = 20

How to sort a HashMap in Java

Without any more information, it's hard to know exactly what you want. However, when choosing what data structure to use, you need to take into account what you need it for. Hashmaps are not designed for sorting - they are designed for easy retrieval. So in your case, you'd probably have to extract each element from the hashmap, and put them into a data structure more conducive to sorting, such as a heap or a set, and then sort them there.

How can I send large messages with Kafka (over 15MB)?

You need to adjust three (or four) properties:

  • Consumer side:fetch.message.max.bytes - this will determine the largest size of a message that can be fetched by the consumer.
  • Broker side: replica.fetch.max.bytes - this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
  • Broker side: message.max.bytes - this is the largest size of the message that can be received by the broker from a producer.
  • Broker side (per topic): max.message.bytes - this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes.)

I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.

PHP Fatal error: Cannot access empty property

Interesting:

  1. You declared an array var $my_value = array();
  2. Pushed value into it $a->my_value[] = 'b';
  3. Assigned a string to variable. (so it is no more array) $a->set_value ('c');
  4. Tried to push a value into array, that does not exist anymore. (it's string) $a->my_class('d');

And your foreach wont work anymore.

How to resolve Nodejs: Error: ENOENT: no such file or directory

I tried something and got this error Error: ENOENT: no such file or directory, open 'D:\Website\Nodemailer\Nodemailer-application\views\layouts\main.handlebars'

The fix I got was to literally construct the directory as it is seen. This means labeling the items exactly as shown, It is weird that I gave the computer what it wants.

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

check for network issues, to bypass the exception case code

In my case, I was using a custom index, that index had no route and such would trigger the exception case code. The exception case bug still exists and still masks the real issue, however I was able to work around this by testing the connectivity with other tools such as nc -vzw1 myindex.example.org 443 and retrying when the network was up.

Simple JavaScript problem: onClick confirm not preventing default action

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

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

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

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

(note that delete is a keyword)

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

Select statement to find duplicates on certain fields

To get the list of fields for which there are multiple records, you can use..

select field1,field2,field3, count(*)
  from table_name
  group by field1,field2,field3
  having count(*) > 1

Check this link for more information on how to delete the rows.

http://support.microsoft.com/kb/139444

There should be a criterion for deciding how you define "first rows" before you use the approach in the link above. Based on that you'll need to use an order by clause and a sub query if needed. If you can post some sample data, it would really help.

Getting the text that follows after the regex match

You can do this with "just the regular expression" as you asked for in a comment:

(?<=sentence).*

(?<=sentence) is a positive lookbehind assertion. This matches at a certain position in the string, namely at a position right after the text sentence without making that text itself part of the match. Consequently, (?<=sentence).* will match any text after sentence.

This is quite a nice feature of regex. However, in Java this will only work for finite-length subexpressions, i. e. (?<=sentence|word|(foo){1,4}) is legal, but (?<=sentence\s*) isn't.

Bootstrap Modal immediately disappearing

My code somehow had the bootstrap.min.js included twice. I removed one of them and everything works fine now.

asynchronous vs non-blocking

Blocking call: Control returns only when the call completes.

Non blocking call: Control returns immediately. Later OS somehow notifies the process that the call is complete.


Synchronous program: A program which uses Blocking calls. In order not to freeze during the call it must have 2 or more threads (that's why it's called Synchronous - threads are running synchronously).

Asynchronous program: A program which uses Non blocking calls. It can have only 1 thread and still remain interactive.

How to make in CSS an overlay over an image?

You can achieve this with this simple CSS/HTML:

.image-container {
    position: relative;
    width: 200px;
    height: 300px;
}
.image-container .after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    color: #FFF;
}
.image-container:hover .after {
    display: block;
    background: rgba(0, 0, 0, .6);
}

HTML

<div class="image-container">
    <img src="http://lorempixel.com/300/200" />
    <div class="after">This is some content</div>
</div>

Demo: http://jsfiddle.net/6Mt3Q/


UPD: Here is one nice final demo with some extra stylings.

_x000D_
_x000D_
.image-container {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
}_x000D_
.image-container img {display: block;}_x000D_
.image-container .after {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    display: none;_x000D_
    color: #FFF;_x000D_
}_x000D_
.image-container:hover .after {_x000D_
    display: block;_x000D_
    background: rgba(0, 0, 0, .6);_x000D_
}_x000D_
.image-container .after .content {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    font-family: Arial;_x000D_
    text-align: center;_x000D_
    width: 100%;_x000D_
    box-sizing: border-box;_x000D_
    padding: 5px;_x000D_
}_x000D_
.image-container .after .zoom {_x000D_
    color: #DDD;_x000D_
    font-size: 48px;_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    margin: -30px 0 0 -19px;_x000D_
    height: 50px;_x000D_
    width: 45px;_x000D_
    cursor: pointer;_x000D_
}_x000D_
.image-container .after .zoom:hover {_x000D_
    color: #FFF;_x000D_
}
_x000D_
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="image-container">_x000D_
    <img src="http://lorempixel.com/300/180" />_x000D_
    <div class="after">_x000D_
        <span class="content">This is some content. It can be long and span several lines.</span>_x000D_
        <span class="zoom">_x000D_
            <i class="fa fa-search"></i>_x000D_
        </span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Converting ArrayList to HashMap

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }

Having the output of a console application in Visual Studio instead of the console

Use System.Diagnostics.Trace

Depending on what listeners you attach, trace output can go to the debug window, the console, a file, database, or all at once. The possibilities are literally endless, as implementing your own TraceListener is extremely simple.

How to configure Fiddler to listen to localhost?

try putting your machine name/IP address instead of 'localhost' into URL. Works for me...

How to insert newline in string literal?

static class MyClass
{
   public const string NewLine="\n";
}

string x = "first line" + MyClass.NewLine + "second line"

How do I connect to a MySQL Database in Python?

Just a modification in above answer. Simply run this command to install mysql for python

sudo yum install MySQL-python
sudo apt-get install MySQL-python

remember! It is case sensitive.

Quickly create a large file on a Linux system

Linux & all filesystems

xfs_mkfile 10240m 10Gigfile

Linux & and some filesystems (ext4, xfs, btrfs and ocfs2)

fallocate -l 10G 10Gigfile

OS X, Solaris, SunOS and probably other UNIXes

mkfile 10240m 10Gigfile

HP-UX

prealloc 10Gigfile 10737418240

Explanation

Try mkfile <size> myfile as an alternative of dd. With the -n option the size is noted, but disk blocks aren't allocated until data is written to them. Without the -n option, the space is zero-filled, which means writing to the disk, which means taking time.

mkfile is derived from SunOS and is not available everywhere. Most Linux systems have xfs_mkfile which works exactly the same way, and not just on XFS file systems despite the name. It's included in xfsprogs (for Debian/Ubuntu) or similar named packages.

Most Linux systems also have fallocate, which only works on certain file systems (such as btrfs, ext4, ocfs2, and xfs), but is the fastest, as it allocates all the file space (creates non-holey files) but does not initialize any of it.

How to set the maxAllowedContentLength to 500MB while running on IIS7?

The limit of requests in .Net can be configured from two properties together:

First

  • Web.Config/system.web/httpRuntime/maxRequestLength
  • Unit of measurement: kilobytes
  • Default value 4096 KB (4 MB)
  • Max. value 2147483647 KB (2 TB)

Second

  • Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength (in bytes)
  • Unit of measurement: bytes
  • Default value 30000000 bytes (28.6 MB)
  • Max. value 4294967295 bytes (4 GB)

References:

Example:

<location path="upl">
   <system.web>
     <!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
     <!-- 100 MB in kilobytes -->
     <httpRuntime maxRequestLength="102400" />
   </system.web>
   <system.webServer>
     <security>
       <requestFiltering>          
         <!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
         <!-- 100 MB in bytes -->
         <requestLimits maxAllowedContentLength="104857600" />
       </requestFiltering>
     </security>
   </system.webServer>
 </location>

What is the use of BindingResult interface in spring MVC?

Well its a sequential process. The Request first treat by FrontController and then moves towards our own customize controller with @Controller annotation.

but our controller method is binding bean using modelattribute and we are also performing few validations on bean values.

so instead of moving the request to our controller class, FrontController moves it towards one interceptor which creates the temp object of our bean and the validate the values. if validation successful then bind the temp obj values with our actual bean which is stored in @ModelAttribute otherwise if validation fails it does not bind and moves the resp towards error page or wherever u want.

enter image description here

How to compare each item in a list with the rest, only once?

Your solution is correct, but your outer loop is still longer than needed. You don't need to compare the last element with anything else because it's been already compared with all the others in the previous iterations. Your inner loop still prevents that, but since we're talking about collision detection you can save the unnecessary check.

Using the same language you used to illustrate your algorithm, you'd come with something like this:

for (int i = 0, i < mylist.size() - 1; ++i)
    for (int j = i + 1, j < mylist.size(); --j)
        compare(mylist[i], mylist[j])

How does autowiring work in Spring?

Depends on whether you want the annotations route or the bean XML definition route.

Say you had the beans defined in your applicationContext.xml:

<beans ...>

    <bean id="userService" class="com.foo.UserServiceImpl"/>

    <bean id="fooController" class="com.foo.FooController"/>

</beans>

The autowiring happens when the application starts up. So, in fooController, which for arguments sake wants to use the UserServiceImpl class, you'd annotate it as follows:

public class FooController {

    // You could also annotate the setUserService method instead of this
    @Autowired
    private UserService userService;

    // rest of class goes here
}

When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically. If you have more than one UserService bean, then you'll have to qualify which one it should use.

If you do the following:

UserService service = new UserServiceImpl();

It will not pick up the @Autowired unless you set it yourself.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

The regex you're looking for is ^[A-Za-z.\s_-]+$

  • ^ asserts that the regular expression must match at the beginning of the subject
  • [] is a character class - any character that matches inside this expression is allowed
  • A-Z allows a range of uppercase characters
  • a-z allows a range of lowercase characters
  • . matches a period rather than a range of characters
  • \s matches whitespace (spaces and tabs)
  • _ matches an underscore
  • - matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-) instead and put it anywhere in the character class, but that's less clear
  • + asserts that the preceding expression (in our case, the character class) must match one or more times
  • $ Finally, this asserts that we're now at the end of the subject

When you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.

MySQL SELECT last few days?

Use for a date three days ago:

WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -3 DAY);

Check the DATE_ADD documentation.

Or you can use:

WHERE t.date >= ( CURDATE() - INTERVAL 3 DAY )

Set drawable size programmatically

You can try button.requestLayout(). When the background size is changed, it needs to remeasure and layout, but it won't do it

Check whether a cell contains a substring

I like Rink.Attendant.6 answer. I actually want to check for multiple strings and did it this way:

First the situation: Names that can be home builders or community names and I need to bucket the builders as one group. To do this I am looking for the word "builder" or "construction", etc. So -

=IF(OR(COUNTIF(A1,"*builder*"),COUNTIF(A1,"*builder*")),"Builder","Community")

How do I get a TextBox to only accept numeric input in WPF?

The event handler is previewing text input. Here a regular expression matches the text input only if it is not a number, and then it is not made to entry textbox.

If you want only letters then replace the regular expression as [^a-zA-Z].

XAML

<TextBox Name="NumberTextBox" PreviewTextInput="NumberValidationTextBox"/>

XAML.CS FILE

using System.Text.RegularExpressions;
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}

How to set the holo dark theme in a Android app?

By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.

So just set it to:

<style name="AppTheme" parent="android:Theme.Holo" />

How do I rename a column in a database table using SQL?

In MySQL, the syntax is ALTER TABLE ... CHANGE:

ALTER TABLE <table_name> CHANGE <column_name> <new_column_name> <data_type> ...

Note that you can't just rename and leave the type and constraints as is; you must retype the data type and constraints after the new name of the column.

How to read from input until newline is found using scanf()?

Sounds like a homework problem. scanf() is the wrong function to use for the problem. I'd recommend getchar() or getch().

Note: I'm purposefully not solving the problem since this seems like homework, instead just pointing you in the right direction.

How to remove specific session in asp.net?

A single way to remove sessions is setting it to null;

Session["your_session"] = null;

How to download Visual Studio Community Edition 2015 (not 2017)

You can use these links to download Visual Studio 2015

Community Edition:

And for anyone in the future who might be looking for the other editions here are the links for them as well:

Professional Edition:

Enterprise Edition:

How to generate random positive and negative numbers in Java

(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))

Limiting the number of characters in a string, and chopping off the rest

You can also use String.format("%3.3s", "abcdefgh"). The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So

System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");

will produce

'abc' '  a'

(you can remove quotes, obviously).

SQL how to check that two tables has exactly the same data?

Enhancement to dietbuddha's answer...

select * from
(
    select * from tableA
    minus
    select * from tableB
)
union all
select * from
(
    select * from tableB
    minus
    select * from tableA
)

Add swipe to delete UITableViewCell

You can try this:

func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
    return true
}

func tableView(tableView: UITableView!, commitEditingStyle editingStyle:   UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) {
        NamesTable.beginUpdates()
        Names.removeAtIndex(indexPath!.row)
        NamesTable.deleteRowsAtIndexPaths([indexPath], withRowAnimation: nil)
        NamesTable.endUpdates()

    }
}

How do you determine what SQL Tables have an identity column programmatically

I think this works for SQL 2000:

SELECT 
    CASE WHEN C.autoval IS NOT NULL THEN
        'Identity'
    ELSE
        'Not Identity'
    AND
FROM
    sysobjects O
INNER JOIN
    syscolumns C
ON
    O.id = C.id
WHERE
    O.NAME = @TableName
AND
    C.NAME = @ColumnName

How to call URL action in MVC with javascript function?

try:

var url = '/Home/Index/' + e.value;
 window.location = window.location.host + url; 

That should get you where you want.

What does "control reaches end of non-void function" mean?

Make sure that your code is returning a value of given return-type irrespective of conditional statements

This code snippet was showing the same error

int search(char arr[], int start, int end, char value)
{
    int i;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            return i;
    }
}

This is the working code after little changes

int search(char arr[], int start, int end, char value)
{
    int i;
    int index=-1;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            index=i;
    }
    return index;
}

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

Some other service may be using port 80: try to stop the other services: HTTPD, SSL, NGINX, PHP, with the command sudo systemctl stop and then use the command sudo systemctl start httpd

ASP.NET MVC JsonResult Date Format

Just to expand on casperOne's answer.

The JSON spec does not account for Date values. MS had to make a call, and the path they chose was to exploit a little trick in the javascript representation of strings: the string literal "/" is the same as "\/", and a string literal will never get serialized to "\/" (even "\/" must be mapped to "\\/").

See http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2 for a better explanation (scroll down to "From JavaScript Literals to JSON")

One of the sore points of JSON is the lack of a date/time literal. Many people are surprised and disappointed to learn this when they first encounter JSON. The simple explanation (consoling or not) for the absence of a date/time literal is that JavaScript never had one either: The support for date and time values in JavaScript is entirely provided through the Date object. Most applications using JSON as a data format, therefore, generally tend to use either a string or a number to express date and time values. If a string is used, you can generally expect it to be in the ISO 8601 format. If a number is used, instead, then the value is usually taken to mean the number of milliseconds in Universal Coordinated Time (UTC) since epoch, where epoch is defined as midnight January 1, 1970 (UTC). Again, this is a mere convention and not part of the JSON standard. If you are exchanging data with another application, you will need to check its documentation to see how it encodes date and time values within a JSON literal. For example, Microsoft's ASP.NET AJAX uses neither of the described conventions. Rather, it encodes .NET DateTime values as a JSON string, where the content of the string is /Date(ticks)/ and where ticks represents milliseconds since epoch (UTC). So November 29, 1989, 4:55:30 AM, in UTC is encoded as "\/Date(628318530718)\/".

A solution would be to just parse it out:

value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));

However I've heard that there is a setting somewhere to get the serializer to output DateTime objects with the new Date(xxx) syntax. I'll try to dig that out.


The second parameter of JSON.parse() accepts a reviver function where prescribes how the value originally produced by, before being returned.

Here is an example for date:

var parsed = JSON.parse(data, function(key, value) {
  if (typeof value === 'string') {
    var d = /\/Date\((\d*)\)\//.exec(value);
    return (d) ? new Date(+d[1]) : value;
  }
  return value;
});

See the docs of JSON.parse()

What is the easiest way to encrypt a password when I save it to the registry?

If you want to be able to decrypt the password, I think the easiest way would be to use DPAPI (user store mode) to encrypt/decrypt. This way you don't have to fiddle with encryption keys, store them somewhere or hard-code them in your code - in both cases somebody can discover them by looking into registry, user settings or using Reflector.

Otherwise use hashes SHA1 or MD5 like others have said here.

How do I declare an array variable in VBA?

David, Error comes Microsoft Office Excel has stopped working. Two options check online for a solution and close the programme and other option Close the program I am sure error is in my array but I am reading everything and seem this is way to define arrays.

Sort & uniq in Linux shell

I have worked on some servers where sort don't support '-u' option. there we have to use

sort xyz | uniq

CSV new-line character seen in unquoted field error

Try to run dos2unix on your windows imported files first

How do I redirect to another webpage?

You need to put this line in your code:

$(location).attr("href","http://stackoverflow.com");

If you don't have jQuery, go with JavaScript:

window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");

Histogram Matplotlib

I know this does not answer your question, but I always end up on this page, when I search for the matplotlib solution to histograms, because the simple histogram_demo was removed from the matplotlib example gallery page.

Here is a solution, which doesn't require numpy to be imported. I only import numpy to generate the data x to be plotted. It relies on the function hist instead of the function bar as in the answer by @unutbu.

import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

import matplotlib.pyplot as plt
plt.hist(x, bins=50)
plt.savefig('hist.png')

enter image description here

Also check out the matplotlib gallery and the matplotlib examples.

Change mysql user password using command line

As of MySQL 5.7.6, use ALTER USER

Example:

ALTER USER 'username' IDENTIFIED BY 'password';

Because:

  • SET PASSWORD ... = PASSWORD('auth_string') syntax is deprecated as of MySQL 5.7.6 and will be removed in a future MySQL release.

  • SET PASSWORD ... = 'auth_string' syntax is not deprecated, but ALTER USER is now the preferred statement for assigning passwords.

Get environment value in controller

You can not access the environment variable like this.

Inside the .env file you write

IMAP_HOSTNAME_TEST=imap.gmail.com  // I am okay with this

Next, inside the config folder there is a file, mail.php. You may use this file to code. As you are working with mail functionality. You might use another file as well.

return [

//..... other declarations
'imap_hostname_test' => env('IMAP_HOSTNAME_TEST'),
// You are hiding the value inside the configuration as well

];

You can call the variable from a controller using 'config(. Whatever file you are using inside config folder. You need to use that file name (without extension) + '.' + 'variable name' + ')'. In the current case you can call the variable as follows.

$hostname = config('mail.imap_hostname_test');

Since you declare the variable inside mail.php and the variable name is imap_hostname_test, you need to call it like this. If you declare this variable inside app.php then you should call

$hostname = config('app.imap_hostname_test');

How to convert dd/mm/yyyy string into JavaScript Date object?

Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object

    function newUYDate(pDate) {
      let dd = pDate.split("/")[0].padStart(2, "0");
      let mm = pDate.split("/")[1].padStart(2, "0");
      let yyyy = pDate.split("/")[2].split(" ")[0];
      let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
      let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
      let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
    
      mm = (parseInt(mm) - 1).toString(); // January is 0
    
      return new Date(yyyy, mm, dd, hh, mi, secs);
    }

How to add an object to an ArrayList in Java

You need to use the new operator when creating the object

Contacts.add(new Data(name, address, contact)); // Creating a new object and adding it to list - single step

or else

Data objt = new Data(name, address, contact); // Creating a new object
Contacts.add(objt); // Adding it to the list

and your constructor shouldn't contain void. Else it becomes a method in your class.

public Data(String n, String a, String c) { // Constructor has the same name as the class and no return type as such

Android video streaming example

I had the same problem but finally I found the way.

Here is the walk through:

1- Install VLC on your computer (SERVER) and go to Media->Streaming (Ctrl+S)

2- Select a file to stream or if you want to stream your webcam or... click on "Capture Device" tab and do the configuration and finally click on "Stream" button.

3- Here you should do the streaming server configuration, just go to "Option" tab and paste the following command:

:sout=#transcode{vcodec=mp4v,vb=400,fps=10,width=176,height=144,acodec=mp4a,ab=32,channels=1,samplerate=22050}:rtp{sdp=rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/}

NOTE: Replace YOURCOMPUTER_SERVER_IP_ADDR with your computer IP address or any server which is running VLC...

NOTE: You can see, the video codec is MP4V which is supported by android.

4- go to eclipse and create a new project for media playbak. create a VideoView object and in the OnCreate() function write some code like this:

mVideoView = (VideoView) findViewById(R.id.surface_view);

mVideoView.setVideoPath("rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/");
mVideoView.setMediaController(new MediaController(this));

5- run the apk on the device (not simulator, i did not check it) and wait for the playback to be started. please consider the buffering process will take about 10 seconds...

Question: Anybody know how to reduce buffering time and play video almost live ?

How to get the Full file path from URI

Working for all api version (tested on Android 10)

val returnCursor: Cursor? = context.contentResolver.query(uri, null, null, null, null)
            val columnIndex = returnCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            returnCursor.moveToFirst();
            val path = returnCursor.getString(columnIndex)

Limit Get-ChildItem recursion depth

As of powershell 5.0, you can now use the -Depth parameter in Get-ChildItem!

You combine it with -Recurse to limit the recursion.

Get-ChildItem -Recurse -Depth 2

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.

e.g.:

Return None value.

>>> def test1():
...    print "In function."
... 
>>> a = test1()
In function.
>>> print a
None
>>> 
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>> 

Use return statement

>>> def test():
...   return "ACV"
... 
>>> print test()
ACV
>>> 
>>> a = test()
>>> print a
ACV
>>> 

Writing String to Stream and reading it back does not work

Try this "one-liner" from Delta's Blog, String To MemoryStream (C#).

MemoryStream stringInMemoryStream =
   new MemoryStream(ASCIIEncoding.Default.GetBytes("Your string here"));

The string will be loaded into the MemoryStream, and you can read from it. See Encoding.GetBytes(...), which has also been implemented for a few other encodings.

Count work days between two dates

None of the functions above work for the same week or deal with holidays. I wrote this:

create FUNCTION [dbo].[ShiftHolidayToWorkday](@date date)
RETURNS date
AS
BEGIN
    IF DATENAME( dw, @Date ) = 'Saturday'
        SET @Date = DATEADD(day, - 1, @Date)

    ELSE IF DATENAME( dw, @Date ) = 'Sunday'
        SET @Date = DATEADD(day, 1, @Date)

    RETURN @date
END
GO

create FUNCTION [dbo].[GetHoliday](@date date)
RETURNS varchar(50)
AS
BEGIN
    declare @s varchar(50)

    SELECT @s = CASE
        WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]  ) + '-01-01') = @date THEN 'New Year'
        WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]+1) + '-01-01') = @date THEN 'New Year'
        WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]  ) + '-07-04') = @date THEN 'Independence Day'
        WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]  ) + '-12-25') = @date THEN 'Christmas Day'
        --WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]) + '-12-31') = @date THEN 'New Years Eve'
        --WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]) + '-11-11') = @date THEN 'Veteran''s Day'

        WHEN [Month] = 1  AND [DayOfMonth] BETWEEN 15 AND 21 AND [DayName] = 'Monday' THEN 'Martin Luther King Day'
        WHEN [Month] = 5  AND [DayOfMonth] >= 25             AND [DayName] = 'Monday' THEN 'Memorial Day'
        WHEN [Month] = 9  AND [DayOfMonth] <= 7              AND [DayName] = 'Monday' THEN 'Labor Day'
        WHEN [Month] = 11 AND [DayOfMonth] BETWEEN 22 AND 28 AND [DayName] = 'Thursday' THEN 'Thanksgiving Day'
        WHEN [Month] = 11 AND [DayOfMonth] BETWEEN 23 AND 29 AND [DayName] = 'Friday' THEN 'Day After Thanksgiving'
        ELSE NULL END
    FROM (
        SELECT
            [Year] = YEAR(@date),
            [Month] = MONTH(@date),
            [DayOfMonth] = DAY(@date),
            [DayName]   = DATENAME(weekday,@date)
    ) c

    RETURN @s
END
GO

create FUNCTION [dbo].GetHolidays(@year int)
RETURNS TABLE 
AS
RETURN (  
    select dt, dbo.GetHoliday(dt) as Holiday
    from (
        select dateadd(day, number, convert(varchar,@year) + '-01-01') dt
        from master..spt_values 
        where type='p' 
        ) d
    where year(dt) = @year and dbo.GetHoliday(dt) is not null
)

create proc UpdateHolidaysTable
as

if not exists(select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'Holidays')
    create table Holidays(dt date primary key clustered, Holiday varchar(50))

declare @year int
set @year = 1990

while @year < year(GetDate()) + 20
begin
    insert into Holidays(dt, Holiday)
    select a.dt, a.Holiday
    from dbo.GetHolidays(@year) a
        left join Holidays b on b.dt = a.dt
    where b.dt is null

    set @year = @year + 1
end

create FUNCTION [dbo].[GetWorkDays](@StartDate DATE = NULL, @EndDate DATE = NULL)
RETURNS INT 
AS
BEGIN
    IF @StartDate IS NULL OR @EndDate IS NULL
        RETURN  0

    IF @StartDate >= @EndDate 
        RETURN  0

    DECLARE @Days int
    SET @Days = 0

    IF year(@StartDate) * 100 + datepart(week, @StartDate) = year(@EndDate) * 100 + datepart(week, @EndDate) 
        --same week
        select @Days = (DATEDIFF(dd, @StartDate, @EndDate))
      - (CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
      - (CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
      - (select count(*) from Holidays where dt between @StartDate and @EndDate)
    ELSE
        --diff weeks
        select @Days = (DATEDIFF(dd, @StartDate, @EndDate) + 1)
      - (DATEDIFF(wk, @StartDate, @EndDate) * 2)
      - (CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
      - (CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
      - (select count(*) from Holidays where dt between @StartDate and @EndDate)
 
    RETURN  @Days
END

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Or simply run this comment to add the server Certificate to your database:

echo $(echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpGilabPort 2>/dev/null  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p') >> /etc/ssl/certs/ca-certificates.crt

Then do git clone again.

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Add

$mail->SMTPOptions = array(
'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
));

before

mail->send()

and replace

require "mailer/class.phpmailer.php";

with

require "mailer/PHPMailerAutoload.php";

Sql select rows containing part of string

SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2&region=0&page=1', LEN(URL))

Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx

Tomcat view catalina.out log file

Sometimes it is located in different places. It depends on the server. You can use find to find it:

 find / -name catalina.out 

If you encounter permission issues, add sudo to the command:

sudo find / -name catalina.out

That's all.

I hope this helps

How to create a DateTime equal to 15 minutes ago?

datetime.datetime.now() - datetime.timedelta(0, 15 * 60)

timedelta is a "change in time". It takes days as the first parameter and seconds in the second parameter. 15 * 60 seconds is 15 minutes.

How to use std::sort to sort an array in C++

In C++0x/11 we get std::begin and std::end which are overloaded for arrays:

#include <algorithm>

int main(){
  int v[2000];
  std::sort(std::begin(v), std::end(v));
}

If you don't have access to C++0x, it isn't hard to write them yourself:

// for container with nested typedefs, non-const version
template<class Cont>
typename Cont::iterator begin(Cont& c){
  return c.begin();
}

template<class Cont>
typename Cont::iterator end(Cont& c){
  return c.end();
}

// const version
template<class Cont>
typename Cont::const_iterator begin(Cont const& c){
  return c.begin();
}

template<class Cont>
typename Cont::const_iterator end(Cont const& c){
  return c.end();
}

// overloads for C style arrays
template<class T, std::size_t N>
T* begin(T (&arr)[N]){
  return &arr[0];
}

template<class T, std::size_t N>
T* end(T (&arr)[N]){
  return arr + N;
}

Make multiple-select to adjust its height to fit options without scroll bar

The way a select box is rendered is determined by the browser itself. So every browser will show you the height of the option list box in another height. You can't influence that. The only way you can change that is to make an own select from the scratch.

How to have stored properties in Swift, the same way I had on Objective-C?

In PURE SWIFT with WEAK reference handling

import Foundation
import UIKit

extension CustomView {
    
    // can make private
    static let storedProperties = WeakDictionary<UIView, Properties>()
    
    struct Properties {
        var url: String = ""
        var status = false
        var desc: String { "url: \(url), status: \(status)" }
    }
    
    var properties: Properties {
        get {
            return CustomView.storedProperties.get(forKey: self) ?? Properties()
        }
        set {
            CustomView.storedProperties.set(forKey: self, object: newValue)
        }
    }
}

var view: CustomView? = CustomView()
print("1 print", view?.properties.desc ?? "nil")
view?.properties.url = "abc"
view?.properties.status = true
print("2 print", view?.properties.desc ?? "nil")
view = nil

WeakDictionary.swift

import Foundation

private class WeakHolder<T: AnyObject>: Hashable {
    weak var object: T?
    let hash: Int

    init(object: T) {
        self.object = object
        hash = ObjectIdentifier(object).hashValue
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(hash)
    }

    static func ==(lhs: WeakHolder, rhs: WeakHolder) -> Bool {
        return lhs.hash == rhs.hash
    }
}

class WeakDictionary<T1: AnyObject, T2> {
    private var dictionary = [WeakHolder<T1>: T2]()

    func set(forKey: T1, object: T2?) {
        dictionary[WeakHolder(object: forKey)] = object
    }

    func get(forKey: T1) -> T2? {
        let obj = dictionary[WeakHolder(object: forKey)]
        return obj
    }

    func forEach(_ handler: ((key: T1, value: T2)) -> Void) {
        dictionary.forEach {
            if let object = $0.key.object, let value = dictionary[$0.key] {
                handler((object, value))
            }
        }
    }
    
    func clean() {
        var removeList = [WeakHolder<T1>]()
        dictionary.forEach {
            if $0.key.object == nil {
                removeList.append($0.key)
            }
        }
        removeList.forEach {
            dictionary[$0] = nil
        }
    }
}

SQL how to make null values come last when sorting ascending

USE NVL function

  select * from MyTable order by NVL(MyDate, to_date('1-1-1','DD-MM-YYYY'))

Here's the alternative of NVL in most famous DBMS

How to remove leading and trailing spaces from a string

You can use:

  • String.TrimStart - Removes all leading occurrences of a set of characters specified in an array from the current String object.
  • String.TrimEnd - Removes all trailing occurrences of a set of characters specified in an array from the current String object.
  • String.Trim - combination of the two functions above

Usage:

string txt = "                   i am a string                                    ";
char[] charsToTrim = { ' ' };    
txt = txt.Trim(charsToTrim)); // txt = "i am a string"

EDIT:

txt = txt.Replace(" ", ""); // txt = "iamastring"   

Convert pem key to ssh-rsa format

ssh-keygen -i -m PKCS8 -f public-key.pem

JavaScript: Passing parameters to a callback function

When you have a callback that will be called by something other than your code with a specific number of params and you want to pass in additional params you can pass a wrapper function as the callback and inside the wrapper pass the additional param(s).

function login(accessedViaPopup) {
    //pass FB.login a call back function wrapper that will accept the
    //response param and then call my "real" callback with the additional param
    FB.login(function(response){
        fb_login_callback(response,accessedViaPopup);
    });
}

//handles respone from fb login call
function fb_login_callback(response, accessedViaPopup) {
    //do stuff
}

JAX-WS - Adding SOAP Headers

In jaxws-rt-2.2.10-ources.jar!\com\sun\xml\ws\transport\http\client\HttpTransportPipe.java:

public Packet process(Packet request) {
        Map<String, List<String>> userHeaders = (Map<String, List<String>>) request.invocationProperties.get(MessageContext.HTTP_REQUEST_HEADERS);
        if (userHeaders != null) {
            reqHeaders.putAll(userHeaders);

So, Map<String, List<String>> from requestContext with key MessageContext.HTTP_REQUEST_HEADERS will be copied to SOAP headers. Sample of Application Authentication with JAX-WS via headers

BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY keys are processed special way in HttpTransportPipe.addBasicAuth(), adding standard basic authorization Authorization header.

See also Message Context in JAX-WS

How to regex in a MySQL query

In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*'). See here:

SQL Function

Description


REGEXP_LIKE

This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.

...

REGEXP_REPLACE

This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.

...

REGEXP_INSTR

This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.

...

REGEXP_SUBSTR

This function returns the actual substring matching the regular expression pattern you specify.

(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$' for a beginning (^) and end ($) match, e.g.: '^regex.*$'.)

Checking for the correct number of arguments

#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.

More friendly error reporting:

#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  exit 1
fi

How to clone an InputStream?

You want to use Apache's CloseShieldInputStream:

This is a wrapper that will prevent the stream from being closed. You'd do something like this.

InputStream is = null;

is = getStream(); //obtain the stream 
CloseShieldInputStream csis = new CloseShieldInputStream(is);

// call the bad function that does things it shouldn't
badFunction(csis);

// happiness follows: do something with the original input stream
is.read();

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

add async defer at the begining of map api key call.

How do I increase memory on Tomcat 7 when running as a Windows Service?

The answer to my own question is, I think, to use tomcat7.exe:

cd $CATALINA_HOME
.\bin\service.bat install tomcat
.\bin\tomcat7.exe //US//tomcat7 --JvmMs=512 --JvmMx=1024 --JvmSs=1024

Also, you can launch the UI tool mentioned by BalusC without the system tray or using the installer with tomcat7w.exe

.\bin\tomcat7w.exe //ES//tomcat

An additional note to this:

Setting the --JvmXX parameters (through the UI tool or the command line) may not be enough. You may also need to specify the JVM memory values explicitly. From the command line it may look like this:

bin\tomcat7w.exe //US//tomcat7 --JavaOptions=-Xmx=1024;-Xms=512;..

Be careful not to override the other JavaOption values. You can try updating bin\service.bat or use the UI tool and append the java options (separate each value with a new line).

Does HTML5 <video> playback support the .avi format?

There are three formats with a reasonable level of support: H.264 (MPEG-4 AVC), OGG Theora (VP3) and WebM (VP8). See the wiki linked by Sam for which browsers support which; you will typically need at least one of those plus Flash fallback.

Whilst most browsers won't touch AVI, there are some browser builds that expose all the multimedia capabilities of the underlying OS to <video>. These browser will indeed be able to play AVI, as long as they have matching codecs installed (AVI can contain about a million different video and audio formats). In particular Safari on OS X with QuickTime, or Konqi with GStreamer.

Personally I think this is an absolutely disastrous idea, as it exposes a very large codec codebase to the net, a codebase that was mostly not written to be resistant to network attacks. One of the worst drawbacks of media player plugins was the huge number of security holes they made available to every web page exploit. Let's not make this mistake again.

.ssh/config file for windows (git)

There is an option IdentityFile which you can use in your ~/.ssh/config file and specify key file for each host.

Host host_with_key1.net
  IdentityFile ~/.ssh/id_rsa

Host host_with_key2.net
  IdentityFile ~/.ssh/id_rsa_test

More info: http://linux.die.net/man/5/ssh_config

Also look at http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/

What is the correct format to use for Date/Time in an XML file

What does the DTD have to say?

If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.

If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.

OnClick Send To Ajax

Tried and working. you are using,

<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

I am using javascript , (don't know about php), use id ="status" in textarea like

<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag

<srcipt>
function UpdateStatus(){

//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({

        type:"GET",//or POST
        url:'http://localhost:7080/ajaxforjson/Testajax',
                           //  (or whatever your url is)
        data:{data1:var1},
        //can send multipledata like {data1:var1,data2:var2,data3:var3
        //can use dataType:'text/html' or 'json' if response type expected 
        success:function(responsedata){
               // process on data
               alert("got response as "+"'"+responsedata+"'");

        }
     })

}
</script>

and jsp is like

the servlet will look like:   //webservlet("/zcvdzv") is just for url annotation
@WebServlet("/Testajax")

public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
    super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String data1=request.getParameter("data1");
    //do processing on datas pass in other java class to add to DB
    // i am adding or concatenate
    String data="i Got : "+"'"+data1+"' ";
    System.out.println(" data1 : "+data1+"\n data "+data);
    response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

I got this resolution at openshift.com.

Resolution:

This error occurs only on Windows machine with Ruby 2.0.0 version. Until we officially support Ruby 2.0 please downgrade to Ruby 1.9.

On Windows, you can install Ruby 1.9.3 alongside 2.0. Change your %PATH% to c:\ruby193\ or whatever directory you installed to prior to installing the gem.

Need to remove href values when printing in Chrome

It doesn't. Somewhere in your print stylesheet, you must have this section of code:

a[href]::after {
    content: " (" attr(href) ")"
}

The only other possibility is you have an extension doing it for you.

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

Add following at this location C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64 FileName: sgen.exe.config(If you dont find this file, create and add one)

_x000D_
_x000D_
 <?xml version ="1.0"?>_x000D_
_x000D_
<configuration>_x000D_
 <runtime>        _x000D_
        <generatePublisherEvidence enabled="false"/>    _x000D_
    </runtime>_x000D_
_x000D_
    <startup useLegacyV2RuntimeActivationPolicy="true">_x000D_
_x000D_
                <supportedRuntime version="v4.0" />_x000D_
_x000D_
    </startup>    _x000D_
_x000D_
</configuration>
_x000D_
_x000D_
_x000D_

Doing this resolved the issue

Text on image mouseover?

For people coming from the future, you can now do this purely in CSS.

_x000D_
_x000D_
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; 
  margin: 5rem;
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  width: 120px;
  bottom: 100%;
  left: 50%;
  margin-left: -60px;

  position: absolute;
  z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
}
_x000D_
<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>
_x000D_
_x000D_
_x000D_

How can I use Html.Action?

Another case is http redirection. If your page redirects http requests to https, then may be your partial view tries to redirect by itself.

It causes same problem again. For this problem, you can reorganize your .net error pages or iis error pages configuration.

Just make sure you are redirecting requests to right error or not found page and make sure this error page contains non problematic partial. If your page supports only https, do not forward requests to error page without using https, if error page contains partial, this partials tries to redirect seperately from requested url, it causes problem.

Jackson how to transform JsonNode to ArrayNode without casting?

In Java 8 you can do it like this:

import java.util.*;
import java.util.stream.*;

List<JsonNode> datasets = StreamSupport
    .stream(datasets.get("datasets").spliterator(), false)
    .collect(Collectors.toList())

php delete a single file in directory

Simply You Can Use It

    $sql="select * from tbl_publication where id='5'";
    $result=mysql_query($sql);
    $res=mysql_fetch_array($result);
    //Getting File Name From DB
    $pdfname = $res1['pdfname'];
    //pdf is directory where file exist
    unlink("pdf/".$pdfname);

Why use $_SERVER['PHP_SELF'] instead of ""

In addition to above answers, another way of doing it is $_SERVER['PHP_SELF'] or simply using an empty string is to use __DIR__.
OR
If you're on a lower PHP version (<5.3), a more common alternative is to use dirname(__FILE__)
Both returns the folder name of the file in context.

EDIT
As Boann pointed out that this returns the on-disk location of the file. WHich you would not ideally expose as a url. In that case dirname($_SERVER['PHP_SELF']) can return the folder name of the file in context.

PHP validation/regex for URL

For anyone developing with WordPress, just use

esc_url_raw($url) === $url

to validate a URL (here's WordPress' documentation on esc_url_raw). It handles URLs much better than filter_var($url, FILTER_VALIDATE_URL) because it is unicode and XSS-safe. (Here is a good article mentioning all the problems with filter_var).

Difference between two dates in years, months, days in JavaScript

Using Plane Javascript:

function dateDiffInDays(start, end) {
    var MS_PER_DAY = 1000 * 60 * 60 * 24;
    var a = new Date(start);
    var b = new Date(end);

    const diffTime = Math.abs(a - b);
    const diffDays = Math.ceil(diffTime / MS_PER_DAY); 
    console.log("Days: ", diffDays);

    // Discard the time and time-zone information.
    const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
    const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
    return Math.floor((utc2 - utc1) / MS_PER_DAY);
}

function dateDiffInDays_Months_Years(start, end) {
    var m1 = new Date(start);
    var m2 = new Date(end);
    var yDiff = m2.getFullYear() - m1.getFullYear();
    var mDiff = m2.getMonth() - m1.getMonth();
    var dDiff = m2.getDate() - m1.getDate();

    if (dDiff < 0) {
        var daysInLastFullMonth = getDaysInLastFullMonth(start);
        if (daysInLastFullMonth < m1.getDate()) {
            dDiff = daysInLastFullMonth + dDiff + (m1.getDate() - 

daysInLastFullMonth);
        } else {
            dDiff = daysInLastFullMonth + dDiff;
        }
        mDiff--;
    }
    if (mDiff < 0) {
        mDiff = 12 + mDiff;
        yDiff--;
    }
    console.log('Y:', yDiff, ', M:', mDiff, ', D:', dDiff);
}
function getDaysInLastFullMonth(day) {
    var d = new Date(day);
    console.log(d.getDay() );

    var lastDayOfMonth = new Date(d.getFullYear(), d.getMonth() + 1, 0);
    console.log('last day of month:', lastDayOfMonth.getDate() ); //

    return lastDayOfMonth.getDate();
}

Using moment.js:

function dateDiffUsingMoment(start, end) {
    var a = moment(start,'M/D/YYYY');
    var b = moment(end,'M/D/YYYY');
    var diffDaysMoment = b.diff(a, 'days');
    console.log('Moments.js : ', diffDaysMoment);

    preciseDiffMoments(a,b);
}
function preciseDiffMoments( a, b) {
    var m1= a, m2=b;
    m1.add(m2.utcOffset() - m1.utcOffset(), 'minutes'); // shift timezone of m1 to m2
    var yDiff = m2.year() - m1.year();
    var mDiff = m2.month() - m1.month();
    var dDiff = m2.date() - m1.date();
    if (dDiff < 0) {
        var daysInLastFullMonth = moment(m2.year() + '-' + (m2.month() + 1), 

"YYYY-MM").subtract(1, 'M').daysInMonth();
        if (daysInLastFullMonth < m1.date()) { // 31/01 -> 2/03
            dDiff = daysInLastFullMonth + dDiff + (m1.date() - 

daysInLastFullMonth);
        } else {
            dDiff = daysInLastFullMonth + dDiff;
        }
        mDiff--;
    }
    if (mDiff < 0) {
        mDiff = 12 + mDiff;
        yDiff--;
    }
    console.log('getMomentum() Y:', yDiff, ', M:', mDiff, ', D:', dDiff);
}

Tested the above functions using following samples:

var sample1 = all('2/13/2018', '3/15/2018'); // {'M/D/YYYY'} 30, Y: 0 , M: 1 , D: 2
console.log(sample1);

var sample2 = all('10/09/2019', '7/7/2020'); // 272, Y: 0 , M: 8 , D: 29
console.log(sample2);

function all(start, end) {
    dateDiffInDays(start, end);
    dateDiffInDays_Months_Years(start, end);

    try {
        dateDiffUsingMoment(start, end);
    } catch (e) {
        console.log(e); 
    }
}

SQL, How to convert VARCHAR to bigint?

I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.

select CONVERT(bigint,'60') as seconds 

and it returns

60

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

This error occured because phpmyadmin directory has all permissions (777). you can resolved this problem by executing the following command.

sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php

Calling variable defined inside one function from another function

def anotherFunction(word):
    for letter in word:              
        print("_", end=" ")

def oneFunction(lists):
    category = random.choice(list(lists.keys()))
    word = random.choice(lists[category])
    return anotherFunction(word)

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

You can use IN operator as below

select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)

Warning: X may be used uninitialized in this function

You get the warning because you did not assign a value to one, which is a pointer. This is undefined behavior.

You should declare it like this:

Vector* one = malloc(sizeof(Vector));

or like this:

Vector one;

in which case you need to replace -> operator with . like this:

one.a = 12;
one.b = 13;
one.c = -11;

Finally, in C99 and later you can use designated initializers:

Vector one = {
   .a = 12
,  .b = 13
,  .c = -11
};

PHP move_uploaded_file() error?

I ran into a very obscure and annoying cause of error 6. After goofing around with some NFS mounted volumes, uploads started failing. Problem resolved by restarting services

systemctl restart php-fpm.service
systemctl restart httpd.service

How to add List<> to a List<> in asp.net

  1. Use Concat or Union extension methods. You have to make sure that you have this direction using System.Linq; in order to use LINQ extensions methods.

  2. Use the AddRange method.

How to prevent a double-click using jQuery?

I have the similar issue. You can use setTimeout() to avoid the double-click.

//some codes here above after the click then disable it

// also check here if there's an attribute disabled

// if there's an attribute disabled in the btn tag then // return. Convert that into js.

$('#btn1').prop("disabled", true);

setTimeout(function(){
    $('#btn1').prop("disabled", false);
}, 300);

Proper way to concatenate variable strings

As simple as joining lists in python itself.

ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost

localhost | SUCCESS => {
  "msg": "list-joined-together" }

Works the same way using variables:

ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost

Reloading .env variables without restarting server (Laravel 5, shared hosting)

In config/database.php I changed the default DB connection from mysql to sqlite. I deleted the .env file (actually renamed it) and created the sqlite file with touch storage/database.sqlite. The migration worked with sqlite.

Then I switched back the config/database.php default DB connection to mysql and recovered the .env file. The migration worked with mysql.

It doesn't make sense I guess. Maybe was something serverside.

Spring configure @ResponseBody JSON format

You can configure the ObjectMapper as a bean in your Spring xml file. What holds a reference to the ObjectMapper is the MappingJacksonJsonView class. You then need to attach the view to a ViewResolver.

Something like this should work:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
      <property name="mediaTypes">
      <map>
        <entry key="json" value="application/json" />
        <entry key="html" value="text/html" />
      </map>
    </property>
    <property name="viewResolvers">
      <list>
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="prefix" value="/WEB-INF/jsp/" />
          <property name="suffix" value=".jsp" />
        </bean>
      </list>
    </property>
    <property name="defaultViews">
      <list>
        <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
          <property name="prefixJson" value="false" />
          <property name="objectMapper" value="customObjectMapper" />
        </bean>
      </list>
    </property>
  </bean>

Where customObjectMapper is defined elsewhere in the xml file. Note that you can directly set Spring property values with the Enums Jackson defines; see this question.

Also, ContentNegotiatingViewResolver probably isn't required, it's just the code I am using in an existing project.

Move existing, uncommitted work to a new branch in Git

3 Steps to Commit your changes

Suppose you have created a new branch on GitHub with the name feature-branch.

enter image description here

FETCH

    git pull --all         Pull all remote branches
    git branch -a          List all branches now

Checkout and switch to the feature-branch directory. You can simply copy the branch name from the output of branch -a command above

git checkout -b feature-branch

VALIDATE

Next use the git branch command to see the current branch. It will show feature-branch with * In front of it

git branch         

COMMIT

git add .   add all files
git commit -m "Rafactore code or use your message"

Take update and the push changes on the origin server

 git pull origin feature-branch
 git push origin feature-branch

Run a task every x-minutes with Windows Task Scheduler

After you select the minimum repeat option (5 minutes or 10 minutes) you can highlight the number and write whatever number you want