Programs & Examples On #Hadoop plugins

Plugins for the Apache™ Hadoop™ project.

RecyclerView vs. ListView

Major advantage :

ViewHolder is not available by default in ListView. We will be creating explicitly inside the getView(). RecyclerView has inbuilt Viewholder.

Convert Uri to String and String to Uri

I am not sure if you got this resolved. To follow up on "CommonsWare's" comment.

That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.

Change

Uri uri=Uri.parse("/external/images/media/470939");

to

Uri uri=Uri.parse("content://external/images/media/470939");

in my case

Uri uri = Uri.parse("content://media/external/images/media/6562");

How to make Bootstrap carousel slider use mobile left/right swipe

Same functionality I prefer than using much heavy jQuery mobile is Carousel Swipe. I suggest directly jump in to source code on github, and copy file carousel-swipe.js in to your project directory.

Use swiper events as bellow:

$('#carousel-example-generic').carousel({
      interval: false 
  });

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

Tip #2

Can't you use the classical 2> redirection operator.

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL
if(!$?){
   'foo'
}

I don't like errors so I avoid them at all costs.

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

You can also get a direct link to a view within a folder by using "TreeValue", "TreeField" and "RootFolder".

Example:

http://sharepoint/Docs/YourLibrary/Forms/YourView.aspx?RootFolder=MyFolder&TreeField=Folders&TreeValue=MyFolder

To further explain: I have a SharePoint site, with a docs library called YourLibrary. I have a folder called MyFolder. I created a view that can be used at any level of that Library structure with a URL path of YourView.aspx Using that link, it will take me to the view I created, with all the filters and styles, but only show the results that would occur in the contents of that folder in RootFolder and TreeValue.

EditorFor() and html properties

I'm surprised no one mentioned passing it in "additionalViewData" and reading it on the other side.

View (with line breaks, for clarity):

<%= Html.EditorFor(c => c.propertyname, new
    {
        htmlAttributes = new
        {
            @class = "myClass"
        }
    }
)%>

Editor template:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>

<%= Html.TextBox("", Model, ViewData["htmlAttributes"])) %>

Converting Go struct to JSON

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

How do I delete multiple rows in Entity Framework (without foreach)

For anyone using EF5, following extension library can be used: https://github.com/loresoft/EntityFramework.Extended

context.Widgets.Delete(w => w.WidgetId == widgetId);

Running multiple async tasks and waiting for them all to complete

Yet another answer...but I usually find myself in a case, when I need to load data simultaneously and put it into variables, like:

var cats = new List<Cat>();
var dog = new Dog();

var loadDataTasks = new Task[]
{
    Task.Run(async () => cats = await LoadCatsAsync()),
    Task.Run(async () => dog = await LoadDogAsync())
};

try
{
    await Task.WhenAll(loadDataTasks);
}
catch (Exception ex)
{
    // handle exception
}

Add spaces between the characters of a string in Java?

I believe what he was looking for was mime code carrier return type code such as %0D%0A (for a Return or line break) and \u00A0 (for spacing) or alternatively $#032

How do I measure separate CPU core usage for a process?

dstat -C 0,1,2,3 

Will also give you the CPU usage of first 4 cores. Of course, if you have 32 cores then this command gets a little bit longer but useful if you only interested in few cores.

For example, if you only interested in core 3 and 7 then you could do

dstat -C 3,7

How do I compile the asm generated by GCC?

You can use GAS, which is gcc's backend assembler:

http://linux.die.net/man/1/as

How to convert a date String to a Date or Calendar object?

tl;dr

LocalDate.parse( "2015-01-02" )

java.time

Java 8 and later has a new java.time framework that makes these other answers outmoded. This framework is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See the Tutorial.

The old bundled classes, java.util.Date/.Calendar, are notoriously troublesome and confusing. Avoid them.

LocalDate

Like Joda-Time, java.time has a class LocalDate to represent a date-only value without time-of-day and without time zone.

ISO 8601

If your input string is in the standard ISO 8601 format of yyyy-MM-dd, you can ask that class to directly parse the string with no need to specify a formatter.

The ISO 8601 formats are used by default in java.time, for both parsing and generating string representations of date-time values.

LocalDate localDate = LocalDate.parse( "2015-01-02" );

Formatter

If you have a different format, specify a formatter from the java.time.format package. You can either specify your own formatting pattern or let java.time automatically localize as appropriate to a Locale specifying a human language for translation and cultural norms for deciding issues such as period versus comma.

Formatting pattern

Read the DateTimeFormatter class doc for details on the codes used in the format pattern. They vary a bit from the old outmoded java.text.SimpleDateFormat class patterns.

Note how the second argument to the parse method is a method reference, syntax added to Java 8 and later.

String input = "January 2, 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "MMMM d, yyyy" , Locale.US );
LocalDate localDate = LocalDate.parse ( input , formatter );

Dump to console.

System.out.println ( "localDate: " + localDate );

localDate: 2015-01-02

Localize automatically

Or rather than specify a formatting pattern, let java.time localize for you. Call DateTimeFormatter.ofLocalizedDate, and be sure to specify the desired/expected Locale rather than rely on the JVM’s current default which can change at any moment during runtime(!).

String input = "January 2, 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG );
formatter = formatter.withLocale ( Locale.US );
LocalDate localDate = LocalDate.parse ( input , formatter );

Dump to console.

System.out.println ( "input: " + input + " | localDate: " + localDate );

input: January 2, 2015 | localDate: 2015-01-02

Conda: Installing / upgrading directly from github

I found a reference to this in condas issues. The following should now work.

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - git+https://github.com/pythonforfacebook/facebook-sdk.git

How to make a checkbox checked with jQuery?

You don't need to control your checkBoxes with jQuery. You can do it with some simple JavaScript.

This JS snippet should work fine:

document.TheFormHere.test.Value = true;

find if an integer exists in a list of integers

The way you did is correct. It works fine with that code: x is true. probably you made a mistake somewhere else.

List<int> ints = new List<int>( new[] {1,5,7}); // 1

List<int> intlist=new List<int>() { 0,2,3,4,1}; // 2

var i = 5;
var x = ints.Contains(i);   // return true or false

QtCreator: No valid kits found

For QT 5.* if you face error at Kits, like No Valid Kits Found, go to Options->Build&Run-> (Kits tab) then you see a Manual category which should list Desktop as the default.

Just go to your OS Terminal and write sudo apt-get install qt5-default, go back to QT Creator and Start your New Project, and there you see the kit option Desktop included in the list.

Cancel split window in Vim

From :help opening-window (search for "Closing a window" - /Closing a window)

  • :q[uit] close the current window and buffer. If it is the last window it will also exit vim
  • :bd[elete] unload the current buffer and close the current window
  • :qa[all] or :quita[ll] will close all buffers and windows and exit vim (:qa! to force without saving changes)
  • :clo[se] close the current window but keep the buffer open. If there is only one window this command fails
  • :hid[e] hide the buffer in the current window (Read more at :help hidden)
  • :on[ly] close all other windows but leave all buffers open

Regular expression for checking if capital letters are found consecutively in a string?

Aside from tchrists excellent post concerning unicode, I think you don't need the complex solution with a negative lookahead... Your definition requires an Uppercase-letter followed by at least one group of (a lowercase letter optionally followed by an Uppercase-letter)

^
[A-Z]    // Start with an uppercase Letter
(        // A Group of:
  [a-z]  // mandatory lowercase letter
  [A-Z]? // an optional Uppercase Letter at the end
         // or in between lowercase letters
)+       // This group at least one time
$

Just a bit more compact and easier to read I think...

Run JavaScript when an element loses focus

You're looking for the onblur event. Look here, for more details.

How to correctly close a feature branch in Mercurial?

imho there are two cases for branches that were forgot to close

Case 1: branch was not merged into default

in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.

hg up myBranch
hg commit --close-branch

Case 2: branch was merged into default

This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.

in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!

hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch

Hope this helps future readers.

How to add bootstrap to an angular-cli project

It doesn't matter which JS framework you are using, importing bootstrap to your project is easy by following 2 steps below:

Install bootstrap using npm i -S bootstrap or yarn add bootstrap.

In styles.css or styles.scss, import bootstrap as @import '~bootstrap/dist/css/bootstrap.min.css'.

Create database from command line

PostgreSQL Create Database - Steps to create database in Postgres.

  1. Login to server using postgres user.
    su - postgres
  2. Connect to postgresql database.
bash-4.1$ psql
psql (12.1)
Type "help" for help.
postgres=#
  1. Execute below command to create database.
CREATE DATABASE database_name;

Check for detailed information below: https://orahow.com/postgresql-create-database/

Fling gesture detection on grid layout

Gestures are those subtle motions to trigger interactions between the touch screen and the user. It lasts for the time between the first touch on the screen to the point when the last finger leaves the surface.

Android provides us with a class called GestureDetector using which we can detect common gestures like tapping down and up, swiping vertically and horizontally (fling), long and short press, double taps, etc. and attach listeners to them.

Make our Activity class implement GestureDetector.OnDoubleTapListener (for double tap gesture detection) and GestureDetector.OnGestureListener interfaces and implement all the abstract methods.For more info. you may visit https://developer.android.com/training/gestures/detector.html . Courtesy

For Demo Test.GestureDetectorDemo

What is the minimum I have to do to create an RPM file?

Similarly, I needed to create an rpm with just a few files. Since these files were source controlled, and because it seemed silly, I didn't want to go through taring them up just to have rpm untar them. I came up with the following:

  1. Set up your environment:

    mkdir -p ~/rpm/{BUILD,RPMS}

    echo '%_topdir %(echo "$HOME")/rpm' > ~/.rpmmacros

  2. Create your spec file, foobar.spec, with the following contents:

    Summary: Foo to the Bar
    Name: foobar
    Version: 0.1
    Release: 1
    Group: Foo/Bar
    License: FooBarPL
    Source: %{expand:%%(pwd)}
    BuildRoot: %{_topdir}/BUILD/%{name}-%{version}-%{release}
    
    %description
    %{summary}
    
    %prep
    rm -rf $RPM_BUILD_ROOT
    mkdir -p $RPM_BUILD_ROOT/usr/bin
    mkdir -p $RPM_BUILD_ROOT/etc
    cd $RPM_BUILD_ROOT
    cp %{SOURCEURL0}/foobar ./usr/bin/
    cp %{SOURCEURL0}/foobar.conf ./etc/
    
    %clean
    rm -r -f "$RPM_BUILD_ROOT"
    
    %files
    %defattr(644,root,root)
    %config(noreplace) %{_sysconfdir}/foobar.conf
    %defattr(755,root,root)
    %{_bindir}/foobar
    
  3. Build your rpm: rpmbuild -bb foobar.spec

There's a little hackery there specifying the 'source' as your current directory, but it seemed far more elegant then the alternative, which was to, in my case, write a separate script to create a tarball, etc, etc.

Note: In my particular situation, my files were arranged in folders according to where they needed to go, like this:

./etc/foobar.conf
./usr/bin/foobar

and so the prep section became:

%prep
rm -rf $RPM_BUILD_ROOT
mkdir -p $RPM_BUILD_ROOT
cd $RPM_BUILD_ROOT
tar -cC %{SOURCEURL0} --exclude 'foobar.spec' -f - ./ | tar xf -

Which is a little cleaner.

Also, I happen to be on a RHEL5.6 with rpm versions 4.4.2.3, so your mileage may vary.

Merging two images in C#/.NET

This will add an image to another.

using (Graphics grfx = Graphics.FromImage(image))
{
    grfx.DrawImage(newImage, x, y)
}

Graphics is in the namespace System.Drawing

How to restart a node.js server

At first open terminal/command line then go to your project directory, now install nodemon by using command npm install nodemon --save-dev this command will make sure it saved as developer dependency. If you are working with expressjs then in your package file it will look like

{
  "name": "expressjs-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "^2.0.4"
  },
  "devDependencies": {
    "nodemon": "^2.0.3"
  }
}

now modify the "start" value in your package.json file, for production we will use the exsiting value but for development will use nodemon to track the changes in source file without restarting server. There for new value for start is "start": "if [[$NODE_ENV=='production']]; then node ./bin/www; else nodemon ./bin/www; fi"

final package.json file will look like

{
  "name": "expressjs-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "if [[$NODE_ENV=='production']]; then node ./bin/www; else nodemon ./bin/www; fi"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "^2.0.4"
  },
  "devDependencies": {
    "nodemon": "^2.0.3"
  }
}

to uninstall nodemon jusy simply run the command npm uninstall nodemon

How to bind a List to a ComboBox?

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }

    public Country()
    {
        Cities = new List<City>();
    }
}

public class City 
{
    public string Name { get; set; } 
}

List<Country> Countries = new List<Country>
{
    new Country
    {
        Name = "Germany",
        Cities =
        {
            new City {Name = "Berlin"},
            new City {Name = "Hamburg"}
        }
    },
    new Country
    {
        Name = "England",
        Cities =
        {
            new City {Name = "London"},
            new City {Name = "Birmingham"}
        }
    }
};
bindingSource1.DataSource = Countries;
member_CountryComboBox.DataSource = bindingSource1.DataSource;
member_CountryComboBox.DisplayMember = "Name";
member_CountryCombo

Box.ValueMember = "Name";

This is the code I am using now.

Check if the number is integer

Reading the R language documentation, as.integer has more to do with how the number is stored than if it is practically equivalent to an integer. is.integer tests if the number is declared as an integer. You can declare an integer by putting a L after it.

> is.integer(66L)
[1] TRUE
> is.integer(66)
[1] FALSE

Also functions like round will return a declared integer, which is what you are doing with x==round(x). The problem with this approach is what you consider to be practically an integer. The example uses less precision for testing equivalence.

> is.wholenumber(1+2^-50)
[1] TRUE
> check.integer(1+2^-50)
[1] FALSE

So depending on your application you could get into trouble that way.

JavaScript chop/slice/trim off last character in string

You can, in fact, remove the last arr.length - 2 items of an array using arr.length = 2, which if the array length was 5, would remove the last 3 items.

Sadly, this does not work for strings, but we can use split() to split the string, and then join() to join the string after we've made any modifications.

_x000D_
_x000D_
var str = 'string'

String.prototype.removeLast = function(n) {
  var string = this.split('')
  string.length = string.length - n

  return string.join('')
}

console.log(str.removeLast(3))
_x000D_
_x000D_
_x000D_

Saving images in Python at a very high quality

If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image:

plt.savefig('destination_path.eps', format='eps')

I have found that EPS files work best and the dpi parameter is what really makes them look good in a document.

To specify the orientation of the figure before saving, simply call the following before the plt.savefig call, but after creating the plot (assuming you have plotted using an axes with the name ax):

ax.view_init(elev=elevation_angle, azim=azimuthal_angle)

Where elevation_angle is a number (in degrees) specifying the polar angle (down from vertical z axis) and the azimuthal_angle specifies the azimuthal angle (around the z axis).

I find that it is easiest to determine these values by first plotting the image and then rotating it and watching the current values of the angles appear towards the bottom of the window just below the actual plot. Keep in mind that the x, y, z, positions appear by default, but they are replaced with the two angles when you start to click+drag+rotate the image.

Splitting a string into separate variables

Foreach-object operation statement:

$a,$b = 'hi.there' | foreach split .
$a,$b

hi
there

jQuery changing css class to div

$(document).ready(function () {

            $("#divId").toggleClass('cssclassname'); // toggle class
});

**OR**

$(document).ready(function() {
        $("#objectId").click(function() {  // click or other event to change the div class
                $("#divId").toggleClass("cssclassname");     // toggle class
        )}; 
)};

How to insert array of data into mysql using php

I've a PHP library which helps to insert array into MySQL Database. By using this you can create update and delete. Your array key value should be same as the table column value. Just using a single line code for the create operation

DB::create($db, 'YOUR_TABLE_NAME', $dataArray);

where $db is your Database connection.

Similarly, You can use this for update and delete. Select operation will be available soon. Github link to download : https://github.com/pairavanvvl/crud

Split string into array of characters?

According to this code golfing solution by Gaffi, the following works:

a = Split(StrConv(s, 64), Chr(0))

Regex to check with starts with http://, https:// or ftp://

You need a whole input match here.

System.out.println(test.matches("^(http|https|ftp)://.*$")); 

Edit:(Based on @davidchambers's comment)

System.out.println(test.matches("^(https?|ftp)://.*$")); 

Java rounding up to an int using Math.ceil

Java provides only floor division / by default. But we can write ceiling in terms of floor. Let's see:

Any integer y can be written with the form y == q*k+r. According to the definition of floor division (here floor) which rounds off r,

floor(q*k+r, k) == q  , where 0 = r = k-1

and of ceiling division (here ceil) which rounds up r1,

ceil(q*k+r1, k) == q+1  , where 1 = r1 = k

where we can substitute r+1 for r1:

ceil(q*k+r+1, k) == q+1  , where 0 = r = k-1


Then we substitute the first equation into the third for q getting

ceil(q*k+r+1, k) == floor(q*k+r, k) + 1  , where 0 = r = k-1

Finally, given any integer y where y = q*k+r+1 for some q,k,r, we have

ceil(y, k) == floor(y-1, k) + 1

And we are done. Hope this helps.

How to solve time out in phpmyadmin?

I had the same issue and I used command line in order to import the SQL file. This method has 3 advantages:

  1. It is a very easy way by running only 1 command line
  2. It runs way faster
  3. It does not have limitation

If you want to do this just follow this 3 steps:

  1. Navigate to this path (i use wamp):

    C:\wamp\bin\mysql\mysql5.6.17\bin>

  2. Copy your sql file inside this path (ex file.sql)

  3. Run this command:

    mysql -u username -p database_name < file.sql

Note: if you already have your msql enviroment variable path set, you don't need to move your file.sql in the bin directory and you should only navigate to the path of the file.

Resize image with javascript canvas (smoothly)

Based on K3N answer, I rewrite code generally for anyone wants

var oc = document.createElement('canvas'), octx = oc.getContext('2d');
    oc.width = img.width;
    oc.height = img.height;
    octx.drawImage(img, 0, 0);
    while (oc.width * 0.5 > width) {
       oc.width *= 0.5;
       oc.height *= 0.5;
       octx.drawImage(oc, 0, 0, oc.width, oc.height);
    }
    oc.width = width;
    oc.height = oc.width * img.height / img.width;
    octx.drawImage(img, 0, 0, oc.width, oc.height);

UPDATE JSFIDDLE DEMO

Here is my ONLINE DEMO

Java Replace Line In Text File

just how to replace strings :) as i do first arg will be filename second target string third one the string to be replaced instead of targe

public class ReplaceString{
      public static void main(String[] args)throws Exception {
        if(args.length<3)System.exit(0);
        String targetStr = args[1];
        String altStr = args[2];
        java.io.File file = new java.io.File(args[0]);
        java.util.Scanner scanner = new java.util.Scanner(file);
        StringBuilder buffer = new StringBuilder();
        while(scanner.hasNext()){
          buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
          if(scanner.hasNext())buffer.append("\n");
        }
        scanner.close();
        java.io.PrintWriter printer = new java.io.PrintWriter(file);
        printer.print(buffer);
        printer.close();
      }
    }

I forgot the password I entered during postgres installation

The file .pgpass in a user's home directory or the file referenced by PGPASSFILE can contain passwords to be used if the connection requires a password (and no password has been specified otherwise). On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile).

This file should contain lines of the following format:

hostname:port:database:username:password

(You can add a reminder comment to the file by copying the line above and preceding it with #.) Each of the first four fields can be a literal value, or *, which matches anything. The password field from the first line that matches the current connection parameters will be used. (Therefore, put more-specific entries first when you are using wildcards.) If an entry needs to contain : or \, escape this character with . A host name of localhost matches both TCP (host name localhost) and Unix domain socket (pghost empty or the default socket directory) connections coming from the local machine. In a standby server, a database name of replication matches streaming replication connections made to the master server. The database field is of limited usefulness because users have the same password for all databases in the same cluster.

On Unix systems, the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored. On Microsoft Windows, it is assumed that the file is stored in a directory that is secure, so no special permissions check is made.

jQuery: Can I call delay() between addClass() and such?

delay does not work on none queue functions, so we should use setTimeout().

And you don't need to separate things. All you need to do is including everything in a setTimeOut method:

setTimeout(function () {
    $("#div").addClass("error").delay(1000).removeClass("error");
}, 1000);

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

Are you using Git-Bash in Windows? I was getting the same error until I tried PowerShell and magically this error disappeared.

Trying to get Laravel 5 email to work

None of the above solutions worked for me on localhost. I even allowed access from less secure apps, allowed access through display unlock captcha and set the verify peer and verify peer name to false for SSL.

Eventually, I used the open source SMTP testing solution of MailHog. The steps are as follows:

  1. Download the latest version of MailHog for your OS
  2. Specify the following settings in your .env file

MAIL_DRIVER=smtp

MAIL_HOST=127.0.0.1

MAIL_PORT=1025

MAIL_USERNAME=testuser

MAIL_PASSWORD=testpwd

MAIL_ENCRYPTION=null

[email protected]

  1. Run the downloaded file of MailHog
  2. Send Email
  3. Check sent email by going to localhost:8025

How can I align button in Center or right using IONIC framework?

To use center alignment in ionic app code itself, you can use the following code:

<ion-row center>  
 <ion-col text-center>   
  <button ion-button>Search</button>  
 </ion-col> 
</ion-row>

To use right alignment in ionic app code itself, you can use the following code:

<ion-row right>  
 <ion-col text-right>   
  <button ion-button>Search</button>  
 </ion-col> 
</ion-row>

Load an image from a url into a PictureBox

If you are trying to load the image at your form_load, it's a better idea to use the code

pictureBox1.LoadAsync(@"http://google.com/test.png");

not only loading from web but also no lag in your form loading.

How to detect if JavaScript is disabled?

I think you could insert an image tag into a noscript tag and look at the stats how many times your site and how often this image has been loaded.

TimePicker Dialog from clicking EditText

public class **Your java Class** extends ActionBarActivity implements  View.OnClickListener{
date = (EditText) findViewById(R.id.date);
date.setInputType(InputType.TYPE_NULL);
        date.requestFocus();
        date.setOnClickListener(this);
        dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

        setDateTimeField();

private void setDateTimeField() {
        Calendar newCalendar = Calendar.getInstance();
        fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                date.setText(dateFormatter.format(newDate.getTime()));
            }

        }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));

    }
@Override
    public void onClick(View v) {
        fromDatePickerDialog.show();
    }
}

How do I use method overloading in Python?

I write my answer in Python 3.2.1.

def overload(*functions):
    return lambda *args, **kwargs: functions[len(args)](*args, **kwargs)

How it works:

  1. overload takes any amount of callables and stores them in tuple functions, then returns lambda.
  2. The lambda takes any amount of arguments, then returns result of calling function stored in functions[number_of_unnamed_args_passed] called with arguments passed to the lambda.

Usage:

class A:
    stackoverflow=overload(                    \
        None, \ 
        #there is always a self argument, so this should never get called
        lambda self: print('First method'),      \
        lambda self, i: print('Second method', i) \
    )

How to break lines in PowerShell?

I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)

Thanks!

Can't install nuget package because of "Failed to initialize the PowerShell host"

All I needed to do was restart Visual Studio, open the NuGet Package Manager Console, and then using the Manage NuGet Packages dialog worked.

Single TextView with multiple colored text

I don't know, since when this is possible, but you can simply add <font> </font> to your string.xml which will automatically change the color per text. No need to add any additional code such as spannable text etc.

Example

<string name="my_formatted_text">
    <font color="#FF0707">THIS IS RED</font>
    <font color="#0B132B">AND NOW BLUE</font>
</string>

Stored procedure - return identity as output parameter or scalar

SELECT IDENT_CURRENT('databasename.dbo.tablename') AS your identity column;

Delete specific line number(s) from a text file using sed?

This is very often a symptom of an antipattern. The tool which produced the line numbers may well be replaced with one which deletes the lines right away. For example;

grep -nh error logfile | cut -d: -f1 | deletelines logfile

(where deletelines is the utility you are imagining you need) is the same as

grep -v error logfile

Having said that, if you are in a situation where you genuinely need to perform this task, you can generate a simple sed script from the file of line numbers. Humorously (but perhaps slightly confusingly) you can do this with sed.

sed 's%$%d%' linenumbers

This accepts a file of line numbers, one per line, and produces, on standard output, the same line numbers with d appended after each. This is a valid sed script, which we can save to a file, or (on some platforms) pipe to another sed instance:

sed 's%$%d%' linenumbers | sed -f - logfile

On some platforms, sed -f does not understand the option argument - to mean standard input, so you have to redirect the script to a temporary file, and clean it up when you are done, or maybe replace the lone dash with /dev/stdin or /proc/$pid/fd/1 if your OS (or shell) has that.

As always, you can add -i before the -f option to have sed edit the target file in place, instead of producing the result on standard output. On *BSDish platforms (including OSX) you need to supply an explicit argument to -i as well; a common idiom is to supply an empty argument; -i ''.

Oracle - What TNS Names file am I using?

On my development machine I have three different versions of Oracle client software. I manage the tnsnames.ora file in one of them. In the other two, I have entered in the tnsnames.ora file:

ifile=path_to_tnsnames.ora_file/tnsnames.ora

This way, if for some reason the wrong tnsnames.ora file is used by a client, it will always end up at the up-to-date version.

Using variables inside a bash heredoc

Don't use quotes with <<EOF:

var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF

Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).

What is the "hasClass" function with plain JavaScript?

The most effective one liner that

  • returns a boolean (as opposed to Orbling's answer)
  • Does not return a false positive when searching for thisClass on an element that has class="thisClass-suffix".
  • is compatible with every browser down to at least IE6

function hasClass( target, className ) {
    return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
}

Swift - how to make custom header for UITableView?

Did you set the section header height in the viewDidLoad?

self.tableView.sectionHeaderHeight = 70

Plus you should replace

self.view.addSubview(view)

by

view.addSubview(label)

Finally you have to check your frames

let view = UIView(frame: CGRect.zeroRect)

and eventually the desired text color as it seems to be currently white on white.

Mocha / Chai expect.to.throw not catching thrown errors

As this answer says, you can also just wrap your code in an anonymous function like this:

expect(function(){
    model.get('z');
}).to.throw('Property does not exist in model schema.');

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

I know I'm late to the party but you can accomplish this with plain CSS as well:

HTML:

(It can be any HTML element, if you're using an inline element like a <span> for example, make sure you make it a block/inline-block element with display:block; or display:inline-block):

<div class="up"></div>

and

<div class="down"></div>

CSS:

.up {
   height:0;
   width:0;
   border-top:100px solid black;
   border-left:100px solid transparent;
   transform:rotate(-45deg);   
  }

.down {
   height:0;
   width:0;
   border-bottom:100px solid black;
   border-right:100px solid transparent;
   transform:rotate(-45deg); 
  }

You can also accomplish it using :before and :after pseudo-elements, which is actually a better way since you avoid creating extra markup. But that's up to you on how you'd like to accomplish it.

--

Here's a Demo in CodePen with many arrow possibilities.

How to add a new column to a CSV file?

I used pandas and it worked well... While I was using it, I had to open a file and add some random columns to it and then save back to same file only.

This code adds multiple column entries, you may edit as much you need.

import pandas as pd

csv_input = pd.read_csv('testcase.csv')         #reading my csv file
csv_input['Phone1'] = csv_input['Name']         #this would also copy the cell value 
csv_input['Phone2'] = csv_input['Name']
csv_input['Phone3'] = csv_input['Name']
csv_input['Phone4'] = csv_input['Name']
csv_input['Phone5'] = csv_input['Name']
csv_input['Country'] = csv_input['Name']
csv_input['Website'] = csv_input['Name']
csv_input.to_csv('testcase.csv', index=False)   #this writes back to your file

If you want that cell value doesn't gets copy, so first of all create a empty Column in your csv file manually, like you named it as Hours then, Now for this you can add this line in above code,

csv_input['New Value'] = csv_input['Hours']

or simply we can, without adding the manual column, we can

csv_input['New Value'] = ''    #simple and easy

I Hope it helps.

How do I resolve git saying "Commit your changes or stash them before you can merge"?

Before using reset think about using revert so you can always go back.

https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert

On request

Source: https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert

git reset vs git revert   sonic0002        2019-02-02 08:26:39 

When maintaining code using version control systems such as git, it is unavoidable that we need to rollback some wrong commits either due to bugs or temp code revert. In this case, rookie developers would be very nervous because they may get lost on what they should do to rollback their changes without affecting others, but to veteran developers, this is their routine work and they can show you different ways of doing that. In this post, we will introduce two major ones used frequently by developers.

  • git reset
  • git revert

What are their differences and corresponding use cases? We will discuss them in detail below. git reset Assuming we have below few commits. enter image description here

Commit A and B are working commits, but commit C and D are bad commits. Now we want to rollback to commit B and drop commit C and D. Currently HEAD is pointing to commit D 5lk4er, we just need to point HEAD to commit B a0fvf8 to achieve what we want.  It's easy to use git reset command.

git reset --hard a0fvf8

After executing above command, the HEAD will point to commit B. enter image description here

But now the remote origin still has HEAD point to commit D, if we directly use git push to push the changes, it will not update the remote repo, we need to add a -f option to force pushing the changes.

git push -f

The drawback of this method is that all the commits after HEAD will be gone once the reset is done. In case one day we found that some of the commits ate good ones and want to keep them, it is too late. Because of this, many companies forbid to use this method to rollback changes.

git revert The use of git revert is to create a new commit which reverts a previous commit. The HEAD will point to the new reverting commit.  For the example of git reset above, what we need to do is just reverting commit D and then reverting commit C. 

git revert 5lk4er
git revert 76sdeb

Now it creates two new commit D' and C',  enter image description here

In above example, we have only two commits to revert, so we can revert one by one. But what if there are lots of commits to revert? We can revert a range indeed.

git revert OLDER_COMMIT^..NEWER_COMMIT

This method would not have the disadvantage of git reset, it would point HEAD to newly created reverting commit and it is ok to directly push the changes to remote without using the -f option. Now let's take a look at a more difficult example. Assuming we have three commits but the bad commit is the second commit.  enter image description here

It's not a good idea to use git reset to rollback the commit B since we need to keep commit C as it is a good commit. Now we can revert commit C and B and then use cherry-pick to commit C again.  enter image description here

From above explanation, we can find out that the biggest difference between git reset and git revert is that git reset will reset the state of the branch to a previous state by dropping all the changes post the desired commit while git revert will reset to a previous state by creating new reverting commits and keep the original commits. It's recommended to use git revert instead of git reset in enterprise environment.  Reference: https://kknews.cc/news/4najez2.html

jQuery datepicker, onSelect won't work

$('.date-picker').datepicker({
                    autoclose : true,
                    todayHighlight : true,
                    clearBtn: true,
                    format: 'yyyy-mm-dd', 
                    onSelect: function(value, date) { 
                         alert(123);
                    },
                    todayBtn: "linked",
                    startView: 0, maxViewMode: 0,minViewMode:0

                    }).on('changeDate',function(ev){
                    //this is right events ,trust me
                    }
});

How do I upgrade to Python 3.6 with conda?

Best method I found:

source activate old_env
conda env export > old_env.yml

Then process it with something like this:

with open('old_env.yml', 'r') as fin, open('new_env.yml', 'w') as fout:
    for line in fin:
        if 'py35' in line:  # replace by the version you want to supersede
            line = line[:line.rfind('=')] + '\n'
        fout.write(line)

then edit manually the first (name: ...) and last line (prefix: ...) to reflect your new environment name and run:

conda env create -f new_env.yml

you might need to remove or change manually the version pin of a few packages for which which the pinned version from old_env is found incompatible or missing for the new python version.

I wish there was a built-in, easier way...

How to set the font style to bold, italic and underlined in an Android TextView?

I don't know about underline, but for bold and italic there is "bolditalic". There is no mention of underline here: http://developer.android.com/reference/android/widget/TextView.html#attr_android:textStyle

Mind you that to use the mentioned bolditalic you need to, and I quote from that page

Must be one or more (separated by '|') of the following constant values.

so you'd use bold|italic

You could check this question for underline: Can I underline text in an android layout?

How to store a list in a column of a database table

If you need to query on the list, then store it in a table.

If you always want the list, you could store it as a delimited list in a column. Even in this case, unless you have VERY specific reasons not to, store it in a lookup table.

How do you cache an image in Javascript

Even though your question says "using javascript", you can use the prefetch attribute of a link tag to preload any asset. As of this writing (Aug 10, 2016) it isn't supported in Safari, but is pretty much everywhere else:

<link rel="prefetch" href="(url)">

More info on support here: http://caniuse.com/#search=prefetch

Note that IE 9,10 aren't listed in the caniuse matrix because Microsoft has discontinued support for them.

So if you were really stuck on using javascript, you could use jquery to dynamically add these elements to your page as well ;-)

Binding a generic list to a repeater - ASP.NET

You should use ToList() method. (Don't forget about System.Linq namespace)

ex.:

IList<Model> models = Builder<Model>.CreateListOfSize(10).Build();
List<Model> lstMOdels = models.ToList();

How often should Oracle database statistics be run?

Make sure to balance the risk that fresh statistics cause undesirable changes to query plans against the risk that stale statistics can themselves cause query plans to change.

Imagine you have a bug database with a table ISSUE and a column CREATE_DATE where the values in the column increase more or less monotonically. Now, assume that there is a histogram on this column that tells Oracle that the values for this column are uniformly distributed between January 1, 2008 and September 17, 2008. This makes it possible for the optimizer to reasonably estimate the number of rows that would be returned if you were looking for all issues created last week (i.e. September 7 - 13). If the application continues to be used and the statistics are never updated, though, this histogram will be less and less accurate. So the optimizer will expect queries for "issues created last week" to be less and less accurate over time and may eventually cause Oracle to change the query plan negatively.

How to get client IP address using jQuery

function GetUserIP(){
  var ret_ip;
  $.ajaxSetup({async: false});
  $.get('http://jsonip.com/', function(r){ 
    ret_ip = r.ip; 
  });
  return ret_ip;
}

If you want to use the IP and assign it to a variable, Try this. Just call GetUserIP()

In a bootstrap responsive page how to center a div

Update for Bootstrap 4

Now that Bootstrap 4 is flexbox, vertical alignment is easier. Given a full height flexbox div, just us my-auto for even top and bottom margins...

<div class="container h-100 d-flex justify-content-center">
    <div class="jumbotron my-auto">
      <h1 class="display-3">Hello, world!</h1>
    </div>
</div>

http://codeply.com/go/ayraB3tjSd/bootstrap-4-vertical-center


Vertical center in Bootstrap 4

Is it possible to format an HTML tooltip (title attribute)?

Try using entity codes such as &#013; for CR, &#010; for LF, and &#009; for TAB.

For example:

_x000D_
_x000D_
<div title="1)&#009;A&#013;&#010;2)&#009;B">Hover Me</div>
_x000D_
_x000D_
_x000D_

How to declare strings in C

You shouldn't use the third one because its wrong. "String" takes 7 bytes, not 5.

The first one is a pointer (can be reassigned to a different address), the other two are declared as arrays, and cannot be reassigned to different memory locations (but their content may change, use const to avoid that).

Checking for the correct number of arguments

cat script.sh

    var1=$1
    var2=$2
    if [ "$#" -eq 2 ]
    then
            if [ -d $var1 ]
            then
            echo directory ${var1} exist
            else
            echo Directory ${var1} Does not exists
            fi
            if [ -d $var2 ]
            then
            echo directory ${var2} exist
            else
            echo Directory ${var2} Does not exists
            fi
    else
    echo "Arguments are not equals to 2"
    exit 1
    fi

execute it like below -

./script.sh directory1 directory2

Output will be like -

directory1 exit
directory2 Does not exists

How does the communication between a browser and a web server take place?

Your browser first resolves the servername via DNS to an IP. Then it opens a TCP connection to the webserver and tries to communicate via HTTP. Usually that is on TCP-port 80 but you can specify a different one (http://server:portnumber).

HTTP looks like this:

Once it is connected, it sends the request, which looks like:

GET /site HTTP/1.0
Header1: bla
Header2: blub
{emptyline}

E.g., a header might be Authorization or Range. See here for more.

Then the server responds like this:

200 OK
Header3: foo
Header4: bar

content following here...

E.g., a header might be Date or Content-Type. See here for more.

Look at Wikipedia for HTTP for some more information about this protocol.

Named capturing groups in JavaScript regex?

As Tim Pietzcker said ECMAScript 2018 introduces named capturing groups into JavaScript regexes. But what I did not find in the above answers was how to use the named captured group in the regex itself.

you can use named captured group with this syntax: \k<name>. for example

var regexObj = /(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>/

and as Forivin said you can use captured group in object result as follow:

let result = regexObj.exec('2019-28-06 year is 2019');
// result.groups.year === '2019';
// result.groups.month === '06';
// result.groups.day === '28';

_x000D_
_x000D_
  var regexObj = /(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>/mgi;_x000D_
_x000D_
function check(){_x000D_
    var inp = document.getElementById("tinput").value;_x000D_
    let result = regexObj.exec(inp);_x000D_
    document.getElementById("year").innerHTML = result.groups.year;_x000D_
    document.getElementById("month").innerHTML = result.groups.month;_x000D_
    document.getElementById("day").innerHTML = result.groups.day;_x000D_
}
_x000D_
td, th{_x000D_
  border: solid 2px #ccc;_x000D_
}
_x000D_
<input id="tinput" type="text" value="2019-28-06 year is 2019"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span>Pattern: "(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>";_x000D_
<br/>_x000D_
<br/>_x000D_
<button onclick="check()">Check!</button>_x000D_
<br/>_x000D_
<br/>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>_x000D_
        <span>Year</span>_x000D_
      </th>_x000D_
      <th>_x000D_
        <span>Month</span>_x000D_
      </th>_x000D_
      <th>_x000D_
        <span>Day</span>_x000D_
      </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <span id="year"></span>_x000D_
      </td>_x000D_
      <td>_x000D_
        <span id="month"></span>_x000D_
      </td>_x000D_
      <td>_x000D_
        <span id="day"></span>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Exit a while loop in VBS/VBA

Incredibly old question, but bearing in mind that the OP said he does not want to use Do While and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop:

This never runs anything if the status is already at "Fail"...

While (i < 20 And Not bShouldStop)
    If (Status = "Fail") Then
        bShouldStop = True
    Else
        i = i + 1
        '
        ' Do Something
        '
    End If  
Wend

Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.

While (i < 20 And Not bShouldStop)
    i = i + 1
    '
    ' Do Something
    '

    If (Status = "Fail") Then
        bShouldStop = True
    End If  
Wend

Ultimately, if the variable Status is being modified inside the While (and assuming you don't need i outside the while, it makes no difference really, but just wanted to present multiple options...

How to remove the last element added into the List?

I would rather use Last() from LINQ to do it.

rows = rows.Remove(rows.Last());

or

rows = rows.Remove(rows.LastOrDefault());

Hibernate: How to set NULL query-parameter value with HQL?

This is not a Hibernate specific issue (it's just SQL nature), and YES, there IS a solution for both SQL and HQL:

@Peter Lang had the right idea, and you had the correct HQL query. I guess you just needed a new clean run to pick up the query changes ;-)

The below code absolutely works and it is great if you keep all your queries in orm.xml

from CountryDTO c where ((:status is null and c.status is null) or c.status = :status) and c.type =:type

If your parameter String is null then the query will check if the row's status is null as well. Otherwise it will resort to compare with the equals sign.

Notes:

The issue may be a specific MySql quirk. I only tested with Oracle.

The above query assumes that there are table rows where c.status is null

The where clause is prioritized so that the parameter is checked first.

The parameter name 'type' may be a reserved word in SQL but it shouldn't matter since it is replaced before the query runs.

If you needed to skip the :status where_clause altogether; you can code like so:

from CountryDTO c where (:status is null or c.status = :status) and c.type =:type

and it is equivalent to:

sql.append(" where ");
if(status != null){
  sql.append(" c.status = :status and ");
}
sql.append(" c.type =:type ");

Getting first value from map in C++

As simple as:

your_map.begin()->first // key
your_map.begin()->second // value

Android fastboot waiting for devices

In my case (on windows 10), it would connect fine to adb and I could type any adb commands. But as soon as it got to the bootloader using adb reboot bootloader I wasn't able to perform any fastboot commands.

What I did notice that in the device manager that it refreshed when I connected to device. Next thing to do was to check what changed when connecting. Apparently the fastboot device was inside the Kedacom USB Device. Not really sure what that was, but I updated the device to use a different driver, in my case the Fastboot interface (Google USB ID), and that fixed my waiting for device issue

php REQUEST_URI

I think that parse_str is what you're looking for, something like this should do the trick for you:

parse_str($_SERVER['QUERY_STRING'], $vars);

Then the $vars array will hold all the passed arguments.

How can I revert a single file to a previous version?

Extracted from here: http://git.661346.n2.nabble.com/Revert-a-single-commit-in-a-single-file-td6064050.html

 git revert <commit> 
 git reset 
 git add <path> 
 git commit ... 
 git reset --hard # making sure you didn't have uncommited changes earlier 

It worked very fine to me.

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

Solution 1: configure Java 7

It is need to enable TLS 1.2 protocol with Java property in the command line

mvn -Dhttps.protocols=TLSv1.2 install

install is just an example of a goal

The same error for ant can be solved by this way

java -Dhttps.protocols=TLSv1.2 -cp %ANT_HOME%/lib/ant-launcher.jar org.apache.tools.ant.launch.Launcher

Solution 2: use Java 7 with Oracle Advanced Support

Also problem can be solved by updating the Java 7 version. But the last available version (7u80) doesn't fix the problem. It is need to use an update provided with Oracle Advanced Support (formerly known as Java for Business).

Solution 3: use Java 8 instead

Configure $JAVA_HOME to point to Java 8.

How to compare data between two table in different databases using Sql Server 2008?

Another solution (non T-SQL): you can use tablediff utility. For example if you want to compare two tables (Localitate) from two different servers (ROBUH01 & ROBUH02) you can use this shell command:

C:\Program Files\Microsoft SQL Server\100\COM>tablediff -sourceserver ROBUH01 -s
ourcedatabase SIM01 -sourceschema dbo -sourcetable Localitate -destinationserver
 ROBUH02 -destinationschema dbo -destinationdatabase SIM02 -destinationtable Lo
calitate

Results:

Microsoft (R) SQL Server Replication Diff Tool Copyright (c) 2008 Microsoft Corporation User-specified agent parameter values: 
-sourceserver ROBUH01 
-sourcedatabase SIM01 
-sourceschema dbo 
-sourcetable Localitate 
-destinationserver ROBUH02 
-destinationschema dbo 
-destinationdatabase SIM02 
-destinationtable Localitate 

Table [SIM01].[dbo].[Localitate] on ROBUH01 and Table [SIM02].[dbo].[Localitate ] on ROBUH02 have 10 differences. 

Err Id Dest. 
Only 21433 Dest. 
Only 21434 Dest. 
Only 21435 Dest. 
Only 21436 Dest. 
Only 21437 Dest. 
Only 21438 Dest. 
Only 21439 Dest. 
Only 21441 Dest. 
Only 21442 Dest. 
Only 21443 
The requested operation took 9,9472657 seconds.
------------------------------------------------------------------------

How to reshape data from long to wide format

You can do this with the reshape() function, or with the melt() / cast() functions in the reshape package. For the second option, example code is

library(reshape)
cast(dat1, name ~ numbers)

Or using reshape2

library(reshape2)
dcast(dat1, name ~ numbers)

Java Class that implements Map and keeps insertion order?

LinkedHashMap will return the elements in the order they were inserted into the map when you iterate over the keySet(), entrySet() or values() of the map.

Map<String, String> map = new LinkedHashMap<String, String>();

map.put("id", "1");
map.put("name", "rohan");
map.put("age", "26");

for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

This will print the elements in the order they were put into the map:

id = 1
name = rohan 
age = 26 

How do I apply CSS3 transition to all properties except background-position?

Hope not to be late. It is accomplished using only one line!

-webkit-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
-moz-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
-o-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0; 

That works on Chrome. You have to separate the CSS properties with a comma.

Here is a working example: http://jsfiddle.net/H2jet/

Working with time DURATION, not time of day

I don't know how to make the chart label the axis in the format "X1 min : X2 sec", but here's another way to get durations, in the format of minutes with decimals representing seconds (.5 = 30 sec, .25 = 15 sec, etc.)

Suppose in column A you have your time data, for example in cell A1 you have 12:03:06, which your 3min 6sec data misinterpreted as 3:06 past midnight, and column B is free.

In cell B1 enter this formula: =MINUTE(A1) + SECOND(A1)/60 and hit enter/return. Grab the lower right corner of cell B2 and drag as far down as the A column goes to apply the formula to all data in col A.

Last step, be sure to highlight all of column B and set it to Number format (the application of the formula may have automatically set format to Time).

Sites not accepting wget user agent header

You need to set both the user-agent and the referer:

 wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer  connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip

How can I send and receive WebSocket messages on the server side?

Clojure, the decode function assumes frame is sent as map of {:data byte-array-buffer :size int-size-of-buffer}, because the actual size may not be the same size as the byte-array depending on chunk size of your inputstream.

Code posted here: https://gist.github.com/viperscape/8918565

(defn ws-decode [frame]
  "decodes websocket frame"
  (let [data (:data frame)
        dlen (bit-and (second data) 127)
        mstart (if (== dlen 127) 10 (if (== dlen 126) 4 2))
        mask (drop 2 (take (+ mstart 4) data))
        msg (make-array Byte/TYPE (- (:size frame) (+ mstart 4)))]
   (loop [i (+ mstart 4), j 0]
      (aset-byte msg j (byte (bit-xor (nth data i) (nth mask (mod j 4)))))
      (if (< i (dec(:size frame))) (recur (inc i) (inc j))))
    msg))

(defn ws-encode [data]
  "takes in bytes, return websocket frame"
  (let [len (count data)
        blen (if (> len 65535) 10 (if (> len 125) 4 2))
        buf (make-array Byte/TYPE (+ len blen))
        _ (aset-byte buf 0 -127) ;;(bit-or (unchecked-byte 0x80) 
                                           (unchecked-byte 0x1)
        _ (if (= 2 blen) 
            (aset-byte buf 1 len) ;;mask 0, len
            (do
              (dorun(map #(aset-byte buf %1 
                      (unchecked-byte (bit-and (bit-shift-right len (*(- %2 2) 8))
                                               255)))
                      (range 2 blen) (into ()(range 2 blen))))
              (aset-byte buf 1 (if (> blen 4) 127 126))))
        _ (System/arraycopy data 0 buf blen len)]
    buf))

Fatal error: Class 'Illuminate\Foundation\Application' not found

In my case composer was not installed in that directory. So I run

composer install

then error resolved.

or you can try

composer update --no-scripts
cd bootstrap/cache/->rm -rf *.php
composer dump-autoload

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

this works for ubuntu 15.10:

sudo locale-gen "en_US.UTF-8"
sudo dpkg-reconfigure locales

Unable to load script from assets index.android.bundle on windows

Use mkdir ... /assets && react-native bundle --platform.. CAN NOT solve this problem completely,

Notice that, you have to run this command regenerate the files every time when code edited, and it show error again after Reload or Debug JS Remotely.

The fundamental cause this issue is your app cannot connect with server (because of some unknown reason)

Here is my solution:

  • Firstly, start service in other host and port like:

    react-native start --port 8082 --host 0.0.0.0

  • Then, open app dev menu > Dev Setting > Debug server host for device

  • Input youripv4address:8082
  • dev menu > Reload

Hope this helps

WRONGTYPE Operation against a key holding the wrong kind of value php

This error means that the value indexed by the key "l_messages" is not of type hash, but rather something else. You've probably set it to that other value earlier in your code. Try various other value-getter commands, starting with GET, to see which one works and you'll know what type is actually here.

How to check if a registry value exists using C#?

        internal static Func<string, string, bool> regKey = delegate (string KeyLocation, string Value)
        {
            // get registry key with Microsoft.Win32.Registrys
            RegistryKey rk = (RegistryKey)Registry.GetValue(KeyLocation, Value, null); // KeyLocation and Value variables from method, null object because no default value is present. Must be casted to RegistryKey because method returns object.
            if ((rk) == null) // if the RegistryKey is null which means it does not exist
            {
                // the key does not exist
                return false; // return false because it does not exist
            }
            // the registry key does exist
            return true; // return true because it does exist
        };

usage:

        // usage:
        /* Create Key - while (loading)
        {
            RegistryKey k;
            k = Registry.CurrentUser.CreateSubKey("stuff");
            k.SetValue("value", "value");
            Thread.Sleep(int.MaxValue);
        }; // no need to k.close because exiting control */


        if (regKey(@"HKEY_CURRENT_USER\stuff  ...  ", "value"))
        {
             // key exists
             return;
        }
        // key does not exist

What exactly does a jar file contain?

JAR stands for Java ARchive. It's a file format based on the popular ZIP file format and is used for aggregating many files into one. Although JAR can be used as a general archiving tool, the primary motivation for its development was so that Java applets and their requisite components (.class files, images and sounds) can be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece. This greatly improves the speed with which an applet can be loaded onto a web page and begin functioning. The JAR format also supports compression, which reduces the size of the file and improves download time still further. Additionally, individual entries in a JAR file may be digitally signed by the applet author to authenticate their origin.

Allow user to select camera or gallery for image

Resolved too big image issue and avoid to out of memory.

    private static final int SELECT_PICTURE = 0;
    private static final int REQUEST_CAMERA = 1;
    private ImageView mImageView;

    private void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Library",
                "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment
                            .getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, REQUEST_CAMERA);
                } else if (items[item].equals("Choose from Library")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"),
                            SELECT_PICTURE);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {
                File f = new File(Environment.getExternalStorageDirectory()
                        .toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bm;
                    BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
                    btmapOptions.inSampleSize = 2;
                    bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
                            btmapOptions);

                    // bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
                    mImageView.setImageBitmap(bm);

                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "test";
                    f.delete();
                    OutputStream fOut = null;
                    File file = new File(path, String.valueOf(System
                            .currentTimeMillis()) + ".jpg");
                    fOut = new FileOutputStream(file);
                    bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                    fOut.flush();
                    fOut.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                String tempPath = getPath(selectedImageUri, this.getActivity());
                Bitmap bm;
                btmapOptions.inSampleSize = 2;
                BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
                bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
                mImageView.setImageBitmap(bm);
            }
        }
    }
    public String getPath(Uri uri, Activity activity) {
        String[] projection = {MediaStore.MediaColumns.DATA};
        Cursor cursor = activity
                .managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

How to change letter spacing in a Textview?

More space:

  android:letterSpacing="0.1"

Less space:

 android:letterSpacing="-0.07"

How do I remove the first characters of a specific column in a table?

Why use LEN so you have 2 string functions? All you need is character 5 on...

...SUBSTRING (Code1, 5, 8000)...

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

Ctrl + . shows the menu. I find this easier to type than the alternative, Alt + Shift + F10.

This can be re-bound to something more familiar by going to Tools > Options > Environment > Keyboard > Visual C# > View.QuickActions

How can I get a specific parameter from location.search?

The easiest way is to have

if (document.location.search.indexOf('yourtext=') >= 0) {
    // your code
} else {
    // what happens?
}

indexOf()

The indexOf(text) function returns

  • A WHOLE NUMBER BELOW 0 when the text passed in the function is not in whatever variable or string you are looking for - in this case document.location.search.
  • A WHOLE NUMBER EQUAL TO 0 OR HIGHER when the text passed in the function is in whatever variable or string you are looking for - in this case document.location.search.

I hope this was useful, @gumbo

How to get parameter on Angular2 route in Angular way?

As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:

private _entityId: number;

constructor(private _route: ActivatedRoute) {
    // ...
}

ngOnInit() {
    // For a static snapshot of the route...
    this._entityId = this._route.snapshot.paramMap.get('id');

    // For subscribing to the observable paramMap...
    this._route.paramMap.pipe(
        switchMap((params: ParamMap) => this._entityId = params.get('id'))
    );

    // Or as an alternative, with slightly different execution...
    this._route.paramMap.subscribe((params: ParamMap) =>  {
        this._entityId = params.get('id');
    });
}

I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.

Source in Angular Docs

How to insert a row in an HTML table body in JavaScript

I think this script is what exactly you need

var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)

Writing a new line to file in PHP (line feed)

Use PHP_EOL which outputs \r\n or \n depending on the OS.

How to know if a Fragment is Visible?

getUserVisibleHint() comes as true only when the fragment is on the view and visible

How to count no of lines in text file and store the value into a variable using batch script?

I usually use something more like this for /f %%a in (%_file%) do (set /a Lines+=1)

Undo a Git merge that hasn't been pushed yet

You have to change your HEAD, Not yours of course but git HEAD....

So before answering let's add some background, explaining what is this HEAD.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time. (excluding git worktree)

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD.

enter image description here

On the command line, it will look like this- SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch

enter image description here

enter image description here

A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there reset && checkout modify the HEAD.

enter image description here

How to add a where clause in a MySQL Insert statement?

UPDATE users SET username='&username', password='&password' where id='&id'

This query will ask you to enter the username,password and id dynamically

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

I was now able to find reason behind the error guys. It's on the webhosting site settings not on my app pool or what so ever. I changed the asp.net version from 2.0 to 4.0 but I forgot to click the update button. I feel so embarrased. :( I've been struggling for days to fix this error and only to found out its on the webhosting site settings. GgrrRR.. As of now I'm facing new error but has nothing to do with this question. Anyway thanks guys for your efforts to help me. :)

Get value when selected ng-option changes

Best practise is to create an object (always use a . in ng-model)

In your controller:

var myObj: {
     ngModelValue: null
};

and in your template:

<select 
    ng-model="myObj.ngModelValue" 
    ng-options="o.id as o.name for o in options">
</select>

Now you can just watch

myObj.ngModelValue

or you can use the ng-change directive like so:

<select 
    ng-model="myObj.ngModelValue" 
    ng-options="o.id as o.name for o in options"
    ng-change="myChangeCallback()">
</select>

The egghead.io video "The Dot" has a really good overview, as does this very popular stack overflow question: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Checking Bash exit status of several commands efficiently

When I use ssh I need to distinct between problems caused by connection issues and error codes of remote command in errexit (set -e) mode. I use the following function:

# prepare environment on calling site:

rssh="ssh -o ConnectionTimeout=5 -l root $remote_ip"

function exit255 {
    local flags=$-
    set +e
    "$@"
    local status=$?
    set -$flags
    if [[ $status == 255 ]]
    then
        exit 255
    else
        return $status
    fi
}
export -f exit255

# callee:

set -e
set -o pipefail

[[ $rssh ]]
[[ $remote_ip ]]
[[ $( type -t exit255 ) == "function" ]]

rjournaldir="/var/log/journal"
if exit255 $rssh "[[ ! -d '$rjournaldir/' ]]"
then
    $rssh "mkdir '$rjournaldir/'"
fi
rconf="/etc/systemd/journald.conf"
if [[ $( $rssh "grep '#Storage=auto' '$rconf'" ) ]]
then
    $rssh "sed -i 's/#Storage=auto/Storage=persistent/' '$rconf'"
fi
$rssh systemctl reenable systemd-journald.service
$rssh systemctl is-enabled systemd-journald.service
$rssh systemctl restart systemd-journald.service
sleep 1
$rssh systemctl status systemd-journald.service
$rssh systemctl is-active systemd-journald.service

How to create a GUID/UUID in Python

The uuid module provides immutable UUID objects (the UUID class) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122.

If all you want is a unique ID, you should probably call uuid1() or uuid4(). Note that uuid1() may compromise privacy since it creates a UUID containing the computer’s network address. uuid4() creates a random UUID.

Docs:

Example (for both Python 2 and 3):

>>> import uuid
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'

INSERT SELECT statement in Oracle 11G

Get rid of the values keyword and the parens. You can see an example here.

This is basic INSERT syntax:

INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...);

This is the INSERT SELECT syntax:

INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2";

Check whether specific radio button is checked

Your selector won't select the input field, and if it did it would return a jQuery object. Try this:

$('#test2').is(':checked'); 

How do I read the file content from the Internal storage - Android App

For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE

try {
            FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
            fos.write(csv.getBytes());
            fos.close();
            File file = Main.this.getFileStreamPath("exported_data.csv");
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

How to get all elements which name starts with some string?

You can try using jQuery with the Attribute Contains Prefix Selector.

$('[id|=q1_]')

Haven't tested it though.

How to check if a file exists in Go?

You should use the os.Stat() and os.IsNotExist() functions as in the following example:

// Exists reports whether the named file or directory exists.
func Exists(name string) bool {
    if _, err := os.Stat(name); err != nil {
        if os.IsNotExist(err) {
            return false
        }
    }
    return true
}

The example is extracted from here.

doGet and doPost in Servlets

Both GET and POST are used by the browser to request a single resource from the server. Each resource requires a separate GET or POST request.

  1. The GET method is most commonly (and is the default method) used by browsers to retrieve information from servers. When using the GET method the 3rd section of the request packet, which is the request body, remains empty.

The GET method is used in one of two ways: When no method is specified, that is when you or the browser is requesting a simple resource such as an HTML page, an image, etc. When a form is submitted, and you choose method=GET on the HTML tag. If the GET method is used with an HTML form, then the data collected through the form is sent to the server by appending a "?" to the end of the URL, and then adding all name=value pairs (name of the html form field and value entered in that field) separated by an "&" Example: GET /sultans/shop//form1.jsp?name=Sam%20Sultan&iceCream=vanilla HTTP/1.0 optional headeroptional header<< empty line >>>

The name=value form data will be stored in an environment variable called QUERY_STRING. This variable will be sent to a processing program (such as JSP, Java servlet, PHP etc.)

  1. The POST method is used when you create an HTML form, and request method=POST as part of the tag. The POST method allows the client to send form data to the server in the request body section of the request (as discussed earlier). The data is encoded and is formatted similar to the GET method, except that the data is sent to the program through the standard input.

Example: POST /sultans/shop//form1.jsp HTTP/1.0 optional headeroptional header<< empty line >>> name=Sam%20Sultan&iceCream=vanilla

When using the post method, the QUERY_STRING environment variable will be empty. Advantages/Disadvantages of GET vs. POST

Advantages of the GET method: Slightly faster Parameters can be entered via a form or by appending them after the URL Page can be bookmarked with its parameters

Disadvantages of the GET method: Can only send 4K worth of data. (You should not use it when using a textarea field) Parameters are visible at the end of the URL

Advantages of the POST method: Parameters are not visible at the end of the URL. (Use for sensitive data) Can send more that 4K worth of data to server

Disadvantages of the POST method: Can cannot be bookmarked with its data

Using StringWriter for XML Serialization

First of all, beware of finding old examples. You've found one that uses XmlTextWriter, which is deprecated as of .NET 2.0. XmlWriter.Create should be used instead.

Here's an example of serializing an object into an XML column:

public void SerializeToXmlColumn(object obj)
{
    using (var outputStream = new MemoryStream())
    {
        using (var writer = XmlWriter.Create(outputStream))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj);
        }

        outputStream.Position = 0;
        using (var conn = new SqlConnection(Settings.Default.ConnectionString))
        {
            conn.Open();

            const string INSERT_COMMAND = @"INSERT INTO XmlStore (Data) VALUES (@Data)";
            using (var cmd = new SqlCommand(INSERT_COMMAND, conn))
            {
                using (var reader = XmlReader.Create(outputStream))
                {
                    var xml = new SqlXml(reader);

                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@Data", xml);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}

How to use SQL LIKE condition with multiple values in PostgreSQL?

You can use regular expression operator (~), separated by (|) as described in Pattern Matching

select column_a from table where column_a ~* 'aaa|bbb|ccc'

Mocking Logger and LoggerFactory with PowerMock and Mockito

EDIT 2020-09-21: Since 3.4.0, Mockito supports mocking static methods, API is still incubating and is likely to change, in particular around stubbing and verification. It requires the mockito-inline artifact. And you don't need to prepare the test or use any specific runner. All you need to do is :

@Test
public void name() {
    try (MockedStatic<LoggerFactory> integerMock = mockStatic(LoggerFactory.class)) {
        final Logger logger = mock(Logger.class);
        integerMock.when(() -> LoggerFactory.getLogger(any(Class.class))).thenReturn(logger);
        new Controller().log();
        verify(logger).warn(any());
    }
}

The two inportant aspect in this code, is that you need to scope when the static mock applies, i.e. within this try block. And you need to call the stubbing and verification api from the MockedStatic object.


@Mick, try to prepare the owner of the static field too, eg :

@PrepareForTest({GoodbyeController.class, LoggerFactory.class})

EDIT1 : I just crafted a small example. First the controller :

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Controller {
    Logger logger = LoggerFactory.getLogger(Controller.class);

    public void log() { logger.warn("yup"); }
}

Then the test :

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Controller.class, LoggerFactory.class})
public class ControllerTest {

    @Test
    public void name() throws Exception {
        mockStatic(LoggerFactory.class);
        Logger logger = mock(Logger.class);
        when(LoggerFactory.getLogger(any(Class.class))).thenReturn(logger);
        
        new Controller().log();
        
        verify(logger).warn(anyString());
    }
}

Note the imports ! Noteworthy libs in the classpath : Mockito, PowerMock, JUnit, logback-core, logback-clasic, slf4j


EDIT2 : As it seems to be a popular question, I'd like to point out that if these log messages are that important and require to be tested, i.e. they are feature / business part of the system then introducing a real dependency that make clear theses logs are features would be a so much better in the whole system design, instead of relying on static code of a standard and technical classes of a logger.

For this matter I would recommend to craft something like= a Reporter class with methods such as reportIncorrectUseOfYAndZForActionX or reportProgressStartedForActionX. This would have the benefit of making the feature visible for anyone reading the code. But it will also help to achieve tests, change the implementations details of this particular feature.

Hence you wouldn't need static mocking tools like PowerMock. In my opinion static code can be fine, but as soon as the test demands to verify or to mock static behavior it is necessary to refactor and introduce clear dependencies.

Facebook Open Graph Error - Inferred Property

Are those tags on 'http://www.mywebaddress.com'?

Bear in mind the linter will follow the og:url tag as this tag should point to the canonical URL of the piece of content - so if you have a page, e.g. 'http://mywebaddress.com/article1' with an og:url tag pointing to 'http://mywebaddress.com', Facebook will go there and read the tags there also.

Failing that, the most common reason i've seen for seemingly correct tags not being detected by the linter is user-agent detection returning different content to Facebook's crawler than the content you're seeing when you manually check

HTML Mobile -forcing the soft keyboard to hide

Scott S's answer worked perfectly.

I was coding a web-based phone dialpad for mobile, and every time the user would press a number on the keypad (composed of td span elements in a table), the softkeyboard would pop up. I also wanted the user to not be able to tap into the input box of the number being dialed. This actually solved both problems in 1 shot. The following was used:

<input type="text" id="phone-number" onfocus="blur();" />

Sort objects in an array alphabetically on one property of the array

Here is a simple function you can use to sort array of objects through their properties; it doesn't matter if the property is a type of string or integer, it will work.

_x000D_
_x000D_
    var cars = [_x000D_
        {make:"AMC",        model:"Pacer",  year:1978},_x000D_
        {make:"Koenigsegg", model:"CCGT",   year:2011},_x000D_
        {make:"Pagani",     model:"Zonda",  year:2006},_x000D_
    ];_x000D_
_x000D_
    function sortObjectsByProp(objectsArr, prop, ascending = true) {_x000D_
        let objectsHaveProp = objectsArr.every(object => object.hasOwnProperty(prop));_x000D_
        if(objectsHaveProp)    {_x000D_
            let newObjectsArr = objectsArr.slice();_x000D_
            newObjectsArr.sort((a, b) => {_x000D_
                if(isNaN(Number(a[prop])))  {_x000D_
                    let textA = a[prop].toUpperCase(),_x000D_
                        textB = b[prop].toUpperCase();_x000D_
                    if(ascending)   {_x000D_
                        return textA < textB ? -1 : textA > textB ? 1 : 0;_x000D_
                    } else {_x000D_
                        return textB < textA ? -1 : textB > textA ? 1 : 0;_x000D_
                    }_x000D_
                } else {_x000D_
                    return ascending ? a[prop] - b[prop] : b[prop] - a[prop];_x000D_
                }_x000D_
            });_x000D_
            return newObjectsArr;_x000D_
        }_x000D_
        return objectsArr;_x000D_
    }_x000D_
_x000D_
    let sortedByMake = sortObjectsByProp(cars, "make"); // returns ascending order by its make;_x000D_
    let sortedByYear = sortObjectsByProp(cars, "year", false); // returns descending order by its year,since we put false as a third argument;_x000D_
    console.log(sortedByMake);_x000D_
    console.log(sortedByYear);
_x000D_
_x000D_
_x000D_

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

How can I show/hide a specific alert with twitter bootstrap?

On top of all the previous answers, dont forget to hide your alert before using it with a simple style="display:none;"

<div class="alert alert-success" id="passwordsNoMatchRegister" role="alert" style="display:none;" >Message of the Alert</div>

Then use either:

$('#passwordsNoMatchRegister').show();

$('#passwordsNoMatchRegister').fadeIn();

$('#passwordsNoMatchRegister').slideDown();

What is the best way to use a HashMap in C++?

Here's a more complete and flexible example that doesn't omit necessary includes to generate compilation errors:

#include <iostream>
#include <unordered_map>

class Hashtable {
    std::unordered_map<const void *, const void *> htmap;

public:
    void put(const void *key, const void *value) {
            htmap[key] = value;
    }

    const void *get(const void *key) {
            return htmap[key];
    }

};

int main() {
    Hashtable ht;
    ht.put("Bob", "Dylan");
    int one = 1;
    ht.put("one", &one);
    std::cout << (char *)ht.get("Bob") << "; " << *(int *)ht.get("one");
}

Still not particularly useful for keys, unless they are predefined as pointers, because a matching value won't do! (However, since I normally use strings for keys, substituting "string" for "const void *" in the declaration of the key should resolve this problem.)

WP -- Get posts by category?

'category_name'=>'this cat' also works but isn't printed in the WP docs

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

Try something like this:

foreach (ListItem listItem in YrChkBox.Items)
{
    if (listItem.Selected)
    { 
       //do some work 
    }
    else 
    { 
      //do something else 
    }
}

How to use Python to execute a cURL command?

For sake of simplicity, maybe you should consider using the Requests library.

An example with json response content would be something like:

import requests
r = requests.get('https://github.com/timeline.json')
r.json()

If you look for further information, in the Quickstart section, they have lots of working examples.

EDIT:

For your specific curl translation:

import requests
url = 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere'
payload = open("request.json")
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
r = requests.post(url, data=payload, headers=headers)

install apt-get on linux Red Hat server

wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm

rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm

maybe some URL is broken,please research it. Enjoy~~

Where to change the value of lower_case_table_names=2 on windows xampp

Do these steps:

  1. open your MySQL configuration file: [drive]\xampp\mysql\bin\my.ini
  2. look up for: # The MySQL server [mysqld]
  3. add this right below it: lower_case_table_names = 2
  4. save the file and restart MySQL service

From: http://webdev.issimplified.com/2010/03/02/mysql-on-windows-force-table-names-to-lowercase/

SSL peer shut down incorrectly in Java

Apart from the accepted answer, other problems can cause the exception too. For me it was that the certificate was not trusted (i.e., self-signed cert and not in the trust store).

If the certificate file does not exists, or could not be loaded (e.g., typo in path) can---in certain circumstances---cause the same exception.

Failed to find target with hash string 'android-25'

You don't need to update anything. Just download the SDK for API 25 from Android SDK Manager or by launching Android standalone SDK manager. The error is for missing platform and not for missing tool.Android SDK Manager Android Studio 2.2.2

No Exception while type casting with a null in java

This is by design. You can cast null to any reference type. Otherwise you wouldn't be able to assign it to reference variables.

Regex select all text between tags

To exclude the delimiting tags:

(?<=<pre>)(.*?)(?=</pre>)

(?<=<pre>) looks for text after <pre>

(?=</pre>) looks for text before </pre>

Results will text inside pre tag

Python xticks in subplots

See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:

  • If you want to set the xticklabels:

    ax.set_xticks([1,4,5]) 
    ax.set_xticklabels([1,4,5], fontsize=12)
    
  • If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):

    ax.tick_params(axis="x", labelsize=12) 
    
  • To do it all at once:

    plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold", 
             horizontalalignment="left")`
    

Find files in created between a date range

List files between 2 dates

find . -type f -newermt "2019-01-01" ! -newermt "2019-05-01"

or

find path -type f -newermt "2019-01-01" ! -newermt "2019-05-01"

Android runOnUiThread explanation

If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?

You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:

private void populateTable() {
    runOnUiThread(new Runnable(){
        public void run() {
            //If there are stories, add them to the table
            for (Parcelable currentHeadline : allHeadlines) {
                addHeadlineToTable(currentHeadline);
            }
            try {
                dialog.dismiss();
            } catch (final Exception ex) {
                Log.i("---","Exception in thread");
            }
        }
    });
}

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

This will prevent the auto-filling of password into the input field's (type="password").

<form autocomplete="off">
  <input type="password" autocomplete="new-password">
</form>

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How to change border color of textarea on :focus

.input:focus {
    outline: none !important;
    border:1px solid red;
    box-shadow: 0 0 10px #719ECE;
}

Best way to center a <div> on a page vertically and horizontally?

If you are looking at the new browsers(IE10+),

then you can make use of transform property to align a div at the center.

<div class="center-block">this is any div</div>

And css for this should be:

.center-block {
  top:50%;
  left: 50%;
  transform: translate3d(-50%,-50%, 0);
  position: absolute;
}

The catch here is that you don't even have to specify the height and width of the div as it takes care by itself.

Also, if you want to position a div at the center of another div, then you can just specify the position of outer div as relative and then this CSS starts working for your div.

How it works:

When you specify left and top at 50%, the div goes at the the bottom right quarter of the page with its top-left end pinned at the center of the page. This is because, the left/top properties(when given in %) are calculated based on height of the outer div(in your case, window).

But transform uses height/width of the element to determine translation, so you div will move left(50% width) and top(50% its height) since they are given in negatives, thus aligning it to the center of the page.

If you have to support older browsers(and sorry including IE9 as well) then the table cell is most popular method to use.

jQuery equivalent of JavaScript's addEventListener method

You should now use the .on() function to bind events.

Adding a directory to PATH in Ubuntu

you can set it in .bashrc

PATH=$PATH:/opt/ActiveTcl-8.5/bin;export PATH;

How do I convert datetime to ISO 8601 in PHP

If you try set a value in datetime-local

date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));

//output : 2010-12-30T23:21

Offset a background image from the right using CSS

If you would like to use this for adding arrows/other icons to a button for example then you could use css pseudo-elements?

If it's really a background-image for the whole button, I tend to incorporate the spacing into the image, and just use

background-position: right 0;

But if I have to add for example a designed arrow to a button, I tend to have this html:

<a href="[url]" class="read-more">Read more</a>

And tend to do the following with CSS:

.read-more{
    position: relative;
    padding: 6px 15px 6px 35px;//to create space on the right
    font-size: 13px;
    font-family: Arial;
}

.read-more:after{
    content: '';
    display: block;
    width: 10px;
    height: 15px;
    background-image: url('../images/btn-white-arrow-right.png');
    position: absolute;
    right: 12px;
    top: 10px;
}

By using the :after selector, I add a element using CSS just to contain this small icon. You could do the same by just adding a span or <i> element inside the a-element. But I think this is a cleaner way of adding icons to buttons and it is cross-browser supported.

you can check out the fiddle here: http://codepen.io/anon/pen/PNzYzZ

Check if a key exists inside a json object

This code causes esLint issue: no-prototype-builtins

foo.hasOwnProperty("bar") 

The suggest way here is:

Object.prototype.hasOwnProperty.call(foo, "bar");

How to display image from database using php

put this code to your php page.

$sql = "SELECT * FROM userdetail";
$result = mysqli_query("connection ", $sql);

while ($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
    echo "<img src='images/".$row['image']."'>";
    echo "<p>".$row['text']. "</p>";
}

i hope this is work.

How to print HTML content on click of a button, but not the page?

Here is a pure css version

_x000D_
_x000D_
.example-print {_x000D_
    display: none;_x000D_
}_x000D_
@media print {_x000D_
   .example-screen {_x000D_
       display: none;_x000D_
    }_x000D_
    .example-print {_x000D_
       display: block;_x000D_
    }_x000D_
}
_x000D_
<div class="example-screen">You only see me in the browser</div>_x000D_
_x000D_
<div class="example-print">You only see me in the print</div>
_x000D_
_x000D_
_x000D_

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

You're mixing up HTML with XHTML.

Usually a <!DOCTYPE> declaration is used to distinguish between versions of HTMLish languages (in this case, HTML or XHTML).

Different markup languages will behave differently. My favorite example is height:100%. Look at the following in a browser:

XHTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <style type="text/css">
    table { height:100%;background:yellow; }
  </style>
</head>
<body>
  <table>
    <tbody>
      <tr><td>How tall is this?</td></tr>
    </tbody>
  </table>
</body>
</html>

... and compare it to the following: (note the conspicuous lack of a <!DOCTYPE> declaration)

HTML (quirks mode)

<html>
<head>
  <style type="text/css">
    table { height:100%;background:yellow; }
  </style>
</head>
<body>
  <table>
    <tbody>
      <tr><td>How tall is this?</td></tr>
    </tbody>
  </table>
</body>
</html>

You'll notice that the height of the table is drastically different, and the only difference between the 2 documents is the type of markup!

That's nice... now, what does <html xmlns="http://www.w3.org/1999/xhtml"> do?

That doesn't answer your question though. Technically, the xmlns attribute is used by the root element of an XHTML document: (according to Wikipedia)

The root element of an XHTML document must be html, and must contain an xmlns attribute to associate it with the XHTML namespace.

You see, it's important to understand that XHTML isn't HTML but XML - a very different creature. (ok, a kind of different creature) The xmlns attribute is just one of those things the document needs to be valid XML. Why? Because someone working on the standard said so ;) (you can read more about XML namespaces on Wikipedia but I'm omitting that info 'cause it's not actually relevant to your question!)

But then why is <html xmlns="http://www.w3.org/1999/xhtml"> fixing the CSS?

If structuring your document like so... (as you suggest in your comment)

<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html>
<head>
[...]

... is fixing your document, it leads me to believe that you don't know that much about CSS and HTML (no offense!) and that the truth is that without <html xmlns="http://www.w3.org/1999/xhtml"> it's behaving normally and with <html xmlns="http://www.w3.org/1999/xhtml"> it's not - and you just think it is, because you're used to writing invalid HTML and thus working in quirks mode.

The above example I provided is an example of that same problem; most people think height:100% should result in the height of the <table> being the whole window, and that the DOCTYPE is actually breaking their CSS... but that's not really the case; rather, they just don't understand that they need to add a html, body { height:100%; } CSS rule to achieve their desired effect.

How to automatically add user account AND password with a Bash script?

You can use expect in your bash script.

From http://www.seanodonnell.com/code/?id=21

#!/usr/bin/expect 
######################################### 
#$ file: htpasswd.sh 
#$ desc: Automated htpasswd shell script 
######################################### 
#$ 
#$ usage example: 
#$ 
#$ ./htpasswd.sh passwdpath username userpass 
#$ 
###################################### 

set htpasswdpath [lindex $argv 0] 
set username [lindex $argv 1] 
set userpass [lindex $argv 2] 

# spawn the htpasswd command process 
spawn htpasswd $htpasswdpath $username 

# Automate the 'New password' Procedure 
expect "New password:" 
send "$userpass\r" 

expect "Re-type new password:" 
send "$userpass\r"

Table with fixed header and fixed column on pure css

If you only want to use pure HTML and CSS i've got a solution for your problem:
In this jsFiddle you can see a non-script solution that provides a table with a fixed header. It shouldn't be a problem to adapt the markup for a fixed first column as well. You would just need to create a absolute-positioned table for the first column inside the hWrapper-div and reposition the vWrapper-div.
Providing dynamic content should not be a problem using server-side or browser-side tempting-engines, my solution works well in all modern browsers and older browsers from IE8 onwards.

Relative instead of Absolute paths in Excel VBA

Just to clarify what yalestar said, this will give you the relative path:

Workbooks.Open FileName:= ThisWorkbook.Path & "\TRICATEndurance Summary.html"

Difference between Convert.ToString() and .ToString()

ToString() Vs Convert.ToString()

Similarities :-

Both are used to convert a specific type to string i.e int to string, float to string or an object to string.

Difference :-

ToString() can't handle null while in case with Convert.ToString() will handle null value.

Example :

namespace Marcus
{
    class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    class Startup
    {
        public static void Main()
        {
            Employee e = new Employee();
            e = null;

            string s = e.ToString(); // This will throw an null exception
            s = Convert.ToString(e); // This will throw null exception but it will be automatically handled by Convert.ToString() and exception will not be shown on command window.
        }
    }
}

What is the difference between SQL and MySQL?

SQL is the actual language that as defined by the ISO and ANSI. Here is a link to the Wikipedia article. MySQL is a specific implementation of this standard. I believe Oracle bought the company that originally developed MySQL. Other companies also have their own implementations of the SQL standard.

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

O(2N)

O(2N) denotes an algorithm whose growth doubles with each additon to the input data set. The growth curve of an O(2N) function is exponential - starting off very shallow, then rising meteorically. An example of an O(2N) function is the recursive calculation of Fibonacci numbers:

int Fibonacci (int number)
{
if (number <= 1) return number;
return Fibonacci(number - 2) + Fibonacci(number - 1);
}

@import vs #import - iOS 7

It seems that since XCode 7.x a lot of warnings are coming out when enabling clang module with CLANG_ENABLE_MODULES

Take a look at Lots of warnings when building with Xcode 7 with 3rd party libraries

Closing a file after File.Create

File.Create returns a FileStream object that you can call Close() on.

Create a BufferedImage from file and make it TYPE_INT_ARGB

BufferedImage in = ImageIO.read(img);

BufferedImage newImage = new BufferedImage(
    in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = newImage.createGraphics();
g.drawImage(in, 0, 0, null);
g.dispose();

How to select a dropdown value in Selenium WebDriver using Java

If you want to write all in one line try

new Select (driver.findElement(By.id("designation"))).selectByVisibleText("Programmer ");

Python: OSError: [Errno 2] No such file or directory: ''

Have you noticed that you don't get the error if you run

python ./script.py

instead of

python script.py

This is because sys.argv[0] will read ./script.py in the former case, which gives os.path.dirname something to work with. When you don't specify a path, sys.argv[0] reads simply script.py, and os.path.dirname cannot determine a path.

How to add a search box with icon to the navbar in Bootstrap 3?

I tried @PhilNicholas 's code and got the same problem of @its_me said in the comments that search bar show up on the next line of navbar, and I found that form need to be added an attribute width.

<form role="search" style="width: 15em; margin: 0.3em 2em;">
    <div class="input-group">
        <input type="text" class="form-control" placeholder="Search">
        <div class="input-group-btn">
            <button type="submit" class="btn btn-default">
                <span class="glyphicon glyphicon-search"></span>
            </button>
        </div>
    </div>
</form> 

Convert Little Endian to Big Endian

OP's code is incorrect for the following reasons:

  • The swaps are being performed on a nibble (4-bit) boundary, instead of a byte (8-bit) boundary.
  • The shift-left << operations of the final four swaps are incorrect, they should be shift-right >> operations and their shift values would also need to be corrected.
  • The use of intermediary storage is unnecessary, and the code can therefore be rewritten to be more concise/recognizable. In doing so, some compilers will be able to better-optimize the code by recognizing the oft-used pattern.

Consider the following code, which efficiently converts an unsigned value:

// Swap endian (big to little) or (little to big)
uint32_t num = 0x12345678;
uint32_t res =
    ((num & 0x000000FF) << 24) |
    ((num & 0x0000FF00) << 8) |
    ((num & 0x00FF0000) >> 8) |
    ((num & 0xFF000000) >> 24);

printf("%0x\n", res);

The result is represented here in both binary and hex, notice how the bytes have swapped:

?0111 1000 0101 0110 0011 0100 0001 0010?

78563412

Optimizing

In terms of performance, leave it to the compiler to optimize your code when possible. You should avoid unnecessary data structures like arrays for simple algorithms like this, doing so will usually cause different instruction behavior such as accessing RAM instead of using CPU registers.

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

Well your solution above depends on the image being a jpeg file. For a general solution i used

$img = $_POST['image'];
$img = substr(explode(";",$img)[1], 7);
file_put_contents('img.png', base64_decode($img));

How do I get a Date without time in Java?

You can use the DateUtils.truncate from Apache Commons library.

Example:

DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH)

PHP mail function doesn't complete sending of e-mail

Add a mail header in the mail function:

$header = "From: [email protected]\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$header.= "X-Priority: 1\r\n";

$status = mail($to, $subject, $message, $header);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}

json.dumps vs flask.jsonify

The jsonify() function in flask returns a flask.Response() object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.dumps() method will just return an encoded string, which would require manually adding the MIME type header.

See more about the jsonify() function here for full reference.

Edit: Also, I've noticed that jsonify() handles kwargs or dictionaries, while json.dumps() additionally supports lists and others.

How to set the timezone in Django?

Here is the list of valid timezones:

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

You can use

TIME_ZONE = 'Europe/Istanbul'

for UTC+02:00

Can't ignore UserInterfaceState.xcuserstate

This works for me

  1. Open the folder which contains the project file project.xcworkspace from the terminal.

  2. Write this command: git rm --cached *xcuserstate

This will remove the file.

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

You mistyped the set command – you missed the backslash after C:. It should be:

C:\>set path=C:\Program Files (x86)\Java\jdk1.7.0\bin

Java - checking if parseInt throws exception

You could try

NumberUtils.isParsable(yourInput)

It is part of org/apache/commons/lang3/math/NumberUtils and it checks whether the string can be parsed by Integer.parseInt(String), Long.parseLong(String), Float.parseFloat(String) or Double.parseDouble(String).

See below:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isParsable-java.lang.String-

syntaxerror: unexpected character after line continuation character in python

You need to quote that filename:

f = open("D\\python\\HW\\2_1 - Copy.cp", "r")

Otherwise the bare backslash after the D is interpreted as a line-continuation character, and should be followed by a newline. This is used to extend long expressions over multiple lines, for readability:

print "This is a long",\
      "line of text",\
      "that I'm printing."

Also, you shouldn't have semicolons (;) at the end of your statements in Python.

CSS: Hover one element, effect for multiple elements?

You'd need to use JavaScript to accomplish this, I think.

jQuery:

$(function(){
   $("#innerContainer").hover(
        function(){
            $("#innerContainer").css('border-color','#FFF');
            $("#outerContainer").css('border-color','#FFF');
        },
        function(){
            $("#innerContainer").css('border-color','#000');
            $("#outerContainer").css('border-color','#000');
        }
    );
});

Adjust the values and element id's accordingly :)

Determine if an element has a CSS class with jQuery

from the FAQ

elem = $("#elemid");
if (elem.is (".class")) {
   // whatever
}

or:

elem = $("#elemid");
if (elem.hasClass ("class")) {
   // whatever
}

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

Disable SELinux

Disable SELinux temporarily

sudo setenforce 0

Restart httpd service

service httpd restart

Disable SELinux persistently (after reboot)

vi /etc/selinux/config

Add line and save

SELINUX=disabled

how to get all markers on google-maps-v3

I'm assuming you have multiple markers that you wish to display on a google map.

The solution is two parts, one to create and populate an array containing all the details of the markers, then a second to loop through all entries in the array to create each marker.

Not know what environment you're using, it's a little difficult to provide specific help.

My best advice is to take a look at this article & accepted answer to understand the principals of creating a map with multiple markers: Display multiple markers on a map with their own info windows

How to get an HTML element's style values in javascript?

I believe you are now able to use Window.getComputedStyle()

Documentation MDN

var style = window.getComputedStyle(element[, pseudoElt]);

Example to get width of an element:

window.getComputedStyle(document.querySelector('#mainbar')).width

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

What's the difference between KeyDown and KeyPress in .NET?

From Blogging Developer:

In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

Note: You can also try out the Key Event Tester (available on the above-mentioned site) to understand this concept.

Limit Get-ChildItem recursion depth

I tried to limit Get-ChildItem recursion depth using Resolve-Path

$PATH = "."
$folder = get-item $PATH 
$FolderFullName = $Folder.FullName
$PATHs = Resolve-Path $FolderFullName\*\*\*\
$Folders = $PATHs | get-item | where {$_.PsIsContainer}

But this works fine :

gci "$PATH\*\*\*\*"

Coding Conventions - Naming Enums

In our codebase; we typically declare enums in the class that they belong to.

So for your Fruit example, We would have a Fruit class, and inside that an Enum called Fruits.

Referencing it in the code looks like this: Fruit.Fruits.Apple, Fruit.Fruits.Pear, etc.

Constants follow along the same line, where they either get defined in the class to which they're relevant (so something like Fruit.ORANGE_BUSHEL_SIZE); or if they apply system-wide (i.e. an equivalent "null value" for ints) in a class named "ConstantManager" (or equivalent; like ConstantManager.NULL_INT). (side note; all our constants are in upper case)

As always, your coding standards probably differ from mine; so YMMV.

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

It turns out that there is a way to do this, although I'm not sure I've found the 'proper' way since this required hours of reading source code from multiple projects. In other words, this might be a lot of dumb work (but it works).

First, there is no way to get at the server.xml in the embedded Tomcat, either to augment it or replace it. This must be done programmatically.

Second, the 'require_https' setting doesn't help since you can't set cert info that way. It does set up forwarding from http to https, but it doesn't give you a way to make https work so the forwarding isnt helpful. However, use it with the stuff below, which does make https work.

To begin, you need to provide an EmbeddedServletContainerFactory as explained in the Embedded Servlet Container Support docs. The docs are for Java but the Groovy would look pretty much the same. Note that I haven't been able to get it to recognize the @Value annotation used in their example but its not needed. For groovy, simply put this in a new .groovy file and include that file on the command line when you launch spring boot.

Now, the instructions say that you can customize the TomcatEmbeddedServletContainerFactory class that you created in that code so that you can alter web.xml behavior, and this is true, but for our purposes its important to know that you can also use it to tailor server.xml behavior. Indeed, reading the source for the class and comparing it with the Embedded Tomcat docs, you see that this is the only place to do that. The interesting function is TomcatEmbeddedServletContainerFactory.addConnectorCustomizers(), which may not look like much from the Javadocs but actually gives you the Embedded Tomcat object to customize yourself. Simply pass your own implementation of TomcatConnectorCustomizer and set the things you want on the given Connector in the void customize(Connector con) function. Now, there are about a billion things you can do with the Connector and I couldn't find useful docs for it but the createConnector() function in this this guys personal Spring-embedded-Tomcat project is a very practical guide. My implementation ended up looking like this:

package com.deepdownstudios.server

import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.*
import org.springframework.stereotype.*

@Configuration
class MyConfiguration {

@Bean
public EmbeddedServletContainerFactory servletContainer() {
final int port = 8443;
final String keystoreFile = "/path/to/keystore"
final String keystorePass = "keystore-password"
final String keystoreType = "pkcs12"
final String keystoreProvider = "SunJSSE"
final String keystoreAlias = "tomcat"

TomcatEmbeddedServletContainerFactory factory = 
        new TomcatEmbeddedServletContainerFactory(this.port);
factory.addConnectorCustomizers( new TomcatConnectorCustomizer() {
    void    customize(Connector con) {
        Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler();
            proto.setSSLEnabled(true);
        con.setScheme("https");
        con.setSecure(true);
        proto.setKeystoreFile(keystoreFile);
        proto.setKeystorePass(keystorePass);
        proto.setKeystoreType(keystoreType);
        proto.setProperty("keystoreProvider", keystoreProvider);
        proto.setKeyAlias(keystoreAlias);
    }
});
return factory;
}
}

The Autowiring will pick up this implementation an run with it. Once I fixed my busted keystore file (make sure you call keytool with -storetype pkcs12, not -storepass pkcs12 as reported elsewhere), this worked. Also, it would be far better to provide the parameters (port, password, etc) as configuration settings for testing and such... I'm sure its possible if you can get the @Value annotation to work with Groovy.

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus

See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

In my case, I have solved this way:

$scope.MyObject = // get from database or other sources;
$scope.MyObject.Date = new Date($scope.MyObject.Date);

and input type date is ok

dropping infinite values from dataframes in pandas?

Use (fast and simple):

df = df[np.isfinite(df).all(1)]

This answer is based on DougR's answer in an other question. Here an example code:

import pandas as pd
import numpy as np
df=pd.DataFrame([1,2,3,np.nan,4,np.inf,5,-np.inf,6])
print('Input:\n',df,sep='')
df = df[np.isfinite(df).all(1)]
print('\nDropped:\n',df,sep='')

Result:

Input:
    0
0  1.0000
1  2.0000
2  3.0000
3     NaN
4  4.0000
5     inf
6  5.0000
7    -inf
8  6.0000

Dropped:
     0
0  1.0
1  2.0
2  3.0
4  4.0
6  5.0
8  6.0

Virtual member call in a constructor

When an object written in C# is constructed, what happens is that the initializers run in order from the most derived class to the base class, and then constructors run in order from the base class to the most derived class (see Eric Lippert's blog for details as to why this is).

Also in .NET objects do not change type as they are constructed, but start out as the most derived type, with the method table being for the most derived type. This means that virtual method calls always run on the most derived type.

When you combine these two facts you are left with the problem that if you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called.

This problem is, of course, mitigated if you mark your class as sealed to ensure that it is the most derived type in the inheritance hierarchy - in which case it is perfectly safe to call the virtual method.

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

Please find the actual css from Bootstrap

.container-fluid {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}
.row {
  margin-right: -15px;
  margin-left: -15px;
}

When you add a .container-fluid class, it adds a horizontal padding of 15px, and the same will be removed when you add a .row class as a child element by the negative margin set on row.

Is Visual Studio Community a 30 day trial?

For VS2019 I was able to signup with my github account:

enter image description here enter image description here enter image description here enter image description here

Then it will send password to your email and you will be able to sign.

OnclientClick and OnClick is not working at the same time?

OnClientClick seems to be very picky when used with OnClick.

I tried unsuccessfully with the following use cases:

OnClientClick="return ValidateSearch();" 
OnClientClick="if(ValidateSearch()) return true;"
OnClientClick="ValidateSearch();"

But they did not work. The following worked:

<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" 
  OnClick="keywordSearch_Click" 
  OnClientClick="if (!ValidateSearch()) { return false;};" />

Multiple Image Upload PHP form with one input

Multipal image uplode with other taBLE $sql1 = "INSERT INTO event(title) VALUES('$title')";

        $result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
        $lastid= $connection->insert_id;
        foreach ($_FILES["file"]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK ){
                $name = $lastid.$_FILES['file']['name'][$key];
                $target_dir = "photo/";
                $sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
                $result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
                move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
            }
        }

And how to fetch

$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());


  if($result->num_rows > 0) {
      while($r = mysqli_fetch_assoc($result)){
        $eventid= $r['id'];
        $sqli="select id,image from photos where eventid='".$eventid."'";
        $resulti=mysqli_query($connection,$sqli);
        $image_json_array = array();
        while($row = mysqli_fetch_assoc($resulti)){
            $image_id = $row['id'];
            $image_name = $row['image'];
            $image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
        }
        $msg1[] = array ("imagelist" => $image_json_array);

      }

in ajax $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}}); } })})

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

Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.

 <telerik:RadScriptBlock ID="radSript1" runat="server">
   <script type="text/javascript">
        //Your javascript
   </script>
</telerik>

Regards Örvar

Java Error opening registry key

I would have tagged this as a comment but cant (dont have the rep) just wanted to thank Tilman. I was trying to get PDFsam (PDF Split and Merge) to work to no avail.

At launch it would produce an error stating that it could not find JRE 1.6.0. I Have both 32 and 64 bit versions and they check out fine at the java website in their respective browsers.

Tried uninstalling/reinstalling and rebooting repeatedly as well as using JavaRa. No such luck, still no go.

I looked in the registry after reading this post and there was no ...\SOFTWARE\JavaSoft\ key so I added each with their respective string values pointing to my x86 version (PDFsam is a 32bit program). This got past the first problem but an error popped up about amd64 libraries suggesting the machine wanted to run the 64bit version. So I changed the paths to the 64bit JRE and PDFsam now works.

FYI - I got here by searching for Java registry keys after I was unable to launch javaw.exe from command prompt (even after adding the requisite paths to system path), making the aforementioned changes solved this as well.

SQL Data Reader - handling Null column values

As an addition to the answer by marc_s, you can use a more generic extension method to get values from the SqlDataReader:

public static T SafeGet<T>(this SqlDataReader reader, int col)
    {
        return reader.IsDBNull(col) ? default(T) : reader.GetFieldValue<T>(col);
    }

How to spyOn a value property (rather than a method) with Jasmine

Suppose there is a method like this that needs testing The src property of the tiny image needs checking

function reportABCEvent(cat, type, val) {
                var i1 = new Image(1, 1);
                var link = getABC('creosote');
                    link += "&category=" + String(cat);
                    link += "&event_type=" + String(type);
                    link += "&event_value=" + String(val);
                    i1.src = link;
                }

The spyOn() below causes the "new Image" to be fed the fake code from the test the spyOn code returns an object that only has a src property

As the variable "hook" is scoped to be visible in the fake code in the SpyOn and also later after the "reportABCEvent" is called

describe("Alphabetic.ads", function() {
    it("ABC events create an image request", function() {
    var hook={};
    spyOn(window, 'Image').andCallFake( function(x,y) {
          hook={ src: {} }
          return hook;
      }
      );
      reportABCEvent('testa', 'testb', 'testc');
      expect(hook.src).
      toEqual('[zubzub]&arg1=testa&arg2=testb&event_value=testc');
    });

This is for jasmine 1.3 but might work on 2.0 if the "andCallFake" is altered to the 2.0 name

Excel VBA select range at last row and column

The simplest modification (to the code in your question) is this:

    Range("A" & Rows.Count).End(xlUp).Select
    Selection.EntireRow.Delete

Which can be simplified to:

    Range("A" & Rows.Count).End(xlUp).EntireRow.Delete

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

When using $_SERVER["REMOTE_ADDR"], I get the server's IP address rather than the visitor's.

Then something is wrong, or odd, with your configuration.

  • Are you using some sort of reverse proxy? In that case, @simshaun's suggestion may work.

  • Do you have anything else out of the ordinary in your web server config?

  • Can you show the PHP code you are using?

  • Can you show what the address looks like. Is it a local one, or a Internet address?