Programs & Examples On #Vhosts

How to redirect to a different domain using NGINX?

Temporary redirect

rewrite ^ http://www.RedirectToThisDomain.com$request_uri? redirect;

Permanent redirect

rewrite ^ http://www.RedirectToThisDomain.com$request_uri? permanent;

In nginx configuration file for specific site:

server {    
    server_name www.example.com;
    rewrite ^ http://www.RedictToThisDomain.com$request_uri? redirect;

}

Apache giving 403 forbidden errors

it doesn't, however, solve the problem, because on e.g. open SUSE Tumbleweed, custom source build is triggering the same 401 error on default web page, which is configured accordingly with Indexes and

Require all granted

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

Okay: This is what I did now and it's solved:

My httpd-vhosts.conf looks like this now:

<VirtualHost dropbox.local:80>
    DocumentRoot "E:/Documenten/Dropbox/Dropbox/dummy-htdocs"
    ServerName dropbox.local
    ErrorLog "logs/dropbox.local-error.log"
    CustomLog "logs/dropbox.local-access.log" combined
    <Directory "E:/Documenten/Dropbox/Dropbox/dummy-htdocs">
        # AllowOverride All      # Deprecated
        # Order Allow,Deny       # Deprecated
        # Allow from all         # Deprecated

        # --New way of doing it
        Require all granted    
    </Directory>
</VirtualHost>

First, I saw that it's necessary to have set the <Directory xx:xx> options. So I put the <Directory > [..] </Directory>-part INSIDE the <VirtualHost > [..] </VirtualHost>. After that, I added AllowOverride AuthConfig Indexes to the <Directory> options.

Now http://localhost also points to the dropbox-virtualhost. So I added dropbox.local to <VirtualHost *:80> which makes it as <VirtualHost dropbox.local:80>

FINALLY it works :D!

I'm a happy man! :) :)

I hope someone else can use this information.

C# - Simplest way to remove first occurrence of a substring from another string

You could use an extension method for fun. Typically I don't recommend attaching extension methods to such a general purpose class like string, but like I said this is fun. I borrowed @Luke's answer since there is no point in re-inventing the wheel.

[Test]
public void Should_remove_first_occurrance_of_string() {

    var source = "ProjectName\\Iteration\\Release1\\Iteration1";

    Assert.That(
        source.RemoveFirst("\\Iteration"),
        Is.EqualTo("ProjectName\\Release1\\Iteration1"));
}

public static class StringExtensions {
    public static string RemoveFirst(this string source, string remove) {
        int index = source.IndexOf(remove);
        return (index < 0)
            ? source
            : source.Remove(index, remove.Length);
    }
}

wget/curl large file from google drive

Here is workaround which I came up download files from Google Drive to my Google Cloud Linux shell.

  1. Share the file to PUBLIC and with Edit permissions using advanced sharing.
  2. You will get a sharing link which would have an ID. See the link:- drive.google.com/file/d/[ID]/view?usp=sharing
  3. Copy that ID and Paste it in the following link:-

googledrive.com/host/[ID]

  1. The above link would be our download link.
  2. Use wget to download the file:-

wget https://googledrive.com/host/[ID]

  1. This command will download the file with name as [ID] with no extension and but with same file size on the same location where you ran the wget command.
  2. Actually, I downloaded a zipped folder in my practice. so I renamed that awkward file using:-

mv [ID] 1.zip

  1. then using

unzip 1.zip

we will get the files.

How to get address location from latitude and longitude in Google Map.?

You have to make one ajax call to get the required result, in this case you can use Google API to get the same

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false

Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level

Converting string into datetime

It would do the helpful for converting string to datetime and also with time zone

def convert_string_to_time(date_string, timezone):
    from datetime import datetime
    import pytz
    date_time_obj = datetime.strptime(date_string[:26], '%Y-%m-%d %H:%M:%S.%f')
    date_time_obj_timezone = pytz.timezone(timezone).localize(date_time_obj)

    return date_time_obj_timezone

date = '2018-08-14 13:09:24.543953+00:00'
TIME_ZONE = 'UTC'
date_time_obj_timezone = convert_string_to_time(date, TIME_ZONE)

How do I get the offset().top value of an element without using jQuery?

use getBoundingClientRect if $el is the actual DOM object:

var top = $el.getBoundingClientRect().top;

JSFiddle

Fiddle will show that this will get the same value that jquery's offset top will give you

Edit: as mentioned in comments this does not account for scrolled content, below is the code that jQuery uses

https://github.com/jquery/jquery/blob/master/src/offset.js (5/13/2015)

offset: function( options ) {
    //...

    var docElem, win, rect, doc,
        elem = this[ 0 ];

    if ( !elem ) {
        return;
    }

    rect = elem.getBoundingClientRect();

    // Make sure element is not hidden (display: none) or disconnected
    if ( rect.width || rect.height || elem.getClientRects().length ) {
        doc = elem.ownerDocument;
        win = getWindow( doc );
        docElem = doc.documentElement;

        return {
            top: rect.top + win.pageYOffset - docElem.clientTop,
            left: rect.left + win.pageXOffset - docElem.clientLeft
        };
    }
}

Twitter bootstrap modal-backdrop doesn't disappear

Another point of view to this question. (I'm using the bootstrap.js version 3.3.6)

I mistaken initialize modal both by manually in javascript:

$('#myModal').modal({
   keyboard: false
})

and by using

data-toggle="modal"

in this button like example below (shown in document)

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>

so the result its create two instance of

<div class="modal-backdrop fade in"></div>

append to the body of my html when open the modal. This can be the cause when closing the modal by using function:

$('#myModal').modal('hide');

it remove only one backdrop instance (as show above) so the backdrop won't disappeared. But it did disappear if you use data-dismiss="modal" add on html as show in bootstrap doc.

So the solution to my problem is to only initialize modal manually in javascript and not using data attribute, In this way I can both close the modal manually and by using data-dismiss="modal" features.

Hope this will help if you encountered the same problem as me.

Make footer stick to bottom of page correctly

Use min-height as some pixel value, instead of %.
Like:

min-height:620px;
height:auto;

and footer as:

.footer {
    height:70px;
    clear:both;
    position:relative;
    bottom:0;
    width: 100%;
}

Send message to specific client with socket.io and node.js

io.sockets.sockets[socket.id].emit(...) worked for me in v0.9

Developing C# on Linux

Now Microsoft is migrating to open-source - see CoreFX (GitHub).

Purge Kafka Topic

Another, rather manual, approach for purging a topic is:

in the brokers:

  1. stop kafka broker
    sudo service kafka stop
  2. delete all partition log files (should be done on all brokers)
    sudo rm -R /kafka-storage/kafka-logs/<some_topic_name>-*

in zookeeper:

  1. run zookeeper command line interface
    sudo /usr/lib/zookeeper/bin/zkCli.sh
  2. use zkCli to remove the topic metadata
    rmr /brokers/topic/<some_topic_name>

in the brokers again:

  1. restart broker service
    sudo service kafka start

Dynamic height for DIV

calculate the height of each link no do this

document.getElementById("products").style.height= height_of_each_link* no_of_link

Override default Spring-Boot application.properties settings in Junit Test

I just configured min as the following :

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console


# changing the name of my data base for testing
spring.datasource.url= jdbc:h2:mem:mockedDB
spring.datasource.username=sa
spring.datasource.password=sa



# in testing i don`t need to know the port

#Feature that determines what happens when no accessors are found for a type
#(and there are no annotations to indicate it is meant to be serialized).
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false`enter code here`

How to get the full path of running process?

using System;
using System.Diagnostics;

class Program
{
    public static void printAllprocesses()
    {
        Process[] processlist = Process.GetProcesses();

        foreach (Process process in processlist)
        {
            try
            {
                String fileName = process.MainModule.FileName;
                String processName = process.ProcessName;

                Console.WriteLine("processName : {0},  fileName : {1}", processName, fileName);
            }catch(Exception e)
            {
                /* You will get access denied exception for system processes, We are skiping the system processes here */
            }

        }
    }

    static void Main()
    {
        printAllprocesses();
    }

}

How to quickly and conveniently create a one element arraylist

Yet another alternative is double brace initialization, e.g.

new ArrayList<String>() {{ add(s); }};

but it is inefficient and obscure. Therefore only suitable:

  • in code that doesn't mind memory leaks, such as most unit tests and other short-lived programs;
  • and if none of the other solutions apply, which I think implies you've scrolled all the way down here looking to populate a different type of container than the ArrayList in the question.

End of File (EOF) in C

That's a lot of questions.

  1. Why EOF is -1: usually -1 in POSIX system calls is returned on error, so i guess the idea is "EOF is kind of error"

  2. any boolean operation (including !=) returns 1 in case it's TRUE, and 0 in case it's FALSE, so getchar() != EOF is 0 when it's FALSE, meaning getchar() returned EOF.

  3. in order to emulate EOF when reading from stdin press Ctrl+D

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are the same. Numeric is functionally equivalent to decimal.

MSDN: decimal and numeric

Adding image inside table cell in HTML

You have a TH floating at the top of your table which isn't within a TR. Fix that.

With regards to your image problem you;re referencing the image absolutely from your computer's hard drive. Don't do that.

You also have a closing tag which shouldn't be there.

It should be:

<img src="h.gif" alt="" border="3" height="100" width="100" />

Also this:

<table border = 5 bordercolor = red align = center>

Your colspans are also messed up. You only seem to have three columns but have colspans of 14 and 4 in your code.

Should be:

<table border="5" bordercolor="red" align="center">

Also you have no DOCTYPE declared. You should at least add:

<!DOCTYPE html> 

java.io.InvalidClassException: local class incompatible:

One thing that could have happened:

  • 1: you create your serialized data with a given library A (version X)
  • 2: you then try to read this data with the same library A (but version Y)

Hence, at compile time for the version X, the JVM will generate a first Serial ID (for version X) and it will do the same with the other version Y (another Serial ID).

When your program tries to de-serialize the data, it can't because the two classes do not have the same Serial ID and your program have no guarantee that the two Serialized objects correspond to the same class format.

Assuming you changed your constructor in the mean time and this should make sense to you.

Array vs. Object efficiency in JavaScript

It's not really a performance question at all, since arrays and objects work very differently (or are supposed to, at least). Arrays have a continuous index 0..n, while objects map arbitrary keys to arbitrary values. If you want to supply specific keys, the only choice is an object. If you don't care about the keys, an array it is.

If you try to set arbitrary (numeric) keys on an array, you really have a performance loss, since behaviourally the array will fill in all indexes in-between:

> foo = [];
  []
> foo[100] = 'a';
  "a"
> foo
  [undefined, undefined, undefined, ..., "a"]

(Note that the array does not actually contain 99 undefined values, but it will behave this way since you're [supposed to be] iterating the array at some point.)

The literals for both options should make it very clear how they can be used:

var arr = ['foo', 'bar', 'baz'];     // no keys, not even the option for it
var obj = { foo : 'bar', baz : 42 }; // associative by its very nature

How to Add Date Picker To VBA UserForm

In Access 2013. Drop a "Text Box" control onto your form. On the Property Sheet for the control under the Format tab find the Format property. Set this to one of the date format options. Job's done.

Refresh a page using PHP

I've found two ways to refresh PHP content:

1. Using the HTML meta tag:

echo("<meta http-equiv='refresh' content='1'>"); //Refresh by HTTP 'meta'

2. Using PHP refresh rate:

$delay = 0; // Where 0 is an example of a time delay. You can use 5 for 5 seconds, for example!
header("Refresh: $delay;"); 

Cordova - Error code 1 for command | Command failed for

Faced same problem. Problem lies in required version not installed. Hack is simple Goto Platforms>platforms.json Edit platforms.json in front of android modify the version to the one which is installed on system.

How can I find an element by CSS class with XPath?

This selector should work but will be more efficient if you replace it with your suited markup:

//*[contains(@class, 'Test')]

Or, since we know the sought element is a div:

//div[contains(@class, 'Test')]

But since this will also match cases like class="Testvalue" or class="newTest", @Tomalak's version provided in the comments is better:

//div[contains(concat(' ', @class, ' '), ' Test ')]

If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):

//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]

Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.

What do these operators mean (** , ^ , %, //)?

You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:

  • The ** operator does exponentiation. a ** b is a raised to the b power. The same ** symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).
  • The ^ operator does a binary xor. a ^ b will return a value with only the bits set in a or in b but not both. This one is simple!
  • The % operator is mostly to find the modulus of two integers. a % b returns the remainder after dividing a by b. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b, rather than the same sign as a. The same operator is also used for the "old" style of string formatting, so a % b can return a string if a is a format string and b is a value (or tuple of values) which can be inserted into a.
  • The // operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b). In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division at the top of your files. I strongly recommend it!)

How to use if, else condition in jsf to display image

Instead of using the "c" tags, you could also do the following:

<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />

<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>

I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?

jQuery get selected option value (not the text, but the attribute 'value')

For a select like this

<select class="btn btn-info pull-right" id="list-name" style="width: auto;">
   <option id="0">CHOOSE AN OPTION</option>
   <option id="127">John Doe</option>
   <option id="129" selected>Jane Doe</option>

... you can get the id this way:

$('#list-name option:selected').attr('id');

Or you can use value instead, and get it the easy way...

<select class="btn btn-info pull-right" id="list-name" style="width: auto;">
   <option value="0">CHOOSE AN OPTION</option>
   <option value="127">John Doe</option>
   <option value="129" selected>Jane Doe</option>

like this:

$('#list-name').val();

Using momentjs to convert date to epoch then back to date

There are a few things wrong here:

  • First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".

  • .unix() returns Unix Time in whole seconds, but the default moment constructor accepts a timestamp in milliseconds. You should instead use .valueOf() to return milliseconds. Note that calling .unix()*1000 would also work, but it would result in a loss of precision.

  • You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:

    moment("10/15/2014 9:00", "M/D/YYYY H:mm")
    
  • .calendar() has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format() function instead. Again, you may want to pass a format specifier.

  • To answer your questions in comments, No - you don't need to call .local() or .utc().

Putting it all together:

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);

On my machine, in the US Pacific time zone, it results in:

Values are: ts = 1413388800000, s = 10/15/2014 9:00

Since the input value is interpreted in terms of local time, you will get a different value for ts if you are in a different time zone.

Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix() to return the timestamp in whole seconds, and moment.unix(ts) to parse it back to a moment.

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);

How to do a subquery in LINQ?

This is how I've been doing subqueries in LINQ, I think this should get what you want. You can replace the explicit CompanyRoleId == 2... with another subquery for the different roles you want or join it as well.

from u in Users
join c in (
    from crt in CompanyRolesToUsers
    where CompanyRoleId == 2
    || CompanyRoleId == 3
    || CompanyRoleId == 4) on u.UserId equals c.UserId
where u.lastname.Contains("fra")
select u;

Export pictures from excel file into jpg using VBA

''' Set Range you want to export to the folder

Workbooks("your workbook name").Sheets("yoursheet name").Select

Dim rgExp As Range: Set rgExp = Range("A1:H31")
''' Copy range as picture onto Clipboard
rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
''' Create an empty chart with exact size of range copied
With ActiveSheet.ChartObjects.Add(Left:=rgExp.Left, Top:=rgExp.Top, _
Width:=rgExp.Width, Height:=rgExp.Height)
.Name = "ChartVolumeMetricsDevEXPORT"
.Activate
End With
''' Paste into chart area, export to file, delete chart.
ActiveChart.Paste
ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Chart.Export "C:\ExportmyChart.jpg"
ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Delete

How do I use the new computeIfAbsent function?

multi-map

This is really helpful if you want to create a multimap without resorting to the Google Guava library for its implementation of MultiMap.

For example, suppose you want to store a list of students who enrolled for a particular subject.

The normal solution for this using JDK library is:

Map<String,List<String>> studentListSubjectWise = new TreeMap<>();
List<String>lis = studentListSubjectWise.get("a");
if(lis == null) {
    lis = new ArrayList<>();
}
lis.add("John");

//continue....

Since it have some boilerplate code, people tend to use Guava Mutltimap.

Using Map.computeIfAbsent, we can write in a single line without guava Multimap as follows.

studentListSubjectWise.computeIfAbsent("a", (x -> new ArrayList<>())).add("John");

Stuart Marks & Brian Goetz did a good talk about this https://www.youtube.com/watch?v=9uTVXxJjuco

Overriding fields or properties in subclasses

Option 2 is a non-starter - you can't override fields, you can only hide them.

Personally, I'd go for option 1 every time. I try to keep fields private at all times. That's if you really need to be able to override the property at all, of course. Another option is to have a read-only property in the base class which is set from a constructor parameter:

abstract class Mother
{
    private readonly int myInt;
    public int MyInt { get { return myInt; } }

    protected Mother(int myInt)
    {
        this.myInt = myInt;
    }
}

class Daughter : Mother
{
    public Daughter() : base(1)
    {
    }
}

That's probably the most appropriate approach if the value doesn't change over the lifetime of the instance.

gpg: no valid OpenPGP data found

This problem might occur if you are behind corporate proxy and corporation uses its own certificate. Just add "--no-check-certificate" in the command. e.g. wget --no-check-certificate -qO - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -

It works. If you want to see what is going on, you can use verbose command instead of quiet before adding "--no-check-certificate" option. e.g. wget -vO - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add - This will tell you to use "--no-check-certificate" if you are behind proxy.

Vibrate and Sound defaults on notification

I m using the followung code and its working fine for me .

private void sendNotification(String msg) {
    Log.d(TAG, "Preparing to send notification...: " + msg);
    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("GCM Notification")
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    Log.d(TAG, "Notification sent successfully.");
}

Difference between int and double

int is a binary representation of a whole number, double is a double-precision floating point number.

Why is Git better than Subversion?

All the answers here are as expected, programmer centric, however what happens if your company uses revision control outside of source code? There are plenty of documents which aren't source code which benefit from version control, and should live close to code and not in another CMS. Most programmers don't work in isolation - we work for companies as part of a team.

With that in mind, compare ease of use, in both client tooling and training, between Subversion and git. I can't see a scenario where any distributed revision control system is going to be easier to use or explain to a non-programmer. I'd love to be proven wrong, because then I'd be able to evaluate git and actually have a hope of it being accepted by people who need version control who aren't programmers.

Even then, if asked by management why we should move from a centralised to distributed revision control system, I'd be hard pressed to give an honest answer, because we don't need it.

Disclaimer: I became interested in Subversion early on (around v0.29) so obviously I'm biased, but the companies I've worked for since that time are benefiting from my enthusiasm because I've encouraged and supported its use. I suspect this is how it happens with most software companies. With so many programmers jumping on the git bandwagon, I wonder how many companies are going to miss out on the benefits of using version control outside of source code? Even if you have separate systems for different teams, you're missing out on some of the benefits, such as (unified) issue tracking integration, whilst increasing maintenance, hardware and training requirements.

Git submodule head 'reference is not a tree' error

This may also happen when you have a submodule pointing to a repository that was rebased and the given commit is "gone". While the commit may still be in the remote repository, it is not in a branch. If you can't create a new branch (e.g. not your repository), you're stuck with having to update the super project to point to a new commit. Alternatively you can push one of your copies of the submodules elsewhere and then update the super-project to point to that repository instead.

How can I trigger the click event of another element in ng-click using angularjs?

If you are getting $scope binding errors make sure you wrap the click event code on a setTimeout Function.

VIEW

<input id="upload"
    type="file"
    ng-file-select="onFileSelect($files)"
    style="display: none;">

<button type="button"
    ng-click="clickUpload()">Upload</button>

CONTROLLER

$scope.clickUpload = function(){
    setTimeout(function () {
      angular.element('#upload').trigger('click');
    }, 0);
};

Is there a way to create and run javascript in Chrome?

if you don't want to create an explicitly a js file but still want to test your javascript code, you can use snippets to run your JS code.

Follow the steps here:

  1. Open Dev Tools
  2. Go to Sources Tab
  3. Under Sources tab go to snippets, + New snippet
  4. Past your JS code in the editor then run command + enter in Mac. You should see the output in console if you are using console.log or similar to test. You can edit the current web page that you have open or run scripts, load more javascript files. (Just note: this snippets are not stored on as a js file, unless you explicitly did, on your computer so if you remove chrome you will lose all your snippets);
  5. You also have a option to save as your snippet if you right click on your snippet.

code javascript using snippets in dev tools

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

How to get a value from the last inserted row?

If you are using Statement, go for the following

//MY_NUMBER is the column name in the database 
String generatedColumns[] = {"MY_NUMBER"};
Statement stmt = conn.createStatement();

//String sql holds the insert query
stmt.executeUpdate(sql, generatedColumns);

ResultSet rs = stmt.getGeneratedKeys();

// The generated id

if(rs.next())
long key = rs.getLong(1);

If you are using PreparedStatement, go for the following

String generatedColumns[] = {"MY_NUMBER"};
PreparedStatement pstmt = conn.prepareStatement(sql,generatedColumns);
pstmt.setString(1, "qwerty");

pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if(rs.next())
long key = rs.getLong(1);

Why can't I use background image and color together?

Make half of the image transparent so the background colour is seen through it.

Else simply add another div taking up 50% up the container div and float it either left or right. Then apply either the image or the colour to it.

jQuery: Clearing Form Inputs

You may try

$("#addRunner input").each(function(){ ... });

Inputs are no selectors, so you do not need the : Haven't tested it with your code. Just a fast guess!

Android: where are downloaded files saved?

Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard (or some variation of that name) which is usually symlinked to to a directory in /storage like /storage/sdcard0 or /storage/0 sometimes the emulated storage is mounted to /sdcard and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Since the filesystems and sdcard support varies among devices.

see similar question for more info how to access downloads folder in android?

Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard

Cron and virtualenv

I've added the following script as manage.sh inside my Django project, it sources the virtualenv and then runs the manage.py script with whatever arguments you pass to it. It makes it very easy in general to run commands inside the virtualenv (cron, systemd units, basically anywhere):

#! /bin/bash

# this is a convenience script that first sources the venv (assumed to be in
# ../venv) and then executes manage.py with whatever arguments you supply the
# script with. this is useful if you need to execute the manage.py from
# somewhere where the venv isn't sourced (e.g. system scripts)

# get the script's location
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# source venv <- UPDATE THE PATH HERE WITH YOUR VENV's PATH
source $DIR/../venv/bin/activate

# run manage.py script
$DIR/manage.py "$@"

Then in your cron entry you can just run:

0 3 * * * /home/user/project/manage.sh command arg

Just remember that you need to make the manage.sh script executable

Safely remove migration In Laravel

DO NOT run php artisan migrate:fresh that's gonna drop all the tables

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

TableExport

TableExport - The simple, easy-to-implement library to export HTML tables to xlsx, xls, csv, and txt files.

To use this library, simple call the TableExport constructor:

new TableExport(document.getElementsByTagName("table"));

// OR simply

TableExport(document.getElementsByTagName("table"));

// OR using jQuery

$("table").tableExport(); 

Additional properties can be passed-in to customize the look and feel of your tables, buttons, and exported data. See here more info

Create a HTML table where each TR is a FORM

You may have issues with column width, but you can set those explicitly.

<table>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  </table>

You may want to also consider making it a single form, and then using jQuery to select the form elements from the row you want, serialize them, and submit them as the form.

See: http://api.jquery.com/serialize/

Also, there are a number of very nice grid plugins: http://www.google.com/search?q=jquery+grid&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

load and execute order of scripts

After testing many options I've found that the following simple solution is loading the dynamically loaded scripts in the order in which they are added in all modern browsers

loadScripts(sources) {
    sources.forEach(src => {
        var script = document.createElement('script');
        script.src = src;
        script.async = false; //<-- the important part
        document.body.appendChild( script ); //<-- make sure to append to body instead of head 
    });
}

loadScripts(['/scr/script1.js','src/script2.js'])

What does 'IISReset' do?

When you change an ASP.NET website's configuration file, it restarts the application to reflect the changes...

When you do an IIS reset, that restarts all applications running on that IIS instance.

Listen for key press in .NET console app

From the video curse Building .NET Console Applications in C# by Jason Roberts at http://www.pluralsight.com

We could do following to have multiple running process

  static void Main(string[] args)
    {
        Console.CancelKeyPress += (sender, e) =>
        {

            Console.WriteLine("Exiting...");
            Environment.Exit(0);
        };

        Console.WriteLine("Press ESC to Exit");

        var taskKeys = new Task(ReadKeys);
        var taskProcessFiles = new Task(ProcessFiles);

        taskKeys.Start();
        taskProcessFiles.Start();

        var tasks = new[] { taskKeys };
        Task.WaitAll(tasks);
    }

    private static void ProcessFiles()
    {
        var files = Enumerable.Range(1, 100).Select(n => "File" + n + ".txt");

        var taskBusy = new Task(BusyIndicator);
        taskBusy.Start();

        foreach (var file in files)
        {
            Thread.Sleep(1000);
            Console.WriteLine("Procesing file {0}", file);
        }
    }

    private static void BusyIndicator()
    {
        var busy = new ConsoleBusyIndicator();
        busy.UpdateProgress();
    }

    private static void ReadKeys()
    {
        ConsoleKeyInfo key = new ConsoleKeyInfo();

        while (!Console.KeyAvailable && key.Key != ConsoleKey.Escape)
        {

            key = Console.ReadKey(true);

            switch (key.Key)
            {
                case ConsoleKey.UpArrow:
                    Console.WriteLine("UpArrow was pressed");
                    break;
                case ConsoleKey.DownArrow:
                    Console.WriteLine("DownArrow was pressed");
                    break;

                case ConsoleKey.RightArrow:
                    Console.WriteLine("RightArrow was pressed");
                    break;

                case ConsoleKey.LeftArrow:
                    Console.WriteLine("LeftArrow was pressed");
                    break;

                case ConsoleKey.Escape:
                    break;

                default:
                    if (Console.CapsLock && Console.NumberLock)
                    {
                        Console.WriteLine(key.KeyChar);
                    }
                    break;
            }
        }
    }
}

internal class ConsoleBusyIndicator
{
    int _currentBusySymbol;

    public char[] BusySymbols { get; set; }

    public ConsoleBusyIndicator()
    {
        BusySymbols = new[] { '|', '/', '-', '\\' };
    }
    public void UpdateProgress()
    {
        while (true)
        {
            Thread.Sleep(100);
            var originalX = Console.CursorLeft;
            var originalY = Console.CursorTop;

            Console.Write(BusySymbols[_currentBusySymbol]);

            _currentBusySymbol++;

            if (_currentBusySymbol == BusySymbols.Length)
            {
                _currentBusySymbol = 0;
            }

            Console.SetCursorPosition(originalX, originalY);
        }
    }

How do I check if there are duplicates in a flat list?

Recommended for short lists only:

any(thelist.count(x) > 1 for x in thelist)

Do not use on a long list -- it can take time proportional to the square of the number of items in the list!

For longer lists with hashable items (strings, numbers, &c):

def anydup(thelist):
  seen = set()
  for x in thelist:
    if x in seen: return True
    seen.add(x)
  return False

If your items are not hashable (sublists, dicts, etc) it gets hairier, though it may still be possible to get O(N logN) if they're at least comparable. But you need to know or test the characteristics of the items (hashable or not, comparable or not) to get the best performance you can -- O(N) for hashables, O(N log N) for non-hashable comparables, otherwise it's down to O(N squared) and there's nothing one can do about it:-(.

Get string character by index - Java

Like this:

String a ="hh1hhhhhhhh";
char s = a.charAt(3);

How do I correct this Illegal String Offset?

if(isset($rule["type"]) && ($rule["type"] == "radio") || ($rule["type"] == "checkbox") )
{
    if(!isset($data[$field]))
        $data[$field]="";
}

Programmatically register a broadcast receiver

for LocalBroadcastManager

   Intent intent = new Intent("any.action.string");
   LocalBroadcastManager.getInstance(context).
                                sendBroadcast(intent);

and register in onResume

LocalBroadcastManager.getInstance(
                    ActivityName.this).registerReceiver(chatCountBroadcastReceiver, filter);

and Unregister it onStop

LocalBroadcastManager.getInstance(
                ActivityName.this).unregisterReceiver(chatCountBroadcastReceiver);

and recieve it ..

mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("mBroadcastReceiver", "onReceive");
        }
    };

where IntentFilter is

 new IntentFilter("any.action.string")

Manually install Gradle and use it in Android Studio

https://services.gradle.org/distributions/

Download The Latest Gradle Distribution File and Extract It, Then Copy all Files and Paste it Under:

C:\Users\{USERNAME}\.gradle\wrapper\dists\

How can I convert an image into Base64 string using JavaScript?

As far as I know, an image can be converted into a Base64 string either by FileReader() or storing it in the canvas element and then use toDataURL() to get the image. I had the similar kind of problem you can refer this.

Convert an image to canvas that is already loaded

Text-align class for inside a table

Just add a "custom" stylesheet which is loaded after Bootstrap´s stylesheet. So the class definitions are overloaded.

In this stylesheet declare the alignment as follows:

.table .text-right {text-align: right}
.table .text-left {text-align: left}
.table .text-center {text-align: center}

Now you are able to use the "common" alignment conventions for td and th elements.

How to Apply Mask to Image in OpenCV?

You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.

BeanFactory vs ApplicationContext

In a real-time scenario, the difference between the Spring IOC Core container (BeanFactory) and Advanced J2EE container (ApplicationContext) are as follows.

  1. BeanFactory will create objects for the beans (i.e., for POJO classes) mentioned in the spring.xml file (<bean></bean>) only when you call the .getBean() method, but whereas ApplicationContext creates the objects for all the beans (<bean></bean> if its scope is not explicitly mentioned as "Prototype") configured in the spring.xml while loading the spring.xml file itself.

  2. BeanFactory: (Lazy container because it creates the objects for the beans only when you explicitly call from the user/main class)

    /*
     * Using core Container - Lazy container - Because it creates the bean objects On-Demand
     */
    //creating a resource
    Resource r = (Resource) new ClassPathResource("com.spring.resources/spring.xml");
    //creating BeanFactory 
    BeanFactory factory=new XmlBeanFactory(r);
    
    //Getting the bean for the POJO class "HelloWorld.java"
    HelloWorld worldObj1 = (HelloWorld) factory.getBean("test");
    

    ApplicationContext: (Eager container because of creating the objects of all singleton beans while loading the spring.xml file itself)

    ApplicationContext context = new ClassPathXmlApplicationContext("com/ioc/constructorDI/resources/spring.xml");
    
  3. Technically, using ApplicationContext is recommended because in real-time applications, the bean objects will be created while the application is getting started in the server itself. This reduces the response time for the user request as the objects are already available to respond.

Android: show/hide a view using an animation

Try this.

view.animate()
    .translationY(0)
    .alpha(0.0f)
    .setListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            view.setVisibility(View.GONE);
        }
    });

How to copy commits from one branch to another?

git cherry-pick : Apply the changes introduced by some existing commits

Assume we have branch A with (X, Y, Z) commits. We need to add these commits to branch B. We are going to use the cherry-pick operations.

When we use cherry-pick, we should add commits on branch B in the same chronological order that the commits appear in Branch A.

cherry-pick does support a range of commits, but if you have merge commits in that range, it gets really complicated

git checkout B
git cherry-pick SHA-COMMIT-X
git cherry-pick SHA-COMMIT-Y
git cherry-pick SHA-COMMIT-Z

Example of workflow :

enter image description here

We can use cherry-pick with options

-e or --edit : With this option, git cherry-pick will let you edit the commit message prior to committing.

-n or --no-commit : Usually the command automatically creates a sequence of commits. This flag applies the changes necessary to cherry-pick each named commit to your working tree and the index, without making any commit. In addition, when this option is used, your index does not have to match the HEAD commit. The cherry-pick is done against the beginning state of your index.

Here an interesting article concerning cherry-pick.

java.lang.IllegalArgumentException: contains a path separator

I got the above error message while trying to access a file from Internal Storage using openFileInput("/Dir/data.txt") method with subdirectory Dir.

You cannot access sub-directories using the above method.

Try something like:

FileInputStream fIS = new FileInputStream (new File("/Dir/data.txt"));

How do I apply the for-each loop to every character in a String?

In Java 8 we can solve it as:

String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));    

The method chars() returns an IntStream as mentioned in doc:

Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.

Why use forEachOrdered and not forEach ?

The behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this question for more.

We could also use codePoints() to print, see this answer for more details.

How do you convert a time.struct_time object into a datetime object?

Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.

from datetime import datetime
from time import mktime

dt = datetime.fromtimestamp(mktime(struct))

Remove files from Git commit

Just wanted to complement the top answer as I had to run an extra command:

git reset --soft HEAD^
git checkout origin/master <filepath>

Cheers!

Android - Launcher Icon Size

No need for third party tools when Android Studio can generate icons for us.

  • File -> New -> Image Asset

  • Then choose Launcher Icons as the Asset Type:

  • Choose a High-res image for the Image file:

Android Generate Launcher Icons

  • Next -> Finish to generate icons

generate ic laucher icons

Finally update android:icon name field in AndroidManifest.xml if required.

How to do a logical OR operation for integer comparison in shell scripting?

And in Bash

 line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
 vpid=`ps -ef|  grep wowzaDataSync | grep -v grep  | awk '{print $2}'`
 echo "-------->"${line1}
    if [ -z $line1 ] && [ ! -z $vpid ]
    then
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Process Is Working Fine"
    else
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Prcess Hanging Due To Exception With PID :"${pid}
   fi

OR in Bash

line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
vpid=`ps -ef|  grep wowzaDataSync | grep -v grep  | awk '{print $2}'`
echo "-------->"${line1}
   if [ -z $line1 ] || [ ! -z $vpid ]
    then
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Process Is Working Fine"
    else
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Prcess Hanging Due To Exception With PID :"${pid}
  fi

Code formatting shortcuts in Android Studio for Operation Systems

It's Ctrl + Alt + L for Windows. For a complete list of keyboard shortcuts please take a look at the user manual: https://developer.android.com/studio/intro/keyboard-shortcuts.html

DELETE ... FROM ... WHERE ... IN

Try adding parentheses around the row in table1 e.g.

DELETE 
  FROM table1
 WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);

The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.

Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:

MERGE INTO table1 AS t1
   USING table2 AS s1
      ON t1.stn = s1.stn
         AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;

VBA - Range.Row.Count

In case anyone looks at this again, you can use this:

Sub test()
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Sheet1")

    Dim k As Long
    k = sh.Range("A1", sh.Range("A1").End(xlDown).End(xlDown).End(xlUp)).Rows.Count
End Sub

Find object by its property in array of objects with AngularJS way

you can use angular's filter https://docs.angularjs.org/api/ng/filter/filter

in your controller:

$filter('filter')(myArray, {'id':73}) 

or in your HTML

{{ myArray | filter : {'id':73} }}

How to encrypt and decrypt file in Android?

I had a similar problem and for encrypt/decrypt i came up with this solution:

public static byte[] generateKey(String password) throws Exception
{
    byte[] keyStart = password.getBytes("UTF-8");

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
    sr.setSeed(keyStart);
    kgen.init(128, sr);
    SecretKey skey = kgen.generateKey();
    return skey.getEncoded();
}

public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
{

    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(fileData);

    return encrypted;
}

public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
{
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);

    byte[] decrypted = cipher.doFinal(fileData);

    return decrypted;
}

To save a encrypted file to sd do:

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();

To decode a file use:

byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);

For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/

How can I force browsers to print background images in CSS?

Like @ckpepper02 said, the body content:url option works well. I found however that if you modify it slightly you can just use it to add a header image of sorts using the :before pseudo element as follows.

@media print {
  body:before { content: url(img/printlogo.png);}
}

That will slip the image at the top of the page, and from my limited testing, it works in Chrome and the IE9

-hanz

How to Parse a JSON Object In Android

In the end I solved it by using JSONObject.get rather than JSONObject.getString and then cast test to a String.

private void saveData(String result) {
    try {
        JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("results");
        test = (String) json2.get("name");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

In Swift 5 or xcode 11 and later set (View controller-based status bar appearance) key in info.plist as NO Then go to project target and select general, Set status bar style to dark or light

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Use of main thread to present and dismiss view controller worked for me.

DispatchQueue.main.async { self.present(viewController, animated: true, completion: nil) }

Convert command line arguments into an array in Bash

The importance of the double quotes is worth emphasizing. Suppose an argument contains whitespace.

Code:

#!/bin/bash
printf 'arguments:%s\n' "$@"
declare -a arrayGOOD=( "$@" )
declare -a arrayBAAD=(  $@  )

printf '\n%s:\n' arrayGOOD
declare -p arrayGOOD
arrayGOODlength=${#arrayGOOD[@]}
for (( i=1; i<${arrayGOODlength}+1; i++ ));
do
   echo "${arrayGOOD[$i-1]}"
done

printf '\n%s:\n' arrayBAAD
declare -p arrayBAAD
arrayBAADlength=${#arrayBAAD[@]}
for (( i=1; i<${arrayBAADlength}+1; i++ ));
do
   echo "${arrayBAAD[$i-1]}"
done

Output:

> ./bash-array-practice.sh 'The dog ate the "flea" -- and ' the mouse.
arguments:The dog ate the "flea" -- and 
arguments:the
arguments:mouse.

arrayGOOD:
declare -a arrayGOOD='([0]="The dog ate the \"flea\" -- and " [1]="the" [2]="mouse.")'
The dog ate the "flea" -- and 
the
mouse.

arrayBAAD:
declare -a arrayBAAD='([0]="The" [1]="dog" [2]="ate" [3]="the" [4]="\"flea\"" [5]="--" [6]="and" [7]="the" [8]="mouse.")'
The
dog
ate
the
"flea"
--
and
the
mouse.
> 

ReportViewer Client Print Control "Unable to load client print control"?

Our Server environment : SQL2008 x64 SP2 Reporting Services on Windows Server 2008 x64,

Client PC environment: Windows XP SP2 with IE6 or higher, all users are login to Active Directory, users are not members of local Administrator or power user group.

Error: When a user printing a report getting an error as "Unable to load client print control"

Solution that work for us: replace following files in sql 2008 with SQL 2008 R2

Program Files\Microsoft SQL Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer\bin RSClientPrint-x86.cab RSClientPrint-x64.cab RSClientPrint-ia64.cab

Once you replace the files one server users wont get above error and they do not required local power user or admin right to download Active X. Recommending to add report server URL as a trusted site (add to Trusted sites) via Active Directory GP.

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

This one doesn't alter the original newer branch, and gives you the opportunity to make further modifications before final commit.

git checkout new -b tmp
git merge -s ours old -m 'irrelevant'
git checkout old
git merge --squash tmp
git branch -D tmp
#do any other stuff you want
git add -A; git commit -m 'foo' #commit (or however you like)

Intercept and override HTTP requests from WebView

This may helps:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
    String url = request.getUrl().toString();
    WebResourceResponse response = super.shouldInterceptRequest(view, request);
    // load native js
    if (url != null && url.contains(INJECTION_TOKEN/* scheme define */)) {

        response = new WebResourceResponse(
                "text/javascript",
                "utf-8",
                loadJsInputStream(url, JsCache.getJsFilePath(path) /* InputStream */));
    }
    return response;
}

How to read/write from/to file using Go?

New Way

Starting with Go 1.16, use os.ReadFile to load the file to memory, use os.WriteFile to write to a file from memory.

Be careful with the os.ReadFile because it reads the whole file into memory.

package main

import "os"

func main() {
    b, err := os.ReadFile("input.txt")
    if err != nil {
        log.Fatal(err)
    }

    // `data` contains everything your file does
    // This writes it to the Standard Out
    os.Stdout.Write(data)

    // You can also write it to a file as a whole
    err = os.WriteFile("destination.txt", b, 0644)
    if err != nil {
        log.Fatal(err)
    }
}

System.out.println() shortcut on Intellij IDEA

Yeah, you can do it. Just open Settings -> Live Templates. Create new one with syso as abbreviation and System.out.println($END$); as Template text.

How to set focus to a button widget programmatically?

Yeah it's possible.

Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();

or in XML

<Button ...><requestFocus /></Button>

Important Note: The button widget needs to be focusable and focusableInTouchMode. Most widgets are focusable but not focusableInTouchMode by default. So make sure to either set it in code

myBtn.setFocusableInTouchMode(true);

or in XML

android:focusableInTouchMode="true"

Why does corrcoef return a matrix?

corrcoef returns the normalised covariance matrix.

The covariance matrix is the matrix

Cov( X, X )    Cov( X, Y )

Cov( Y, X )    Cov( Y, Y )

Normalised, this will yield the matrix:

Corr( X, X )    Corr( X, Y )

Corr( Y, X )    Corr( Y, Y )

correlation1[0, 0 ] is the correlation between Strategy1Returns and itself, which must be 1. You just want correlation1[ 0, 1 ].

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

I had a similar problem. Just to help out someone with the same issue:

My error was the user file attribute for the files in /var/www. After changing them back to the user "www-data", the problem was gone.

How to configure Visual Studio to use Beyond Compare

VS2013 on 64-bit Windows 7 requires these settings: Tools | Options | Source Control | Jazz Source Control

CHECK THE CHECKBOX Use an external compare tool ... (easy to miss this)

2-Way Compare Location of Executable: C:\Program Files (x86)\Beyond Compare 3\BCompare.exe

3-Way Conflict Compare Location of Executable: C:\Program Files (x86)\Beyond Compare 3\BCompare.exe

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

Get current time in milliseconds in Python?

These multiplications to 1000 for milliseconds may be decent for solving or making some prerequisite acceptable. It could be used to fill a gap in your database which doesn't really ever use it. Although, for real situations which require precise timing it would ultimately fail. I wouldn't suggest anyone use this method for mission-critical operations which require actions, or processing at specific timings.

For example: round-trip pings being 30-80ms in the USA... You couldn't just round that up and use it efficiently.

My own example requires tasks at every second which means if I rounded up after the first tasks responded I would still incur the processing time multiplied every main loop cycle. This ended up being a total function call every 60 seconds. that's ~1440 a day.. not too accurate.

Just a thought for people looking for more accurate reasoning beyond solving a database gap which never really uses it.

Using regular expressions to do mass replace in Notepad++ and Vim

There is a very simple solution to this unless I have not understood the problem. The following regular expression:

(.*)(>)(.*)

will match the pattern specified in your post.

So, in notepad++ you find (.*)(>)(.*) and replace it with \3.

The regular expressions are basically greedy in the sense that if you specify (.*) it will match the whole line and what you want to do is break it down somehow so that you can extract the string you want to keep. Here, I have done exactly the same and it works fine in Notepad++ and Editplus3.

Reporting Services Remove Time from DateTime in Expression

Since SSRS utilizes VB, you can do the following:

=Today() 'returns date only

If you were to use:

=Now() 'returns date and current timestamp

Array versus linked-list

Fast insertion and removal are indeed the best arguments for linked lists. If your structure grows dynamically and constant-time access to any element isn't required (such as dynamic stacks and queues), linked lists are a good choice.

Is there an exponent operator in C#?

I'm surprised no one has mentioned this, but for the simple (and probably most encountered) case of squaring, you just multiply by itself.

float someNumber;

float result = someNumber * someNumber;

Possible to iterate backwards through a foreach?

Before using foreach for iteration, reverse the list by the reverse method:

    myList.Reverse();
    foreach( List listItem in myList)
    {
       Console.WriteLine(listItem);
    }

Python: Select subset from list based on index set

I see 2 options.

  1. Using numpy:

    property_a = numpy.array([545., 656., 5.4, 33.])
    property_b = numpy.array([ 1.2,  1.3, 2.3, 0.3])
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = property_a[good_objects]
    property_bsel = property_b[good_indices]
    
  2. Using a list comprehension and zip it:

    property_a = [545., 656., 5.4, 33.]
    property_b = [ 1.2,  1.3, 2.3, 0.3]
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = [x for x, y in zip(property_a, good_objects) if y]
    property_bsel = [property_b[i] for i in good_indices]
    

How do I check which version of NumPy I'm using?

It is good to know the version of numpy you run, but strictly speaking if you just need to have specific version on your system you can write like this:

pip install numpy==1.14.3 and this will install the version you need and uninstall other versions of numpy.

How to remove .html from URL?

Thanks for your replies. I have already solved my problem. Suppose I have my pages under http://www.yoursite.com/html, the following .htaccess rules apply.

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /html/(.*).html\ HTTP/
   RewriteRule .* http://localhost/html/%1 [R=301,L]

   RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /html/(.*)\ HTTP/
   RewriteRule .* %1.html [L]
</IfModule>

How do you clear the SQL Server transaction log?

Use the DBCC ShrinkFile ({logicalLogName}, TRUNCATEONLY) command. If this is a test database and you are trying to save/reclaim space, this will help.

Remember though that TX logs do have a sort of minimum/steady state size that they will grow up to. Depending upon your recovery model you may not be able to shrink the log - if in FULL and you aren't issuing TX log backups the log can't be shrunk - it will grow forever. If you don't need TX log backups, switch your recovery model to Simple.

And remember, never ever under any circumstances delete the log (LDF) file! You will pretty much have instant database corruption. Cooked! Done! Lost data! If left "unrepaired" the main MDF file could become corrupt permanently.

Never ever delete the transaction log - you will lose data! Part of your data is in the TX Log (regardless of recovery model)... if you detach and "rename" the TX log file that effectively deletes part of your database.

For those that have deleted the TX Log you may want to run a few checkdb commands and fix the corruption before you lose more data.

Check out Paul Randal's blog posts on this very topic, bad advice.

Also in general do not use shrinkfile on the MDF files as it can severely fragment your data. Check out his Bad Advice section for more info ("Why you should not shrink your data files")

Check out Paul's website - he covers these very questions. Last month he walked through many of these issues in his Myth A Day series.

How to save a PNG image server-side, from a base64 data string

It's simple :

Let's imagine that you are trying to upload a file within js framework, ajax request or mobile application (Client side)

  1. Firstly you send a data attribute that contains a base64 encoded string.
  2. In the server side you have to decode it and save it in a local project folder.

Here how to do it using PHP

<?php 

$base64String = "kfezyufgzefhzefjizjfzfzefzefhuze"; // I put a static base64 string, you can implement you special code to retrieve the data received via the request.

$filePath = "/MyProject/public/uploads/img/test.png";

file_put_contents($filePath, base64_decode($base64String));

?>

Centering the image in Bootstrap

Update 2018

Bootstrap 2.x

You could create a new CSS class such as:

.img-center {margin:0 auto;}

And then, add this to each IMG:

 <img src="images/2.png" class="img-responsive img-center">

OR, just override the .img-responsive if you're going to center all images..

 .img-responsive {margin:0 auto;}

Demo: http://bootply.com/86123

Bootstrap 3.x

EDIT - With the release of Bootstrap 3.0.1, the center-block class can now be used without any additional CSS..

 <img src="images/2.png" class="img-responsive center-block">

Bootstrap 4

In Bootstrap 4, the mx-auto class (auto x-axis margins) can be used to center images that are display:block. However, img is display:inline by default so text-center can be used on the parent.

<div class="container">
    <div class="row">
        <div class="col-12">
            <img class="mx-auto d-block" src="//placehold.it/200">  
        </div>
    </div>
    <div class="row">
        <div class="col-12 text-center">
            <img src="//placehold.it/200">  
        </div>
    </div>
</div>

Bootsrap 4 - center image demo

How do you add PostgreSQL Driver as a dependency in Maven?

Depending on your PostgreSQL version you would need to add the postgresql driver to your pom.xml file.

For PostgreSQL 9.1 this would be:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
    </dependencies>
</project>

You can get the code for the dependency (as well as any other dependency) from maven's central repository

If you are using postgresql 9.2+:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.1</version>
        </dependency>
    </dependencies>
</project>

You can check the latest versions and dependency snippets from:

Check if application is on its first run

There is no way to know that through the Android API. You have to store some flag by yourself and make it persist either in a SharedPreferenceEditor or using a database.

If you want to base some licence related stuff on this flag, I suggest you use an obfuscated preference editor provided by the LVL library. It's simple and clean.

Regards, Stephane

How do I test a website using XAMPP?

Just make a new folder inside C:\xampp\htdocs like C:\xampp\htdocs\test and place your index.php or whatever file in it. Access it by browsing localhost/test/

Good luck!

Twitter Bootstrap: Print content of modal window

Another solution

Here is a new solution based on Bennett McElwee answer in the same question as mentioned below.

Tested with IE 9 & 10, Opera 12.01, Google Chrome 22 and Firefox 15.0.
jsFiddle example

1.) Add this CSS to your site:

@media screen {
  #printSection {
      display: none;
  }
}

@media print {
  body * {
    visibility:hidden;
  }
  #printSection, #printSection * {
    visibility:visible;
  }
  #printSection {
    position:absolute;
    left:0;
    top:0;
  }
}

2.) Add my JavaScript function

function printElement(elem, append, delimiter) {
    var domClone = elem.cloneNode(true);

    var $printSection = document.getElementById("printSection");

    if (!$printSection) {
        $printSection = document.createElement("div");
        $printSection.id = "printSection";
        document.body.appendChild($printSection);
    }

    if (append !== true) {
        $printSection.innerHTML = "";
    }

    else if (append === true) {
        if (typeof (delimiter) === "string") {
            $printSection.innerHTML += delimiter;
        }
        else if (typeof (delimiter) === "object") {
            $printSection.appendChild(delimiter);
        }
    }

    $printSection.appendChild(domClone);
}?

You're ready to print any element on your site!
Just call printElement() with your element(s) and execute window.print() when you're finished.

Note: If you want to modify the content before it is printed (and only in the print version), checkout this example (provided by waspina in the comments): http://jsfiddle.net/95ezN/121/

One could also use CSS in order to show the additional content in the print version (and only there).


Former solution

I think, you have to hide all other parts of the site via CSS.

It would be the best, to move all non-printable content into a separate DIV:

<body>
  <div class="non-printable">
    <!-- ... -->
  </div>

  <div class="printable">
    <!-- Modal dialog comes here -->
  </div>
</body>

And then in your CSS:

.printable { display: none; }

@media print
{
    .non-printable { display: none; }
    .printable { display: block; }
}

Credits go to Greg who has already answered a similar question: Print <div id="printarea"></div> only?

There is one problem in using JavaScript: the user cannot see a preview - at least in Internet Explorer!

Turning off eslint rule for a specific file

To disable specific rules for file(s) inside folder(s), you need to use the "overrides" key of your .eslintrc config file.

For example, if you want to remove the following rules:

  1. no-use-before-define
  2. max-lines-per-function

For all files inside the following main directory:

/spec

You can add this to your .eslintrc file...

"overrides": [
  {
    "files": ["spec/**/*.js"],
    "rules": {
      "no-use-before-define": ["off"],
      "max-lines-per-function": ["off"]
    }
  }
]

Note that I used ** inside the spec/**/*.js glob, which means I am looking recursively for all subfolders inside the folder called spec and selecting all files that ends with js in order to remove the desired rules from them.

How to fix a header on scroll

You need some JS to do scroll events. The best way to do this is to set a new CSS class for the fixed position that will get assigned to the relevant div when scrolling goes past a certain point.

HTML

<div class="sticky"></div>

CSS

.fixed {
    position: fixed;
    top:0; left:0;
    width: 100%; }

jQuery

$(window).scroll(function(){
  var sticky = $('.sticky'),
      scroll = $(window).scrollTop();

  if (scroll >= 100) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

Example fiddle: http://jsfiddle.net/gxRC9/501/


EDIT: Extended example

If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, offset().top can be used.

var stickyOffset = $('.sticky').offset().top;

$(window).scroll(function(){
  var sticky = $('.sticky'),
      scroll = $(window).scrollTop();

  if (scroll >= stickyOffset) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

Extended example fiddle: http://jsfiddle.net/gxRC9/502/

How to run or debug php on Visual Studio Code (VSCode)

XDebug changed some configuration settings.

Old settings:

xdebug.remote_enable = 1
xdebug.remote_autostart = 1
xdebug.remote_port = 9000

New settings:

xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_port=9000

So you should paste the latter in php.ini file. More info: XDebug Changed Configuration Settings

How to Call VBA Function from Excel Cells?

Here's the answer

Steps to follow:

  1. Open the Visual Basic Editor. In Excel, hit Alt+F11 if on Windows, Fn+Option+F11 if on a Mac.

  2. Insert a new module. From the menu: Insert -> Module (Don't skip this!).

  3. Create a Public function. Example:

    Public Function findArea(ByVal width as Double, _
                             ByVal height as Double) As Double
        ' Return the area
        findArea = width * height
    End Function
    
  4. Then use it in any cell like you would any other function: =findArea(B12,C12).

Bootstrap fullscreen layout with 100% height

All you have to do is have a height of 100vh on your main container/wrapper, and then set height 100% or 50% for child elements.. depending on what you're trying to achieve. I tried to copy your mock up in a basic sense.

In case you want to center stuff within, look into flexbox. I put in an example for you.

You can view it on full screen, and resize the browser and see how it works. The layout stays the same.

_x000D_
_x000D_
.left {_x000D_
  background: grey;  _x000D_
}_x000D_
_x000D_
.right {_x000D_
  background: black;  _x000D_
}_x000D_
_x000D_
.main-wrapper {_x000D_
  height: 100vh;  _x000D_
}_x000D_
_x000D_
.section {_x000D_
  height: 100%;  _x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.half {_x000D_
  background: #f9f9f9;_x000D_
  height: 50%;  _x000D_
  width: 100%;_x000D_
  margin: 15px 0;_x000D_
}_x000D_
_x000D_
h4 {_x000D_
  color: white;  _x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<div class="main-wrapper">_x000D_
  <div class="section left col-xs-3">_x000D_
    <div class="half"><h4>Top left</h4></div>_x000D_
    <div class="half"><h4>Bottom left</h4></div>_x000D_
  </div>_x000D_
  <div class="section right col-xs-9">_x000D_
    <h4>Extra step: center stuff here</h4>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

array of string with unknown size

You can't create an array without a size. You'd need to use a list for that.

Test if registry value exists

One-liner:

$valueExists = (Get-Item $regKeyPath -EA Ignore).Property -contains $regValueName

Execution failed for task :':app:mergeDebugResources'. Android Studio

Okay here is a simple fix.

This error popped in front of me when I tried to manually change .jpg file to .png and then was copying & pasting it in my 'drawable' folder.

I rebuild and cleaned Project many times but nothing happened, then I removed that .png image and replaced that file with a different pre-existing .png image (or you can change it by help of paint and then paste it in drawable folder)

Now rebuild and clean the project . It works.

Hope it helps..!

hide div tag on mobile view only?

Well, I think that there are simple solutions than mentioned here on this page! first of all, let's make an example:

You have 1 DIV and want to hide thas DIV on Desktop and show on Mobile (or vice versa). So, let's presume that the DIV position placed in the Head section and named as header_div.

The global code in your CSS file will be: (for the same DIV):

.header_div {
    display: none;
}

@media all and (max-width: 768px){
.header_div {
    display: block;
}
}

So simple and no need to make 2 div's one for desktop and the other for mobile.

Hope this helps.

Thank you.

How do I rename the android package name?

This modification needs three steps :

  1. Change the package name in the manifest
  2. Refactor the name of your package with right click -> refactor -> rename in the tree view, then Android studio will display a window, select "rename package"
  3. Change manually the application Id in the build.gradle file : android / defaultconfig / application ID

Then clean / rebuild the project

Pass a data.frame column name to a function

As an extra thought, if is needed to pass the column name unquoted to the custom function, perhaps match.call() could be useful as well in this case, as an alternative to deparse(substitute()):

df <- data.frame(A = 1:10, B = 2:11)

fun <- function(x, column){
  arg <- match.call()
  max(x[[arg$column]])
}

fun(df, A)
#> [1] 10

fun(df, B)
#> [1] 11

If there is a typo in the column name, then would be safer to stop with an error:

fun <- function(x, column) max(x[[match.call()$column]])
fun(df, typo)
#> Warning in max(x[[match.call()$column]]): no non-missing arguments to max;
#> returning -Inf
#> [1] -Inf

# Stop with error in case of typo
fun <- function(x, column){
  arg <- match.call()
  if (is.null(x[[arg$column]])) stop("Wrong column name")
  max(x[[arg$column]])
}

fun(df, typo)
#> Error in fun(df, typo): Wrong column name
fun(df, A)
#> [1] 10

Created on 2019-01-11 by the reprex package (v0.2.1)

I do not think I would use this approach since there is extra typing and complexity than just passing the quoted column name as pointed in the above answers, but well, is an approach.

How to use Select2 with JSON via Ajax request?

Here I give you my example which contain --> Country flag, City, State, Country.

Here is my output.

enter image description here

Attach these two Cdn js or links.

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>

js script

//for apend flag of country.

function formatState (state) {
    console.log(state);
    if (!state.id) {
      return state.text;
    }
    var baseUrl = "admin/images/flags";
    var $state = $(
      '<span><img src="'+baseUrl+ '/' + state.contryflage.toLowerCase() + '.png"  class="img-flag" /> ' +state.text+ '</span>'
    );
    return $state;
  };


$(function(){
    $("#itemSearch").select2({
    minimumInputLength: 2,
    templateResult: formatState, //this is for append country flag.
    ajax: {
        url: URL,
        dataType: 'json',
        type: "POST",
        data: function (term) {
            return {
                term: term
            };
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.name+', '+item.state.name+', '+item.state.coutry.name,
                        id: item.id,
                        contryflage:item.state.coutry.sortname
                    }
                })
            };
        }

    }
});

Expected JSON response.

[
   {
      "id":7570,
      "name":"Brussels",
      "state":{
         "name":"Brabant",
         "coutry":{
            "sortname":"BE",
            "name":"Belgium",

         }
      }
   },
   {
      "id":7575,
      "name":"Brussels",
      "state":{
         "name":"Brabant Wallon",
         "coutry":{
            "sortname":"BE",
            "name":"Belgium",

         }
      }
   },
   {
      "id":7578,
      "name":"Brussel",
      "state":{
         "name":"Brussel",
         "coutry":{
            "sortname":"BE",
            "name":"Belgium",

         }
      }
   },

]

How to detect my browser version and operating system using JavaScript?

PPK's script is THE authority for this kind of things, as @Jalpesh said, this might point you in the right way

var wn = window.navigator,
        platform = wn.platform.toString().toLowerCase(),
        userAgent = wn.userAgent.toLowerCase(),
        storedName;

// ie
    if (userAgent.indexOf('msie',0) !== -1) {
        browserName = 'ie';
        os = 'win';
        storedName = userAgent.match(/msie[ ]\d{1}/).toString();
        version = storedName.replace(/msie[ ]/,'');

        browserOsVersion = browserName + version;
    }

Taken from https://github.com/leopic/jquery.detectBrowser.js/blob/sans-jquery/jquery.detectBrowser.sansjQuery.js

How to replace a character from a String in SQL?

UPDATE databaseName.tableName
SET columnName = replace(columnName, '?', '''')
WHERE columnName LIKE '%?%'

How to take backup of a single table in a MySQL database?

You can either use mysqldump from the command line:

mysqldump -u username -p password dbname tablename > "path where you want to dump"

You can also use MySQL Workbench:

Go to left > Data Export > Select Schema > Select tables and click on Export

How to do a scatter plot with empty circles in Python?

Basend on the example of Gary Kerr and as proposed here one may create empty circles related to specified values with following code:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.markers import MarkerStyle

x = np.random.randn(60) 
y = np.random.randn(60)
z = np.random.randn(60)

g=plt.scatter(x, y, s=80, c=z)
g.set_facecolor('none')
plt.colorbar()
plt.show()

JavaScript associative array to JSON

I posted a fix for this here

You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):

// Upgrade for JSON.stringify, updated to allow arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

Python - Convert a bytes array into JSON format

To convert this bytesarray directly to json, you could first convert the bytesarray to a string with decode(), utf-8 is standard. Change the quotation markers.. The last step is to remove the " from the dumped string, to change the json object from string to list.

dumps(s.decode()).replace("'", '"')[1:-1]

Change / Add syntax highlighting for a language in Sublime 2/3

This is my recipe

Note: This isn't exactly what OP is asking. These instructions will help you change the colors of items (comments, keywords, etc) that are defined syntax matching rules. For example, use these instructions to change so that all code comments are colored blue instead of green.

I believe the OP is asking how to define this as an item to be colored when found in a JavaScript source file.

  1. Install Package: PackageResourceViewer

  2. Ctrl+Shift+P > [PackageResourceViewer: Open Resource] > [Color Scheme - Default] > [Marina.sublime-color-scheme] (or whichever color scheme you use)

  3. The above command will open a new tab to the file "Marina.sublime-color-scheme".

    • For me, this file was located in my roaming profile %appdata% (C:\Users\walter\AppData\Roaming\Sublime Text 3\Packages\Color Scheme - Default\) .
    • However, if I browse to that path in Windows Explorer, [Color Scheme - Default] is not of a child-dir of [Packages] dir. I suspect that PackageResourceViewer is doing some virtualization.

optional step: On the new color-scheme tab: Ctrl+Shift+P > [Set Syntax: JSON]

  1. Search for the rule you want to change. I wanted to make comments be move visible, so I searched for "Comment"

    • I found it in the "rules" section
 "rules":
    [
        {
            "name": "Comment",
            "scope": "comment, punctuation.definition.comment",
            "foreground": "var(blue6)"
        },
  1. Search for the string "blue6": to find the color variable definitions section. I found it in the "variables" section.

  2. Pick a new color using a tool like http://hslpicker.com/ .

  3. Either define a new color variable, or overwrite the color setting for blue6.

    • Warning: overwriting blue6 will affect all other text-elements in that color scheme which also use blue6 ("Punctuation" "Accessor").
  4. Save your file, the changes will be applied instantly to any open files/tabs.

NOTES

Sublime will handle any of these color styles. Possibly more.

hsla = hue, saturation, lightness, alpha rgba = red, green, blue, alpha

hsla(151, 100%, 41%, 1) - last param is the alpha level (transparency) 1 = opaque, 0.5 = half-transparent, 0 = full-transparent

hsl(151, 100%, 41%) - no alpha channel

rgba(0, 209, 108, 1) - rgb with an alpha channel

rgb(0, 209, 108) - no alpha channel

How to save data in an android app

OP is asking for a "save" function, which is more than just preserving data across executions of the program (which you must do for the app to be worth anything.)

I recommend saving the data in a file on the sdcard which allows you to not only recall it later, but allows the user to mount the device as an external drive on their own computer and grab the data for use in other places.

So you really need a multi-point system:

1) Implement onSaveInstanceState(). In this method, you're passed a Bundle, which is basically like a dictionary. Store as much information in the bundle as would be needed to restart the app exactly where it left off. In your onCreate() method, check for the passed-in bundle to be non-null, and if so, restore the state from the bundle.

2) Implement onPause(). In this method, create a SharedPreferences editor and use it to save whatever state you need to start the app up next time. This mainly consists of the users' preferences (hence the name), but anything else relavent to the app's start-up state should go here as well. I would not store scores here, just the stuff you need to restart the app. Then, in onCreate(), whenever there's no bundle object, use the SharedPreferences interface to recall those settings.

3a) As for things like scores, you could follow Mathias's advice above and store the scores in the directory returned in getFilesDir(), using openFileOutput(), etc. I think this directory is private to the app and lives in main storage, meaning that other apps and the user would not be able to access the data. If that's ok with you, then this is probably the way to go.

3b) If you do want other apps or the user to have direct access to the data, or if the data is going to be very large, then the sdcard is the way to go. Pick a directory name like com/user1446371/basketballapp/ to avoid collisions with other applications (unless you're sure that your app name is reasonably unique) and create that directory on the sdcard. As Mathias pointed out, you should first confirm that the sdcard is mounted.

File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory()) {
    fail("sdcard not available");
}
File datadir = new File(sdcard, "com/user1446371/basketballapp/");
if( !datadir.exists() && !datadir.mkdirs() ) {
    fail("unable to create data directory");
}
if( !datadir.isDirectory() ) {
    fail("exists, but is not a directory");
}
// Now use regular java I/O to read and write files to data directory

I recommend simple CSV files for your data, so that other applications can read them easily.

Obviously, you'll have to write activities that allow "save" and "open" dialogs. I generally just make calls to the openintents file manager and let it do the work. This requires that your users install the openintents file manager to make use of these features, however.

Division in Python 2.7. and 3.3

"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:

float(20)/15 #1.33333333

HTTP Basic Authentication credentials passed in URL and encryption

Not necessarily true. It will be encrypted on the wire however it still lands in the logs plain text

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

This happens when you specify the incorrect position for the notifyItemChanged , notifyItemRangeInserted etc.For me :

Before : (Erroneous)

public void addData(List<ChannelItem> list) {
  int initialSize = list.size();
  mChannelItemList.addAll(list);
  notifyItemRangeChanged(initialSize - 1, mChannelItemList.size());
 } 

After : (Correct)

 public void addData(List<ChannelItem> list) {
  int initialSize = mChannelItemList.size();
  mChannelItemList.addAll(list);
  notifyItemRangeInserted(initialSize, mChannelItemList.size()-1); //Correct position 
 }

How to undo a successful "git cherry-pick"?

A cherry-pick is basically a commit, so if you want to undo it, you just undo the commit.

when I have other local changes

Stash your current changes so you can reapply them after resetting the commit.

$ git stash
$ git reset --hard HEAD^
$ git stash pop  # or `git stash apply`, if you want to keep the changeset in the stash

when I have no other local changes

$ git reset --hard HEAD^

Why does JSHint throw a warning if I am using const?

I got this same warning when using an export statement. I'm using VS Code and used a similar approach to Wenlong Jiang's solution.

  1. User Settings

  2. JSHint config

  3. "jshint.config": {} (Edit)

  4. Use double quotes when specifying "esversion"

    Or copy this snippet into User Settings:

    "jshint.options": {
      "esversion": 6,
    }
    

Creating a .jshintrc file isn't necessary if you want to configure the global jshint settings for your editor

How to count number of unique values of a field in a tab-delimited text file?

You can make use of cut, sort and uniq commands as follows:

cat input_file | cut -f 1 | sort | uniq

gets unique values in field 1, replacing 1 by 2 will give you unique values in field 2.

Avoiding UUOC :)

cut -f 1 input_file | sort | uniq

EDIT:

To count the number of unique occurences you can make use of wc command in the chain as:

cut -f 1 input_file | sort | uniq | wc -l

Standard concise way to copy a file in Java?

To copy a file and save it to your destination path you can use the method below.

public void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dst);
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

Convert datetime to Unix timestamp and convert it back in python

For working with UTC timezones:

time_stamp = calendar.timegm(dt.timetuple())

datetime.utcfromtimestamp(time_stamp)

Ansible: filter a list by its attributes

I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:

- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"

would return:

ok: [localhost] => {
    "msg": [
        "172.16.1.100"
    ]
}

Combining two expressions (Expression<Func<T, bool>>)

I needed to achieve the same results, but using something more generic (as the type was not known). Thanks to marc's answer I finally figured out what I was trying to achieve:

    public static LambdaExpression CombineOr(Type sourceType, LambdaExpression exp, LambdaExpression newExp) 
    {
        var parameter = Expression.Parameter(sourceType);

        var leftVisitor = new ReplaceExpressionVisitor(exp.Parameters[0], parameter);
        var left = leftVisitor.Visit(exp.Body);

        var rightVisitor = new ReplaceExpressionVisitor(newExp.Parameters[0], parameter);
        var right = rightVisitor.Visit(newExp.Body);

        var delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
        return Expression.Lambda(delegateType, Expression.Or(left, right), parameter);
    }

New warnings in iOS 9: "all bitcode will be dropped"

If you are using CocoaPods and you want to disable Bitcode for all libraries, use the following command in the Podfile

post_install do |installer|
    installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['ENABLE_BITCODE'] = 'NO'
        end
    end
end

SSH SCP Local file to Remote in Terminal Mac Os X

Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.

So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:

Using scp, copy file to a directory in the remote user's account, for example the Documents directory:

scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents

Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:

ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www

make arrayList.toArray() return more specific types

A shorter version of converting List to Array of specific type (for example Long):

Long[] myArray = myList.toArray(Long[]::new);

Oracle: how to set user password unexpire?

If you create a user using a profile like this:

CREATE PROFILE my_profile LIMIT
       PASSWORD_LIFE_TIME 30;
ALTER USER scott PROFILE my_profile;

then you can change the password lifetime like this:

ALTER PROFILE my_profile LIMIT
  PASSWORD_LIFE_TIME UNLIMITED;

I hope that helps.

Problem in running .net framework 4.0 website on iis 7.0

Go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header. Change ASP.NET 4.0 from "Not Allowed" to "Allowed".

What are all codecs and formats supported by FFmpeg?

You can see the list of supported codecs in the official documentation:

Supported video codecs

Supported audio codecs

Kill a postgresql session/connection

Remote scenario. But if you're trying to run tests in a rails app, and you get something like

"ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR: database "myapp_test" is being accessed by other users DETAIL: There is 1 other session using the database."

Make sure you close pgAdmin or any other postgres GUI tools before running tests.

HTML code for INR

How about using fontawesome icon for Indian Rupee (INR).

Add font awesome CSS from CDN in the Head section of your HTML page:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

And then using the font like this:

<i class="fa fa-inr" aria-hidden="true"></i>

How to convert string to long

Do this:

long l = Long.parseLong(str);

However, always check that str contains digits to prevent throwing exceptions. For instance:

String str="ABCDE";
long l = Long.parseLong(str);

would throw an exception but this

String str="1234567";
long l = Long.parseLong(str);

won't.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

It usually happens because one of the following reasons:

  • Entity Set is mapped from Database view
  • A custom Database query
  • Database table doesn't have a primary key

After doing so, you may still need to update in the Entity Framework designer (or alternatively delete the entity and then add it) before you stop getting the error.

Send a SMS via intent

This is another solution using SMSManager:

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("PhoneNumber-example:+989147375410", null, "SMS Message Body", null, null);

Getting a Request.Headers value

The following code should allow you to check for the existance of the header you're after in Request.Headers:

if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
    // Can now check if the value is true:
    var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

My two cents: came across the same error message in RHEL7.3 while running the openssl command with root CA certificate. The reason being, while downloading the certificate from AD server, Encoding was selected as DER instead of Base64. Once the proper version of encoding was selected for the new certificate download, error was resolved

Hope this helps for new users :-)

mysqldump exports only one table

try this. There are in general three ways to use mysqldump—

in order to dump a set of one or more tables,

shell> mysqldump [options] db_name [tbl_name ...]

a set of one or more complete databases

shell> mysqldump [options] --databases db_name ...

or an entire MySQL server—as shown here:

shell> mysqldump [options] --all-databases

SQL Server - after insert trigger - update another column in the same table

create or replace 
TRIGGER triggername BEFORE INSERT  ON 
table FOR EACH ROW 
BEGIN
/*
Write any select condition if you want to get the data from other tables
*/
:NEW.COLUMNA:= UPPER(COLUMNA); 
--:NEW.COUMNa:= NULL;
END; 

The above trigger will update the column value before inserting. For example if we give the value of COLUMNA as null it will update the column as null for each insert statement.

onKeyPress Vs. onKeyUp and onKeyDown

KeyPress, KeyUp and KeyDown are analogous to, respectively: Click, MouseUp, and MouseDown.

  1. Down happens first
  2. Press happens second (when text is entered)
  3. Up happens last (when text input is complete).

The exception is webkit, which has an extra event in there:

keydown
keypress
textInput     
keyup

Below is a snippet you can use to see for yourself when the events get fired:

_x000D_
_x000D_
window.addEventListener("keyup", log);
window.addEventListener("keypress", log);
window.addEventListener("keydown", log);

function log(event){
  console.log( event.type );
}
_x000D_
_x000D_
_x000D_

Angular 2.0 and Modal Dialog

This is a simple approach that does not depend on jquery or any other library except Angular 2. The component below (errorMessage.ts) can be used as a child view of any other component. It is simply a bootstrap modal that is always open or shown. It's visibility is governed by the ngIf statement.

errorMessage.ts

import { Component } from '@angular/core';
@Component({
    selector: 'app-error-message',
    templateUrl: './app/common/errorMessage.html',
})
export class ErrorMessage
{
    private ErrorMsg: string;
    public ErrorMessageIsVisible: boolean;

    showErrorMessage(msg: string)
    {
        this.ErrorMsg = msg;
        this.ErrorMessageIsVisible = true;
    }

    hideErrorMsg()
    {
        this.ErrorMessageIsVisible = false;
    }
}

errorMessage.html

<div *ngIf="ErrorMessageIsVisible" class="modal fade show in danger" id="myModal" role="dialog">
    <div class="modal-dialog">

        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Error</h4>
            </div>
            <div class="modal-body">
                <p>{{ErrorMsg}}</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" (click)="hideErrorMsg()">Close</button>
            </div>
        </div>
    </div>
</div>

This is an example parent control (some non-relevant code has been omitted for brevity):

parent.ts

import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/common';
import {Router, RouteSegment, OnActivate, ROUTER_DIRECTIVES } from '@angular/router';
import { OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';


@Component({
    selector: 'app-application-detail',
    templateUrl: './app/permissions/applicationDetail.html',
    directives: [ROUTER_DIRECTIVES, ErrorMessage]  // Note ErrorMessage is a directive
})
export class ApplicationDetail implements OnActivate
{
    @ViewChild(ErrorMessage) errorMsg: ErrorMessage;  // ErrorMessage is a ViewChild



    // yada yada


    onSubmit()
    {
        let result = this.permissionsService.SaveApplication(this.Application).subscribe(x =>
        {
            x.Error = true;
            x.Message = "This is a dummy error message";

            if (x.Error) {
                this.errorMsg.showErrorMessage(x.Message);
            }
            else {
                this.router.navigate(['/applicationsIndex']);
            }
        });
    }

}

parent.html

<app-error-message></app-error-message>
// your html...

In Java, what is the best way to determine the size of an object?

There isn't a method call, if that's what you're asking for. With a little research, I suppose you could write your own. A particular instance has a fixed sized derived from the number of references and primitive values plus instance bookkeeping data. You would simply walk the object graph. The less varied the row types, the easier.

If that's too slow or just more trouble than it's worth, there's always good old-fashioned row counting rule-of-thumbs.

How to get exit code when using Python subprocess communicate method?

Popen.communicate will set the returncode attribute when it's done(*). Here's the relevant documentation section:

Popen.returncode 
  The child return code, set by poll() and wait() (and indirectly by communicate()). 
  A None value indicates that the process hasn’t terminated yet.

  A negative value -N indicates that the child was terminated by signal N (Unix only).

So you can just do (I didn't test it but it should work):

import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode

(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls wait.

How to add images to README.md on GitHub?

I have solved this problem. You only need to refer to someone else's readme file.

At first,you should upload an image file to github code library ! Then direct reference to the address of the image file .



enter image description here

enter image description here

How do I disable a Pylint warning?

You can also use the following command:

pylint --disable=C0321  test.py

My Pylint version is 0.25.1.

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Your application has an AppCompat theme

<application
    android:theme="@style/AppTheme">

But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme

<activity android:name=".MainActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

You could define your own fullscreen theme like so (notice AppCompat in the parent=)

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Then set that on the Activity.

<activity android:name=".MainActivity"
    android:theme="@style/AppFullScreenTheme" >

Note: There might be an AppCompat theme that's already full screen, but don't know immediately

How to get date in BAT file

Locale-independent one liner to get any date format you like. I use it to generate archive names. Back quote option is needed because PowerShell command line is using single quotes.

:: Get date in yyyyMMdd_HHmm format to use with file name.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Get formatted yesterday date.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).AddDays^(-1^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Show file name with the date.
echo Archive.%DTime%.zip

Carriage return in C?

Program prints ab, goes back one character and prints si overwriting the b resulting asi. Carriage return returns the caret to the first column of the current line. That means the ha will be printed over as and the result is hai

Problems with Android Fragment back stack

I know it's a old quetion but i got the same problem and fix it like this:

First, Add Fragment1 to BackStack with a name (e.g "Frag1"):

frag = new Fragment1();

transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detailFragment, frag);
transaction.addToBackStack("Frag1");
transaction.commit();

And then, Whenever you want to go back to Fragment1 (even after adding 10 fragments above it), just call popBackStackImmediate with the name:

getSupportFragmentManager().popBackStackImmediate("Frag1", 0);

Hope it will help someone :)

Change jsp on button click

Just use two forms.

In the first form action attribute will have name of the second jdp page and your 1st button. In the second form there will be 2nd button with action attribute thats giving the name of your 3rd jsp page.

It will be like this :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form name="main1"  method="get" action="2nd.jsp">
        <input type="submit" name="ter" value="LOGOUT" >
    </form>
    <DIV ALIGN="left"><form name="main0" action="3rd.jsp" method="get">
        <input type="submit" value="FEEDBACK">
    </form></DIV>
</body>
</html>

PHP - iterate on string characters

If your strings are in Unicode you should use preg_split with /u modifier

From comments in php documentation:

function mb_str_split( $string ) { 
    # Split at all position not after the start: ^ 
    # and not before the end: $ 
    return preg_split('/(?<!^)(?!$)/u', $string ); 
} 

How to programmatically clear application data

Following up to @edovino's answer, the way of clearing all of an application's preferences programmatically would be

private void clearPreferences() {
    try {
        // clearing app data
        Runtime runtime = Runtime.getRuntime();
        runtime.exec("pm clear YOUR_APP_PACKAGE_GOES HERE");

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

Warning: the application will force close.

pip install failing with: OSError: [Errno 13] Permission denied on directory

So, I got this same exact error for a completely different reason. Due to a totally separate, but known Homebrew + pip bug, I had followed this workaround listed on Google Cloud's help docs, where you create a .pydistutils.cfg file in your home directory. This file has special config that you're only supposed to use for your install of certain libraries. I should have removed that disutils.cfg file after installing the packages, but I forgot to do so. So the fix for me was actually just...

rm ~/.pydistutils.cfg.

And then everything worked as normal. Of course, if you have some config in that file for a real reason, then you won't want to just straight rm that file. But in case anyone else did that workaround, and forgot to remove that file, this did the trick for me!

Is there any way to wait for AJAX response and halt execution?

use async:false attribute along with url and data. this will help to execute ajax call immediately and u can fetch and use data from server.

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        async:false
        success: function(data) {
            return data;
        }
    });
}

How to access the elements of a function's return array?

The underlying problem revolves around accessing the data within the array, as Felix Kling points out in the first response.

In the following code, I've accessed the values of the array with the print and echo constructs.

function data()
{

    $a = "abc";
    $b = "def";
    $c = "ghi";

    $array = array($a, $b, $c);

    print_r($array);//outputs the key/value pair

    echo "<br>";

    echo $array[0].$array[1].$array[2];//outputs a concatenation of the values

}

data();

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

For me, it was the missing 'web.config' file. After adding it to the deployed project directory in asp net core 3.1 app, the problem was solved.

Joining three tables using MySQL

Use ANSI syntax and it will be a lot more clear how you are joining the tables:

SELECT s.name as Student, c.name as Course 
FROM student s
    INNER JOIN bridge b ON s.id = b.sid
    INNER JOIN course c ON b.cid  = c.id 
ORDER BY s.name 

What is an uber jar?

The different names are just ways of packaging java apps.

Skinny – Contains ONLY the bits you literally type into your code editor, and NOTHING else.

Thin – Contains all of the above PLUS the app’s direct dependencies of your app (db drivers, utility libraries, etc).

Hollow – The inverse of Thin – Contains only the bits needed to run your app but does NOT contain the app itself. Basically a pre-packaged “app server” to which you can later deploy your app, in the same style as traditional Java EE app servers, but with important differences.

Fat/Uber – Contains the bit you literally write yourself PLUS the direct dependencies of your app PLUS the bits needed to run your app “on its own”.

Source: Article from Dzone

Visual representation of JAR types

Reposted from: https://stackoverflow.com/a/57592130/9470346

Does Eclipse have line-wrap

In Version: 2019-12 (4.14.0) on MAC

Go to Windows -> Editor -> Toggle Word Wrap

Autowiring two beans implementing same interface - how to set default bean to autowire?

The reason why @Resource(name = "{your child class name}") works but @Autowired sometimes don't work is because of the difference of their Matching sequence

Matching sequence of @Autowire
Type, Qualifier, Name

Matching sequence of @Resource
Name, Type, Qualifier

The more detail explanation can be found here:
Inject and Resource and Autowired annotations

In this case, different child class inherited from the parent class or interface confuses @Autowire, because they are from same type; As @Resource use Name as first matching priority , it works.

What is the purpose of the : (colon) GNU Bash builtin?

It's similar to pass in Python.

One use would be to stub out a function until it gets written:

future_function () { :; }

Twitter Bootstrap Modal Form Submit

Updated 2018

Do you want to close the modal after submit? Whether the form in inside the modal or external to it you should be able to use jQuery ajax to submit the form.

Here is an example with the form inside the modal:

<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
        <form id="myForm" method="post">
          <input type="hidden" value="hello" id="myField">
            <button id="myFormSubmit" type="submit">Submit</button>
        </form>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>
    </div>
</div>

And the jQuery ajax to get the form fields and submit it..

$('#myFormSubmit').click(function(e){
      e.preventDefault();
      alert($('#myField').val());
      /*
      $.post('http://path/to/post', 
         $('#myForm').serialize(), 
         function(data, status, xhr){
           // do something here with response;
         });
      */
});

Bootstrap 3 example


Bootstrap 4 example

How can I update NodeJS and NPM to the next versions?

Just with this code

npm install update

Transmitting newline character "\n"

Try using %0A in the URL, just like you've used %20 instead of the space character.

Checking something isEmpty in Javascript?

See http://underscorejs.org/#isEmpty

isEmpty_.isEmpty(object) Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.

How to set minDate to current date in jQuery UI Datepicker?

can also use:

$("input.DateFrom").datepicker({
    minDate: 'today'
});

Scroll to the top of the page after render in react.js

This works for me.

import React, { useEffect } from 'react';

useEffect(() => {
    const body = document.querySelector('#root');

    body.scrollIntoView({
        behavior: 'smooth'
    }, 500)

}, []);

Using only CSS, show div on hover over <a>

You can do something like this:

_x000D_
_x000D_
div {_x000D_
    display: none;_x000D_
}_x000D_
    _x000D_
a:hover + div {_x000D_
    display: block;_x000D_
}
_x000D_
<a>Hover over me!</a>_x000D_
<div>Stuff shown on hover</div>
_x000D_
_x000D_
_x000D_

This uses the adjacent sibling selector, and is the basis of the suckerfish dropdown menu.

HTML5 allows anchor elements to wrap almost anything, so in that case the div element can be made a child of the anchor. Otherwise the principle is the same - use the :hover pseudo-class to change the display property of another element.

Printing HashMap In Java

keySet() only returns a set of keys from your hashmap, you should iterate this key set and the get the value from the hashmap using these keys.

In your example, the type of the hashmap's key is TypeKey, but you specified TypeValue in your generic for-loop, so it cannot be compiled. You should change it to :

for (TypeKey name: example.keySet()){
            String key = name.toString();
            String value = example.get(name).toString();  
            System.out.println(key + " " + value);  
} 

Update for Java8:

 example.entrySet().forEach(entry->{
    System.out.println(entry.getKey() + " " + entry.getValue());  
 });

If you don't require to print key value and just need the hashmap value, you can use others' suggestions.

Another question: Is this collection is zero base? I mean if it has 1 key and value will it size be 0 or 1?

The collection returned from keySet() is a Set.You cannot get the value from a Set using an index, so it is not a question of whether it is zero-based or one-based. If your hashmap has one key, the keySet() returned will have one entry inside, and its size will be 1.

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

How to validate a url in Python? (Malformed or not)

Actually, I think this is the best way.

from django.core.validators import URLValidator
from django.core.exceptions import ValidationError

val = URLValidator(verify_exists=False)
try:
    val('http://www.google.com')
except ValidationError, e:
    print e

If you set verify_exists to True, it will actually verify that the URL exists, otherwise it will just check if it's formed correctly.

edit: ah yeah, this question is a duplicate of this: How can I check if a URL exists with Django’s validators?

Jquery button click() function is not working

You need to use a delegated event handler, as the #add elements dynamically appended won't have the click event bound to them. Try this:

$("#buildyourform").on('click', "#add", function() {
    // your code...
});

Also, you can make your HTML strings easier to read by mixing line quotes:

var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');

Or even supplying the attributes as an object:

var fieldWrapper = $('<div></div>', { 
    'class': 'fieldwrapper',
    'name': 'field' + intId,
    'id': 'field' + intId
});

SOAP client in .NET - references or examples?

Here you can find a nice tutorial for calling a NuSOAP-based web-service from a .NET client application. But IMO, you should also consider the WSO2 Web Services Framework for PHP (WSO2 WSF/PHP) for servicing. See WSO2 Web Services Framework for PHP 2.0 Significantly Enhances Industry’s Only PHP Library for Creating Both SOAP and REST Services. There is also a webminar about it.

Now, in .NET world I also encourage the use of WCF, taking into account the interoperability issues. An interoperability example can be found here, but this example uses a PHP-client + WCF-service instead of the opposite. Feel free to implement the PHP-service & WFC-client.

There are some WCF's related open source projects on codeplex.com that I found very productive. These projects are very useful to design & implement Win Forms and Windows Presentation Foundation applications: Smart Client, Web Client and Mobile Client. They can be used in combination with WCF to wisely call any kind of Web services.

Generally speaking, the patterns & practices team summarize good practices & designs in various open source projects that dealing with the .NET platform, specially for the web. So I think it's a good starting point for any design decision related to .NET clients.

Jquery to get the id of selected value from dropdown

First set a custom attribute into your option for example nameid (you can set non-standardized attribute of an HTML element, it's allowed):

'<option nameid= "' + n.id + "' value="' + i + '">' + n.names + '</option>'

then you can easily get attribute value using jquery .attr() :

$('option:selected').attr("nameid")

For Example:

<select id="jobSel" class="longcombo" onchange="GetNameId">
    <option nameid="32" value="1">test1</option>
    <option nameid="67" value="1">test2</option>
    <option nameid="45" value="1">test3</option>    
    </select>    

Jquery:

function GetNameId(){
   alert($('#jobSel option:selected').attr("nameid"));
}

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Can't access 127.0.0.1

In windows first check under services if world wide web publishing services is running. If not start it.

If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.

How to set a JVM TimeZone Properly

On windows 7 and for JDK6, I had to add -Duser.timezone="Europe/Sofia" to the JAVA_TOOL_OPTIONS system variable located under "My computer=>Properties=>Advanced System Settings=>Environment Variables".

If you already have some other property set for JAVA_TOOL_OPTIONS just append a space and then insert your property string.

Using scanner.nextLine()

or

int selection = Integer.parseInt(scanner.nextLine());

Iterate through object properties

You basically want to loop through each property in the object.

JSFiddle

var Dictionary = {
  If: {
    you: {
      can: '',
      make: ''
    },
    sense: ''
  },
  of: {
    the: {
      sentence: {
        it: '',
        worked: ''
      }
    }
  }
};

function Iterate(obj) {
  for (prop in obj) {
    if (obj.hasOwnProperty(prop) && isNaN(prop)) {
      console.log(prop + ': ' + obj[prop]);
      Iterate(obj[prop]);
    }
  }
}
Iterate(Dictionary);

How to select a column name with a space in MySQL

Generally the first step is to not do that in the first place, but if this is already done, then you need to resort to properly quoting your column names:

SELECT `Business Name` FROM annoying_table

Usually these sorts of things are created by people who have used something like Microsoft Access and always use a GUI to do their thing.

Reverse a string in Java

String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);

How to detect when keyboard is shown and hidden

Swift 5

There answers above are correct. Although I would prefer to create a helper to wrap up the notification's observers.

The benefit:

  1. You don't have to repeat each time you handle the keyboard behaviors.
  2. You can extend other notification by implement other enum value
  3. It's useful when you have to deal with keyboard in several controllers.

Sample code:

extension KeyboardHelper {
    enum Animation {
        case keyboardWillShow
        case keyboardWillHide
    }

    typealias HandleBlock = (_ animation: Animation, _ keyboardFrame: CGRect, _ duration: TimeInterval) -> Void
}

final class KeyboardHelper {
    private let handleBlock: HandleBlock

    init(handleBlock: @escaping HandleBlock) {
        self.handleBlock = handleBlock
        setupNotification()
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    private func setupNotification() {
        _ = NotificationCenter.default
            .addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weak self] notification in
                self?.handle(animation: .keyboardWillShow, notification: notification)
            }

        _ = NotificationCenter.default
            .addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { [weak self] notification in
                self?.handle(animation: .keyboardWillHide, notification: notification)
            }
    }

    private func handle(animation: Animation, notification: Notification) {
        guard let userInfo = notification.userInfo,
            let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
        else { return }

        handleBlock(animation, keyboardFrame, duration)
    }
}

How to use:

private var keyboardHelper: KeyboardHelper?
...

override func viewDidLoad() {
   ...
   keyboardHelper = KeyboardHelper { [unowned self] animation, keyboardFrame, duration in
        switch animation {
        case .keyboardWillShow:
            print("keyboard will show")
        case .keyboardWillHide:
            print("keyboard will hide")
        }
    }

}

In Git, how do I figure out what my current revision is?

There are many ways git log -1 is the easiest and most common, I think

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

How to Display Selected Item in Bootstrap Button Dropdown Title

Here is my version of this which I hope can save some of your time :)

enter image description here jQuery PART:

$(".dropdown-menu").on('click', 'li a', function(){
  var selText = $(this).children("h4").html();


 $(this).parent('li').siblings().removeClass('active');
    $('#vl').val($(this).attr('data-value'));
  $(this).parents('.btn-group').find('.selection').html(selText);
  $(this).parents('li').addClass("active");
});

HTML PART:

<div class="container">
  <div class="btn-group">
    <a class="btn btn-default dropdown-toggle btn-blog " data-toggle="dropdown" href="#" id="dropdownMenu1" style="width:200px;"><span class="selection pull-left">Select an option </span> 
      <span class="pull-right glyphiconglyphicon-chevron-down caret" style="float:right;margin-top:10px;"></span></a>

     <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
       <li><a href="#" class="" data-value=1><p> HER Can you write extra text or <b>HTLM</b></p> <h4> <span class="glyphicon glyphicon-plane"></span>  <span> Your Option 1</span> </h4></a>  </li>
       <li><a href="#" class="" data-value=2><p> HER Can you write extra text or <i>HTLM</i> or some long long long long long long long long long long text </p><h4> <span class="glyphicon glyphicon-briefcase"></span> <span>Your Option 2</span>  </h4></a>
      </li>
      <li class="divider"></li>
   <li><a href="#" class="" data-value=3><p> HER Can you write extra text or <b>HTLM</b> or some </p><h4> <span class="glyphicon glyphicon-heart text-danger"></span> <span>Your Option 3</span>  </h4></a>
      </li>
    </ul>
  </div>
  <input type="text" id="vl" />
</div>  

Capture key press without placing an input element on the page?

Detect key press, including key combinations:

window.addEventListener('keydown', function (e) {
  if (e.ctrlKey && e.keyCode == 90) {
    // Ctrl + z pressed
  }
});

Benefit here is that you are not overwriting any global properties, but instead merely introducing a side effect. Not good, but definitely a whole lot less nefarious than other suggestions on here.

Where do I find the line number in the Xcode editor?

  1. Go to Xcode preferences by clicking on "Xcode" in the left hand side upper corner.

  2. Select "Text Editing".

  3. Select "Show: Line numbers" and click on check box for enable it.

  4. Close it.

Then you will see the line number in Xcode.

How do I get a div to float to the bottom of its container?

A chose this approach of @dave-kok. But it works only if the whole content suits without scrolling. I appreciate if somebody will improve

outer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 100%;
}
.space {
    float: right;
    height: 75%;  
}
.floateable {
    width: 40%;
    height: 25%;
    float: right;
    clear: right;  
 }

Here is code http://jsfiddle.net/d9t9joh2/

How do I calculate the normal vector of a line segment?

If we define dx = x2 - x1 and dy = y2 - y1, then the normals are (-dy, dx) and (dy, -dx).

Note that no division is required, and so you're not risking dividing by zero.

How to edit default.aspx on SharePoint site without SharePoint Designer

You can always use Sharepoint Solution Generator to create a project and edit in VS2008.

You can find the Generator along with Sharepoint Developer tools.