Programs & Examples On #Pychecker

Pylint, PyChecker or PyFlakes?

pep8 was recently added to PyPi.

  • pep8 - Python style guide checker
  • pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

It is now super easy to check your code against pep8.

See http://pypi.python.org/pypi/pep8

how to get the 30 days before date from Todays Date

T-SQL

declare @thirtydaysago datetime
declare @now datetime
set @now = getdate()
set @thirtydaysago = dateadd(day,-30,@now)

select @now, @thirtydaysago

or more simply

select dateadd(day, -30, getdate())

(DATEADD on BOL/MSDN)

MYSQL

SELECT DATE_ADD(NOW(), INTERVAL -30 DAY)

( more DATE_ADD examples on ElectricToolbox.com)

Nginx 403 forbidden for all files

If you still see permission denied after verifying the permissions of the parent folders, it may be SELinux restricting access.

To check if SELinux is running:

# getenforce

To disable SELinux until next reboot:

# setenforce Permissive

Restart Nginx and see if the problem persists. To allow nginx to serve your www directory (make sure you turn SELinux back on before testing this. i.e, setenforce Enforcing)

# chcon -Rt httpd_sys_content_t /path/to/www

See my answer here for more details

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

One thing that really hung me up, was when I inspected this html in the browser, instead of seeing it expanded to something like:

<button ng-click="removeTask(1234)">remove</button>

I saw:

<button ng-click="removeTask(task.id)">remove</button>

However, the latter works!

This is because you are in the "Angular World", when inside ng-click="" Angular all ready knows about task.id as you are inside it's model. There is no need to use Data binding, as in {{}}.

Further, if you wanted to pass the task object itself, you can like:

<button ng-click="removeTask(task)">remove</button>

What does "where T : class, new()" mean?

Those are generic type constraints. In your case there are two of them:

where T : class

Means that the type T must be a reference type (not a value type).

where T : new()

Means that the type T must have a parameter-less constructor. Having this constraint will allow you to do something like T field = new T(); in your code which you wouldn't be able to do otherwise.

You then combine the two using a comma to get:

where T : class, new()

Why do I get access denied to data folder when using adb?

if you know the application package you can cd directly to that folder..

eg cd data/data/com.yourapp

this will drop you into a directory that is read/writable so you can change files as needed. Since the folder is the same on the emulator, you can use that to get the folder path.

Calculating Distance between two Latitude and Longitude GeoCoordinates

And here, for those still not satisfied (like me), the original code from .NET-Frameworks GeoCoordinate class, refactored into a standalone method:

public double GetDistance(double longitude, double latitude, double otherLongitude, double otherLatitude)
{
    var d1 = latitude * (Math.PI / 180.0);
    var num1 = longitude * (Math.PI / 180.0);
    var d2 = otherLatitude * (Math.PI / 180.0);
    var num2 = otherLongitude * (Math.PI / 180.0) - num1;
    var d3 = Math.Pow(Math.Sin((d2 - d1) / 2.0), 2.0) + Math.Cos(d1) * Math.Cos(d2) * Math.Pow(Math.Sin(num2 / 2.0), 2.0);
    
    return 6376500.0 * (2.0 * Math.Atan2(Math.Sqrt(d3), Math.Sqrt(1.0 - d3)));
}

AngularJS - difference between pristine/dirty and touched/untouched

AngularJS Developer Guide - CSS classes used by AngularJS

  • @property {boolean} $untouched True if control has not lost focus yet.
  • @property {boolean} $touched True if control has lost focus.
  • @property {boolean} $pristine True if user has not interacted with the control yet.
  • @property {boolean} $dirty True if user has already interacted with the control.

How do I find out which process is locking a file using .NET?

One of the good things about handle.exe is that you can run it as a subprocess and parse the output.

We do this in our deployment script - works like a charm.

Can an XSLT insert the current date?

Late answer, but my solution works in Eclipse XSLT. Eclipse uses XSLT 1 at time of this writing. You can install an XSLT 2 engine like Saxon. Or you can use the XSLT 1 solution below to insert current date and time.

<xsl:value-of select="java:util.Date.new()"/>

This will call Java's Data class to output the date. It will not work unless you also put the following "java:" definition in your <xsl:stylesheet> tag.

<xsl:stylesheet [...snip...]
         xmlns:java="java"
         [...snip...]>

I hope that helps someone. This simple answer was difficult to find for me.

using CASE in the WHERE clause

This is working Oracle example but it should work in MySQL too.

You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.

SELECT empno, ename, job
  FROM scott.emp
 WHERE (CASE WHEN job = 'MANAGER' THEN '1'  
         WHEN job = 'CLERK'   THEN '2' 
         ELSE '0'  END) IN (1, 2)

Keyboard shortcut to comment lines in Sublime Text 3

For me, on Mac OS Sierra :

{ "keys": ["super+forward_slash"], "command": "toggle_comment", "args": { "block": true } }, { "keys": ["super+alt+:"], "command": "toggle_comment", "args": { "block": false } },

db.collection is not a function when using MongoClient v3.0

MongoClient.connect(url (err, client) => {
    if(err) throw err;

    let database = client.db('databaseName');

    database.collection('name').find()
    .toArray((err, results) => {
        if(err) throw err;

        results.forEach((value)=>{
            console.log(value.name);
        });
    })
})

The only problem with your code is that you are accessing the object that's holding the database handler. You must access the database directly (see database variable above). This code will return your database in an array and then it loops through it and logs the name for everyone in the database.

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

How to press back button in android programmatically?

you can simply use onBackPressed();

or if you are using fragment you can use getActivity().onBackPressed()

How to Alter a table for Identity Specification is identity SQL Server

You don't set value to default in a table. You should clear the option "Default value or Binding" first.

How to programmatically add controls to a form in VB.NET

To add controls dynamically to the form, do the following code. Here we are creating textbox controls to add dynamically.

Public Class Form1
    Private m_TextBoxes() As TextBox = {}

    Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles Button1.Click

        ' Get the index for the new control.
        Dim i As Integer = m_TextBoxes.Length

        ' Make room.
        ReDim Preserve m_TextBoxes(i)

        ' Create and initialize the control.
        m_TextBoxes(i) = New TextBox
        With m_TextBoxes(i)
            .Name = "TextBox" & i.ToString()
            If m_TextBoxes.Length < 2 Then
                ' Position the first one.
                .SetBounds(8, 8, 100, 20)
            Else
                ' Position subsequent controls.
                .Left = m_TextBoxes(i - 1).Left
                .Top = m_TextBoxes(i - 1).Top + m_TextBoxes(i - _
                    1).Height + 4
                .Size = m_TextBoxes(i - 1).Size
            End If

            ' Save the control's index in the Tag property.
            ' (Or you can get this from the Name.)
            .Tag = i
        End With

        ' Give the control an event handler.
        AddHandler m_TextBoxes(i).TextChanged, AddressOf TextBox_TextChanged

        ' Add the control to the form.
        Me.Controls.Add(m_TextBoxes(i))
    End Sub

    'When you enter text in one of the TextBoxes, the TextBox_TextChanged event
    'handler displays the control's name and its current text.
    Private Sub TextBox_TextChanged(ByVal sender As  _
    System.Object, ByVal e As System.EventArgs)
        ' Display the current text.
        Dim txt As TextBox = DirectCast(sender, TextBox)
        Debug.WriteLine(txt.Name & ": [" & txt.Text & "]")
    End Sub
End Class

How can I close a dropdown on click outside?

You can write directive:

@Directive({
  selector: '[clickOut]'
})
export class ClickOutDirective implements AfterViewInit {
  @Input() clickOut: boolean;

  @Output() clickOutEvent: EventEmitter<any> = new EventEmitter<any>();

  @HostListener('document:mousedown', ['$event']) onMouseDown(event: MouseEvent) {

       if (this.clickOut && 
         !event.path.includes(this._element.nativeElement))
       {
           this.clickOutEvent.emit();
       }
  } 


}

In your component:

@Component({
  selector: 'app-root',
  template: `
    <h1 *ngIf="isVisible" 
      [clickOut]="true" 
      (clickOutEvent)="onToggle()"
    >{{title}}</h1>
`,
  styleUrls: ['./app.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  title = 'app works!';

  isVisible = false;

  onToggle() {
    this.isVisible = !this.isVisible;
  }
}

This directive emit event when html element is containing in DOM and when [clickOut] input property is 'true'. It listen mousedown event to handle event before element will be removed from DOM.

And one note: firefox doesn't contain property 'path' on event you can use function to create path:

const getEventPath = (event: Event): HTMLElement[] => {
  if (event['path']) {
    return event['path'];
  }
  if (event['composedPath']) {
    return event['composedPath']();
  }
  const path = [];
  let node = <HTMLElement>event.target;
  do {
    path.push(node);
  } while (node = node.parentElement);
  return path;
};

So you should change event handler on the directive: event.path should be replaced getEventPath(event)

This module can help. https://www.npmjs.com/package/ngx-clickout It contains the same logic but also handle esc event on source html element.

How to check whether an array is empty using PHP?

Some decent answers, but just thought I'd expand a bit to explain more clearly when PHP determines if an array is empty.


Main Notes:

An array with a key (or keys) will be determined as NOT empty by PHP.

As array values need keys to exist, having values or not in an array doesn't determine if it's empty, only if there are no keys (AND therefore no values).

So checking an array with empty() doesn't simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.


So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name="array[]").
A non empty array will be produced for each field as there will be auto incremented key values for each form field's array.

Take these arrays for example:

/* Assigning some arrays */

// Array with user defined key and value
$ArrayOne = array("UserKeyA" => "UserValueA", "UserKeyB" => "UserValueB");

// Array with auto increment key and user defined value
// as a form field would return with user input
$ArrayTwo[] = "UserValue01";
$ArrayTwo[] = "UserValue02";

// Array with auto incremented key and no value
// as a form field would return without user input
$ArrayThree[] = '';
$ArrayThree[] = '';

If you echo out the array keys and values for the above arrays, you get the following:

ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]

ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]

ARRAY THREE:
[0] => []
[1] => []

And testing the above arrays with empty() returns the following results:

ARRAY ONE:
$ArrayOne is not empty

ARRAY TWO:
$ArrayTwo is not empty

ARRAY THREE:
$ArrayThree is not empty

An array will always be empty when you assign an array but don't use it thereafter, such as:

$ArrayFour = array();

This will be empty, ie PHP will return TRUE when using if empty() on the above.

So if your array has keys - either by eg a form's input names or if you assign them manually (ie create an array with database column names as the keys but no values/data from the database), then the array will NOT be empty().

In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.

However it is not the best method if you simply need to know "if values exist" returns TRUE or FALSE. There are various methods to determine if an array has any values when it's know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).


Here's an approach which uses very little code to check if an array has values:

Using array_filter():
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

$EmptyTestArray = array_filter($ArrayOne);

if (!empty($EmptyTestArray))
  {
    // do some tests on the values in $ArrayOne
  }
else
  {
    // Likely not to need an else, 
    // but could return message to user "you entered nothing" etc etc
  }

Running array_filter() on all three example arrays (created in the first code block in this answer) results in the following:

ARRAY ONE:
$arrayone is not empty

ARRAY TWO:
$arraytwo is not empty

ARRAY THREE:
$arraythree is empty

So when there are no values, whether there are keys or not, using array_filter() to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don't need to loop through it for any other reason, then this is the simplest in terms of code needed.


I'm not experienced in checking overheads, but it would be good to know the differences between using array_filter() and foreach checking if a value is found.

Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

Does static constexpr variable inside a function make sense?

In addition to given answer, it's worth noting that compiler is not required to initialize constexpr variable at compile time, knowing that the difference between constexpr and static constexpr is that to use static constexpr you ensure the variable is initialized only once.

Following code demonstrates how constexpr variable is initialized multiple times (with same value though), while static constexpr is surely initialized only once.

In addition the code compares the advantage of constexpr against const in combination with static.

#include <iostream>
#include <string>
#include <cassert>
#include <sstream>

const short const_short = 0;
constexpr short constexpr_short = 0;

// print only last 3 address value numbers
const short addr_offset = 3;

// This function will print name, value and address for given parameter
void print_properties(std::string ref_name, const short* param, short offset)
{
    // determine initial size of strings
    std::string title = "value \\ address of ";
    const size_t ref_size = ref_name.size();
    const size_t title_size = title.size();
    assert(title_size > ref_size);

    // create title (resize)
    title.append(ref_name);
    title.append(" is ");
    title.append(title_size - ref_size, ' ');

    // extract last 'offset' values from address
    std::stringstream addr;
    addr << param;
    const std::string addr_str = addr.str();
    const size_t addr_size = addr_str.size();
    assert(addr_size - offset > 0);

    // print title / ref value / address at offset
    std::cout << title << *param << " " << addr_str.substr(addr_size - offset) << std::endl;
}

// here we test initialization of const variable (runtime)
void const_value(const short counter)
{
    static short temp = const_short;
    const short const_var = ++temp;
    print_properties("const", &const_var, addr_offset);

    if (counter)
        const_value(counter - 1);
}

// here we test initialization of static variable (runtime)
void static_value(const short counter)
{
    static short temp = const_short;
    static short static_var = ++temp;
    print_properties("static", &static_var, addr_offset);

    if (counter)
        static_value(counter - 1);
}

// here we test initialization of static const variable (runtime)
void static_const_value(const short counter)
{
    static short temp = const_short;
    static const short static_var = ++temp;
    print_properties("static const", &static_var, addr_offset);

    if (counter)
        static_const_value(counter - 1);
}

// here we test initialization of constexpr variable (compile time)
void constexpr_value(const short counter)
{
    constexpr short constexpr_var = constexpr_short;
    print_properties("constexpr", &constexpr_var, addr_offset);

    if (counter)
        constexpr_value(counter - 1);
}

// here we test initialization of static constexpr variable (compile time)
void static_constexpr_value(const short counter)
{
    static constexpr short static_constexpr_var = constexpr_short;
    print_properties("static constexpr", &static_constexpr_var, addr_offset);

    if (counter)
        static_constexpr_value(counter - 1);
}

// final test call this method from main()
void test_static_const()
{
    constexpr short counter = 2;

    const_value(counter);
    std::cout << std::endl;

    static_value(counter);
    std::cout << std::endl;

    static_const_value(counter);
    std::cout << std::endl;

    constexpr_value(counter);
    std::cout << std::endl;

    static_constexpr_value(counter);
    std::cout << std::endl;
}

Possible program output:

value \ address of const is               1 564
value \ address of const is               2 3D4
value \ address of const is               3 244

value \ address of static is              1 C58
value \ address of static is              1 C58
value \ address of static is              1 C58

value \ address of static const is        1 C64
value \ address of static const is        1 C64
value \ address of static const is        1 C64

value \ address of constexpr is           0 564
value \ address of constexpr is           0 3D4
value \ address of constexpr is           0 244

value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0

As you can see yourself constexpr is initilized multiple times (address is not the same) while static keyword ensures that initialization is performed only once.

How do I get the backtrace for all the threads in GDB?

Is there a command that does?

thread apply all where

Using CSS td width absolute, position

The reason it doesn't work in the link your provided is because you are trying to display a 300px column PLUS 52 columns the span 7 columns each. Shrink the number of columns and it works. You can't fit that many on the screen.

If you want to force the columns to fit try setting:

body {min-width:4150px;}

see my jsfiddle: http://jsfiddle.net/Mkq8L/6/ @mike I can't comment yet.

Check if value exists in Postgres array

Watch out for the trap I got into: When checking if certain value is not present in an array, you shouldn't do:

SELECT value_variable != ANY('{1,2,3}'::int[])

but use

SELECT value_variable != ALL('{1,2,3}'::int[])

instead.

Cache busting via params

As others have said, cache busting with a query param is usually considered a Bad Idea (tm), and has been for a long time. It's better to reflect the version in the file name. Html5 Boilerplate recommends against using the query string, among others.

That said, of the recommendations I have seen which cited a source, all seem to take their wisdom from a 2008 article by Steve Souders. His conclusions are based on the behaviour of proxies at the time, and they may or may not be relevant these days. Still, in the absence of more current information, changing the file name is the safe option.

Where is the IIS Express configuration / metabase file found?

For Visual Studio 2019 (v16.2.4) I was only able to find this file here:

C:\Users\\Documents\IISExpress\config\applicationhost.config applicationhost.config

Hope this helps as I wasn't able to find the .vs folder location as mentioned in the above suggestions.

How do I view the Explain Plan in Oracle Sql developer?

We use Oracle PL/SQL Developer(Version 12.0.7). And we use F5 button to view the explain plan.

SVN upgrade working copy

You can also get strange messages about the need to upgrade your working copy when there are other working copies nested into yours. I had this issue with a Symphony project were some framework folders are working copy, that I suppose have not been cleaned up properly before they were published.

In this case, just make a file search for .svn, and delete the .svn folders that you don't want (don't delete yours at the root of course).

how to check confirm password field in form without reloading page

WITHOUT clicking the button you will have to listen to the change event of the input fields

var confirmField = document.getElementById("confirm_password");
var passwordField = document.getElementById("password");

function checkPasswordMatch(){
    var status = document.getElementById("password_status");
    var submit = document.getElementById("submit");

    status.innerHTML = "";
    submit.removeAttribute("disabled");

    if(confirmField.value === "")
        return;

    if(passwordField.value === confirmField.value)
        return;

    status.innerHTML = "Passwords don't match";
    submit.setAttribute("disabled", "disabled");
}

passWordField.addEventListener("change", function(event){
    checkPasswordMatch();
});
confirmField.addEventListener("change", function(event){
    checkPasswordMatch();
});

then add the status element to your html:

<p id="password_status"></p>

and set the submit button id to submit

... id="submit" />

hope this helps you

Regex for numbers only

^\d+$, which is "start of string", "1 or more digits", "end of string" in English.

X close button only using css

As a pure CSS solution for the close or 'times' symbol you can use the ISO code with the content property. I often use this for :after or :before pseudo selectors.

The content code is \00d7.

Example

div:after{
  display: inline-block;
  content: "\00d7"; /* This will render the 'X' */
}

You can then style and position the pseudo selector in any way you want. Hope this helps someone :).

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

C99 N1256 standard draft

http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

6.5.3.4 The sizeof operator:

3 When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding.

6.7.2.1 Structure and union specifiers:

13 ... There may be unnamed padding within a structure object, but not at its beginning.

and:

15 There may be unnamed padding at the end of a structure or union.

The new C99 flexible array member feature (struct S {int is[];};) may also affect padding:

16 As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

Annex J Portability Issues reiterates:

The following are unspecified: ...

  • The value of padding bytes when storing values in structures or unions (6.2.6.1)

C++11 N3337 standard draft

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

5.3.3 Sizeof:

2 When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array.

9.2 Class members:

A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [ Note: There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment. — end note ]

I only know enough C++ to understand the note :-)

Android marshmallow request permission?

It may be a cleaner way. Add all your permissions in an array like

private static final String[] INITIAL_PERMS={
            android.Manifest.permission.ACCESS_FINE_LOCATION,
            android.Manifest.permission.ACCESS_COARSE_LOCATION
    };
    private static final int INITIAL_REQUEST=1337;

Whatever your permision is create method for each permision

@RequiresApi(api = Build.VERSION_CODES.M)
private boolean canAccessFineLocation() {
    return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
}

@RequiresApi(api = Build.VERSION_CODES.M)
private boolean canAccessCoarseLocation() {
    return(hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION));
}

@RequiresApi(api = Build.VERSION_CODES.M)
private boolean hasPermission(String perm) {
    return(PackageManager.PERMISSION_GRANTED == checkSelfPermission(perm));
}

Call this method in onCreate

 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
      if(!canAccessCoarseLocation() || !canAccessFineLocation()){
            requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);
        }
 }

Now override onRequestPermissionsResult

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if(requestCode == INITIAL_REQUEST){
        if (canAccessFineLocation() && canAccessCoarseLocation())  {
            //call your method
        }
        else {
            //show Toast or alert that this permissions is neccessary
        }
    }
}

Simulating ENTER keypress in bash script

Here is sample usage using expect:

#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }

Check: man expect for further information.

How to detect Adblock on my website?

I understand your tension and you can check if element has been created by script or element is hidden. And if we speak about ad-blocking you can count only on the element visibility, not on the element presence.

Element created with third-party script will never be present, that if script is not reachable at the moment (DNS error, remote web server error, offline web page preload, etc), and you'll always get false positive.

All other answers with checks are correct, but keep this in mind.

Identifier not found error on function call

Unlike other languages you may be used to, everything in C++ has to be declared before it can be used. The compiler will read your source file from top to bottom, so when it gets to the call to swapCase, it doesn't know what it is so you get an error. You can declare your function ahead of main with a line like this:

void swapCase(char *name);

or you can simply move the entirety of that function ahead of main in the file. Don't worry about having the seemingly most important function (main) at the bottom of the file. It is very common in C or C++ to do that.

Creating random numbers with no duplicates

There is algorithm of card batch: you create ordered array of numbers (the "card batch") and in every iteration you select a number at random position from it (removing the selected number from the "card batch" of course).

How to get class object's name as a string in Javascript?

This is pretty old, but I ran across this question via Google, so perhaps this solution might be useful to others.

function GetObjectName(myObject){
    var objectName=JSON.stringify(myObject).match(/"(.*?)"/)[1];
    return objectName;
}

It just uses the browser's JSON parser and regex without cluttering up the DOM or your object too much.

Using env variable in Spring Boot's application.properties

The easiest way to have different configurations for different environments is to use spring profiles. See externalised configuration.

This gives you a lot of flexibility. I am using it in my projects and it is extremely helpful. In your case you would have 3 profiles: 'local', 'jenkins', and 'openshift'

You then have 3 profile specific property files: application-local.properties, application-jenkins.properties, and application-openshift.properties

There you can set the properties for the regarding environment. When you run the app you have to specify the profile to activate like this: -Dspring.profiles.active=jenkins

Edit

According to the spring doc you can set the system environment variable SPRING_PROFILES_ACTIVE to activate profiles and don't need to pass it as a parameter.

is there any way to pass active profile option for web app at run time ?

No. Spring determines the active profiles as one of the first steps, when building the application context. The active profiles are then used to decide which property files are read and which beans are instantiated. Once the application is started this cannot be changed.

Header set Access-Control-Allow-Origin in .htaccess doesn't work

I activated the Apache module headers a2enmod headers, and the issue has been solved.

Data binding for TextBox

We can use following code

textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

Where

  • "Text" – the property of textbox
  • model – the model object enter code here
  • "Name" – the value of model which to bind the textbox.

How can I iterate over an enum?

In Bjarne Stroustrup's C++ programming language book, you can read that he's proposing to overload the operator++ for your specific enum. enum are user-defined types and overloading operator exists in the language for these specific situations.

You'll be able to code the following:

#include <iostream>
enum class Colors{red, green, blue};
Colors& operator++(Colors &c, int)
{
     switch(c)
     {
           case Colors::red:
               return c=Colors::green;
           case Colors::green:
               return c=Colors::blue;
           case Colors::blue:
               return c=Colors::red; // managing overflow
           default:
               throw std::exception(); // or do anything else to manage the error...
     }
}

int main()
{
    Colors c = Colors::red;
    // casting in int just for convenience of output. 
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    return 0;
}

test code: http://cpp.sh/357gb

Mind that I'm using enum class. Code works fine with enum also. But I prefer enum class since they are strong typed and can prevent us to make mistake at compile time.

Calling an executable program using awk

From the AWK man page:

system(cmd)
              executes cmd and returns its exit status

The GNU AWK manual also has a section that, in part, describes the system function and provides an example:

system("date | mail -s 'awk run done' root")

Python: Converting string into decimal number

If you want the result as the nearest binary floating point number use float:

result = [float(x.strip(' "')) for x in A1]

If you want the result stored exactly use Decimal instead of float:

from decimal import Decimal
result = [Decimal(x.strip(' "')) for x in A1]

How do I set a ViewModel on a window in XAML using DataContext property?

There is also this way of specifying the viewmodel:

using Wpf = System.Windows;

public partial class App : Wpf.Application //your skeleton app already has this.
{
    protected override void OnStartup( Wpf.StartupEventArgs e ) //you need to add this.
    {
        base.OnStartup( e );
        MainWindow = new MainView();
        MainWindow.DataContext = new MainViewModel( e.Args );
        MainWindow.Show();
    }
}

<Rant>

All of the solutions previously proposed require that MainViewModel must have a parameterless constructor.

Microsoft is under the impression that systems can be built using parameterless constructors. If you are also under that impression, go ahead and use some of the other solutions.

For those that know that constructors must have parameters, and therefore the instantiation of objects cannot be left in the hands of magic frameworks, the proper way of specifying the viewmodel is the one I showed above.

</Rant>

Is it possible to use global variables in Rust?

You can use static variables fairly easily as long as they are thread-local.

The downside is that the object will not be visible to other threads your program might spawn. The upside is that unlike truly global state, it is entirely safe and is not a pain to use - true global state is a massive pain in any language. Here's an example:

extern mod sqlite;

use std::cell::RefCell;

thread_local!(static ODB: RefCell<sqlite::database::Database> = RefCell::new(sqlite::open("test.db"));

fn main() {
    ODB.with(|odb_cell| {
        let odb = odb_cell.borrow_mut();
        // code that uses odb goes here
    });
}

Here we create a thread-local static variable and then use it in a function. Note that it is static and immutable; this means that the address at which it resides is immutable, but thanks to RefCell the value itself will be mutable.

Unlike regular static, in thread-local!(static ...) you can create pretty much arbitrary objects, including those that require heap allocations for initialization such as Vec, HashMap and others.

If you cannot initialize the value right away, e.g. it depends on user input, you may also have to throw Option in there, in which case accessing it gets a bit unwieldy:

extern mod sqlite;

use std::cell::RefCell;

thread_local!(static ODB: RefCell<Option<sqlite::database::Database>> = RefCell::New(None));

fn main() {
    ODB.with(|odb_cell| {
        // assumes the value has already been initialized, panics otherwise
        let odb = odb_cell.borrow_mut().as_mut().unwrap();
        // code that uses odb goes here
    });
}

Convert date to day name e.g. Mon, Tue, Wed

Very Simply Short week day name with Month and year

echo date('D, d-M-y');

output

Tue, 16-Feb-21

as per my requirements

return $item->start_time->format("D, d-M");

output

Tue, 16-Feb

using extern template (C++11)

If you have used extern for functions before, exactly same philosophy is followed for templates. if not, going though extern for simple functions may help. Also, you may want to put the extern(s) in header file and include the header when you need it.

Installing a dependency with Bower from URL and specify version

Try bower install git://github.com/urin/jquery.balloon.js.git#1.0.3 --save where 1.0.3 is the tag number which you can get by reading tag under releases. Also for URL replace by git:// in order for system to connect.

invalid target release: 1.7

In IntelliJ IDEA this happened to me when I imported a project that had been working fine and running with Java 1.7. I apparently hadn't notified IntelliJ that java 1.7 had been installed on my machine, and it wasn't finding my $JAVA_HOME.

On a Mac, this is resolved by:

Right clicking on the module | Module Settings | Project

and adding the 1.7 SDK by selecting "New" in the Project SDK.

Then go to the main IntelliJ IDEA menu | Preferences | Maven | Runner

and select the correct JRE. In my case it updated correctly Use Project SDK, which was now 1.7.

python dictionary sorting in descending order based on values

Whenever one has a dictionary where the values are integers, the Counter data structure is often a better choice to represent the data than a dictionary.

If you already have a dictionary, a counter can easily be formed by:

c = Counter(d['123'])

as an example from your data.

The most_common function allows easy access to descending order of the items in the counter

The more complete writeup on the Counter data structure is at https://docs.python.org/2/library/collections.html

How to delete a certain row from mysql table with same column values?

You must add an id that auto-increment for each row, after that you can delet the row by its id. so your table will have an unique id for each row and the id_user, id_product ecc...

How can I scroll a web page using selenium webdriver in python?

The ScrollTo() function doesn't work anymore. This is what I used and it worked fine.

driver.execute_script("document.getElementById('mydiv').scrollIntoView();")

Html.ActionLink as a button or an image, not a link

<button onclick="location.href='@Url.Action("NewCustomer", "Customers")'">Checkout >></button>

Python list subtraction operation

If the lists allow duplicate elements, you can use Counter from collections:

from collections import Counter
result = list((Counter(x)-Counter(y)).elements())

If you need to preserve the order of elements from x:

result = [ v for c in [Counter(y)] for v in x if not c[v] or c.subtract([v]) ]

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

How to apply font anti-alias effects in CSS?

Short answer: You can't.

CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.

Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.

There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.

There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.

Turning multiple lines into one comma separated line

Perl one-liner:

perl -pe'chomp, s/$/,/ unless eof' file

or, if you want to be more cryptic:

perl '-peeof||chomp&&s/$/,/' file

java how to use classes in other package?

You have to provide the full path that you want to import.

import com.my.stuff.main.Main;
import com.my.stuff.second.*;

So, in your main class, you'd have:

package com.my.stuff.main

import com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION

class Main {
   public static void main(String[] args) {
      Second second = new Second();
      second.x();  
   }
}

EDIT: adding example in response to Shawn D's comment

There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:

class Main {
    void function() {
        int x = my.package.heirarchy.Foo.aStaticMethod();

        another.package.heirarchy.Baz b = new another.package.heirarchy.Bax();
    }
}

Alternatively, this is useful when you want to differentiate between two classes with the same short name:

class Main {
    void function() {
        java.util.Date utilDate = ...;
        java.sql.Date sqlDate = ...;
    }
}

Date constructor returns NaN in IE, but works in Firefox and Chrome

Try out using getDate feature of datepicker.

$.datepicker.formatDate('yy-mm-dd',new Date(pField.datepicker("getDate")));

Delete all items from a c++ std::vector

class Class;
std::vector<Class*> vec = some_data;

for (unsigned int i=vec.size(); i>0;) {
    --i;
    delete vec[i];
    vec.pop_back();
}
// Free memory, efficient for large sized vector
vec.shrink_to_fit();

Performance: theta(n)

If pure objects (not recommended for large data types, then just vec.clear();

How to comment out a block of Python code in Vim

NERDcommenter is an excellent plugin for commenting which automatically detects a number of filetypes and their associated comment characters. Ridiculously easy to install using Pathogen.

Comment with <leader>cc. Uncomment with <leader>cu. And toggle comments with <leader>c<space>.

(The default <leader> key in vim is \)

How to fetch the dropdown values from database and display in jsp

You can learn some tutorials for JSP page direct access database (mysql) here

Notes:

  • import sql tag library in jsp page

    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

  • then set datasource on page

    <sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://<yourhost>/<yourdb>" user="<user>" password="<password>"/>
    
  • Now query what you want on page

    <sql:query dataSource="${ds}" var="result"> //ref  defined 'ds'
        SELECT * from <your-table>;
    </sql:query>
    
  • Finally you can populate dropdowns on page using c:forEach tag to iterate result rows in select element

    <c:forEach var="row" items="${result.rows}"> //ref set var 'result' <option value='<c:out value="${row.key}"/>'><c:out value="${row.value}"/</option> </c:forEach>

How to parseInt in Angular.js

var app = angular.module('myApp', [])

app.controller('MainCtrl', ['$scope', function($scope){
   $scope.num1 = 1;
   $scope.num2 = 1;
   $scope.total = parseInt($scope.num1 + $scope.num2);

}]);

Demo: parseInt with AngularJS

Input type for HTML form for integer

This might help:

<input type="number" step="1" pattern="\d+" />

step is for convenience (and could be set to another integer), but pattern does some actual enforcing.

Note that since pattern matches the whole expression, it wasn't necessary to express it as ^\d+$.

Even with this outwardly tight regular expression, Chrome and Firefox's implementations, interestingly allow for e here (presumably for scientific notation) as well as - for negative numbers, and Chrome also allows for . whereas Firefox is tighter in rejecting unless the . is followed by 0's only. (Firefox marks the field as red upon the input losing focus whereas Chrome doesn't let you input disallowed values in the first place.)

Since, as observed by others, one should always validate on the server (or on the client too, if using the value locally on the client or wishing to prevent the user from a roundtrip to the server).

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

The error for me was:

Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.2) from [com.android.support:percent:26.0.2] AndroidManifest.xml:25:13-35
    is also present at [com.android.support:support-v4:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:23:9-25:38 to override.

The solution for me was in my project Gradle file I needed to bump my com.google.gms:google-services version.

I was using version 3.1.1:

classpath 'com.google.gms:google-services:3.1.1

And the error resolved after I bumped it to version 3.2.1:

classpath 'com.google.gms:google-services:3.2.1

I had just upgraded all my libraries to the latest including v27.1.1 of all the support libraries and v15.0.0 of all the Firebase libraries when I saw the error.

How disable / remove android activity label and label bar?

There is a code here that does it.

The trick is at this line:

 title.setVisibility(View.GONE);

How to clear the cache in NetBeans

The cache is C:\Users\userName\AppData\Local\NetBeans\Cache\, and then the version name of the folder will specify the correct cache.

You can also do this: Close the IDE. Instead, of deleting files and risking everything, rename this cache folder. Now start the IDE. Once it starts, a new cache folder will be created since the folder is not found. Now you can delete the renamed folder safely.

Looping over a list in Python

Do this instead:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)

Printing out a number in assembly language?

AH = 09 DS:DX = pointer to string ending in "$"

returns nothing


- outputs character string to STDOUT up to "$"
- backspace is treated as non-destructive
- if Ctrl-Break is detected, INT 23 is executed

ref: http://stanislavs.org/helppc/int_21-9.html


.data  

string db 2 dup(' ')

.code  
mov ax,@data  
mov ds,ax

mov al,10  
add al,15  
mov si,offset string+1  
mov bl,10  
div bl  
add ah,48  
mov [si],ah  
dec si  
div bl  
add ah,48  
mov [si],ah  

mov ah,9  
mov dx,string  
int 21h

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

In my case it was a very silly error. I was using a library to read the connection string out of a config file, and I forgot to double back slash.

For example I had: localhost\sqlexpress which was read as localhostsqlexpress when I should rather have had localhost\\sqlexpress note the \

Creating a constant Dictionary in C#

enum Constants
{
    Abc = 1,
    Def = 2,
    Ghi = 3
}

...

int i = (int)Enum.Parse(typeof(Constants), "Def");

ValueError: Wrong number of items passed - Meaning and suggestions?

Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
  }

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');
  }

Getting user input

sys.argv[0] is not the first argument but the filename of the python program you are currently executing. I think you want sys.argv[1]

Correct way to pause a Python program

I have had a similar question and I was using signal:

import signal

def signal_handler(signal_number, frame):
    print "Proceed ..."

signal.signal(signal.SIGINT, signal_handler)
signal.pause()

So you register a handler for the signal SIGINT and pause waiting for any signal. Now from outside your program (e.g. in bash), you can run kill -2 <python_pid>, which will send signal 2 (i.e. SIGINT) to your python program. Your program will call your registered handler and proceed running.

Hide a EditText & make it visible by clicking a menu

Try phoneNumber.setVisibility(View.GONE);

How to read files from resources folder in Scala?

The required file can be accessed as below from resource folder in scala

val file = scala.io.Source.fromFile(s"src/main/resources/app.config").getLines().mkString

docker entrypoint running bash script gets "permission denied"

  1. "Permission denied" prevents your script from being invoked at all. Thus, the only syntax that could be possibly pertinent is that of the first line (the "shebang"), which should look like #!/usr/bin/env bash, or #!/bin/bash, or similar depending on your target's filesystem layout.

  2. Most likely the filesystem permissions not being set to allow execute. It's also possible that the shebang references something that isn't executable, but this is far less likely.

  3. Mooted by the ease of repairing the prior issues.


The simple reading of

docker: Error response from daemon: oci runtime error: exec: "/usr/src/app/docker-entrypoint.sh": permission denied.

...is that the script isn't marked executable.

RUN ["chmod", "+x", "/usr/src/app/docker-entrypoint.sh"]

will address this within the container. Alternately, you can ensure that the local copy referenced by the Dockerfile is executable, and then use COPY (which is explicitly documented to retain metadata).

SQL Server Script to create a new user

If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name

Declare @userName as varchar(50); 
Declare @defaultDataBaseName as varchar(50);
Declare @LoginCreationScript as varchar(max);
Declare @UserCreationScript as varchar(max);
Declare @TempUserCreationScript as varchar(max);
set @defaultDataBaseName = 'data1';
set @userName = 'domain\userName';
set @LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS 
WITH DEFAULT_DATABASE ={dataBaseName}'

set @UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set @LoginCreationScript=Replace(Replace(@LoginCreationScript, '{userName}', @userName), '{dataBaseName}', @defaultDataBaseName)
set @UserCreationScript =Replace(@UserCreationScript, '{userName}', @userName)
Execute(@LoginCreationScript)

/*User creation and role assignment*/
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', @defaultDataBaseName)
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db2')
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db3')
Execute(@TempUserCreationScript)

How to list the tables in a SQLite database file that was opened with ATTACH?

To show all tables, use

SELECT name FROM sqlite_master WHERE type = "table"

To show all rows, I guess you can iterate through all tables and just do a SELECT * on each one. But maybe a DUMP is what you're after?

Pad left or right with string.format (not padleft or padright) with arbitrary string

Edit: I misunderstood your question, I thought you were asking how to pad with spaces.

What you are asking is not possible using the string.Format alignment component; string.Format always pads with whitespace. See the Alignment Component section of MSDN: Composite Formatting.

According to Reflector, this is the code that runs inside StringBuilder.AppendFormat(IFormatProvider, string, object[]) which is called by string.Format:

int repeatCount = num6 - str2.Length;
if (!flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}
this.Append(str2);
if (flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}

As you can see, blanks are hard coded to be filled with whitespace.

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

This is a simple blocking technique:

var waitTill = new Date(new Date().getTime() + seconds * 1000);
while(waitTill > new Date()){}

It's blocking insofar as nothing else will happen in your script (like callbacks). But since this is a console script, maybe it is what you need!

T-SQL query to show table definition?

Another way is to execute sp_columns procedure.

EXEC sys.sp_columns @TABLE_NAME = 'YourTableName'

Given a starting and ending indices, how can I copy part of a string in C?

Just use memcpy.

If the destination isn't big enough, strncpy won't null terminate. if the destination is huge compared to the source, strncpy just fills the destination with nulls after the string. strncpy is pointless, and unsuitable for copying strings.

strncpy is like memcpy except it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.

Use JavaScript to place cursor at end of text in text input element

Notice focus() is at the end, this is for textarea long text compatability.

const end = input.value.length
input.setSelectionRange(end, end)
input.focus()

How to set background color in jquery

You can add your attribute on callback function ({key} , speed.callback, like is

$('.usercontent').animate( {
    backgroundColor:'#ddd',
},1000,function () {
    $(this).css("backgroundColor","red")
});

What is the Oracle equivalent of SQL Server's IsNull() function?

You can use the condition if x is not null then.... It's not a function. There's also the NVL() function, a good example of usage here: NVL function ref.

How can I decode HTML characters in C#?

To decode HTML take a look below code

string s = "Svendborg V&#230;rft A/S";
string a = HttpUtility.HtmlDecode(s);
Response.Write(a);

Output is like

 Svendborg Værft A/S

How can I read numeric strings in Excel cells as string (not numbers)?

Yes, this works perfectly

recommended:

        DataFormatter dataFormatter = new DataFormatter();
        String value = dataFormatter.formatCellValue(cell);

old:

cell.setCellType(Cell.CELL_TYPE_STRING);

even if you have a problem with retrieving a value from cell having formula, still this works.

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

See this answer about the No overload for method 'ToString' takes 1 arguments error.

You cannot format a nullable DateTime - you have to use the DateTime.Value property.

@Model.AuditDate.HasValue ? Model.AuditDate.Value.ToString("mm/dd/yyyy") : string.Empty

Tip: It is always helpful to work this stuff out in a standard class with intellisense before putting it into a view. In this case, you would get a compile error which would be easy to spot in a class.

How to create a generic array in Java?

The forced cast suggested by other people did not work for me, throwing an exception of illegal casting.

However, this implicit cast worked fine:

Item<K>[] array = new Item[SIZE];

where Item is a class I defined containing the member:

private K value;

This way you get an array of type K (if the item only has the value) or any generic type you want defined in the class Item.

How to fix "unable to write 'random state' " in openssl

It may also be that you need to run the console as an administrator. On windows 7, hold ctrl+shift when you launch the console window.

How to highlight cell if value duplicate in same column for google spreadsheet?

From the "Text Contains" dropdown menu select "Custom formula is:", and write: "=countif(A:A, A1) > 1" (without the quotes)

I did exactly as zolley proposed, but there should be done small correction: use "Custom formula is" instead of "Text Contains". And then conditional rendering will work.

Screenshot from menu

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

Adding IN clause List to a JPA Query

You must convert to List as shown below:

    String[] valores = hierarquia.split(".");       
    List<String> lista =  Arrays.asList(valores);

    String jpqlQuery = "SELECT a " +
            "FROM AcessoScr a " +
            "WHERE a.scr IN :param ";

    Query query = getEntityManager().createQuery(jpqlQuery, AcessoScr.class);                   
    query.setParameter("param", lista);     
    List<AcessoScr> acessos = query.getResultList();

CSS scale height to match width - possibly with a formfactor

Solution with Jquery

$(window).resize(function () {
    var width = $("#map").width();
    $("#map").height(width * 1.72);
});

spring data jpa @query and pageable

Declare native count queries for pagination at the query method by using @Query

public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
  countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
  nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);

}

Hope this helps

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods

Excel VBA - select multiple columns not in sequential order

Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.

First I declared all my variables as Public

Then I defined/set each variable

Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges

Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range

With Sheet8




  c = pvt.DataBodyRange.Columns.Count + 1

  d = 3

  r = .Cells(.Rows.Count, 1).End(xlUp).Row

Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
    FormulaRange3.NumberFormat = "0"
    Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
    FormulaRange4.NumberFormat = "0"
    Set SelectRanges = Union(FormulaRange3, FormulaRange4)

When should you NOT use a Rules Engine?

I would strongly recommend business rules engines like Drools as open source or Commercial Rules Engine such as LiveRules.

  • When you have a lot of business policies which are volatile in nature, it is very hard to maintain that part of the core technology code.
  • The rules engine provides a great flexibility of the framework and easy to change and deploy.
  • Rules engines are not to be used everywhere but need to used when you have lot of policies where changes are inevitable on a regular basis.

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

We use IBM Rational Application Developer (RAD) and had the same problem.

ErrorMessage:

Access restriction: The type 'JAXWSProperties' is not API (restriction on required library 'C:\IBM\RAD95\jdk\jre\lib\rt.jar')

Solution:

go to java build path and under Library tab, remove JRE System Library. Then again Add Library --> JRE System Library

How to read .pem file to get private and public key

Java libs makes it almost a one liner to read the public cert, as generated by openssl:

val certificate: X509Certificate = ByteArrayInputStream(
        publicKeyCert.toByteArray(Charsets.US_ASCII))
        .use {
            CertificateFactory.getInstance("X.509")
                    .generateCertificate(it) as X509Certificate
        }

But, o hell, reading the private key was problematic:

  1. First had to remove the begin and end tags, which is not nessarry when reading the public key.
  2. Then I had to remove all the new lines, otherwise it croaks!
  3. Then I had to decode back to bytes using byte 64
  4. Then I was able to produce an RSAPrivateKey.

see this: Final solution in kotlin

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

How do you get total amount of RAM the computer has?

If you happen to be using Mono, then you might be interested to know that Mono 2.8 (to be released later this year) will have a performance counter which reports the physical memory size on all the platforms Mono runs on (including Windows). You would retrieve the value of the counter using this code snippet:

using System;
using System.Diagnostics;

class app
{
   static void Main ()
   {
       var pc = new PerformanceCounter ("Mono Memory", "Total Physical Memory");
       Console.WriteLine ("Physical RAM (bytes): {0}", pc.RawValue);
   }
}

If you are interested in C code which provides the performance counter, it can be found here.

How to recursively download a folder via FTP on Linux

toggle the prompt by PROMPT command.

Usage:

ftp>cd /to/directory    
ftp>prompt    
ftp>mget  *

Failed to find Build Tools revision 23.0.1

Check your $ANDROID_HOME, sometimes is /usr/local/opt/android, but it's not your install sdk path, change it and fix this problem

Printing tuple with string formatting in Python

Note that the % syntax is obsolete. Use str.format, which is simpler and more readable:

t = 1,2,3
print 'This is a tuple {0}'.format(t)

How to use this boolean in an if statement?

Actually, the entire approach would be cleaner if you only had to use one instance of StringBuffer, instead of creating one in every recursive call... I would go for:

private String getWhoozitYs(){
     StringBuffer sb = new StringBuffer();
     while (generator.nextBoolean()) {
         sb.append("y");
     }

     return sb.toString();
}

Remove large .pack file created by git

Scenario A: If your large files were only added to a branch, you don't need to run git filter-branch. You just need to delete the branch and run garbage collection:

git branch -D mybranch
git reflog expire --expire-unreachable=all --all
git gc --prune=all

Scenario B: However, it looks like based on your bash history, that you did merge the changes into master. If you haven't shared the changes with anyone (no git push yet). The easiest thing would be to reset master back to before the merge with the branch that had the big files. This will eliminate all commits from your branch and all commits made to master after the merge. So you might lose changes -- in addition to the big files -- that you may have actually wanted:

git checkout master
git log # Find the commit hash just before the merge
git reset --hard <commit hash>

Then run the steps from the scenario A.

Scenario C: If there were other changes from the branch or changes on master after the merge that you want to keep, it would be best to rebase master and selectively include commits that you want:

git checkout master
git log # Find the commit hash just before the merge
git rebase -i <commit hash>

In your editor, remove lines that correspond to the commits that added the large files, but leave everything else as is. Save and quit. Your master branch should only contain what you want, and no large files. Note that git rebase without -p will eliminate merge commits, so you'll be left with a linear history for master after <commit hash>. This is probably okay for you, but if not, you could try with -p, but git help rebase says combining -p with the -i option explicitly is generally not a good idea unless you know what you are doing.

Then run the commands from scenario A.

Why are you not able to declare a class as static in Java?

As explained above, a Class cannot be static unless it's a member of another Class.

If you're looking to design a class "of which there cannot be multiple instances", you may want to look into the "Singleton" design pattern.

Beginner Singleton info here.

Caveat:

If you are thinking of using the singleton pattern, resist with all your might. It is one of the easiest DesignPatterns to understand, probably the most popular, and definitely the most abused. (source: JavaRanch as linked above)

Search for string and get count in vi editor

Short answer:

:%s/string-to-be-searched//gn

For learning:

There are 3 modes in VI editor as below enter image description here

  • : you are entering from Command to Command-line mode. Now, whatever you write after : is on CLI(Command Line Interface)
  • %s specifies all lines. Specifying the range as % means do substitution in the entire file. Syntax for all occurrences substitution is :%s/old-text/new-text/g
  • g specifies all occurrences in the line. With the g flag , you can make the whole line to be substituted. If this g flag is not used then only first occurrence in the line only will be substituted.
  • n specifies to output number of occurrences
  • //double slash represents omission of replacement text. Because we just want to find.

Once got the number of occurrences, you can Press N Key to see occurrences one-by-one.

For finding and counting in particular range of line number 1 to 10:

:1,10s/hello//gn

  • Please note, % for whole file is repleaced by , separated line numbers.

For finding and replacing in particular range of line number 1 to 10:

:1,10s/helo/hello/gn

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

To change JDK's version, you can do:

1- Project > Properties
2- Go to Java Build Path
3- In Libraries, select JRE System ... and click on Edit
4- Choose your appropriate version and validate

c# why can't a nullable int be assigned null as a value

What Harry S says is exactly right, but

int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));

would also do the trick. (We Resharper users can always spot each other in crowds...)

Fatal error: Call to undefined function mcrypt_encrypt()

If you are using PHP 7.2 or up:

This function was DEPRECATED in PHP 7.1.0, and REMOVED in PHP 7.2.0.

source: http://php.net/manual/en/function.mcrypt-encrypt.php

So you have to replace the php code and find a solution without mcrypt.

Or, I just found out, you can STILL use mcrypt in PHP 7.2.0, but you have to install it as a PHP Extension Community Library. (https://pecl.php.net/)

On Debian/Ubuntu Linux distros:

sudo apt-get -y install gcc make autoconf libc-dev pkg-config
sudo apt-get -y install php7.2-dev
sudo apt-get -y install libmcrypt-dev

then:

sudo pecl install mcrypt-1.0.1

Source: https://www.techrepublic.com/article/how-to-install-mcrypt-for-php-7-2/

Can anonymous class implement interface?

The answer to the question specifically asked is no. But have you been looking at mocking frameworks? I use MOQ but there's millions of them out there and they allow you to implement/stub (partially or fully) interfaces in-line. Eg.

public void ThisWillWork()
{
    var source = new DummySource[0];
    var mock = new Mock<DummyInterface>();

    mock.SetupProperty(m => m.A, source.Select(s => s.A));
    mock.SetupProperty(m => m.B, source.Select(s => s.C + "_" + s.D));

    DoSomethingWithDummyInterface(mock.Object);
}

Setting up and using Meld as your git difftool and mergetool

I follow this simple setup with meld. Meld is free and opensource diff tool. You will see nice side by side comparison of files and directory for any code changes.

  1. Install meld in your Linux using yum/apt.
  2. Add following line in your ~/.gitconfig file
[diff]
    tool = meld
  1. Go to your code repo and type following command to see difference between last committed changes and current working directory (Unstaged uncommited changes)

git difftool --dir-diff ./

  1. To see difference between last committed code and staged code, use following command

git difftool --cached --dir-diff ./

Get current time in milliseconds in Python?

If you want a simple method in your code that returns the milliseconds with datetime:

from datetime import datetime
from datetime import timedelta

start_time = datetime.now()

# returns the elapsed milliseconds since the start of the program
def millis():
   dt = datetime.now() - start_time
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   return ms

Convert a space delimited string to list

try

states.split()

it returns the list

['Alaska',
 'Alabama',
 'Arkansas',
 'American',
 'Samoa',
 'Arizona',
 'California',
 'Colorado']

and this returns the random element of the list

import random
random.choice(states.split())

split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example

states.split('Ari')

returns

['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']

Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here

I see you are probably new to python, so I'd give you some advice how to use python's great documentation

Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language

I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

Passing on command line arguments to runnable JAR

You can pass program arguments on the command line and get them in your Java app like this:

public static void main(String[] args) {
  String pathToXml = args[0];
....
}

Alternatively you pass a system property by changing the command line to:

java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt

and your main class to:

public static void main(String[] args) {
  String pathToXml = System.getProperty("path-to-xml");
....
}

How to extract request http headers from a request using NodeJS connect

Check output of console.log(req) or console.log(req.headers);

What's the difference between Invoke() and BeginInvoke()

Building on Jon Skeet's reply, there are times when you want to invoke a delegate and wait for its execution to complete before the current thread continues. In those cases the Invoke call is what you want.

In multi-threading applications, you may not want a thread to wait on a delegate to finish execution, especially if that delegate performs I/O (which could make the delegate and your thread block).

In those cases the BeginInvoke would be useful. By calling it, you're telling the delegate to start but then your thread is free to do other things in parallel with the delegate.

Using BeginInvoke increases the complexity of your code but there are times when the improved performance is worth the complexity.

How to copy multiple files in one layer using a Dockerfile?

COPY README.md package.json gulpfile.js __BUILD_NUMBER ./

or

COPY ["__BUILD_NUMBER", "README.md", "gulpfile", "another_file", "./"]

You can also use wildcard characters in the sourcefile specification. See the docs for a little more detail.

Directories are special! If you write

COPY dir1 dir2 ./

that actually works like

COPY dir1/* dir2/* ./

If you want to copy multiple directories (not their contents) under a destination directory in a single command, you'll need to set up the build context so that your source directories are under a common parent and then COPY that parent.

How can I get a JavaScript stack trace when I throw an exception?

An update to Eugene's answer: The error object must be thrown in order for IE (specific versions?) to populate the stack property. The following should work better than his current example, and should avoid returning undefined when in IE.

function stackTrace() {
  try {
    var err = new Error();
    throw err;
  } catch (err) {
    return err.stack;
  }
}

Note 1: This sort of thing should only be done when debugging, and disabled when live, especially if called frequently. Note 2: This may not work in all browsers, but seems to work in FF and IE 11, which suits my needs just fine.

Change UITableView height dynamically

Lots of the answers here don't honor changes of the table or are way too complicated. Using a subclass of UITableView that will properly set intrinsicContentSize is a far easier solution when using autolayout. No height constraints etc. needed.

class UIDynamicTableView: UITableView
{
    override var intrinsicContentSize: CGSize {
        self.layoutIfNeeded()
        return CGSize(width: UIViewNoIntrinsicMetric, height: self.contentSize.height)
    }

    override func reloadData() {
        super.reloadData()
        self.invalidateIntrinsicContentSize()
    }
} 

Set the class of your TableView to UIDynamicTableView in the interface builder and watch the magic as this TableView will change it's size after a call to reloadData().

Tar error: Unexpected EOF in archive

May be you have ftped the file in ascii mode instead of binary mode ? If not, this might help.

$ gunzip myarchive.tar.gz

And then untar the resulting tar file using

$ tar xvf myarchive.tar

Hope this helps.

Android EditText Hint

I don't know whether a direct way of doing this is available or not, but you surely there is a workaround via code: listen for onFocus event of EditText, and as soon it gains focus, set the hint to be nothing with something like editText.setHint(""):

This may not be exactly what you have to do, but it may be something like this-

myEditText.setOnFocusListener(new OnFocusListener(){
  public void onFocus(){
    myEditText.setHint("");
  }
});

How to remove close button on the jQuery UI dialog?

$(".ui-button-icon-only").hide();

How can I read a text file from the SD card in Android?

In response to

Don't hardcode /sdcard/

Sometimes we HAVE TO hardcode it as in some phone models the API method returns the internal phone memory.

Known types: HTC One X and Samsung S3.

Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android

Align div right in Bootstrap 3

Add offset8 to your class, for example:

<div class="offset8">aligns to the right</div>

PKIX path building failed: unable to find valid certification path to requested target

On Mac OS I had to open the server's self-signed certificate with system Keychain Access tool, import it, dobubleclick it and then select "Always trust" (even though I set the same in importer). Before that, of course I ran java key took with -importcert to import same file to cacert storage.

How to SELECT a dropdown list item by value programmatically

If anyone else is trying this and facing problem then let me point one possible problem: If you are using Web Application then inside Page_Load if you are loading drop-down from DB and at the sametime you want to load data, then first load your drop-down lists and then load your data with selected drop-down conditions.

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        LoadDropdown(); //drop-downs generated first
        LoadData(); // other data loading and drop-down value selection logic here
    }
}

And for successfully selecting drop-down from code follow the approved answer above which is

ddl.SelectedValue = "2";.

Hope it solves the problem

How to get parameters from the URL with JSP

Use EL (JSP Expression Language):

${param.accountID}

NULL value for int in Update statement

Provided that your int column is nullable, you may write:

UPDATE dbo.TableName
SET TableName.IntColumn = NULL
WHERE <condition>

How to completely uninstall Android Studio from windows(v10)?

First go to android studio folder on location that you installed it ( It’s usually in this path by default ; C:\Program Files\Android\Android Studio, unless you change it when you install Android Studio). Find and run uninstall.exe file.

Wait until uninstallation complete successfully, just few minutes, and after click the close.

To delete any remains of Android Studio setting files, in File Explorer, go to C:\Users\%username%, and delete .android, .AndroidStudio(#version-number) and also .gradle, AndroidStudioProjects if they exist. If you want remain your projects, you’d like to keep AndroidStudioProjects folder.

Then, go to C:\Users\%username%\AppData\Roaming and delete the JetBrains directory.

Note that AppData folder is hidden by default, to make visible it go to view tab and check hidden items in windows8 and10 ( in windows7 Select Folder Options, then select the View tab. Under Advanced settings, select Show hidden files, folders, and drives, and then select OK.

Done, you can remove Android Studio successfully, if you plan to delete SDK tools too, it is enough to remove SDK folder completely.

End-line characters from lines read from text file, using Python

The idiomatic way to do this in Python is to use rstrip('\n'):

for line in open('myfile.txt'):  # opened in text-mode; all EOLs are converted to '\n'
    line = line.rstrip('\n')
    process(line)

Each of the other alternatives has a gotcha:

  • file('...').read().splitlines() has to load the whole file in memory at once.
  • line = line[:-1] will fail if the last line has no EOL.

Best way to create a temp table with same columns and type as a permanent table

This is a MySQL-specific answer, not sure where else it works --

You can create an empty table having the same column definitions with:

CREATE TEMPORARY TABLE temp_foo LIKE foo;

And you can create a populated copy of an existing table with:

CREATE TEMPORARY TABLE temp_foo SELECT * FROM foo;

And the following works in postgres; unfortunately the different RDBMS's don't seem very consistent here:

CREATE TEMPORARY TABLE temp_foo AS SELECT * FROM foo;

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.

Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.

Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).

The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.

Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.

How do I disable and re-enable a button in with javascript?

<script>
function checkusers()
{
   var shouldEnable = document.getElementById('checkbox').value == 0;
   document.getElementById('add_button').disabled = shouldEnable;
}
</script>

Is it possible to use 'else' in a list comprehension?

To use the else in list comprehensions in python programming you can try out the below snippet. This would resolve your problem, the snippet is tested on python 2.7 and python 3.5.

obj = ["Even" if i%2==0 else "Odd" for i in range(10)]

How to determine previous page URL in Angular?

You can use Location as mentioned here.

Here's my code if the link opened on new tab

navBack() {
    let cur_path = this.location.path();
    this.location.back();
    if (cur_path === this.location.path())
     this.router.navigate(['/default-route']);    
  }

Required imports

import { Router } from '@angular/router';
import { Location } from '@angular/common';

How to change color and font on ListView

You need to create a CustomListAdapter.

public class CustomListAdapter extends ArrayAdapter <String> {

    private Context mContext;
    private int id;
    private List <String>items ;

    public CustomListAdapter(Context context, int textViewResourceId , List<String> list ) 
    {
        super(context, textViewResourceId, list);           
        mContext = context;
        id = textViewResourceId;
        items = list ;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent)
    {
        View mView = v ;
        if(mView == null){
            LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mView = vi.inflate(id, null);
        }

        TextView text = (TextView) mView.findViewById(R.id.textView);

        if(items.get(position) != null )
        {
            text.setTextColor(Color.WHITE);
            text.setText(items.get(position));
            text.setBackgroundColor(Color.RED); 
            int color = Color.argb( 200, 255, 64, 64 );
                text.setBackgroundColor( color );

        }

        return mView;
    }

}

The list item looks like this (custom_list.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/textView"
    android:textSize="20px" android:paddingTop="10dip" android:paddingBottom="10dip"/>
</LinearLayout>

Use the TextView api's to decorate your text to your liking

and you will be using it like this

listAdapter = new CustomListAdapter(YourActivity.this , R.layout.custom_list , mList);
mListView.setAdapter(listAdapter);

Open Popup window using javascript

To create a popup you'll need the following script:

<script language="javascript" type="text/javascript">

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


</script>

Then, you link to it by:

  <a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>

If you want you can call the function directly from document.ready also. Or maybe from another function.

Find the nth occurrence of substring in a string

Providing another "tricky" solution, which use split and join.

In your example, we can use

len("substring".join([s for s in ori.split("substring")[:2]]))

What is the !! (not not) operator in JavaScript?

This is a really handy way to check for undefined, "undefined", null, "null", ""

if (!!var1 && !!var2 && !!var3 && !!var4 ){
   //... some code here
}

Do I really need to encode '&' as '&amp;'?

if & is used in html then you should escape it

If & is used in javascript strings e.g. an alert('This & that'); or document.href you don't need to use it.

If you're using document.write then you should use it e.g. document.write(<p>this &amp; that</p>)

How to check programmatically if an application is installed or not in Android?

You can do it using Kotlin extensions :

fun Context.getInstalledPackages(): List<String> {
    val packagesList = mutableListOf<String>()
    packageManager.getInstalledPackages(0).forEach {
        if ( it.applicationInfo.sourceDir.startsWith("/data/app/") && it.versionName != null)
            packagesList.add(it.packageName)
    }
    return packagesList
}

fun Context.isInDevice(packageName: String): Boolean {
    return getInstalledPackages().contains(packageName)
}

How to decode encrypted wordpress admin password?

You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.

There's a good howto here:

https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/

Basically:

  1. generate a new hash from a known password using e.g. http://scriptserver.mainframe8.com/wordpress_password_hasher.php, as described in the above link, or any other product that uses the phpass library,
  2. use your DB interface (e.g. phpMyAdmin) to update the user_pass field with the new hash string.

If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).

What is the behavior difference between return-path, reply-to and from?

for those who got here because the title of the question:

I use Reply-To: address with webforms. when someone fills out the form, the webpage sends an automatic email to the page's owner. the From: is the automatic mail sender's address, so the owner knows it is from the webform. but the Reply-To: address is the one filled in in the form by the user, so the owner can just hit reply to contact them.

SQL: Two select statements in one query

You can union the queries as long as the columns match.

SELECT name,
       games,
       goals
FROM   tblMadrid
WHERE  id = 1
UNION ALL
SELECT name,
       games,
       goals
FROM   tblBarcelona
WHERE  id = 2 

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

I had the same problem in SSIS 2008. I tried to connect to an Oracle 11g using ODAC 12c 32 bit. Tried to install ODAC 12c 64 bit as well. SSIS was actually able to preview the table but when trying to run the package it was giving this error message. Nothing helped. Switched to VS 2013, now it was running in debug mode but got the same error when the running the package using dtexec /f filename. Then I found this page: http://sqlmag.com/comment/reply/17881.

To make it short it says: (if the page is still there just go to the page and follow the instrucrtions...) 1) Download and install the latest version of odac 64 bit xcopy from oracle site. 2) Download and install the latest version of odac 32 bit xcopy from oracle site. How? open a cmd shell AS AN ADMINSTARTOR and run: c:\64bitODACLocation> install.bat oledb c:\odac\odac64. the first parameter is the component you want to install. The second param is where to install to. install the 32 version as well like this: c:\32bitODACLocation> install.bat oledb c:\odac\odac32. 3) Change the path of the system to include c:\odac\odac32; c:\odac\odac32\bin; c:\odac\odac64;c:\odac\odac64\bin IN THIS ORDER. 4) Restart the machine. 5) make sure you have the same tnsnames.ora in both odac32\admin\network and odac64\admin\network folders (or at least the same entry for your connection). 6) Now open up SSIS in visual studio (I used the free 2013 version with the ssis package) - Use OLEDB and then select the Oracle Provider for OLE DB provider as your connection type. Set the name of the entry in your tnsnames.ora as the "server or file name". Username is your schema name (db name) and password is the password for schema. you are done!

Again, you can find the very detailed solution and much more in the original site.

This was the only thing which worked for me and did not mess up my environment.

Cheers! gcr

Setting up Vim for Python

Some time ago I installed Valloric/YouCompleteMe and I find it really awesome. It provides you completion for file paths, function names, methods, variable names... Together with davidhalter/jedi-vim it makes vim great for python programming (the only thing missing now is a linter).

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

The sample DataAnnotations model binder will fill model state with validation errors taken from the DataAnnotations attributes on your model.

JavaScript: What are .extend and .prototype used for?

.extend() is added by many third-party libraries to make it easy to create objects from other objects. See http://api.jquery.com/jQuery.extend/ or http://www.prototypejs.org/api/object/extend for some examples.

.prototype refers to the "template" (if you want to call it that) of an object, so by adding methods to an object's prototype (you see this a lot in libraries to add to String, Date, Math, or even Function) those methods are added to every new instance of that object.

ASP.NET strange compilation error

OK, after days struggling with this issue, I finally fixed it.

  • Not by clearing ASP.NET temp
  • Not by reinstalling the .NET framework!

Simple!

  • I changed the application pool identity from "Local system" to "ApplicationPoolIdentity"

Apparently there was a permission error with my local system that the C# compiler (csc.exe) could not access some resources and source codes.

In order to change your AppPool identity follow steps given here: http://learn.iis.net/page.aspx/624/application-pool-identities/

Ruby Hash to array of values

I would use:

hash.map { |key, value| value }

Django Cookies, how can I set them?

Using Django's session framework should cover most scenarios, but Django also now provide direct cookie manipulation methods on the request and response objects (so you don't need a helper function).

Setting a cookie:

def view(request):
  response = HttpResponse('blah')
  response.set_cookie('cookie_name', 'cookie_value')

Retrieving a cookie:

def view(request):
  value = request.COOKIES.get('cookie_name')
  if value is None:
    # Cookie is not set

  # OR

  try:
    value = request.COOKIES['cookie_name']
  except KeyError:
    # Cookie is not set

Function to convert column number to letter?

what about just converting to the ascii number and using Chr() to convert back to a letter?

col_letter = Chr(Selection.Column + 96)

How to change the interval time on bootstrap carousel?

You can use the options when initializing the carousel, like this:

// interval is in milliseconds. 1000 = 1 second -> so 1000 * 10 = 10 seconds
$('.carousel').carousel({
  interval: 1000 * 10
});

or you can use the interval attribute directly on the HTML tag, like this:

<div class="carousel" data-interval="10000">

The advantage of the latter approach is that you do not have to write any JS for it - while the advantage of the former is that you can compute the interval and initialize it with a variable value at run time.

How to use java.String.format in Scala?

You don't need to use numbers to indicate positioning. By default, the position of the argument is simply the order in which it appears in the string.

Here's an example of the proper way to use this:

String result = String.format("The format method is %s!", "great");
// result now equals  "The format method is great!".

You will always use a % followed by some other characters to let the method know how it should display the string. %s is probably the most common, and it just means that the argument should be treated as a string.

I won't list every option, but I'll give a few examples just to give you an idea:

// we can specify the # of decimals we want to show for a floating point:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// result now equals  "10 / 3 = 3.33"

// we can add commas to long numbers:
result = String.format("Today we processed %,d transactions.", 1000000);
// result now equals  "Today we processed 1,000,000 transactions."

String.format just uses a java.util.Formatter, so for a full description of the options you can see the Formatter javadocs.

And, as BalusC mentions, you will see in the documentation that is possible to change the default argument ordering if you need to. However, probably the only time you'd need / want to do this is if you are using the same argument more than once.

How can I enable MySQL's slow query log without restarting MySQL?

Find log enabled or not?

SHOW VARIABLES LIKE '%log%';

Set the logs:-

SET GLOBAL general_log = 'ON'; 

SET GLOBAL slow_query_log = 'ON'; 

Python logging not outputting anything

For anyone here that wants a super-simple answer: just set the level you want displayed. At the top of all my scripts I just put:

import logging
logging.basicConfig(level = logging.INFO)

Then to display anything at or above that level:

logging.info("Hi you just set your fleeb to level plumbus")

It is a hierarchical set of five levels so that logs will display at the level you set, or higher. So if you want to display an error you could use logging.error("The plumbus is broken").

The levels, in increasing order of severity, are DEBUG, INFO, WARNING, ERROR, and CRITICAL. The default setting is WARNING.

This is a good article containing this information expressed better than my answer:
https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3

How can you tell when a layout has been drawn?

To avoid deprecated code and warnings you can use:

view.getViewTreeObserver().addOnGlobalLayoutListener(
        new ViewTreeObserver.OnGlobalLayoutListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    view.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    view.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
                yourFunctionHere();
            }
        });

using facebook sdk in Android studio

Facebook publishes the SDK on maven central :

Just add :

repositories {
    jcenter()       // IntelliJ main repo.
}

dependencies {
    compile 'com.facebook.android:facebook-android-sdk:+'
}

Display Back Arrow on Toolbar

you can use the tool bar setNavigationIcon method. Android Doc

mToolBar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);

mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        handleOnBackPress();
    }
});

What's the best way to get the last element of an array without deleting it?

What if you want to get the last element of array inside of the loop of it's array?

The code below will result into an infinite loop:

foreach ($array as $item) {
 $last_element = end($array);
 reset($array);
 if ($last_element == $item) {
   // something useful here
 }
}

The solution is obviously simple for non associative arrays:

$last_element = $array[sizeof ($array) - 1];
foreach ($array as $key => $item) {
 if ($last_element == $item) {
   // something useful here
 }
}

Check element CSS display with JavaScript

If the style was declared inline or with JavaScript, you can just get at the style object:

return element.style.display === 'block';

Otherwise, you'll have to get the computed style, and there are browser inconsistencies. IE uses a simple currentStyle object, but everyone else uses a method:

return element.currentStyle ? element.currentStyle.display :
                              getComputedStyle(element, null).display;

The null was required in Firefox version 3 and below.

How to force table cell <td> content to wrap?

I solve it putting a "p" tag inside of my "td" tag like this:

<td><p class="">This is my loooooooong paragraph</p></td>

Then add this properties to the class, using max-width to define how wide you want your field to be

.p-wrap {
  max-width: 400px;
  word-wrap: break-word;
  white-space: pre-wrap;
  font-size: 12px;
}

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

Excel 2010 driver is 64 bit, while the default SSMS import export wizard is 32 therefore the error message.

You can import using the Import Export Data (64 bit) tool. ("C:\Program Files\Microsoft SQL Server\110\DTS\Binn\DTSWizard.exe") notice the path is not Program Files x86.

Add one day to date in javascript

Just for the sake of adding functions to the Date prototype:

In a mutable fashion / style:

Date.prototype.addDays = function(n) {
   this.setDate(this.getDate() + n);
};

// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
   this.addDays(1);
};

Date.prototype.addMonths = function(n) {
   this.setMonth(this.getMonth() + n);
};

Date.prototype.addYears = function(n) {
   this.setFullYear(this.getFullYear() + n);
}

// etc...

var currentDate = new Date();
currentDate.nextDay();

Why is Event.target not Element in Typescript?

JLRishe's answer is correct, so I simply use this in my event handler:

if (event.target instanceof Element) { /*...*/ }

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

I've incurred in a weird behaviour using [].

We have Model "classes" with fields initialised to some value. E.g.:

require([
  "dojo/_base/declare",
  "dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){

   declare("MyWidget", [_WidgetBase], {
     field1: [],
     field2: "",
     function1: function(),
     function2: function()
   });    
});

I found that when the fields are initialised with [] then it would be shared by all Model objects. Making changes to one affects all others.

This doesn't happen initialising them with new Array(). Same for the initialisation of Objects ({} vs new Object())

TBH I am not sure if its a problem with the framework we were using (Dojo)

php variable in html no other way than: <?php echo $var; ?>

I really think you should adopt Smarty template engine as a standard php lib for your projects.

http://www.smarty.net/

Name: {$name|capitalize}<br>

Log4net rolling daily filename with date in the file name

For a RollingLogFileAppender you also need these elements and values:

<rollingStyle value="Date" />
<staticLogFileName value="false" />

Adding custom HTTP headers using JavaScript

I think the easiest way to accomplish it is to use querystring instead of HTTP headers.

How to see remote tags?

You can list the tags on remote repository with ls-remote, and then check if it's there. Supposing the remote reference name is origin in the following.

git ls-remote --tags origin

And you can list tags local with tag.

git tag

You can compare the results manually or in script.

What happens if you don't commit a transaction to a database (say, SQL Server)?

As long as you don't COMMIT or ROLLBACK a transaction, it's still "running" and potentially holding locks.

If your client (application or user) closes the connection to the database before committing, any still running transactions will be rolled back and terminated.

How to split a data frame?

subset() is also useful:

subset(DATAFRAME, COLUMNNAME == "")

For a survey package, maybe the survey package is pertinent?

http://faculty.washington.edu/tlumley/survey/

How to parse month full form string using DateFormat in Java?

You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.

Try specifying the locale you wish to use, for example Locale.US:

DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27,  2007");

Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.

How to append text to a text file in C++?

You could use an fstream and open it with the std::ios::app flag. Have a look at the code below and it should clear your head.

...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...

You can find more information about the open modes here and about fstreams here.

HTML5 placeholder css padding

I've created a fiddle using your screenshot as a background image and stripping out the extra mark-up, and it seems to work fine

http://jsfiddle.net/fLdQG/2/ (webkit browser required)

Does this work for you? If not, can you update the fiddle with your exact mark-up and CSS?

Editing dictionary values in a foreach loop

Along with the other answers, I thought I'd note that if you get sortedDictionary.Keys or sortedDictionary.Values and then loop over them with foreach, you also go through in sorted order. This is because those methods return System.Collections.Generic.SortedDictionary<TKey,TValue>.KeyCollection or SortedDictionary<TKey,TValue>.ValueCollection objects, which maintain the sort of the original dictionary.

Rails filtering array of objects by attribute value

have you tried eager loading?

@attachments = Job.includes(:attachments).find(1).attachments

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

Resolve host name to an ip address

You could use a C function getaddrinfo() to get the numerical address - both ipv4 and ipv6. See the example code here

How to append a newline to StringBuilder

In addition to K.S's response of creating a StringBuilderPlus class and utilising ther adapter pattern to extend a final class, if you make use of generics and return the StringBuilderPlus object in the new append and appendLine methods, you can make use of the StringBuilders many append methods for all different types, while regaining the ability to string string multiple append commands together, as shown below

public class StringBuilderPlus {

    private final StringBuilder stringBuilder;

    public StringBuilderPlus() {
        this.stringBuilder = new StringBuilder();
    }

    public <T> StringBuilderPlus append(T t) {
        stringBuilder.append(t);
        return this;
    }

    public <T> StringBuilderPlus appendLine(T t) {
        stringBuilder.append(t).append(System.lineSeparator());
        return this;
    }

    @Override
    public String toString() {
        return stringBuilder.toString();
    }

    public StringBuilder getStringBuilder() {
        return stringBuilder;
    }
}

you can then use this exactly like the original StringBuilder class:

StringBuilderPlus stringBuilder = new StringBuilderPlus();
stringBuilder.appendLine("test")
    .appendLine('c')
    .appendLine(1)
    .appendLine(1.2)
    .appendLine(1L);

stringBuilder.toString();

Printing the last column of a line in a file

Using Perl

$ cat rayne.txt
A1 123 456
B1 234 567
C1 345 678
A1 098 766
B1 987 6545
C1 876 5434


$ perl -lane ' /A1/ and $x=$F[2] ; END { print "$x" } ' rayne.txt
766

$

How to deal with the URISyntaxException

If you're using RestangularV2 to post to a spring controller in java you can get this exception if you use RestangularV2.one() instead of RestangularV2.all()

Best way to convert string to bytes in Python 3?

Answer for a slightly different problem:

You have a sequence of raw unicode that was saved into a str variable:

s_str: str = "\x00\x01\x00\xc0\x01\x00\x00\x00\x04"

You need to be able to get the byte literal of that unicode (for struct.unpack(), etc.)

s_bytes: bytes = b'\x00\x01\x00\xc0\x01\x00\x00\x00\x04'

Solution:

s_new: bytes = bytes(s, encoding="raw_unicode_escape")

Reference (scroll up for standard encodings):

Python Specific Encodings

Textarea Auto height

html

<textarea id="wmd-input" name="md-content"></textarea>

js

var textarea = $('#wmd-input'),
    top = textarea.scrollTop(),
    height = textarea.height();
    if(top > 0){
       textarea.css("height",top + height)
    }

css

#wmd-input{
    width: 100%;
    overflow: hidden;
    padding: 10px;
}

Find an object in SQL Server (cross-database)

mayby one little change from the top answer, because DB_NAME() returns always content db of execution. so, for me better like below:

sp_MSforeachdb 'select DB_name(db_id(''?'')) as DB, * From ?..sysobjects where xtype in (''U'', ''P'') And name like ''[_]x[_]%'''

In my case I was looking for tables their names started with _x_

Cheers, Ondrej

Best Regular Expression for Email Validation in C#

This C# function uses a regular expression to evaluate whether the passed email address is syntactically valid or not.

public static bool isValidEmail(string inputEmail)
{
   string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
         @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + 
         @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
   Regex re = new Regex(strRegex);
   if (re.IsMatch(inputEmail))
    return (true);
   else
    return (false);
}

How to make a whole 'div' clickable in html and css without JavaScript?

we are using like this

     <label for="1">
<div class="options">
<input type="radio" name="mem" id="1" value="1" checked="checked"/>option one
    </div>
</label>
   <label for="2"> 
<div class="options">
 <input type="radio" name="mem" id="2" value="1" checked="checked"/>option two
</div></label>

using

  <label for="1">

tag and catching is with

id=1

hope this helps.