Programs & Examples On #Application error

Unfortunately MyApp has stopped. How can I solve this?

If you don't have any kind of interesting log in your terminal (or they are not directly related to your app), maybe your problem is due to a native library. In that case, you should check for the "tombstone" files within your terminal.

The default location for the tombstone files depends on every device, but if that's the case, you will have a log telling: Tombstone written to: /data/tombstones/tombstone_06

For more information, check on https://source.android.com/devices/tech/debug.

Failed to resolve version for org.apache.maven.archetypes

Try , It worked for = I just removed "archetypes" folder from below location

C:\Users\Lenovo.m2\repository\org\apache\maven

But you may change following for experiment - download latest binary zip of Maven, add to you C:\ drive and change following....

enter image description here

enter image description here

enter image description here

Change Proxy

 <proxy>
          <id>optional</id>
          <active>true</active>
          <protocol>http</protocol>
          <username></username>
          <password></password>
          <host>10.23.73.253</host>
          <port>8080</port>
          <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
        </proxy>

jQuery count child elements

pure js

selected.children[0].children.length;

_x000D_
_x000D_
let num = selected.children[0].children.length;_x000D_
_x000D_
console.log(num);
_x000D_
<div id="selected">_x000D_
  <ul>_x000D_
    <li>29</li>_x000D_
    <li>16</li>_x000D_
    <li>5</li>_x000D_
    <li>8</li>_x000D_
    <li>10</li>_x000D_
    <li>7</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

This problem will occurred due to some unnecessary changes made in my.cnf file. Try to diff /etc/mysql/my.cnf with one of working mysql servers my.cnf file.

I just replaced /etc/mysql/my.cnf file with new my.cnf file and this works for me.

How to take a screenshot programmatically on iOS

Below method works for OPENGL objects also

//iOS7 or above
- (UIImage *) screenshot {

    CGSize size = CGSizeMake(your_width, your_height);

    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);

    CGRect rec = CGRectMake(0, 0, your_width, your_height);
    [_viewController.view drawViewHierarchyInRect:rec afterScreenUpdates:YES];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

Getting full JS autocompletion under Sublime Text

I developed a new plugin called JavaScript Enhancements, that you can find on Package Control. It uses Flow (javascript static type checker from Facebook) under the hood.

Furthermore, it offers smart javascript autocomplete (compared to my other plugin JavaScript Completions), real-time errors, code refactoring and also a lot of features about creating, developing and managing javascript projects.

See the Wiki to know all the features that it offers!

An introduction to this plugin could be found in this css-tricks.com article: Turn Sublime Text 3 into a JavaScript IDE

Just some quick screenshots:

How can I convert a std::string to int?

What about Boost.Lexical_cast?

Here is their example:

The following example treats command line arguments as a sequence of numeric data:

int main(int argc, char * argv[])
{
    using boost::lexical_cast;
    using boost::bad_lexical_cast;

    std::vector<short> args;

    while(*++argv)
    {
        try
        {
            args.push_back(lexical_cast<short>(*argv));
        }
        catch(bad_lexical_cast &)
        {
            args.push_back(0);
        }
    }
    ...
}

Run an OLS regression with Pandas Data Frame

I don't know if this is new in sklearn or pandas, but I'm able to pass the data frame directly to sklearn without converting the data frame to a numpy array or any other data types.

from sklearn import linear_model

reg = linear_model.LinearRegression()
reg.fit(df[['B', 'C']], df['A'])

>>> reg.coef_
array([  4.01182386e-01,   3.51587361e-04])

What does the 'b' character do in front of a string literal?

In addition to what others have said, note that a single character in unicode can consist of multiple bytes.

The way unicode works is that it took the old ASCII format (7-bit code that looks like 0xxx xxxx) and added multi-bytes sequences where all bytes start with 1 (1xxx xxxx) to represent characters beyond ASCII so that Unicode would be backwards-compatible with ASCII.

>>> len('Öl')  # German word for 'oil' with 2 characters
2
>>> 'Öl'.encode('UTF-8')  # convert str to bytes 
b'\xc3\x96l'
>>> len('Öl'.encode('UTF-8'))  # 3 bytes encode 2 characters !
3

Regular expression \p{L} and \p{N}

These are Unicode property shortcuts (\p{L} for Unicode letters, \p{N} for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)

At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:

[\p{L}\p{N}_.-]*

Run parallel multiple commands at once in the same terminal

To run multiple commands just add && between two commands like this: command1 && command2

And if you want to run them in two different terminals then you do it like this:

gnome-terminal -e "command1" && gnome-terminal -e "command2"

This will open 2 terminals with command1 and command2 executing in them.

Hope this helps you.

Cross-browser window resize event - JavaScript / jQuery

hope it will help in jQuery

define a function first, if there is an existing function skip to next step.

 function someFun() {
 //use your code
 }

browser resize use like these.

 $(window).on('resize', function () {
    someFun();  //call your function.
 });

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

It's hard to tell for sure because you haven't included many details, but I think what is going on is that there are <% ... %> code blocks inside your Page.Header (which is referring to <head runat="server"> - possibly in a master page). Therefore, when you try to add an item to the Controls collection of that control, you get the error message in the title of this question.

If I'm right, then the workaround is to wrap a <asp:placeholder runat="server"> tag around the <% ... %> code block. This makes the code block a child of the Placeholder control, instead of being a direct child of the Page.Header control, but it doesn't change the rendered output at all. Now that the code block is not a direct child of Page.Header you can add things to the header's controls collection without error.

Again, there is a code block somewhere or you wouldn't be seeing this error. If it's not in your aspx page, then the first place I would look is the file referenced by the MasterPageFile attribute at the top of your aspx.

How do you set the max number of characters for an EditText in Android?

Dynamically:

editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_NUM) });

Via xml:

<EditText
    android:maxLength="@integer/max_edittext_length"

Convert image from PIL to openCV format

The code commented works as well, just choose which do you prefer

import numpy as np
from PIL import Image


def convert_from_cv2_to_image(img: np.ndarray) -> Image:
    # return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    return Image.fromarray(img)


def convert_from_image_to_cv2(img: Image) -> np.ndarray:
    # return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
    return np.asarray(img)

How to get Django and ReactJS to work together?

I know this is a couple of years late, but I'm putting it out there for the next person on this journey.

GraphQL has been helpful and way easier compared to DjangoRESTFramework. It is also more flexible in terms of the responses you get. You get what you ask for and don't have to filter through the response to get what you want.

You can use Graphene Django on the server side and React+Apollo/Relay... You can look into it as that is not your question.

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

You need to provide a candidate for autowire. That means that an instance of PasswordHint must be known to spring in a way that it can guess that it must reference it.

Please provide the class head of PasswordHint and/or the spring bean definition of that class for further assistance.

Try changing the name of

PasswordHintAction action;

to

PasswordHintAction passwordHintAction;

so that it matches the bean definition.

Number format in excel: Showing % value without multiplying with 100

In Excel workbook - Select the Cell-goto Format Cells - Number - Custom - in the Type box type as shows (0.00%)

How can I create a copy of an object in Python?

Shallow copy with copy.copy()

#!/usr/bin/env python3

import copy

class C():
    def __init__(self):
        self.x = [1]
        self.y = [2]

# It copies.
c = C()
d = copy.copy(c)
d.x = [3]
assert c.x == [1]
assert d.x == [3]

# It's shallow.
c = C()
d = copy.copy(c)
d.x[0] = 3
assert c.x == [3]
assert d.x == [3]

Deep copy with copy.deepcopy()

#!/usr/bin/env python3
import copy
class C():
    def __init__(self):
        self.x = [1]
        self.y = [2]
c = C()
d = copy.deepcopy(c)
d.x[0] = 3
assert c.x == [1]
assert d.x == [3]

Documentation: https://docs.python.org/3/library/copy.html

Tested on Python 3.6.5.

The tilde operator in Python

It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.

In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1 for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x is equivalent to (-x) - 1.

The reified form of the ~ operator is provided as operator.invert. To support this operator in your own class, give it an __invert__(self) method.

>>> import operator
>>> class Foo:
...   def __invert__(self):
...     print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert

Any class in which it is meaningful to have a "complement" or "inverse" of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__ method to your class. (Note that byte-strings [ex: '\xff'] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)

How to detect pressing Enter on keyboard using jQuery?

$(function(){
  $('.modal-content').keypress(function(e){
    debugger
     var id = this.children[2].children[0].id;
       if(e.which == 13) {
         e.preventDefault();
         $("#"+id).click();
       }
   })
});

How to add image in a TextView text?

This answer is based on this excellent answer by 18446744073709551615. Their solution, though helpful, does not size the image icon with the surrounding text. It also doesn't set the icon colour to that of the surrounding text.

The solution below takes a white, square icon and makes it fit the size and colour of the surrounding text.

public class TextViewWithImages extends TextView {

    private static final String DRAWABLE = "drawable";
    /**
     * Regex pattern that looks for embedded images of the format: [img src=imageName/]
     */
    public static final String PATTERN = "\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E";

    public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public TextViewWithImages(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TextViewWithImages(Context context) {
        super(context);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        final Spannable spannable = getTextWithImages(getContext(), text, getLineHeight(), getCurrentTextColor());
        super.setText(spannable, BufferType.SPANNABLE);
    }

    private static Spannable getTextWithImages(Context context, CharSequence text, int lineHeight, int colour) {
        final Spannable spannable = Spannable.Factory.getInstance().newSpannable(text);
        addImages(context, spannable, lineHeight, colour);
        return spannable;
    }

    private static boolean addImages(Context context, Spannable spannable, int lineHeight, int colour) {
        final Pattern refImg = Pattern.compile(PATTERN);
        boolean hasChanges = false;

        final Matcher matcher = refImg.matcher(spannable);
        while (matcher.find()) {
            boolean set = true;
            for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
                if (spannable.getSpanStart(span) >= matcher.start()
                        && spannable.getSpanEnd(span) <= matcher.end()) {
                    spannable.removeSpan(span);
                } else {
                    set = false;
                    break;
                }
            }
            final String resName = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
            final int id = context.getResources().getIdentifier(resName, DRAWABLE, context.getPackageName());
            if (set) {
                hasChanges = true;
                spannable.setSpan(makeImageSpan(context, id, lineHeight, colour),
                        matcher.start(),
                        matcher.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                );
            }
        }
        return hasChanges;
    }

    /**
     * Create an ImageSpan for the given icon drawable. This also sets the image size and colour.
     * Works best with a white, square icon because of the colouring and resizing.
     *
     * @param context       The Android Context.
     * @param drawableResId A drawable resource Id.
     * @param size          The desired size (i.e. width and height) of the image icon in pixels.
     *                      Use the lineHeight of the TextView to make the image inline with the
     *                      surrounding text.
     * @param colour        The colour (careful: NOT a resource Id) to apply to the image.
     * @return An ImageSpan, aligned with the bottom of the text.
     */
    private static ImageSpan makeImageSpan(Context context, int drawableResId, int size, int colour) {
        final Drawable drawable = context.getResources().getDrawable(drawableResId);
        drawable.mutate();
        drawable.setColorFilter(colour, PorterDuff.Mode.MULTIPLY);
        drawable.setBounds(0, 0, size, size);
        return new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
    }

}

How to use:

Simply embed references to the desired icons in the text. It doesn't matter whether the text is set programatically through textView.setText(R.string.string_resource); or if it's set in xml.

To embed a drawable icon named example.png, include the following string in the text: [img src=example/].

For example, a string resource might look like this:

<string name="string_resource">This [img src=example/] is an icon.</string>

Evenly space multiple views within a container view

Check out the open source library PureLayout. It offers a few API methods for distributing views, including variants where the spacing between each view is fixed (view size varies as needed), and where the size of each view is fixed (spacing between views varies as needed). Note that all of these are accomplished without the use of any "spacer views".

From NSArray+PureLayout.h:

// NSArray+PureLayout.h

// ...

/** Distributes the views in this array equally along the selected axis in their superview. Views will be the same size (variable) in the dimension along the axis and will have spacing (fixed) between them. */
- (NSArray *)autoDistributeViewsAlongAxis:(ALAxis)axis
                                alignedTo:(ALAttribute)alignment
                         withFixedSpacing:(CGFloat)spacing;

/** Distributes the views in this array equally along the selected axis in their superview. Views will be the same size (fixed) in the dimension along the axis and will have spacing (variable) between them. */
- (NSArray *)autoDistributeViewsAlongAxis:(ALAxis)axis
                                alignedTo:(ALAttribute)alignment
                            withFixedSize:(CGFloat)size;

// ...

Since it's all open source, if you're interested to see how this is achieved without spacer views just take a look at the implementation. (It depends on leveraging both the constant and multiplier for the constraints.)

Can I configure a subdomain to point to a specific port on my server

If you want to host multiple websites in a single server in different ports then, method mentioned by MRVDOG won't work. Because browser won't resolve SRV records and will always hit :80 port. For example if your requirement is:

site1.domain.com maps to domain.com:8080
site2.domain.com maps to domain.com:8081

Because often you want to fully utilize the server space you have bought. Then you can try the following:

Step 1: Install proxy server. I will use Nginx here.

apt-get install nginx

Step 2: Edit /etc/nginx/nginx.conf file to add the port mappings. To do so, add the following lines:

server {
    listen 80;
    server_name site1.domain.com;

    location / {
        proxy_pass http://localhost:8080;
    }   
}

server {
    listen 80;
    server_name site2.domain.com;

    location / {
        proxy_pass http://localhost:8081;
    }   
}

This does the magic. So the file will end up looking like following:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##
server {
    listen 80;
    server_name site1.domain.com;

    location / {
        proxy_pass http://localhost:8080;
    }   
}

server {
    listen 80;
    server_name site2.domain.com;

    location / {
        proxy_pass http://localhost:8081;
    }   
}

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}


#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
# 
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

Step 3: Start nginx:

/etc/init.d/nginx start.

Whenever you make any changes to configuration, you need to restart nginx:

/etc/init.d/nginx restart

Finally: Don't forget to add A records in your DNS configuration. All subdomains should point to domain. Like this: enter image description here

Put your static ip instead of 111.11.111.111

Further details:

convert UIImage to NSData

Use if-let block with Data to prevent app crash & safe execution of code, as function UIImagePNGRepresentation returns an optional value.

if let img = UIImage(named: "TestImage.png") {
    if let data:Data = UIImagePNGRepresentation(img) {
       // Handle operations with data here...         
    }
}

Note: Data is Swift 3 class. Use Data instead of NSData with Swift 3

Generic image operations (like png & jpg both):

if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
        if let data:Data = UIImagePNGRepresentation(img) {
               handleOperationWithData(data: data)     
        } else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
               handleOperationWithData(data: data)     
        }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

By using extension:

extension UIImage {

    var pngRepresentationData: Data? {
        return UIImagePNGRepresentation(img)
    }

    var jpegRepresentationData: Data? {
        return UIImageJPEGRepresentation(self, 1.0)
    }
}

*******
if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
      if let data = img.pngRepresentationData {
              handleOperationWithData(data: data)     
      } else if let data = img.jpegRepresentationData {
              handleOperationWithData(data: data)     
     }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

Dialog with transparent background in Android

This is what I did to achieve translucency with AlertDialog.

Created a custom style:

<style name="TranslucentDialog" parent="@android:style/Theme.DeviceDefault.Dialog.Alert">
    <item name="android:colorBackground">#32FFFFFF</item>
</style>

And then create the dialog with:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.TranslucentDialog);
AlertDialog dialog = builder.create();

Left align and right align within div in Bootstrap

In Bootstrap 4 the correct answer is to use the text-xs-right class.

This works because xs denotes the smallest viewport size in BS. If you wanted to, you could apply the alignment only when the viewport is medium or larger by using text-md-right.

In the latest alpha, text-xs-right has been simplified to text-right.

<div class="row">
    <div class="col-md-6">Total cost</div>
    <div class="col-md-6 text-right">$42</div>
</div>

How do I "commit" changes in a git submodule?

Note that if you have committed a bunch of changes in various submodules, you can (or will be soon able to) push everything in one go (ie one push from the parent repo), with:

git push --recurse-submodules=on-demand

git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1) mentions:

"git push --recurse-submodules" learned to optionally look into the histories of submodules bound to the superproject and push them out.

Probably done after this patch and the --on-demand option:

--recurse-submodules=<check|on-demand|no>::

Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.

  • If check is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
    Otherwise the push will be aborted and exit with non-zero status.
  • If on-demand is used, all submodules that changed in the revisions to be pushed will be pushed.
    If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.

This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.

DateTime to javascript date

I know this is a little late, but here's the solution I had to come up with for handling dates when you want to be timezone independent. Essentially it involves converting everything to UTC.

From Javascript to Server:

Send out dates as epoch values with the timezone offset removed.

var d = new Date(2015,0,1) // Jan 1, 2015
// Ajax Request to server ...
$.ajax({
  url: '/target',
  params: { date: d.getTime() - (d.getTimezoneOffset() * 60 * 1000) }
});

The server then recieves 1420070400000 as the date epoch.

On the Server side, convert that epoch value to a datetime object:

DateTime d = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(epoch);

At this point the date is just the date/time provided by the user as they provided it. Effectively it is UTC.

Going the other way:

When the server pulls data from the database, presumably in UTC, get the difference as an epoch (making sure that both date objects are either local or UTC):

long ms = (long)utcDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;

or

long ms = (long)localDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)).TotalMilliseconds;

When javascript receives this value, create a new date object. However, this date object is going to be assumed local time, so you need to offset it by the current timezone:

var epochValue = 1420070400000 // value pulled from server.
var utcDateVal = new Date(epochValue);
var actualDate = new Date(utcDateVal.getTime() + (utcDateVal.getTimezoneOffset() * 60 * 1000))

console.log(utcDateVal); // Wed Dec 31 2014 19:00:00 GMT-0500 (Eastern Standard Time)
console.log(actualDate); // Thu Jan 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)

As far as I know, this should work for any time zone where you need to display dates that are timezone independent.

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

Delaying AngularJS route change until model loaded to prevent flicker

I have had a complex multi-level sliding panel interface, with disabled screen layer. Creating directive on disable screen layer that would create click event to execute the state like

$state.go('account.stream.social.view');

were producing a flicking effect. history.back() instead of it worked ok, however its not always back in history in my case. SO what I find out is that if I simply create attribute href on my disable screen instead of state.go , worked like a charm.

<a class="disable-screen" back></a>

Directive 'back'

app.directive('back', [ '$rootScope', function($rootScope) {

    return {
        restrict : 'A',
        link : function(scope, element, attrs) {
            element.attr('href', $rootScope.previousState.replace(/\./gi, '/'));
        }
    };

} ]);

app.js I just save previous state

app.run(function($rootScope, $state) {      

    $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {         

        $rootScope.previousState = fromState.name;
        $rootScope.currentState = toState.name;


    });
});

How do I kill all the processes in Mysql "show processlist"?

KILL ALL SELECT QUERIES

select concat('KILL ',id,';') 
from information_schema.processlist 
where user='root' 
  and INFO like 'SELECT%' into outfile '/tmp/a.txt'; 
source /tmp/a.txt;

Find records from one table which don't exist in another

The code below would be a bit more efficient than the answers presented above when dealing with larger datasets.

SELECT * FROM Call WHERE 
NOT EXISTS (SELECT 'x' FROM Phone_book where 
Phone_book.phone_number = Call.phone_number)

How can I count the numbers of rows that a MySQL query returned?

> SELECT COUNT(*) AS total FROM foo WHERE bar= 'value';

Git copy file preserving history

In my case, I made the change on my hard drive (cut/pasted about 200 folders/files from one path in my working copy to another path in my working copy), and used SourceTree (2.0.20.1) to stage both the detected changes (one add, one remove), and as long as I staged both the add and remove together, it automatically combined into a single change with a pink R icon (rename I assume).

I did notice that because I had such a large number of changes at once, SourceTree was a little slow detecting all the changes, so some of my staged files look like just adds (green plus) or just deletes (red minus), but I kept refreshing the file status and kept staging new changes as they eventually popped up, and after a few minutes, the whole list was perfect and ready for commit.

I verified that the history is present, as long as when I look for history, I check the "Follow renamed files" option.

How to log SQL statements in Spring Boot?

Putting spring.jpa.properties.hibernate.show_sql=true in application.properties didn't help always.

You can try to add properties.put("hibernate.show_sql", "true"); to the properties of the database configuration.

public class DbConfig {

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource
    ) {
        Map<String, Object> properties = new HashMap();
        properties.put("hibernate.hbm2ddl.auto", "validate");
        properties.put("hibernate.show_sql", "true");

        return builder
                .dataSource(dataSource)
                .packages("com.test.dbsource.domain")
                .persistenceUnit("dbsource").properties(properties)
                .build();
    }

How to check which version of Keras is installed?

You can write:

python
import keras
keras.__version__

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

If you are using Java, you could just replace the x00 characters before the insert like following:

myValue.replaceAll("\u0000", "")

The solution was provided and explained by Csaba in following post:

https://www.postgresql.org/message-id/1171970019.3101.328.camel%40coppola.muc.ecircle.de

Respectively:

in Java you can actually have a "0x0" character in your string, and that's valid unicode. So that's translated to the character 0x0 in UTF8, which in turn is not accepted because the server uses null terminated strings... so the only way is to make sure your strings don't contain the character '\u0000'.

Disable browser cache for entire ASP.NET website

Create a class that inherits from IActionFilter.

public class NoCacheAttribute : ActionFilterAttribute
{  
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

Then put attributes where needed...

[NoCache]
[HandleError]
public class AccountController : Controller
{
    [NoCache]
    [Authorize]
    public ActionResult ChangePassword()
    {
        return View();
    }
}

Can't connect to local MySQL server through socket homebrew

For me, I had installed mariadb long time ago, then installed [email protected].

When I executed mysql -uroot, I get the error: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Reading the answers:

  • I uninstalled mariadb
  • Deleted the folder /usr/local/var/mysql
  • Ran the command mysqld --initialize

Then I was able to mysql -uroot -p

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

Maybe the dlls are being loaded from GAC.

You can uninstall the dll from gac, admin permission are required.

gacutil -u YourDll

Gridview get Checkbox.Checked value

    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox chkbox = (CheckBox)row.FindControl("CheckBox1");
        if (chkbox.Checked == true)
        {
            // Your Code
        }
    }

Content is not allowed in Prolog SAXParserException

to simply remove it, paste your xml file into notepad, you'll see the extra character before the first tag. Remove it & paste back into your file - bof

Xampp-mysql - "Table doesn't exist in engine" #1932

  1. stop mysql
  2. copy xampp\mysql\data\ib* from old server to new server
  3. start mysql

Editing an item in a list<T>

class1 item = lst[index];
item.foo = bar;

How to remove leading and trailing whitespace in a MySQL field?

Just to be clear, TRIM by default only remove spaces (not all whitespaces). Here is the doc: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim

Cannot run the macro... the macro may not be available in this workbook

If you have a space in the name of the workbook you must use single quotes (') around the file name. I have also removed the full stop.

Application.Run "'Python solution macro.xlsm'!PreparetheTables"

How to install PyQt4 on Windows using pip?

With current latest python 3.6.5

pip3 install PyQt5

works fine

How can I make my string property nullable?

It's been a while when the question has been asked and C# changed not much but became a bit better. Take a look Nullable reference types (C# reference)

string notNull = "Hello";
string? nullable = default;
notNull = nullable!; // null forgiveness

C# as a language a "bit" outdated from modern languages and became misleading.

for instance in typescript, swift there's a "?" to clearly say it's a nullable type, be careful. It's pretty clear and it's awesome. C# doesn't/didn't have this ability, as a result, a simple contract IPerson very misleading. As per C# FirstName and LastName could be null but is it true? is per business logic FirstName/LastName really could be null? the answer is we don't know because C# doesn't have the ability to say it directly.

interface IPerson
{
  public string FirstName;
  public string LastName;
}

New features in java 7

In addition to what John Skeet said, here's an overview of the Java 7 project. It includes a list and description of the features.

Note: JDK 7 was released on July 28, 2011, so you should now go to the official java SE site.

Get values from other sheet using VBA

Maybe you can use the script i am using to retrieve a certain cell value from another sheet back to a specific sheet.

Sub reviewRow()
Application.ScreenUpdating = False
Results = MsgBox("Do you want to View selected row?", vbYesNo, "")
If Results = vbYes And Range("C10") > 1 Then
i = Range("C10") //this is where i put the row number that i want to retrieve or review that can be changed as needed
Worksheets("Sheet1").Range("C6") = Worksheets("Sheet2").Range("C" & i) //sheet names can be changed as necessary
End if
Application.ScreenUpdating = True
End Sub

You can make a form using this and personalize it as needed.

Xcode build failure "Undefined symbols for architecture x86_64"

If you're getting this error when trying to link to a C file, first double check the function names for typos. Next double check that you are not trying to call a C function from a C++ / Objective-C++ environment without using the extern C {} construct. I was tearing my hair out because I had a class that was in a .mm file which was trying to call C functions. It doesn't work because in C++, the symbols are mangled. You can actually see the concrete symbols generated using the nm tool. Terminal to the path of the .o files, and run nm -g on the file that is calling the symbol and the one that should have the symbol, and you should see if they match up or not, which can provide clues for the error.

nm -g file.o

You can inspect the C++ symbols demangled with this:

nm -gC file.o

Get an OutputStream into a String

This worked nicely

OutputStream output = new OutputStream() {
    private StringBuilder string = new StringBuilder();

    @Override
    public void write(int b) throws IOException {
        this.string.append((char) b );
    }

    //Netbeans IDE automatically overrides this toString()
    public String toString() {
        return this.string.toString();
    }
};

method call =>> marshaller.marshal( (Object) toWrite , (OutputStream) output);

then to print the string or get it just reference the "output" stream itself As an example, to print the string out to console =>> System.out.println(output);

FYI: my method call marshaller.marshal(Object,Outputstream) is for working with XML. It is irrelevant to this topic.

This is highly wasteful for productional use, there is a way too many conversion and it is a bit loose. This was just coded to prove to you that it is totally possible to create a custom OuputStream and output a string. But just go Horcrux7 way and all is good with merely two method calls.

And the world lives on another day....

How to run shell script file using nodejs?

You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.

hi.sh

echo "Hi There!"

node_program.js

const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
        (error, stdout, stderr) => {
            console.log(stdout);
            console.log(stderr);
            if (error !== null) {
                console.log(`exec error: ${error}`);
            }
        });

Here, when I run the nodejs file, it will execute the shell file and the output would be:

Run

node node_program.js

output

Hi There!

You can execute any script just by mentioning the shell command or shell script in exec callback.

Hope this helps! Happy coding :)

Set initial focus in an Android application

I found this worked best for me.

In AndroidManifest.xml <activity> element add android:windowSoftInputMode="stateHidden"

This always hides the keyboard when entering the activity.

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

How to change fontFamily of TextView in Android

With some trial and error I learned the following.

Within the *.xml you can combine the stock fonts with the following functions, not only with typeface:

 android:fontFamily="serif" 
 android:textStyle="italic"

With this two styles, there was no need to use typeface in any other case. The range of combinations is much more bigger with fontfamily&textStyle.

What is Shelving in TFS?

One point that is missed in a lot of these discussions is how you revert back on the SAME machine on which you shelved your changes. Perhaps obvious to most, but wasn't to me. I believe you perform an Undo Pending Changes - is that right?

I understand the process to be as follows:

  1. To shelve your current pending changes, right click the project, Shelve, add a shelve name
  2. This will save (or Shelve) the changes to the server (no-one will see them)
  3. You then do Undo Pending Changes to revert your code back to the last check-in point
  4. You can then do what you need to do with the reverted code baseline
  5. You can Unshelve the changes at any time (may require some merge confliction)

So, if you want to start some work which you may need to Shelve, make sure you check-in before you start, as the check-in point is where you'll return to when doing the Undo Pending Changes step above.

Clear dropdownlist with JQuery

<select id="ddlvalue" name="ddlvaluename">
<option value='0' disabled selected>Select Value</option>
<option value='1' >Value 1</option>
<option value='2' >Value 2</option>
</select>

<input type="submit" id="btn_submit" value="click me"/>



<script>
$('#btn_submit').on('click',function(){
      $('#ddlvalue').val(0);
});
</script>

Python loop counter in a for loop

Use enumerate() like so:

def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option    

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.

Adding the "Clear" Button to an iPhone UITextField

Swift 4 (adapted from Kristopher Johnson's answer)

textfield.clearButtonMode = .always

textfield.clearButtonMode = .whileEditing

textfield.clearButtonMode = .unlessEditing

textfield.clearButtonMode = .never

Eclipse CDT project built but "Launch Failed. Binary Not Found"

On a Mac, If you also have a similar problem, as Nenad Bulatovic mentioned above, you need to change the Binary Parsers.

Press Command + I to open up properties (or right click on your project and select property)

Make sure you select Mach-O 64 Parser.

enter image description here

Left Outer Join using + sign in Oracle 11g

TableA LEFT OUTER JOIN TableB is equivalent to TableB RIGHT OUTER JOIN Table A.

In Oracle, (+) denotes the "optional" table in the JOIN. So in your first query, it's a P LEFT OUTER JOIN S. In your second query, it's S RIGHT OUTER JOIN P. They're functionally equivalent.

In the terminology, RIGHT or LEFT specify which side of the join always has a record, and the other side might be null. So in a P LEFT OUTER JOIN S, P will always have a record because it's on the LEFT, but S could be null.

See this example from java2s.com for additional explanation.


To clarify, I guess I'm saying that terminology doesn't matter, as it's only there to help visualize. What matters is that you understand the concept of how it works.


RIGHT vs LEFT

I've seen some confusion about what matters in determining RIGHT vs LEFT in implicit join syntax.

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

All I did is swap sides of the terms in the WHERE clause, but they're still functionally equivalent. (See higher up in my answer for more info about that.) The placement of the (+) determines RIGHT or LEFT. (Specifically, if the (+) is on the right, it's a LEFT JOIN. If (+) is on the left, it's a RIGHT JOIN.)


Types of JOIN

The two styles of JOIN are implicit JOINs and explicit JOINs. They are different styles of writing JOINs, but they are functionally equivalent.

See this SO question.

Implicit JOINs simply list all tables together. The join conditions are specified in a WHERE clause.

Implicit JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

Explicit JOINs associate join conditions with a specific table's inclusion instead of in a WHERE clause.

Explicit JOIN

SELECT *
FROM A
LEFT OUTER JOIN B ON A.column = B.column

These Implicit JOINs can be more difficult to read and comprehend, and they also have a few limitations since the join conditions are mixed in other WHERE conditions. As such, implicit JOINs are generally recommended against in favor of explicit syntax.

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__PRETTY_FUNCTION__ handles C++ features: classes, namespaces, templates and overload

main.cpp

#include <iostream>

namespace N {
    class C {
        public:
            template <class T>
            static void f(int i) {
                (void)i;
                std::cout << "__func__            " << __func__ << std::endl
                          << "__FUNCTION__        " << __FUNCTION__ << std::endl
                          << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
            }
            template <class T>
            static void f(double f) {
                (void)f;
                std::cout << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
            }
    };
}

int main() {
    N::C::f<char>(1);
    N::C::f<void>(1.0);
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

Output:

__func__            f
__FUNCTION__        f
__PRETTY_FUNCTION__ static void N::C::f(int) [with T = char]
__PRETTY_FUNCTION__ static void N::C::f(double) [with T = void]

You may also be interested in stack traces with function names: print call stack in C or C++

Tested in Ubuntu 19.04, GCC 8.3.0.

C++20 std::source_location::function_name

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf went into C++20, so we have yet another way to do it.

The documentation says:

constexpr const char* function_name() const noexcept;

6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.

where NTBS means "Null Terminated Byte String".

I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:

#include <iostream>
#include <string_view>
#include <source_location>
 
void log(std::string_view message,
         const std::source_location& location std::source_location::current()
) {
    std::cout << "info:"
              << location.file_name() << ":"
              << location.line() << ":"
              << location.function_name() << " "
              << message << '\n';
}
 
int main() {
    log("Hello world!");
}

Possible output:

info:main.cpp:16:main Hello world!

so note how this returns the caller information, and is therefore perfect for usage in logging, see also: Is there a way to get function name inside a C++ function?

Creating object with dynamic keys

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

The syntax is:

var obj = {
  [myKey]: value,
}

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

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

  callback(null, inputs);
}

Note: A transpiler is still required for browser compatiblity.

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


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

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

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

In your case:

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

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

  callback(null, inputs);
}

Refresh page after form submitting

  //insert this php code, at the end after your closing html tag. 

  <?php
  //setting connection to database
  $con = mysqli_connect("localhost","your-username","your-
  passowrd","your-dbname");

  if(isset($_POST['submit_button'])){

     $txt_area = $_POST['update']; 

       $Our_query= "INSERT INTO your-table-name (field1name, field2name) 
                  VALUES ('abc','def')"; // values should match data 
                 //  type to field names

        $insert_query = mysqli_query($con, $Our_query);

        if($insert_query){
            echo "<script>window.open('form.php','_self') </script>"; 
             // supposing form.php is where you have created this form

          }



   } //if statement close         
  ?>

Hope this helps.

Can I loop through a table variable in T-SQL?

Select Top 1 can easily resolve it without the need of any sequence/order.

Create Function Test_Range()
Returns
@Result Table (ID Int)
As
Begin

Declare @ID Varchar(10) = ''
Declare @Rows Int, @Row Int = 0
Declare @Num Int, @RangeTo Int

Declare @RangeTable Table (ID Varchar(10), RangeFrom Int, RangeTo Int)
Insert Into @RangeTable Values ('A', 1, 10)
Insert Into @RangeTable Values ('B', 25,30)

Set @Rows = (Select Count(*) From @RangeTable)

While @Row <= @Rows
Begin
    Set @Row = @Row + 1
    Select Top 1 @ID = ID, @Num = RangeFrom, @RangeTo = RangeTo  From @RangeTable
    Where ID > @ID
    While @Num <= @RangeTo
    Begin
        Insert Into @Result Values (@Num)
        Set @Num = @Num + 1
    End
End
Return
End

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

Historically, the first extensions used for C++ were .c and .h, exactly like for C. This caused practical problems, especially the .c which didn't allow build systems to easily differentiate C++ and C files.

Unix, on which C++ has been developed, has case sensitive file systems. So some used .C for C++ files. Other used .c++, .cc and .cxx. .C and .c++ have the problem that they aren't available on other file systems and their use quickly dropped. DOS and Windows C++ compilers tended to use .cpp, and some of them make the choice difficult, if not impossible, to configure. Portability consideration made that choice the most common, even outside MS-Windows.

Headers have used the corresponding .H, .h++, .hh, .hxx and .hpp. But unlike the main files, .h remains to this day a popular choice for C++ even with the disadvantage that it doesn't allow to know if the header can be included in C context or not. Standard headers now have no extension at all.

Additionally, some are using .ii, .ixx, .ipp, .inl for headers providing inline definitions and .txx, .tpp and .tpl for template definitions. Those are either included in the headers providing the definition, or manually in the contexts where they are needed.

Compilers and tools usually don't care about what extensions are used, but using an extension that they associate with C++ prevents the need to track out how to configure them so they correctly recognize the language used.

2017 edit: the experimental module support of Visual Studio recognize .ixx as a default extension for module interfaces, clang++ is recognizing .c++m, .cppm and .cxxm for the same purpose.

How to comment multiple lines with space or indent

Pressing Ctrl+K+C or Ctrl+E+C After selecting the lines you want to comment will not give space after slashes. you can use multiline select to provide space as suggested by Habib

Perhaps, you can use /* before the lines you want to comment and after */ in that case you might not need to provide spaces.

/*
  First Line to Comment
  Second Line to Comment
  Third Line to Comment      
*/

How to make connection to Postgres via Node.js

We can also use postgresql-easy. It is built on node-postgres and sqlutil. Note: pg_connection.js & your_handler.js are in the same folder. db.js is in the config folder placed.

pg_connection.js

const PgConnection = require('postgresql-easy');
const dbConfig = require('./config/db');
const pg = new PgConnection(dbConfig);
module.exports = pg;

./config/db.js

module.exports =  {
  database: 'your db',
  host: 'your host',
  port: 'your port',
  user: 'your user',
  password: 'your pwd',
}

your_handler.js

  const pg_conctn = require('./pg_connection');

  pg_conctn.getAll('your table')
    .then(res => {
         doResponseHandlingstuff();
      })
    .catch(e => {
         doErrorHandlingStuff()     
      })

Ways to circumvent the same-origin policy

AnyOrigin didn't function well with some https sites, so I just wrote an open source alternative called whateverorigin.org that seems to work well with https.

Code on github.

Fastest method to escape HTML tags as HTML entities?

The AngularJS source code also has a version inside of angular-sanitize.js.

var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
    // Match everything outside of normal chars and " (quote character)
    NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
/**
 * Escapes all potentially dangerous characters, so that the
 * resulting string can be safely inserted into attribute or
 * element text.
 * @param value
 * @returns {string} escaped text
 */
function encodeEntities(value) {
  return value.
    replace(/&/g, '&amp;').
    replace(SURROGATE_PAIR_REGEXP, function(value) {
      var hi = value.charCodeAt(0);
      var low = value.charCodeAt(1);
      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
    }).
    replace(NON_ALPHANUMERIC_REGEXP, function(value) {
      return '&#' + value.charCodeAt(0) + ';';
    }).
    replace(/</g, '&lt;').
    replace(/>/g, '&gt;');
}

Block direct access to a file over http but allow php script access

in httpd.conf to block browser & wget access to include files especially say db.inc or config.inc . Note you cannot chain file types in the directive instead create multiple file directives.

<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>

to test your config before restarting apache

service httpd configtest

then (graceful restart)

service httpd graceful

Include another JSP file

What you're doing is a static include. A static include is resolved at compile time, and may thus not use a parameter value, which is only known at execution time.

What you need is a dynamic include:

<jsp:include page="..." />

Note that you should use the JSP EL rather than scriptlets. It also seems that you're implementing a central controller with index.jsp. You should use a servlet to do that instead, and dispatch to the appropriate JSP from this servlet. Or better, use an existing MVC framework like Stripes or Spring MVC.

Use curly braces to initialize a Set in Python

Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.

How to delete a file from SD card?

 public static boolean deleteDirectory(File path) {
    // TODO Auto-generated method stub
    if( path.exists() ) {
        File[] files = path.listFiles();
        for(int i=0; i<files.length; i++) {
            if(files[i].isDirectory()) {
                deleteDirectory(files[i]);
            }
            else {
                files[i].delete();
            }
        }
    }
    return(path.delete());
 }

This Code will Help you.. And In Android Manifest You have to get Permission to make modification..

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Add a properties file to IntelliJ's classpath

I have the same problem and it annoys me tremendously!!

I have always thought I was surposed to do as answer 2. That used to work in Intellij 9 (now using 10).

However I figured out that by adding these line to my maven pom file helps:

<build>
  ...
  <resources>
    <resource>
      <directory>src/main/resources</directory>
    </resource>
  </resources>
  ...
</build>

Display HTML form values in same page after submit using Ajax

One more way to do it (if you use form), note that input type is button

<input type="button" onclick="showMessage()" value="submit" />

Complete code is:

<!DOCTYPE html>
<html>
<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
        function showMessage(){
            var message = document.getElementById("message").value;
            display_message.innerHTML= message;
        }
    </script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

But you can do it even without form:

<!DOCTYPE html>
<html>
<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
        function showMessage(){
            var message = document.getElementById("message").value;
            display_message.innerHTML= message;
        }
    </script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

Here you can use either submit or button:

<input type="submit" onclick="showMessage()" value="submit" />

No need to set

return false;

from JavaScript function for neither of those two examples.

Cannot create Maven Project in eclipse

For me the solution was a bit simpler, I just had to clean the repository : .m2/repository/org/apache/maven/archetypes

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

Assume file is already created in the predefined directory with name "table.txt"

  • 1) change the ownership for file :

    sudo chown username:username table.txt
    
  • 2) change the mode of the file

    sudo chmod 777 table.txt
    

Now, try it should work!

Appending to list in Python dictionary

dates_dict[key] = dates_dict.get(key, []).append(date) sets dates_dict[key] to None as list.append returns None.

In [5]: l = [1,2,3]

In [6]: var = l.append(3)

In [7]: print var
None

You should use collections.defaultdict

import collections
dates_dict = collections.defaultdict(list)

node.js, socket.io with SSL

Depending on your needs, you could allow both secure and unsecure connections and still only use one Socket.io instance.

You simply have to instanciate two servers, one for HTTP and one for HTTPS, then attach those servers to the Socket.io instance.

Server side :

// needed to read certificates from disk
const fs          = require( "fs"    );

// Servers with and without SSL
const http        = require( "http"  )
const https       = require( "https" );
const httpPort    = 3333;
const httpsPort   = 3334;
const httpServer  = http.createServer();
const httpsServer = https.createServer({
    "key" : fs.readFileSync( "yourcert.key" ),
    "cert": fs.readFileSync( "yourcert.crt" ),
    "ca"  : fs.readFileSync( "yourca.crt"   )
});
httpServer.listen( httpPort, function() {
    console.log(  `Listening HTTP on ${httpPort}` );
});
httpsServer.listen( httpsPort, function() {
    console.log(  `Listening HTTPS on ${httpsPort}` );
});

// Socket.io
const ioServer = require( "socket.io" );
const io       = new ioServer();
io.attach( httpServer  );
io.attach( httpsServer );

io.on( "connection", function( socket ) {

    console.log( "user connected" );
    // ... your code

});

Client side :

var url    = "//example.com:" + ( window.location.protocol == "https:" ? "3334" : "3333" );
var socket = io( url, {
    // set to false only if you use self-signed certificate !
    "rejectUnauthorized": true
});
socket.on( "connect", function( e ) {
    console.log( "connect", e );
});

If your NodeJS server is different from your Web server, you will maybe need to set some CORS headers. So in the server side, replace:

const httpServer  = http.createServer();
const httpsServer = https.createServer({
    "key" : fs.readFileSync( "yourcert.key" ),
    "cert": fs.readFileSync( "yourcert.crt" ),
    "ca"  : fs.readFileSync( "yourca.crt"   )
});

With:

const CORS_fn = (req, res) => {
    res.setHeader( "Access-Control-Allow-Origin"     , "*"    );
    res.setHeader( "Access-Control-Allow-Credentials", "true" );
    res.setHeader( "Access-Control-Allow-Methods"    , "*"    );
    res.setHeader( "Access-Control-Allow-Headers"    , "*"    );
    if ( req.method === "OPTIONS" ) {
        res.writeHead(200);
        res.end();
        return;
    }
};
const httpServer  = http.createServer( CORS_fn );
const httpsServer = https.createServer({
        "key" : fs.readFileSync( "yourcert.key" ),
        "cert": fs.readFileSync( "yourcert.crt" ),
        "ca"  : fs.readFileSync( "yourca.crt"   )
}, CORS_fn );

And of course add/remove headers and set the values of the headers according to your needs.

Can I load a UIImage from a URL?

And the swift version :

   let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
    var err: NSError?
    var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
    var bgImage = UIImage(data:imageData)

Testing socket connection in Python

You should really post:

  1. The complete source code of your example
  2. The actual result of it, not a summary

Here is my code, which works:

import socket, sys

def alert(msg):
    print >>sys.stderr, msg
    sys.exit(1)

(family, socktype, proto, garbage, address) = \
         socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)

try:
    s.connect(address) 
except Exception, e:
    alert("Something's wrong with %s. Exception type is %s" % (address, e))

When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:

Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

From documentation:

To comply with the SQL standard, IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.

This is exactly your case.

Both IN and NOT IN return NULL which is not an acceptable condition for WHERE clause.

Rewrite your query as follows:

SELECT  *
FROM    match m
WHERE   NOT EXISTS
        (
        SELECT  1
        FROM    email e
        WHERE   e.id = m.id
        )

"replace" function examples

Here's an example where I found the replace( ) function helpful for giving me insight. The problem required a long integer vector be changed into a character vector and with its integers replaced by given character values.

## figuring out replace( )
(test <- c(rep(1,3),rep(2,2),rep(3,1)))

which looks like

[1] 1 1 1 2 2 3

and I want to replace every 1 with an A and 2 with a B and 3 with a C

letts <- c("A","B","C")

so in my own secret little "dirty-verse" I used a loop

for(i in 1:3)
{test <- replace(test,test==i,letts[i])}

which did what I wanted

test
[1] "A" "A" "A" "B" "B" "C"

In the first sentence I purposefully left out that the real objective was to make the big vector of integers a factor vector and assign the integer values (levels) some names (labels).

So another way of doing the replace( ) application here would be

(test <- factor(test,labels=letts))
[1] A A A B B C
Levels: A B C

Textfield with only bottom border

See this JSFiddle

_x000D_
_x000D_
 input[type="text"]_x000D_
    {_x000D_
        border: 0;_x000D_
        border-bottom: 1px solid red;_x000D_
        outline: 0;_x000D_
    }
_x000D_
<form>_x000D_
        <input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

Certify that your Manifest declaration includes android:theme="@style/AppTheme.NoActionBar" tag, like the following:

<activity
    android:name=".PointsScreen"
    android:theme="@style/AppTheme.NoActionBar">
</activity>

How to convert binary string value to decimal

  int base2(String bits) {
    int ans = 0;
    for (int i = bits.length() - 1, f = 1; i >= 0; i--) {
      ans += f * (bits.charAt(i) - '0');
      f <<= 1;
    }
    return ans;
  }

Perform .join on value in array of objects

not sure, but all this answers tho they work but are not optiomal since the are performing two scans and you can perform this in a single scan. Even though O(2n) is considered O(n) is always better to have a true O(n).

const Join = (arr, separator, prop) => {
    let combined = '';
    for (var i = 0; i < arr.length; i++) {
        combined = `${combined}${arr[i][prop]}`;
        if (i + 1 < arr.length)
            combined = `${combined}${separator} `;
    }
    return combined;
}

This might look like old school, but allows me to do thig like this:

skuCombined = Join(option.SKUs, ',', 'SkuNum');

Making a PowerShell POST request if a body param starts with '@'

Use Invoke-RestMethod to consume REST-APIs. Save the JSON to a string and use that as the body, ex:

$JSON = @'
{"@type":"login",
 "username":"[email protected]",
 "password":"yyy"
}
'@

$response = Invoke-RestMethod -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

If you use Powershell 3, I know there have been some issues with Invoke-RestMethod, but you should be able to use Invoke-WebRequest as a replacement:

$response = Invoke-WebRequest -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

If you don't want to write your own JSON every time, you can use a hashtable and use PowerShell to convert it to JSON before posting it. Ex.

$JSON = @{
    "@type" = "login"
    "username" = "[email protected]"
    "password" = "yyy"
} | ConvertTo-Json

FIX CSS <!--[if lt IE 8]> in IE

If you want this to work in IE 8 and below, use

<!--[if lte IE 8]>

lte meaning "Less than or equal".

For more on conditional comments, see e.g. the quirksmode.org page.

SQL Server Regular expressions in T-SQL

You can use VBScript regular expression features using OLE Automation. This is way better than the overhead of creating and maintaining an assembly. Please make sure you go through the comments section to get a better modified version of the main one.

http://blogs.msdn.com/b/khen1234/archive/2005/05/11/416392.aspx

DECLARE @obj INT, @res INT, @match BIT;
DECLARE @pattern varchar(255) = '<your regex pattern goes here>';
DECLARE @matchstring varchar(8000) = '<string to search goes here>';
SET @match = 0;

-- Create a VB script component object
EXEC @res = sp_OACreate 'VBScript.RegExp', @obj OUT;

-- Apply/set the pattern to the RegEx object
EXEC @res = sp_OASetProperty @obj, 'Pattern', @pattern;

-- Set any other settings/properties here
EXEC @res = sp_OASetProperty @obj, 'IgnoreCase', 1;

-- Call the method 'Test' to find a match
EXEC @res = sp_OAMethod @obj, 'Test', @match OUT, @matchstring;

-- Don't forget to clean-up
EXEC @res = sp_OADestroy @obj;

If you get SQL Server blocked access to procedure 'sys.sp_OACreate'... error, use sp_reconfigure to enable Ole Automation Procedures. (Yes, unfortunately that is a server level change!)

More information about the Test method is available here

Happy coding

How to add parameters into a WebRequest?

The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.

//Visual Basic Implementation Request and Response String
  Dim params = "key1=value1&key2=value2"
    Dim byteArray = UTF8.GetBytes(params)
    Dim url = "https://okay.com"
    Dim client = WebRequest.Create(url)
    client.Method = "POST"
    client.ContentType = "application/x-www-form-urlencoded"
    client.ContentLength = byteArray.Length
    Dim stream = client.GetRequestStream()

    //sending the data
    stream.Write(byteArray, 0, byteArray.Length)
    stream.Close()

//getting the full response in a stream        
Dim response = client.GetResponse().GetResponseStream()

//reading the response 
Dim result = New StreamReader(response)

//Writes response string to Console
    Console.WriteLine(result.ReadToEnd())
    Console.ReadKey()

Java Thread Example?

create java application in which you define two threads namely t1 and t2, thread t1 will generate random number 0 and 1 (simulate toss a coin ). 0 means head and one means tail. the other thread t2 will do the same t1 and t2 will repeat this loop 100 times and finally your application should determine how many times t1 guesses the number generated by t2 and then display the score. for example if thread t1 guesses 20 number out of 100 then the score of t1 is 20/100 =0.2 if t1 guesses 100 numbers then it gets score 1 and so on

R Markdown - changing font size and font type in html output

I would definitely use html markers to achieve this. Just surround your text with <p></p> or <font></font> and add the desired attributes. See the following example:

<p style="font-family: times, serif; font-size:11pt; font-style:italic">
    Why did we use these specific parameters during the calculation of the fingerprints?
</p>

This will produce the following output

Font Output

compared to

Default Output

This would work with Jupyter Notebook as well as Typora, but I'm not sure if it is universal.

Lastly, be aware that the html marker overrides the font styling used by Markdown.

"google is not defined" when using Google Maps V3 in Firefox remotely

Changed the

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"> 
      function(){
            myMap()
                }
</script>

and made it

<script type="text/javascript">
      function(){
            myMap()
                }
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"></script>

It worked :)

How to make HTML table cell editable?

Try this code.

$(function () {
 $("td").dblclick(function () {
    var OriginalContent = $(this).text();

    $(this).addClass("cellEditing");
    $(this).html("<input type="text" value="&quot; + OriginalContent + &quot;" />");
    $(this).children().first().focus();

    $(this).children().first().keypress(function (e) {
        if (e.which == 13) {
            var newContent = $(this).val();
            $(this).parent().text(newContent);
            $(this).parent().removeClass("cellEditing");
        }
    });

 $(this).children().first().blur(function(){
    $(this).parent().text(OriginalContent);
    $(this).parent().removeClass("cellEditing");
 });
 });
});

You can also visit this link for more details :

Mac zip compress without __MACOSX folder?

I'm using this Automator Shell Script to fix it after. It's showing up as contextual menu item (right clicking on any file showing up in Finder).

while read -r p; do
  zip -d "$p" __MACOSX/\* || true
  zip -d "$p" \*/.DS_Store || true
done
  1. Create a new Service with Automator
  2. Select "Files and Folders" in "Finder"
  3. Add a "Shell Script Action"

automator shell script

contextual menu item in Finder

how to query child objects in mongodb

If it is exactly null (as opposed to not set):

db.states.find({"cities.name": null})

(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).

If it's the case that the property is not set:

db.states.find({"cities.name": {"$exists": false}})

I've tested the above with a collection created with these two inserts:

db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})

The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or query:

db.states.find({"$or": [
  {"cities.name": null}, 
  {"cities.name": {"$exists": false}}
]})

Changing directory in Google colab (breaking out of the python interpreter)

Use os.chdir. Here's a full example: https://colab.research.google.com/notebook#fileId=1CSPBdmY0TxU038aKscL8YJ3ELgCiGGju

Compactly:

!mkdir abc
!echo "file" > abc/123.txt

import os
os.chdir('abc')

# Now the directory 'abc' is the current working directory.
# and will show 123.txt.
!ls

Change arrow colors in Bootstraps carousel

In bootstrap 4 if you are just changing the colour of the controls you can use the sass variables, typically in custom.scss:

$carousel-control-color: #7b277d;

As highlighted in this github issue note: https://github.com/twbs/bootstrap/issues/21985#issuecomment-281402443

How to install latest version of openssl Mac OS X El Capitan

You can run brew link openssl to link it into /usr/local, if you don't mind the potential problem highlighted in the warning message. Otherwise, you can add the openssl bin directory to your path:

export PATH=$(brew --prefix openssl)/bin:$PATH

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Use Transformation method:

To Hide:

editText.transformationMethod = PasswordTransformationMethod.getInstance()

To Visible:

editText.transformationMethod = SingleLineTransformationMethod.getInstance()

That's it.

Difference between $(this) and event.target?

There are cross browser issues here.

A typical non-jQuery event handler would be something like this :

function doSomething(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

jQuery normalises evt and makes the target available as this in event handlers, so a typical jQuery event handler would be something like this :

function doSomething(evt) {
    var $target = $(this);
    //do stuff here
}

A hybrid event handler which uses jQuery's normalised evt and a POJS target would be something like this :

function doSomething(evt) {
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

How do I specify the JDK for a GlassFish domain?

In Linux file system , Edit below file as this steps

Path - /opt/glassfish3/glassfish/config

File Name - asenv.conf

Add the JAVA HOME path as below to the end of file.

AS_JAVA=/opt/jdk1.8.0_201

Now start the glassfish server.

ArrayList of int array in java

You have to use <Integer> instead of <int>:

int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
    arl.add(i);        
    System.out.println("Arraylist contains:" + arl.get(0));
}

Pycharm and sys.argv arguments

For the sake of others who are wondering on how to get to this window. Here's how:

You can access this by clicking on Select Run/Debug Configurations (to the left of enter image description here) and going to the Edit Configurations. A gif provided for clarity.

enter image description here

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

I get this same error on my Windows 7 machine when the permissions on my cacerts file in my C:\Program Files\Java\jdk1.7.0_51\jre\lib\security folder are not set correctly.

To resolve the issue, I allow the SERVICE and INTERACTIVE users to have all modify permissions on cacerts except "change permissions" and "take ownership" (from Advanced Settings, in the Security properties). I assume that allowing these services to both read and write extended attributes may have something to do with the error going away.

Portable way to check if directory exists [Windows/Linux, C]

stat() works on Linux., UNIX and Windows as well:

#include <sys/types.h>
#include <sys/stat.h>

struct stat info;

if( stat( pathname, &info ) != 0 )
    printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR )  // S_ISDIR() doesn't exist on my windows 
    printf( "%s is a directory\n", pathname );
else
    printf( "%s is no directory\n", pathname );

Use of for_each on map elements

It's unfortunate that you don't have Boost however if your STL implementation has the extensions then you can compose mem_fun_ref and select2nd to create a single functor suitable for use with for_each. The code would look something like this:

#include <algorithm>
#include <map>
#include <ext/functional>   // GNU-specific extension for functor classes missing from standard STL

using namespace __gnu_cxx;  // for compose1 and select2nd

class MyClass
{
public:
    void Method() const;
};

std::map<int, MyClass> Map;

int main(void)
{
    std::for_each(Map.begin(), Map.end(), compose1(std::mem_fun_ref(&MyClass::Method), select2nd<std::map<int, MyClass>::value_type>()));
}

Note that if you don't have access to compose1 (or the unary_compose template) and select2nd, they are fairly easy to write.

What is the difference between a heuristic and an algorithm?

I think Heuristic is more of a constraint used in Learning Based Model in Artificial Intelligent since the future solution states are difficult to predict.

But then my doubt after reading above answers is "How would Heuristic can be successfully applied using Stochastic Optimization Techniques? or can they function as full fledged algorithms when used with Stochastic Optimization?"

http://en.wikipedia.org/wiki/Stochastic_optimization

Installing and Running MongoDB on OSX

mongo => mongo-db console
mongodb => mongo-db server

If you're on Mac and looking for a easier way to start/stop your mongo-db server, then MongoDB Preference Pane is something that you should look into. With it, you start/stop your mongo-db instance via UI. Hope it helps!

How do I show a console output/window in a forms application?

Why not just leave it as a Window Forms app, and create a simple form to mimic the Console. The form can be made to look just like the black-screened Console, and have it respond directly to key press. Then, in the program.cs file, you decide whether you need to Run the main form or the ConsoleForm. For example, I use this approach to capture the command line arguments in the program.cs file. I create the ConsoleForm, initially hide it, then pass the command line strings to an AddCommand function in it, which displays the allowed commands. Finally, if the user gave the -h or -? command, I call the .Show on the ConsoleForm and when the user hits any key on it, I shut down the program. If the user doesn't give the -? command, I close the hidden ConsoleForm and Run the main form.

How do I query using fields inside the new PostgreSQL JSON datatype?

With postgres 9.3 use -> for object access. 4 example

seed.rb

se = SmartElement.new
se.data = 
{
    params:
    [
        {
            type: 1,
            code: 1,
            value: 2012,
            description: 'year of producction'
        },
        {
            type: 1,
            code: 2,
            value: 30,
            description: 'length'
        }
    ]
}

se.save

rails c

SELECT data->'params'->0 as data FROM smart_elements;

returns

                                 data
----------------------------------------------------------------------
 {"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)

You can continue nesting

SELECT data->'params'->0->'type' as data FROM smart_elements;

return

 data
------
 1
(1 row)

REST API 404: Bad URI, or Missing Resource?

As with most things, "it depends". But to me, your practice is not bad and is not going against the HTTP spec per se. However, let's clear some things up.

First, URI's should be opaque. Even if they're not opaque to people, they are opaque to machines. In other words, the difference between http://mywebsite/api/user/13, http://mywebsite/restapi/user/13 is the same as the difference between http://mywebsite/api/user/13 and http://mywebsite/api/user/14 i.e. not the same is not the same period. So a 404 would be completely appropriate for http://mywebsite/api/user/14 (if there is no such user) but not necessarily the only appropriate response.

You could also return an empty 200 response or more explicitly a 204 (No Content) response. This would convey something else to the client. It would imply that the resource identified by http://mywebsite/api/user/14 has no content or is essentially nothing. It does mean that there is such a resource. However, it does not necessarily mean that you are claiming there is some user persisted in a data store with id 14. That's your private concern, not the concern of the client making the request. So, if it makes sense to model your resources that way, go ahead.

There are some security implications to giving your clients information that would make it easier for them to guess legitimate URI's. Returning a 200 on misses instead of a 404 may give the client a clue that at least the http://mywebsite/api/user part is correct. A malicious client could just keep trying different integers. But to me, a malicious client would be able to guess the http://mywebsite/api/user part anyway. A better remedy would be to use UUID's. i.e. http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66 is better than http://mywebsite/api/user/14. Doing that, you could use your technique of returning 200's without giving much away.

Can you find all classes in a package using reflection?

Hello. I always have had some issues with the solutions above (and on other sites).
I, as a developer, am programming a addon for a API. The API prevents the use of any external libraries or 3rd party tools. The setup also consists of a mixture of code in jar or zip files and class files located directly in some directories. So my code had to be able to work arround every setup. After a lot of research I have come up with a method that will work in at least 95% of all possible setups.

The following code is basically the overkill method that will always work.

The code:

This code scans a given package for all classes that are included in it. It will only work for all classes in the current ClassLoader.

/**
 * Private helper method
 * 
 * @param directory
 *            The directory to start with
 * @param pckgname
 *            The package name to search for. Will be needed for getting the
 *            Class object.
 * @param classes
 *            if a file isn't loaded but still is in the directory
 * @throws ClassNotFoundException
 */
private static void checkDirectory(File directory, String pckgname,
        ArrayList<Class<?>> classes) throws ClassNotFoundException {
    File tmpDirectory;

    if (directory.exists() && directory.isDirectory()) {
        final String[] files = directory.list();

        for (final String file : files) {
            if (file.endsWith(".class")) {
                try {
                    classes.add(Class.forName(pckgname + '.'
                            + file.substring(0, file.length() - 6)));
                } catch (final NoClassDefFoundError e) {
                    // do nothing. this class hasn't been found by the
                    // loader, and we don't care.
                }
            } else if ((tmpDirectory = new File(directory, file))
                    .isDirectory()) {
                checkDirectory(tmpDirectory, pckgname + "." + file, classes);
            }
        }
    }
}

/**
 * Private helper method.
 * 
 * @param connection
 *            the connection to the jar
 * @param pckgname
 *            the package name to search for
 * @param classes
 *            the current ArrayList of all classes. This method will simply
 *            add new classes.
 * @throws ClassNotFoundException
 *             if a file isn't loaded but still is in the jar file
 * @throws IOException
 *             if it can't correctly read from the jar file.
 */
private static void checkJarFile(JarURLConnection connection,
        String pckgname, ArrayList<Class<?>> classes)
        throws ClassNotFoundException, IOException {
    final JarFile jarFile = connection.getJarFile();
    final Enumeration<JarEntry> entries = jarFile.entries();
    String name;

    for (JarEntry jarEntry = null; entries.hasMoreElements()
            && ((jarEntry = entries.nextElement()) != null);) {
        name = jarEntry.getName();

        if (name.contains(".class")) {
            name = name.substring(0, name.length() - 6).replace('/', '.');

            if (name.contains(pckgname)) {
                classes.add(Class.forName(name));
            }
        }
    }
}

/**
 * Attempts to list all the classes in the specified package as determined
 * by the context class loader
 * 
 * @param pckgname
 *            the package name to search
 * @return a list of classes that exist within that package
 * @throws ClassNotFoundException
 *             if something went wrong
 */
public static ArrayList<Class<?>> getClassesForPackage(String pckgname)
        throws ClassNotFoundException {
    final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

    try {
        final ClassLoader cld = Thread.currentThread()
                .getContextClassLoader();

        if (cld == null)
            throw new ClassNotFoundException("Can't get class loader.");

        final Enumeration<URL> resources = cld.getResources(pckgname
                .replace('.', '/'));
        URLConnection connection;

        for (URL url = null; resources.hasMoreElements()
                && ((url = resources.nextElement()) != null);) {
            try {
                connection = url.openConnection();

                if (connection instanceof JarURLConnection) {
                    checkJarFile((JarURLConnection) connection, pckgname,
                            classes);
                } else if (connection instanceof FileURLConnection) {
                    try {
                        checkDirectory(
                                new File(URLDecoder.decode(url.getPath(),
                                        "UTF-8")), pckgname, classes);
                    } catch (final UnsupportedEncodingException ex) {
                        throw new ClassNotFoundException(
                                pckgname
                                        + " does not appear to be a valid package (Unsupported encoding)",
                                ex);
                    }
                } else
                    throw new ClassNotFoundException(pckgname + " ("
                            + url.getPath()
                            + ") does not appear to be a valid package");
            } catch (final IOException ioex) {
                throw new ClassNotFoundException(
                        "IOException was thrown when trying to get all resources for "
                                + pckgname, ioex);
            }
        }
    } catch (final NullPointerException ex) {
        throw new ClassNotFoundException(
                pckgname
                        + " does not appear to be a valid package (Null pointer exception)",
                ex);
    } catch (final IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for "
                        + pckgname, ioex);
    }

    return classes;
}

These three methods provide you with the ability to find all classes in a given package.
You use it like this:

getClassesForPackage("package.your.classes.are.in");

The explanation:

The method first gets the current ClassLoader. It then fetches all resources that contain said package and iterates of these URLs. It then creates a URLConnection and determines what type of URl we have. It can either be a directory (FileURLConnection) or a directory inside a jar or zip file (JarURLConnection). Depending on what type of connection we have two different methods will be called.

First lets see what happens if it is a FileURLConnection.
It first checks if the passed File exists and is a directory. If that's the case it checks if it is a class file. If so a Class object will be created and put in the ArrayList. If it is not a class file but is a directory, we simply iterate into it and do the same thing. All other cases/files will be ignored.

If the URLConnection is a JarURLConnection the other private helper method will be called. This method iterates over all Entries in the zip/jar archive. If one entry is a class file and is inside of the package a Class object will be created and stored in the ArrayList.

After all resources have been parsed it (the main method) returns the ArrayList containig all classes in the given package, that the current ClassLoader knows about.

If the process fails at any point a ClassNotFoundException will be thrown containg detailed information about the exact cause.

c# how to add byte to byte array

As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:

var mahByteArray = new ArrayList<byte>();

If you have a byte array from elsewhere, you can use the AddRange function.

mahByteArray.AddRange(mahOldByteArray);

Then you can use Add() and Insert() to add elements.

mahByteArray.Add(0x00); // Adds 0x00 to the end.
mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.

Need it back in an array? .ToArray() has you covered!

mahOldByteArray = mahByteArray.ToArray();

What is the difference between function and procedure in PL/SQL?

The following are the major differences between procedure and function,

  1. Procedure is named PL/SQL block which performs one or more tasks. where function is named PL/SQL block which performs a specific action.
  2. Procedure may or may not return value where as function should return one value.
  3. we can call functions in select statement where as procedure we cant.

converting Java bitmap to byte array

Try this to convert String-Bitmap or Bitmap-String

/**
 * @param bitmap
 * @return converting bitmap and return a string
 */
public static String BitMapToString(Bitmap bitmap){
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte [] b=baos.toByteArray();
    String temp=Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}

/**
 * @param encodedString
 * @return bitmap (from given string)
 */
public static Bitmap StringToBitMap(String encodedString){
    try{
        byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
        Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return bitmap;
    }catch(Exception e){
        e.getMessage();
        return null;
    }
}

MySQL check if a table exists without throwing an exception

$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
    foreach( $row as $key => $value )
    {
        if ( $value = BTABLE )  // BTABLE IS A DEFINED NAME OF TABLE
            echo "exist";
        else
            echo "not exist";
    }
}

Why is "throws Exception" necessary when calling a function?

The throws Exception declaration is an automated way of keeping track of methods that might throw an exception for anticipated but unavoidable reasons. The declaration is typically specific about the type or types of exceptions that may be thrown such as throws IOException or throws IOException, MyException.

We all have or will eventually write code that stops unexpectedly and reports an exception due to something we did not anticipate before running the program, like division by zero or index out of bounds. Since the errors were not expected by the method, they could not be "caught" and handled with a try catch clause. Any unsuspecting users of the method would also not know of this possibility and their programs would also stop.

When the programmer knows certain types of errors may occur but would like to handle these exceptions outside of the method, the method can "throw" one or more types of exceptions to the calling method instead of handling them. If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw. Since programs can have many layers of methods written by many different programs, it becomes difficult (impossible) to keep track of which methods might throw exceptions.

Even though Java has the ability to declare exceptions, you can still write a new method with unhandled and undeclared exceptions, and Java will compile it and you can run it and hope for the best. What Java won't let you do is compile your new method if it uses a method that has been declared as throwing exception(s), unless you either handle the declared exception(s) in your method or declare your method as throwing the same exception(s) or if there are multiple exceptions, you can handle some and throw the rest.

When a programmer declares that the method throws a specific type of exception, it is just an automated way of warning other programmers using the method that an exception is possible. The programmer can then decide to handled the exception or pass on the warning by declaring the calling method as also throwing the same exception. Since the compiler has been warned the exception is possible in this new method, it can automatically check if future callers of the new method handle the exception or declare it and enforcing one or the other to happen.

The nice thing about this type of solution is that when the compiler reports Error: Unhandled exception type java.io.IOException it gives the file and line number of the method that was declared to throw the exception. You can then choose to simply pass the buck and declare your method also "throws IOException". This can be done all the way up to main method where it would then cause the program to stop and report the exception to the user. However, it is better to catch the exception and deal with it in a nice way such as explaining to the user what has happened and how to fix it. When a method does catch and handle the exception, it no longer has to declare the exception. The buck stops there so to speak.

Composer install error - requires ext_curl when it's actually enabled

Not sure why an answer with Linux commands would get so many up votes for a Windows related question, but anyway...

If phpinfo() shows Curl as enabled, yet php -m does NOT, it means that you probably have a php-cli.ini too. run php -i and see which ini file loaded. If it's different, diff it and reflect and differences in the CLI ini file. Then you should be good to go.

Btw download and use Git Bash instead of cmd.exe!

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

Wasted 4+ hours on this.

I have Visual Studio 2017 Enterprise, one of the projects has below error:

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

To resolve above error, I tried to install all below:

However, none of the above worked.

Later, installed Visual Studio 2013 Ultimate, then all worked fine.

Looks like, the older Visual studio is a must to resolve this.

Hope it helps.

Difference between OData and REST web services

OData (Open Data Protocol) is an OASIS standard that defines the best practice for building and consuming RESTful APIs. OData helps you focus on your business logic while building RESTful APIs without having to worry about the approaches to define request and response headers, status codes, HTTP methods, URL conventions, media types, payload formats and query options etc. OData also guides you about tracking changes, defining functions/actions for reusable procedures and sending asynchronous/batch requests etc. Additionally, OData provides facility for extension to fulfil any custom needs of your RESTful APIs.

OData RESTful APIs are easy to consume. The OData metadata, a machine-readable description of the data model of the APIs, enables the creation of powerful generic client proxies and tools. Some of them can help you interact with OData even without knowing anything about the protocol. The following 6 steps demonstrate 6 interesting scenarios of OData consumption across different programming platforms. But if you are a non-developer and would like to simply play with OData, XOData is the best start for you.

for more details at http://www.odata.org/

How to subtract hours from a date in Oracle so it affects the day also

Others have commented on the (incorrect) use of 2/11 to specify the desired interval.

I personally however prefer writing things like that using ANSI interval literals which makes reading the query much easier:

sysdate - interval '2' hour

It also has the advantage of being portable, many DBMS support this. Plus I don't have to fire up a calculator to find out how many hours the expression means - I'm pretty bad with mental arithmetics ;)

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Your json string is wrapped within square brackets ([]), hence it is interpreted as array instead of single RetrieveMultipleResponse object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse, for example :

var objResponse1 = 
    JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);

Convert Current date to integer

Probably You can not, Long is higher datatype than Integer.

or this link might help you

http://www.velocityreviews.com/forums/t142373-convert-date-to-integer-and-back.html

What are the minimum margins most printers can handle?

For every PostScript printer, one part of its driver is an ASCII file called PostScript Printer Description (PPD). PPDs are used in the CUPS printing system on Linux and Mac OS X as well even for non-PostScript printers.

Every PPD MUST, according to the PPD specification written by Adobe, contain definitions of a *ImageableArea (that's a PPD keyword) for each and every media sizes it can handle. That value is given for example as *ImageableArea Folio/8,25x13: "12 12 583 923" for one printer in this office here, and *ImageableArea Folio/8,25x13: "0 0 595 935" for the one sitting in the next room.

These figures mean "Lower left corner is at (12|12), upper right corner is at (583|923)" (where these figures are measured in points; 72pt == 1inch). Can you see that the first printer does print with a margin of 1/6 inch? -- Can you also see that the next one can even print borderless?

What you need to know is this: Even if the printer can do very small margins physically, if the PPD *ImageableArea is set to a wider margin, the print data generated by the driver and sent to the printer will be clipped according to the PPD setting -- not by the printer itself.

These days more and more models appear on the market which can indeed print edge-to-edge. This is especially true for office laser printers. (Don't know about devices for the home use market.) Sometimes you have to enable that borderless mode with a separate switch in the driver settings, sometimes also on the device itself (front panel, or web interface).

Older models, for example HP's, define in their PPDs their margines quite generously, just to be on the supposedly "safe side". Very often HP used 1/3, 1/2 inch or more (like "24 24 588 768" for Letter format). I remember having hacked HP PPDs and tuned them down to "6 6 606 786" (1/12 inch) before the physical boundaries of the device kicked in and enforced a real clipping of the page image.

Now, PCL and other language printers are not that much different in their margin capabilities from PostScript models.

But of course, when it comes to printing of PDF docs, here you can nearly always choose "print to fit" or similarly named options. Even for a file that itself does not use any margins. That "fit" is what the PDF viewer reads from the driver, and the viewer then scales down the page to the *ImageableArea.

jQuery - Uncaught RangeError: Maximum call stack size exceeded

your fadeIn() function calls the fadeOut() function, which calls the fadeIn() function again. the recursion is in the JS.

How to validate an OAuth 2.0 access token for a resource server?

Google way

Google Oauth2 Token Validation

Request:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=1/fFBGRNJru1FQd44AzqT3Zg

Respond:

{
  "audience":"8819981768.apps.googleusercontent.com",
  "user_id":"123456789",
  "scope":"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
  "expires_in":436
} 

Microsoft way

Microsoft - Oauth2 check an authorization

Github way

Github - Oauth2 check an authorization

Request:

GET /applications/:client_id/tokens/:access_token

Respond:

{
  "id": 1,
  "url": "https://api.github.com/authorizations/1",
  "scopes": [
    "public_repo"
  ],
  "token": "abc123",
  "app": {
    "url": "http://my-github-app.com",
    "name": "my github app",
    "client_id": "abcde12345fghij67890"
  },
  "note": "optional note",
  "note_url": "http://optional/note/url",
  "updated_at": "2011-09-06T20:39:23Z",
  "created_at": "2011-09-06T17:26:27Z",
  "user": {
    "login": "octocat",
    "id": 1,
    "avatar_url": "https://github.com/images/error/octocat_happy.gif",
    "gravatar_id": "somehexcode",
    "url": "https://api.github.com/users/octocat"
  }
}

Amazon way

Login With Amazon - Developer Guide (Dec. 2015, page 21)

Request :

https://api.amazon.com/auth/O2/tokeninfo?access_token=Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSR...

Response :

HTTP/l.l 200 OK
Date: Fri, 3l May 20l3 23:22:l0 GMT 
x-amzn-RequestId: eb5be423-ca48-lle2-84ad-5775f45l4b09 
Content-Type: application/json 
Content-Length: 247 

{ 
  "iss":"https://www.amazon.com", 
  "user_id": "amznl.account.K2LI23KL2LK2", 
  "aud": "amznl.oa2-client.ASFWDFBRN", 
  "app_id": "amznl.application.436457DFHDH", 
  "exp": 3597, 
  "iat": l3ll280970
}

Read a file line by line assigning the value to a variable

Use IFS (internal field separator) tool in bash, defines the character using to separate lines into tokens, by default includes <tab> /<space> /<newLine>

step 1: Load the file data and insert into list:

# declaring array list and index iterator
declare -a array=()
i=0

# reading file in row mode, insert each line into array
while IFS= read -r line; do
    array[i]=$line
    let "i++"
    # reading from file path
done < "<yourFullFilePath>"

step 2: now iterate and print the output:

for line in "${array[@]}"
  do
    echo "$line"
  done

echo specific index in array: Accessing to a variable in array:

echo "${array[0]}"

How to make the window full screen with Javascript (stretching all over the screen)

Try this script

<script language="JavaScript">
function fullScreen(theURL) {
window.open(theURL, '', 'fullscreen=yes, scrollbars=auto' );
}
</script>

For calling from script use this code,

window.fullScreen('fullscreen.jsp');

or with hyperlink use this

<a href="javascript:void(0);" onclick="fullScreen('fullscreen.jsp');"> 
Open in Full Screen Window</a>

how to remove empty strings from list, then remove duplicate values from a list

dtList  = dtList.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList()

I assumed empty string and whitespace are like null. If not you can use IsNullOrEmpty (allow whitespace), or s != null

How to display pie chart data values of each slice in chart.js

Easiest way to do this with Chartjs. Just add below line in options:

pieceLabel: {
        fontColor: '#000'
    }

Best of luck

React - How to force a function component to render?

None of these gave me a satisfactory answer so in the end I got what I wanted with the key prop, useRef and some random id generator like shortid.

Basically, I wanted some chat application to play itself out the first time someone opens the app. So, I needed full control over when and what the answers are updated with the ease of async await.

Example code:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// ... your JSX functional component, import shortid somewhere

const [render, rerender] = useState(shortid.generate())

const messageList = useRef([
    new Message({id: 1, message: "Hi, let's get started!"})
])

useEffect(()=>{
    await sleep(500)
    messageList.current.push(new Message({id: 1, message: "What's your name?"}))
    // ... more stuff
    // now trigger the update
    rerender(shortid.generate())
}, [])

// only the component with the right render key will update itself, the others will stay as is and won't rerender.
return <div key={render}>{messageList.current}</div> 

In fact this also allowed me to roll something like a chat message with a rolling .

const waitChat = async (ms) => {
    let text = "."
    for (let i = 0; i < ms; i += 200) {
        if (messageList.current[messageList.current.length - 1].id === 100) {
            messageList.current = messageList.current.filter(({id}) => id !== 100)
        }
        messageList.current.push(new Message({
            id: 100,
            message: text
        }))
        if (text.length === 3) {
            text = "."
        } else {
            text += "."
        }
        rerender(shortid.generate())
        await sleep(200)
    }
    if (messageList.current[messageList.current.length - 1].id === 100) {
        messageList.current = messageList.current.filter(({id}) => id !== 100)
    }
}

Getting an element from a Set

Why:

It seems that Set plays a useful role in providing a means of comparison. It is designed not to store duplicate elements.

Because of this intention/design, if one were to get() a reference to the stored object, then mutate it, it is possible that the design intentions of Set could be thwarted and could cause unexpected behavior.

From the JavaDocs

Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set.

How:

Now that Streams have been introduced one can do the following

mySet.stream()
.filter(object -> object.property.equals(myProperty))
.findFirst().get();

Can I catch multiple Java exceptions in the same catch clause?

If there is a hierarchy of exceptions you can use the base class to catch all subclasses of exceptions. In the degenerate case you can catch all Java exceptions with:

try {
   ...
} catch (Exception e) {
   someCode();
}

In a more common case if RepositoryException is the the base class and PathNotFoundException is a derived class then:

try {
   ...
} catch (RepositoryException re) {
   someCode();
} catch (Exception e) {
   someCode();
}

The above code will catch RepositoryException and PathNotFoundException for one kind of exception handling and all other exceptions are lumped together. Since Java 7, as per @OscarRyz's answer above:

try { 
  ...
} catch( IOException | SQLException ex ) { 
  ...
}

Converting Epoch time into the datetime

Try this:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1347517119))
'2012-09-12 23:18:39'

Also in MySQL, you can FROM_UNIXTIME like:

INSERT INTO tblname VALUES (FROM_UNIXTIME(1347517119))

For your 2nd question, it is probably because getbbb_class.end_time is a string. You can convert it to numeric like: float(getbbb_class.end_time)

Delete all files of specific type (extension) recursively down a directory using a batch file

You can use wildcards with the del command, and /S to do it recursively.

del /S *.jpg

Addendum

@BmyGuest asked why a downvoted answer (del /s c:\*.blaawbg) was any different than my answer.

There's a huge difference between running del /S *.jpg and del /S C:\*.jpg. The first command is executed from the current location, whereas the second is executed on the whole drive.

In the scenario where you delete jpg files using the second command, some applications might stop working, and you'll end up losing all your family pictures. This is utterly annoying, but your computer will still be able to run.

However, if you are working on some project, and want to delete all your dll files in myProject\dll, and run the following batch file:

@echo off

REM This short script will only remove dlls from my project... or will it?

cd \myProject\dll
del /S /Q C:\*.dll

Then you end up removing all dll files form your C:\ drive. All of your applications stop working, your computer becomes useless, and at the next reboot you are teleported in the fourth dimension where you will be stuck for eternity.

The lesson here is not to run such command directly at the root of a drive (or in any other location that might be dangerous, such as %windir%) if you can avoid it. Always run them as locally as possible.

Addendum 2

The wildcard method will try to match all file names, in their 8.3 format, and their "long name" format. For example, *.dll will match project.dll and project.dllold, which can be surprising. See this answer on SU for more detailed information.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.

In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : multiparts) {
        if (!item.isFormField()) {
            //your operations on file
        } else {
            String name = item.getFieldName();
            String value = item.getString();
            //you operations on paramters
        }
}

IIS: Where can I find the IIS logs?

The 100% correct answer for the default location of the log files is...

%SystemDrive%\inetpub\logs\LogFiles

Yes you can enter this into the explorer address bar it'll work.

To be 100% sure, you need to look at the logging for the web site in IIS.

https://docs.microsoft.com/en-us/iis/get-started/whats-new-in-iis-85/enhanced-logging-for-iis85

i.e.

  1. Open IIS Manager.
  2. Select the site or server in the Connections pane,
  3. Double-click Logging.
  4. The location of log files for the site can be found within the Directory field

EDIT: As pointed out by Andy in the comments below you need to ensure when installing IIS that you elected to enable HTTP logging, otherwise HTTP logging won't be available.

Enable HTTP Logging

How to remove class from all elements jquery

try: $(".highlight").removeClass("highlight");. By selecting $(".edgetoedge") you are only running functions at that level.

What USB driver should we use for the Nexus 5?

While Nexus 5 owners wait for a dedicated driver, you could try this driver, which is the one for the LG G2, from LG Electronics' website, since usually USB drivers are not limited to one particular model. This one, for example, seems like a generic USB driver. You are prompted to download the same one for quite a few models on LG Electronics' website.

I hope this helps you ;)

Array functions in jQuery

An easy way to get the max and min value in an array is as follows. This has been explained at get max & min values in array

var myarray = [5,8,2,4,11,7,3];
// Function to get the Max value in Array
Array.max = function( array ){
return Math.max.apply( Math, array );
};

// Function to get the Min value in Array
Array.min = function( array ){
return Math.min.apply( Math, array );
};
// Usage 
alert(Array.max(myarray));
alert(Array.min(myarray));

Application_Start not firing?

I had made some changes based on "Code Analysis on Build" from Visual Studio. Code Analysis suggested "CA1822 Mark members as static" for Application_Start() in Global.asax. I did that and ended up with this problem.

I suggest suppressing this Code Analysis message, and not alter the signature of methods/classes automatically created by platform used for bootstrapping the Application. The signature of the method Application_Start probably was non-static for a reason.

I reverted to this method-signature and Application_Start() was firing again:

    protected void Application_Start()
    { ... }

Check if specific input file is empty

if(!empty($_FILES)) { // code if not uploaded } else { // code if uploaded }

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

How to determine the current iPhone/device model?

There is a helper library for this.

Swift 5

pod 'DeviceKit', '~> 2.0'

Swift 4.0 - Swift 4.2

pod 'DeviceKit', '~> 1.3'

if you just want to determine the model and make something accordingly.

You can use like that :

let isIphoneX = Device().isOneOf([.iPhoneX, .simulator(.iPhoneX)])

In a function :

func isItIPhoneX() -> Bool {
    let device = Device()
    let check = device.isOneOf([.iPhoneX, .iPhoneXr , .iPhoneXs , .iPhoneXsMax ,
                                .simulator(.iPhoneX), .simulator(.iPhoneXr) , .simulator(.iPhoneXs) , .simulator(.iPhoneXsMax) ])
    return check
}

How to center the text in a JLabel?

myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.

Regular expression to match balanced parentheses

While so many answers mention this in some form by saying that regex does not support recursive matching and so on, the primary reason for this lies in the roots of the Theory of Computation.

Language of the form {a^nb^n | n>=0} is not regular. Regex can only match things that form part of the regular set of languages.

Read more @ here

How can you detect the version of a browser?

I want to share this code I wrote for the issue I had to resolve. It was tested in most of the major browsers and works like a charm, for me!

It may seems that this code is very similar to the other answers but it modifyed so that I can use it insted of the browser object in jquery which missed for me recently, of course it is a combination from the above codes, with little improvements from my part I made:

(function($, ua){

var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
    tem, 
    res;

if(/trident/i.test(M[1])){
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    res = 'IE ' + (tem[1] || '');
}
else if(M[1] === 'Chrome'){
    tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
    if(tem != null) 
        res = tem.slice(1).join(' ').replace('OPR', 'Opera');
    else
        res = [M[1], M[2]];
}
else {
    M = M[2]? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if((tem = ua.match(/version\/(\d+)/i)) != null) M = M.splice(1, 1, tem[1]);
    res = M;
}

res = typeof res === 'string'? res.split(' ') : res;

$.browser = {
    name: res[0],
    version: res[1],
    msie: /msie|ie/i.test(res[0]),
    firefox: /firefox/i.test(res[0]),
    opera: /opera/i.test(res[0]),
    chrome: /chrome/i.test(res[0]),
    edge: /edge/i.test(res[0])
}

})(typeof jQuery != 'undefined'? jQuery : window.$, navigator.userAgent);

 console.log($.browser.name, $.browser.version, $.browser.msie); 
// if IE 11 output is: IE 11 true

How to call codeigniter controller function from view

One idea i can give is,

Call that function in controller itself and return value to view file. Like,

class Business extends CI_Controller {
    public function index() {
            $data['css'] = 'profile';

            $data['cur_url'] = $this->getCurrURL(); // the function called and store val
            $this->load->view("home_view",$data);
     }
     function getCurrURL() {
                $currURL='http://'.$_SERVER['HTTP_HOST'].'/'.ltrim($_SERVER['REQUEST_URI'],'/').'';
            return $currURL;
     }

}

in view(home_view.php) use that variable. Like,

echo $cur_url;

Spring Boot Configure and Use Two DataSources

I also had to setup connection to 2 datasources from Spring Boot application, and it was not easy - the solution mentioned in the Spring Boot documentation didn't work. After a long digging through the internet I made it work and the main idea was taken from this article and bunch of other places.

The following solution is written in Kotlin and works with Spring Boot 2.1.3 and Hibernate Core 5.3.7. Main issue was that it was not enough just to setup different DataSource configs, but it was also necessary to configure EntityManagerFactory and TransactionManager for both databases.

Here is config for the first (Primary) database:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "firstDbEntityManagerFactory",
    transactionManagerRef = "firstDbTransactionManager",
    basePackages = ["org.path.to.firstDb.domain"]
)
@EnableTransactionManagement
class FirstDbConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.firstDb")
    fun firstDbDataSource(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Primary
    @Bean(name = ["firstDbEntityManagerFactory"])
    fun firstDbEntityManagerFactory(
        builder: EntityManagerFactoryBuilder,
        @Qualifier("firstDbDataSource") dataSource: DataSource
    ): LocalContainerEntityManagerFactoryBean {
        return builder
            .dataSource(dataSource)
            .packages(SomeEntity::class.java)
            .persistenceUnit("firstDb")
            // Following is the optional configuration for naming strategy
            .properties(
                singletonMap(
                    "hibernate.naming.physical-strategy",
                    "org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl"
                )
            )
            .build()
    }

    @Primary
    @Bean(name = ["firstDbTransactionManager"])
    fun firstDbTransactionManager(
        @Qualifier("firstDbEntityManagerFactory") firstDbEntityManagerFactory: EntityManagerFactory
    ): PlatformTransactionManager {
        return JpaTransactionManager(firstDbEntityManagerFactory)
    }
}

And this is config for second database:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "secondDbEntityManagerFactory",
    transactionManagerRef = "secondDbTransactionManager",
    basePackages = ["org.path.to.secondDb.domain"]
)
@EnableTransactionManagement
class SecondDbConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.secondDb")
    fun secondDbDataSource(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Bean(name = ["secondDbEntityManagerFactory"])
    fun secondDbEntityManagerFactory(
        builder: EntityManagerFactoryBuilder,
        @Qualifier("secondDbDataSource") dataSource: DataSource
    ): LocalContainerEntityManagerFactoryBean {
        return builder
            .dataSource(dataSource)
            .packages(EntityFromSecondDb::class.java)
            .persistenceUnit("secondDb")
            .build()
    }

    @Bean(name = ["secondDbTransactionManager"])
    fun secondDbTransactionManager(
        @Qualifier("secondDbEntityManagerFactory") secondDbEntityManagerFactory: EntityManagerFactory
    ): PlatformTransactionManager {
        return JpaTransactionManager(secondDbEntityManagerFactory)
    }
}

The properties for datasources are like this:

spring.datasource.firstDb.jdbc-url=
spring.datasource.firstDb.username=
spring.datasource.firstDb.password=

spring.datasource.secondDb.jdbc-url=
spring.datasource.secondDb.username=
spring.datasource.secondDb.password=

Issue with properties was that I had to define jdbc-url instead of url because otherwise I had an exception.

p.s. Also you might have different naming schemes in your databases, which was the case for me. Since Hibernate 5 does not support all previous naming schemes, I had to use solution from this answer - maybe it will also help someone as well.

Adding hours to JavaScript Date object?

The below code is to add 4 hours to date(example today's date)

var today = new Date();
today.setHours(today.getHours() + 4);

It will not cause error if you try to add 4 to 23 (see the docs):

If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly

How to initialize an array's length in JavaScript?

ES6 introduces Array.from which lets you create an Array from any "array-like" or iterables objects:

Array.from({length: 10}, (x, i) => i);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In this case {length: 10} represents the minimal definition of an "array-like" object: an empty object with just a length property defined.

Array.from allows for a second argument to map over the resulting array.

Connecting to Microsoft SQL server using Python

An alternative approach would be installing Microsoft ODBC Driver 13, then replace SQLOLEDB with ODBC Driver 13 for SQL Server

Regards.

How to alter a column's data type in a PostgreSQL table?

Cool @derek-kromm, Your answer is accepted and correct, But I am wondering if we need to alter more than the column. Here is how we can do.

ALTER TABLE tbl_name 
ALTER COLUMN col_name TYPE varchar (11), 
ALTER COLUMN col_name2 TYPE varchar (11),
ALTER COLUMN col_name3 TYPE varchar (11);

Documentation

Cheers!! Read Simple Write Simple

Ruby Arrays: select(), collect(), and map()

When dealing with a hash {}, use both the key and value to the block inside the ||.

details.map {|key,item|"" == item}

=>[false, false, true, false, false]

How can I get the named parameters from a URL using Flask?

Use request.args.get(param), for example:

http://10.1.1.1:5000/login?username=alex&password=pw1
@app.route('/login', methods=['GET', 'POST'])
def login():
    username = request.args.get('username')
    print(username)
    password = request.args.get('password')
    print(password)

Here is the referenced link to the code.

java.lang.NoClassDefFoundError in junit

When using in Maven, update artifact junit:junit from e.g. 4.8.2 to 4.11.

Select from one table matching criteria in another?

I have a similar problem (at least I think it is similar). In one of the replies here the solution is as follows:

select
    A.*
from
    table_A A
inner join table_B B
    on A.id = B.id
where
    B.tag = 'chair'

That WHERE clause I would like to be:

WHERE B.tag = A.<col_name>

or, in my specific case:

WHERE B.val BETWEEN A.val1 AND A.val2

More detailed:

Table A carries status information of a fleet of equipment. Each status record carries with it a start and stop time of that status. Table B carries regularly recorded, timestamped data about the equipment, which I want to extract for the duration of the period indicated in table A.

Check if number is decimal

function is_decimal_value( $a ) {
    $d=0; $i=0;
    $b= str_split(trim($a.""));
    foreach ( $b as $c ) {
        if ( $i==0 && strpos($c,"-") ) continue;
        $i++;
        if ( is_numeric($c) ) continue;
        if ( stripos($c,".") === 0 ) {
            $d++;
            if ( $d > 1 ) return FALSE;
            else continue;
        } else
        return FALSE;
    }
    return TRUE;
}

Known Issues with the above function:

1) Does not support "scientific notation" (1.23E-123), fiscal (leading $ or other) or "Trailing f" (C++ style floats) or "trailing currency" (USD, GBP etc)

2) False positive on string filenames that match a decimal: Please note that for example "10.0" as a filename cannot be distinguished from the decimal, so if you are attempting to detect a type from a string alone, and a filename matches a decimal name and has no path included, it will be impossible to discern.

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

Which type of folder structure should be used with Angular 2?

I am going to use this one. Very similar to third one shown by @Marin.

app
|
|___ images
|
|___ fonts
|
|___ css
|
|___ *main.ts*
|   
|___ *main.component.ts*
|
|___ *index.html*
|
|___ components
|   |
|   |___ shared
|   |
|   |___ home
|   |
|   |___ about
|   |
|   |___ product
|
|___ services
|
|___ structures

How can I merge the columns from two tables into one output?

I had a similar problem with a small difference: some a.category_id are not in b and some b.category_id are not in a.
To solve this problem just adapt the excelent answer from beny23 to

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from items_a a
LEFT OUTER JOIN
items_b b 
on a.category_id = b.category_id

Hope this helps someone.
Regards.

How to launch an EXE from Web page (asp.net)

if the applications are C#, you can use ClickOnce deployment, which is a good option if you can't guarentee the user will have the app, however you'll have to re-build the apps with deployment options and grab some boilerplate code from each project.

You can also use Javascript.

Or you can register an application to handle a new web protocol you can define. This could also be an "app selection" protocol, so each time an app is clicked it would link to a page on your new protocol, all handling of this protocol is then passed to your "selection app" which uses arguments to find and launch an app on the clients PC.

HTH

Validate IPv4 address in Java

Regular Expression is the most efficient way to solve this problem. Look at the code below. Along validity, it also checks IP address class in which it belongs and whether it is reserved IP Address or not

Pattern ipPattern;
int[] arr=new int[4];
int i=0;

//Method to check validity
 private String validateIpAddress(String ipAddress) {
      Matcher ipMatcher=ipPattern.matcher(ipAddress);

        //Condition to check input IP format
        if(ipMatcher.matches()) {       

           //Split input IP Address on basis of .
           String[] octate=ipAddress.split("[.]");     
           for(String x:octate) { 

              //Convert String number into integer
              arr[i]=Integer.parseInt(x);             
              i++;
         }

        //Check whether input is Class A IP Address or not
         if(arr[0]<=127) {                          
             if(arr[0]==0||arr[0]==127)
                 return(" is Reserved IP Address of Class A");
             else if(arr[1]==0&&arr[2]==0&&arr[3]==0)
                 return(" is Class A Network address");
             else if(arr[1]==255&&arr[2]==255&&arr[3]==255)
                 return( " is Class A Broadcast address");
             else 
                 return(" is valid IP Address of Class A");
         }

        //Check whether input is Class B IP Address or not
         else if(arr[0]>=128&&arr[0]<=191) {        
             if(arr[2]==0&&arr[3]==0)
                 return(" is Class B Network address");
             else if(arr[2]==255&&arr[3]==255)
                 return(" is Class B Broadcast address");
             else
                 return(" is valid IP Address of Class B");
         }

        //Check whether input is Class C IP Address or not
         else if(arr[0]>=192&&arr[0]<=223) {        
             if(arr[3]==0)
                 return(" is Class C Network address");
             else if(arr[3]==255)
                 return(" is Class C Broadcast address");
             else
                 return( " is valid IP Address of Class C");
        }

        //Check whether input is Class D IP Address or not
        else if(arr[0]>=224&&arr[0]<=239) {          
             return(" is Class D IP Address Reserved for multicasting");
        }

        //Execute if input is Class E IP Address
        else  {                                   
             return(" is Class E IP Address Reserved for Research and Development by DOD");
        }

    }

    //Input not matched with IP Address pattern
    else                                     
        return(" is Invalid IP Address");


}


public static void main(String[] args) {

    Scanner scan= new Scanner(System.in);
    System.out.println("Enter IP Address: ");

    //Input IP Address from user
    String ipAddress=scan.nextLine();  
    scan.close();
    IPAddress obj=new IPAddress();

    //Regex for IP Address
    obj.ipPattern=Pattern.compile("((([0-1]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([0-1]?\\d\\d?|2[0-4]\\d|25[0-5]))");

    //Display output
    System.out.println(ipAddress+ obj.validateIpAddress(ipAddress));

}

How to setup Main class in manifest file in jar produced by NetBeans project

In 7.3 just enable Properties/Build/Package/Copy Dependent Libraries and main class will be added to manifest when building depending on selected target.

Can I install/update WordPress plugins without providing FTP access?

As stated before none of the perm fixes work anymore. You need to change the perms accordingly AND put the following in your wp-config.php:

define('FS_METHOD', 'direct');

iOS9 Untrusted Enterprise Developer with no option to trust

On iOS 9.2 Profiles renamed to Device Management.
Now navigation looks like that:
Settings -> General -> Device Management -> Tap on necessary profile in list -> Trust.

Oracle: SQL query that returns rows with only numeric values

You can use following command -

LENGTH(TRIM(TRANSLATE(string1, '+-.0123456789', '')))

This will return NULL if your string1 is Numeric

your query would be -

select * from tablename 
where LENGTH(TRIM(TRANSLATE(X, '+-.0123456789', ''))) is null

Get form data in ReactJS

If all your inputs / textarea have a name, then you can filter all from event.target:

onSubmit(event){
  const fields = Array.prototype.slice.call(event.target)
      .filter(el => el.name)
      .reduce((form, el) => ({
        ...form,
        [el.name]: el.value,
      }), {})
}

Totally uncontrolled form without onChange methods, value, defaultValue...

How to find out mySQL server ip address from phpmyadmin

MySQL doesn't care what IP its on. Closest you could get would be hostname:

select * from GLOBAL_variables where variable_name like 'hostname';

How do I find the current executable filename?

Environment.GetCommandLineArgs()[0]

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

Finaly I found another answer for this problem. and this is working for me. Just add below datas to the your webconfig file.

<configuration>
 <system.webServer>
  <security>
   <requestFiltering>
    <verbs allowUnlisted="true">
     <add verb="OPTIONS" allowed="false" />
    </verbs>
   </requestFiltering>
  </security>
 </system.webServer>
</configuration>

Form more information, you can visit this web site: http://www.iis.net/learn/manage/configuring-security/use-request-filtering

if you want to test your web site, is it working or not... You can use "HttpRequester" mozilla firefox plugin. for this plugin: https://addons.mozilla.org/En-us/firefox/addon/httprequester/

How to receive POST data in django

You should have access to the POST dictionary on the request object.

Are loops really faster in reverse?

The best approach to answering this sort of question is to actually try it. Set up a loop that counts a million iterations or whatever, and do it both ways. Time both loops, and compare the results.

The answer will probably depend on which browser you are using. Some will have different results than others.

Swift presentViewController

Solved the black screen by adding a navigation controller and setting the second view controller as rootVC.

let vc = ViewController()       
var navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil

Wait until flag=true

If you are allowed to use: async/await on your code, you can try this one:

const waitFor = async (condFunc: () => boolean) => {
  return new Promise((resolve) => {
    if (condFunc()) {
      resolve();
    }
    else {
      setTimeout(async () => {
        await waitFor(condFunc);
        resolve();
      }, 100);
    }
  });
};

const myFunc = async () => {
  await waitFor(() => (window as any).goahead === true);
  console.log('hello world');
};

myFunc();

Demo here: https://stackblitz.com/edit/typescript-bgtnhj?file=index.ts

On the console, just copy/paste: goahead = true.

What's the best mock framework for Java?

I am the creator of PowerMock so obviously I must recommend that! :-)

PowerMock extends both EasyMock and Mockito with the ability to mock static methods, final and even private methods. The EasyMock support is complete, but the Mockito plugin needs some more work. We are planning to add JMock support as well.

PowerMock is not intended to replace other frameworks, rather it can be used in the tricky situations when other frameworks does't allow mocking. PowerMock also contains other useful features such as suppressing static initializers and constructors.

How to get client IP address in Laravel 5+

Solution 1: You can use this type of function for getting client IP

public function getClientIPaddress(Request $request) {
    $clientIp = $request->ip();
    return $clientIp;
}

Solution 2: if the solution1 is not providing accurate IP then you can use this function for getting visitor real IP.

 public function getClientIPaddress(Request $request) {

    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
        $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
        $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
    }
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP)){
        $clientIp = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP)){
        $clientIp = $forward;
    }
    else{
        $clientIp = $remote;
    }

    return $clientIp;
 }

N.B: When you have used load-balancer/proxy-server in your live server then you need to used solution 2 for getting real visitor ip.

How to write header row with csv.DictWriter?

Edit:
In 2.7 / 3.2 there is a new writeheader() method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader() method now available in 2.7 / 3.2:

from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
    dw.writeheader()
    # continue on to write data

Instantiating DictWriter requires a fieldnames argument.
From the documentation:

The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with statement was added in 2.6. If using 2.5: from __future__ import with_statement

with open(infile,'rb') as fin:
    dr = csv.DictReader(fin, delimiter='\t')

# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    headers = {} 
    for n in dw.fieldnames:
        headers[n] = n
    dw.writerow(headers)
    for row in dr:
        dw.writerow(row)

As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:

with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
    for row in dr:
        dw.writerow(row)

jQuery.click() vs onClick

Go for this as it will give you both standard and performance.

 $('#myDiv').click(function(){
      //Some code
 });

As the second method is simple JavaScript code and is faster than jQuery. But here performance will be approximately the same.

SQL: sum 3 columns when one column has a null value?

I would try this:

select sum (case when TotalHousM is null then 0 else TotalHousM end)
       + (case when TotalHousT is null then 0 else TotalHousT end)
       + (case when TotalHousW is null then 0 else TotalHousW end)
       + (case when TotalHousTH is null then 0 else TotalHousTH end)
       + (case when TotalHousF is null then 0 else TotalHousF end)
       as Total
From LeaveRequest

Java's L number (long) specification

I hope you won't mind a slight tangent, but thought you may be interested to know that besides F (for float), D (for double), and L (for long), a proposal has been made to add suffixes for byte and shortY and S respectively. This would eliminate to the need to cast to bytes when using literal syntax for byte (or short) arrays. Quoting the example from the proposal:

MAJOR BENEFIT: Why is the platform better if the proposal is adopted?

cruddy code like

 byte[] stuff = { 0x00, 0x7F, (byte)0x80,  (byte)0xFF};

can be recoded as

 byte[] ufum7 = { 0x00y, 0x7Fy, 0x80y, 0xFFy };

Joe Darcy is overseeing Project Coin for Java 7, and his blog has been an easy way to track these proposals.

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Direct casting vs 'as' operator?

It really depends on whether you know if o is a string and what you want to do with it. If your comment means that o really really is a string, I'd prefer the straight (string)o cast - it's unlikely to fail.

The biggest advantage of using the straight cast is that when it fails, you get an InvalidCastException, which tells you pretty much what went wrong.

With the as operator, if o isn't a string, s is set to null, which is handy if you're unsure and want to test s:

string s = o as string;
if ( s == null )
{
    // well that's not good!
    gotoPlanB();
}

However, if you don't perform that test, you'll use s later and have a NullReferenceException thrown. These tend to be more common and a lot harder to track down once they happens out in the wild, as nearly every line dereferences a variable and may throw one. On the other hand, if you're trying to cast to a value type (any primitive, or structs such as DateTime), you have to use the straight cast - the as won't work.

In the special case of converting to a string, every object has a ToString, so your third method may be okay if o isn't null and you think the ToString method might do what you want.

How to get Text BOLD in Alert or Confirm box?

The alert() dialog is not rendered in HTML, and thus the HTML you have embedded is meaningless.

You'd need to use a custom modal to achieve that.

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

JPA getSingleResult() or null

Here's a good option for doing this:

public static <T> T getSingleResult(TypedQuery<T> query) {
    query.setMaxResults(1);
    List<T> list = query.getResultList();
    if (list == null || list.isEmpty()) {
        return null;
    }

    return list.get(0);
}

Video streaming over websockets using JavaScript

To answer the question:

What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?

Yes, Websocket can be used to transmit over 30 fps and even 60 fps.

The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.

Why should I use IHttpActionResult instead of HttpResponseMessage?

The Web API basically return 4 type of object: void, HttpResponseMessage, IHttpActionResult, and other strong types. The first version of the Web API returns HttpResponseMessage which is pretty straight forward HTTP response message.

The IHttpActionResult was introduced by WebAPI 2 which is a kind of wrap of HttpResponseMessage. It contains the ExecuteAsync() method to create an HttpResponseMessage. It simplifies unit testing of your controller.

Other return type are kind of strong typed classes serialized by the Web API using a media formatter into the response body. The drawback was you cannot directly return an error code such as a 404. All you can do is throwing an HttpResponseException error.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

You can fix this issue by deleting browser cookie from the begining of time. I have tried this and it is working fine for me.

To delete only cookies:

  1. hold down ctrl+shift+delete
  2. remove all check boxes except for cookies of course
  3. use the drop down on top to select "from the beginning of time
  4. click clear browsing data

Delete element in a slice

Rather than thinking of the indices in the [a:]-, [:b]- and [a:b]-notations as element indices, think of them as the indices of the gaps around and between the elements, starting with gap indexed 0 before the element indexed as 0.

enter image description here

Looking at just the blue numbers, it's much easier to see what is going on: [0:3] encloses everything, [3:3] is empty and [1:2] would yield {"B"}. Then [a:] is just the short version of [a:len(arrayOrSlice)], [:b] the short version of [0:b] and [:] the short version of [0:len(arrayOrSlice)]. The latter is commonly used to turn an array into a slice when needed.

Writing to an Excel spreadsheet

OpenPyxl is quite a nice library, built to read/write Excel 2010 xlsx/xlsm files:

https://openpyxl.readthedocs.io/en/stable

The other answer, referring to it is using the deperciated function (get_sheet_by_name). This is how to do it without it:

import openpyxl

wbkName = 'New.xlsx'        #The file should be created before running the code.
wbk = openpyxl.load_workbook(wbkName)
wks = wbk['test1']
someValue = 1337
wks.cell(row=10, column=1).value = someValue
wbk.save(wbkName)
wbk.close

How to import an Oracle database from dmp file and log file?

How was the database exported?

  • If it was exported using exp and a full schema was exported, then

    1. Create the user:

      create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
      
    2. Grant the rights:

      grant connect, create session, imp_full_database to <username>;
      
    3. Start the import with imp:

      imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
      
  • If it was exported using expdp, then start the import with impdp:

    impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
    

Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\).

Either move the export file to the above path or create a directory object to pointing to the path where the dmp file is present and pass the object name to the impdp command above.

How to view file history in Git?

Use git log to view the commit history. Each commit has an associated revision specifier that is a hash key (e.g. 14b8d0982044b0c49f7a855e396206ee65c0e787 and b410ad4619d296f9d37f0db3d0ff5b9066838b39). To view the difference between two different commits, use git diff with the first few characters of the revision specifiers of both commits, like so:

# diff between commits 14b8... and b410...
git diff 14b8..b410
# only include diff of specified files
git diff 14b8..b410 path/to/file/a path/to/file/b

If you want to get an overview over all the differences that happened from commit to commit, use git log or git whatchanged with the patch option:

# include patch displays in the commit history
git log -p
git whatchanged -p
# only get history of those commits that touch specified paths
git log path/a path/b
git whatchanged path/c path/d

Number of days between two dates in Joda-Time

Days Class

Using the Days class with the withTimeAtStartOfDay method should work:

Days.daysBetween(start.withTimeAtStartOfDay() , end.withTimeAtStartOfDay() ).getDays() 

curl_init() function not working

You need to install CURL support for php.

In Ubuntu you can install it via

sudo apt-get install php5-curl

If you're using apt-get then you won't need to edit any PHP configuration, but you will need to restart your Apache.

sudo /etc/init.d/apache2 restart

If you're still getting issues, then try and use phpinfo() to make sure that CURL is listed as installed. (If it isn't, then you may need to open another question, asking why your packages aren't installing.)

There is an installation manual in the PHP CURL documentation.