Programs & Examples On #Activeqt

Qt's ActiveX Framework or ActiveQt for short is Qt's ActiveX and COM support for Windows platform.

Am I trying to connect to a TLS-enabled daemon without TLS?

I was getting the same error on MacOS with sudo and without it.

I have solved it with:

boot2docker start
$(boot2docker shellinit)

P.S.: Thanks to Alan. I found out that this approach is recommended in their official documentation.

P.S.2: Sometimes boot2docker init can be required before running two commands (thank you Aaron).

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

Using SELECT result in another SELECT

You are missing table NewScores, so it can't be found. Just join this table.

If you really want to avoid joining it directly you can replace NewScores.NetScore with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}

How can I get my webapp's base URL in ASP.NET MVC?

The trick with relying upon IIS is that IIS bindings can be different from your public URLs (WCF I'm looking at you), especially with multi-homed production machines. I tend to vector toward using configuration to explicitly define the "base" url for external purposes as that tends to be a bit more successful than extracting it from the Request object.

SQL Server Insert Example

I hope this will help you

Create table :

create table users (id int,first_name varchar(10),last_name varchar(10));

Insert values into the table :

insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

toBe(true) vs toBeTruthy() vs toBeTrue()

Disclamer: This is just a wild guess

I know everybody loves an easy-to-read list:

  • toBe(<value>) - The returned value is the same as <value>
  • toBeTrue() - Checks if the returned value is true
  • toBeTruthy() - Check if the value, when cast to a boolean, will be a truthy value

    Truthy values are all values that aren't 0, '' (empty string), false, null, NaN, undefined or [] (empty array)*.

    * Notice that when you run !![], it returns true, but when you run [] == false it also returns true. It depends on how it is implemented. In other words: (!![]) === ([] == false)


On your example, toBe(true) and toBeTrue() will yield the same results.

How do I iterate through table rows and cells in JavaScript?

You can use .querySelectorAll() to select all td elements, then loop over these with .forEach(). Their values can be retrieved with .innerHTML:

_x000D_
_x000D_
const cells = document.querySelectorAll('td');_x000D_
cells.forEach(function(cell) {_x000D_
  console.log(cell.innerHTML);_x000D_
})
_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

If you want to only select columns from a specific row, you can make use of the pseudo-class :nth-child() to select a specific tr, optionally in conjunction with the child combinator (>) (which can be useful if you have a table within a table):

_x000D_
_x000D_
const cells = document.querySelectorAll('tr:nth-child(2) > td');_x000D_
cells.forEach(function(cell) {_x000D_
  console.log(cell.innerHTML);_x000D_
})
_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

The module ".dll" was loaded but the entry-point was not found

I found the answer: I need to add a new application to the service components in my computer and then add the right DLL's.

Thanks! If anyone has the same problem, I'll be happy to help.

How do you create a custom AuthorizeAttribute in ASP.NET Core?

I'm the asp.net security person. Firstly let me apologize that none of this is documented yet outside of the music store sample or unit tests, and it's all still being refined in terms of exposed APIs. Detailed documentation is here.

We don't want you writing custom authorize attributes. If you need to do that we've done something wrong. Instead, you should be writing authorization requirements.

Authorization acts upon Identities. Identities are created by authentication.

You say in comments you want to check a session ID in a header. Your session ID would be the basis for identity. If you wanted to use the Authorize attribute you'd write an authentication middleware to take that header and turn it into an authenticated ClaimsPrincipal. You would then check that inside an authorization requirement. Authorization requirements can be as complicated as you like, for example here's one that takes a date of birth claim on the current identity and will authorize if the user is over 18;

public class Over18Requirement : AuthorizationHandler<Over18Requirement>, IAuthorizationRequirement
{
        public override void Handle(AuthorizationHandlerContext context, Over18Requirement requirement)
        {
            if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth))
            {
                context.Fail();
                return;
            }

            var dateOfBirth = Convert.ToDateTime(context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth).Value);
            int age = DateTime.Today.Year - dateOfBirth.Year;
            if (dateOfBirth > DateTime.Today.AddYears(-age))
            {
                age--;
            }

            if (age >= 18)
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }
        }
    }
}

Then in your ConfigureServices() function you'd wire it up

services.AddAuthorization(options =>
{
    options.AddPolicy("Over18", 
        policy => policy.Requirements.Add(new Authorization.Over18Requirement()));
});

And finally, apply it to a controller or action method with

[Authorize(Policy = "Over18")]

Forbidden :You don't have permission to access /phpmyadmin on this server

You could simply go to phpmyadmin.conf file and change "deny from all" to "allow from all". Well it worked for me, hope it works for you as well.

Programmatically get height of navigation bar

My application has a couple views that required a customized navigation bar in the UI for look & feel, however without navigation controller. And the application is required to support iOS version prior to iOS 11, so the handy safe area layout guide could not be used, and I have to adjust the position and height of navigation bar programmatically.

I attached the Navigation Bar to its superview directly, skipping the safe area layout guide as mentioned above. And the status bar height could be retrieved from UIApplication easily, but the default navigation bar height is really a pain-ass...

It struck me for almost half a night, with a number of searching and testing, until I finally got the hint from another post (not working to me though), that you could actually get the height from UIView.sizeThatFits(), like this:

- (void)viewWillLayoutSubviews {
    self.topBarHeightConstraint.constant = [UIApplication sharedApplication].statusBarFrame.size.height;
    self.navBarHeightConstraint.constant = [self.navigationBar sizeThatFits:CGSizeZero].height;

    [super viewWillLayoutSubviews];    
}

Finally, a perfect navigation bar looking exactly the same as the built-in one!

How to change onClick handler dynamically?

jQuery:

$('#foo').click(function() { alert('foo'); });

Or if you don't want it to follow the link href:

$('#foo').click(function() { alert('foo'); return false; });

CSS rotation cross browser with jquery.animate()

this is my solution:

var matrixRegex = /(?:matrix\(|\s*,\s*)([-+]?[0-9]*\.?[0-9]+(?:[e][-+]?[0-9]+)?)/gi;

var getMatches = function(string, regex) {
    regex || (regex = matrixRegex);
    var matches = [];
    var match;
    while (match = regex.exec(string)) {
        matches.push(match[1]);
    }
    return matches;
};

$.cssHooks['rotation'] = {
    get: function(elem) {
        var $elem = $(elem);
        var matrix = getMatches($elem.css('transform'));
        if (matrix.length != 6) {
            return 0;
        }
        return Math.atan2(parseFloat(matrix[1]), parseFloat(matrix[0])) * (180/Math.PI);
    }, 
    set: function(elem, val){
        var $elem = $(elem);
        var deg = parseFloat(val);
        if (!isNaN(deg)) {
            $elem.css({ transform: 'rotate(' + deg + 'deg)' });
        }
    }
};
$.cssNumber.rotation = true;
$.fx.step.rotation = function(fx) {
    $.cssHooks.rotation.set(fx.elem, fx.now + fx.unit);
};

then you can use it in the default animate fkt:

//rotate to 90 deg cw
$('selector').animate({ rotation: 90 });

//rotate to -90 deg ccw
$('selector').animate({ rotation: -90 });

//rotate 90 deg cw from current rotation
$('selector').animate({ rotation: '+=90' });

//rotate 90 deg ccw from current rotation
$('selector').animate({ rotation: '-=90' });

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

This worked for me. Add sudo before python

curl https://bootstrap.pypa.io/get-pip.py |sudo python

Storing database records into array

You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:

if (isset($_GET['search'])) {
  $search = mysql_real_escape_string($_GET['search']);
  $sql = "SELECT * FROM users WHERE username = '$search'";
  $res = mysql_query($sql) or trigger_error(mysql_error().$sql);
  $row = mysql_fetch_assoc($res);
  if ($row){
    print_r($row); //do whatever you want with found info
  }
}

Get the string representation of a DOM node

Use Element#outerHTML:

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

console.log(el.outerHTML);

It can also be used to write DOM elements. From Mozilla's documentation:

The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.

https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML

How to avoid Sql Query Timeout

Please check your Windows system event log for any errors specifically for the "Event Source: Dhcp". It's very likely a networking error related to DHCP. Address lease time expired or so. It shouldn't be a problem related to the SQL Server or the query itself.

Just search the internet for "The semaphore timeout period has expired" and you'll get plenty of suggestions what might be a solution for your problem. Unfortunately there doesn't seem to be the solution for this problem.

How do I serialize a Python dictionary into a string, and then back to a dictionary?

Use Python's json module, or simplejson if you don't have python 2.6 or higher.

How to switch between python 2.7 to python 3 from command line?

There is an easier way than all of the above; You can use the PY_PYTHON environment variable. From inside the cmd.exe shell;

For the latest version of Python 2

set PY_PYTHON=2

For the latest version of Python 3

set PY_PYTHON=3

If you want it to be permanent, set it in the control panel. Or use setx instead of set in the cmd.exe shell.

Allow scroll but hide scrollbar

I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.

Just add

::-webkit-scrollbar {display:none;}

To your id or class of the div you're using the scroll bar with.

Here is a helpful link Custom Scroll Bar in Webkit

WPF MVVM ComboBox SelectedItem or SelectedValue not working

In this case, the selecteditem bind doesn't work, because the hash id of the objects are different.

One possible solution is:

Based on the selected item id, recover the object on the itemsource collection and set the selected item property to with it.

Example:

<ctrls:ComboBoxControlBase SelectedItem="{Binding Path=SelectedProfile, Mode=TwoWay}" ItemsSource="{Binding Path=Profiles, Mode=OneWay}" IsEditable="False" DisplayMemberPath="Name" />

The Property binded to ItemSource is:

public ObservableCollection<Profile> Profiles
{
   get { return this.profiles; }
   private set { profiles = value; RaisePropertyChanged("Profiles"); }
}

The property binded to SelectedItem is:

public Profile SelectedProfile 
{
    get { return selectedProfile; }
    set
    {
        if (this.SelectedUser != null)
        {
            this.SelectedUser.Profile = value; 
            RaisePropertyChanged("SelectedProfile");  
        } 
    } 
}

The recovery code is:

    [Command("SelectionChanged")]
    public void SelectionChanged(User selectedUser)
    {
        if (selectedUser != null)
        {
            if (selectedUser is User)
            {
                if (selectedUser.Profile != null)
                {
                    this.SelectedUser = selectedUser;
                    this.selectedProfile = this.Profiles.Where(p => p.Id == this.SelectedUser.Profile.Id).FirstOrDefault();
                    MessageBroker.Instance.NotifyColleagues("ShowItemDetails"); 
                }
            }
        }            
    }

I hope it helps you. I spent a lot of my time searching for answers, but I couldn´t find.

OR is not supported with CASE Statement in SQL Server

Try

CASE WHEN ebv.db_no IN (22978,23218,23219) THEN 'WECS 9500' ELSE 'WECS 9520' END

Error when testing on iOS simulator: Couldn't register with the bootstrap server

Happened a lot for me with Xcode 4.2.1 on Lion. Updated to 4.3.2 and it doesnt happen anymore. Glad they fixed it.

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

Validate fields after user has left a field

outI used a directive. Here is the code:

app.directive('onBlurVal', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs, controller) {

            element.on('focus', function () {
                element.next().removeClass('has-visited');
                element.next().addClass('has-focus');
            });

            element.on('blur', function () {

                element.next().removeClass('has-focus');
                element.next().addClass('has-visited');
            });
        }
    }
})

All my input control has a span element as the next element, which is where my validation message is displayed and so the directive as an attribute is added to each input control.

I also have (optional).has-focus and has-visited css class in my css file which you see being referenced in the directive.

NOTE: remember to add 'on-blur-val' exactly this way to your input control without the apostrophes

PostgreSQL - max number of parameters in "IN" clause?

According to the source code located here, starting at line 850, PostgreSQL doesn't explicitly limit the number of arguments.

The following is a code comment from line 870:

/*
 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
 * possible if the inputs are all scalars (no RowExprs) and there is a
 * suitable array type available.  If not, we fall back to a boolean
 * condition tree with multiple copies of the lefthand expression.
 * Also, any IN-list items that contain Vars are handled as separate
 * boolean conditions, because that gives the planner more scope for
 * optimization on such clauses.
 *
 * First step: transform all the inputs, and detect whether any are
 * RowExprs or contain Vars.
 */

Call a function on click event in Angular 2

Component code:

import { Component } from "@angular/core";

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  public items: Array<string>;

  constructor() {
    this.items = ["item1", "item2", "item3"]
  }

  public open(event, item) {
    alert('Open ' + item);
  }

}

View:

<ion-header>
  <ion-navbar primary>
    <ion-title>
      <span>My App</span>
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-item *ngFor="let item of items" (click)="open($event, item)">
      {{ item }}
    </ion-item>
  </ion-list>
</ion-content>

As you can see in the code, I'm declaring the click handler like this (click)="open($event, item)" and sending both the event and the item (declared in the *ngFor) to the open() method (declared in the component code).

If you just want to show the item and you don't need to get info from the event, you can just do (click)="open(item)" and modify the open method like this public open(item) { ... }

Align contents inside a div

Here is a technique I use that has worked well:

_x000D_
_x000D_
<div>_x000D_
    <div style="display: table-cell; width: 100%">&nbsp;</div>_x000D_
    <div style="display: table-cell; white-space: nowrap;">Something Here</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get custom product attributes in Woocommerce

The answer to "Any idea for getting all attributes at once?" question is just to call function with only product id:

$array=get_post_meta($product->id);

key is optional, see http://codex.wordpress.org/Function_Reference/get_post_meta

Select random lines from a file

# Function to sample N lines randomly from a file
# Parameter $1: Name of the original file
# Parameter $2: N lines to be sampled 
rand_line_sampler() {
    N_t=$(awk '{print $1}' $1 | wc -l) # Number of total lines

    N_t_m_d=$(( $N_t - $2 - 1 )) # Number oftotal lines minus desired number of lines

    N_d_m_1=$(( $2 - 1)) # Number of desired lines minus 1

    # vector to have the 0 (fail) with size of N_t_m_d 
    echo '0' > vector_0.temp
    for i in $(seq 1 1 $N_t_m_d); do
            echo "0" >> vector_0.temp
    done

    # vector to have the 1 (success) with size of desired number of lines
    echo '1' > vector_1.temp
    for i in $(seq 1 1 $N_d_m_1); do
            echo "1" >> vector_1.temp
    done

    cat vector_1.temp vector_0.temp | shuf > rand_vector.temp

    paste -d" " rand_vector.temp $1 |
    awk '$1 != 0 {$1=""; print}' |
    sed 's/^ *//' > sampled_file.txt # file with the sampled lines

    rm vector_0.temp vector_1.temp rand_vector.temp
}

rand_line_sampler "parameter_1" "parameter_2"

WPF Add a Border to a TextBlock

No, you need to wrap your TextBlock in a Border. Example:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />
</Border>

Of course, you can set these properties (BorderThickness, BorderBrush) through styles as well:

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />
</Border>

Refresh Part of Page (div)

Usefetch and innerHTML to load div content

_x000D_
_x000D_
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"

async function refresh() {
  btn.disabled = true;
  dynamicPart.innerHTML = "Loading..."
  dynamicPart.innerHTML = await(await fetch(url)).text();
  setTimeout(refresh,2000);
}
_x000D_
<div id="staticPart">
  Here is static part of page

  <button id="btn" onclick="refresh()">
    Click here to start refreshing every 2s
  </button>
</div>

<div id="dynamicPart">Dynamic part</div>
_x000D_
_x000D_
_x000D_

Named parameters in JDBC

Plain vanilla JDBC does not support named parameters.

If you are using DB2 then using DB2 classes directly:

  1. Using named parameter markers with PreparedStatement objects
  2. Using named parameter markers with CallableStatement objects

Which MySQL data type to use for storing boolean values

BOOL and BOOLEAN are synonyms of TINYINT(1). Zero is false, anything else is true. More information here.

How do I load the contents of a text file into a javascript variable?

If you only want a constant string from the text file, you could include it as JavaScript:

_x000D_
_x000D_
// This becomes the content of your foo.txt file_x000D_
let text = `_x000D_
My test text goes here!_x000D_
`;
_x000D_
<script src="foo.txt"></script>_x000D_
<script>_x000D_
  console.log(text);_x000D_
</script>
_x000D_
_x000D_
_x000D_

The string loaded from the file becomes accessible to JavaScript after being loaded. The `(backtick) character begins and ends a template literal, allowing for both " and ' characters in your text block.

This approach works well when you're attempting to load a file locally, as Chrome will not allow AJAX on URLs with the file:// scheme.

How can I check the size of a collection within a Django template?

I need the collection length to decide whether I should render table <thead></thead>

but don't know why @Django 2.1.7 the chosen answer will fail(empty) my forloop afterward.

I got to use {% if forloop.first %} {% endif %} to overcome:

<table>
    {% for record in service_list %}
        {% if forloop.first %}
            <thead>
            <tr>
                <th>??</th>
            </tr>
            </thead>
        {% endif %}
        <tbody>
        <tr>
            <td>{{ record.date }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

Server unable to read htaccess file, denying access to be safe

As for Apache running on Ubuntu, the solution was to check error log, which showed that the error was related with folder and file permission.

First, check Apache error log

nano /var/log/apache2/error.log

Then set folder permission to be executable

sudo chmod 755 /var/www/html/

Also set file permission to be readable

sudo chmod 644 /var/www/html/.htaccess

Make absolute positioned div expand parent div height

There is a quite simple way to solve this.

You just have to duplicate the content of child1 and child2 in relative divs with display:none in parent div. Say child1_1 and child2_2. Put child2_2 on top and child1_1 at the bottom.

When your jquery (or whatever) calls the absolute div, just set the according relative div (child1_1 or child2_2) with display:block AND visibility:hidden. The relative child will still be invisible but will make parent's div higher.

How do I run a single test using Jest?

With the latest Jest version, you can use one of the following to only run one test, and the same for a test suite.

it.only('test 1', () => {})

test.only('test 1', () => {})

fit('test 1', () => {})

jest 'test 1' may work too if the test name is unique.

SQL SELECT WHERE field contains words

why not use "in" instead?

Select *
from table
where columnname in (word1, word2, word3)

How to disable textbox from editing?

As mentioned above, you can change the property of the textbox "Read Only" to "True" from the properties window.

enter image description here

Android: How to get a custom View's height and width?

Well getheight gets the height, and getwidth gets the width. But you're calling those methods too soon. If you're calling them in oncreate or onresume, the view isn't drawn yet. You have to call it after the view has been drawn.

Word wrap for a label in Windows Forms

There is no autowrap property but this can be done programmatically to size it dynamically. Here is one solution:

  • Select the properties of the label

  • AutoSize = True

  • MaximumSize = (Width, Height) where Width = max size you want the label to be and Height = how many pixels you want it to wrap

    Sample Properties

Query to get the names of all tables in SQL Server 2008 Database

To get the fields info too, you can use the following:

SELECT TABLE_SCHEMA, TABLE_NAME, 
       COLUMN_NAME, substring(DATA_TYPE, 1,1) AS DATA_TYPE
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA NOT IN("information_schema", "mysql", "performance_schema") 
ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION

What is the purpose of nameof?

The ASP.NET Core MVC project uses nameof in the AccountController.cs and ManageController.cs with the RedirectToAction method to reference an action in the controller.

Example:

return RedirectToAction(nameof(HomeController.Index), "Home");

This translates to:

return RedirectToAction("Index", "Home");

and takes takes the user to the 'Index' action in the 'Home' controller, i.e. /Home/Index.

Multiline editing in Visual Studio Code

You can just Alt + click for additional cursors. And as already mentioned, Ctrl + Alt + ? or ?.

Java: How to insert CLOB into oracle database

passing the xml content as string.

table1 

ID   int
XML  CLOB



import oracle.jdbc.OraclePreparedStatement;
/*
Your Code
*/
 void insert(int id, String xml){
    try {
        String sql = "INSERT INTO table1(ID,XML) VALUES ("
                + id
                + "', ? )";
        PreparedStatement ps = conn.prepareStatement(sql);
        ((OraclePreparedStatement) ps).setStringForClob(1, xml);
        ps.execute();
        result = true;
        } catch (Exception e) {
        e.printStackTrace();
    }
  }

How to get the parents of a Python class?

If you want to ensure they all get called, use super at all levels.

Using DISTINCT along with GROUP BY in SQL Server

Perhaps not in the context that you have it, but you could use

SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA

You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.

Calculate cosine similarity given 2 sentence strings

Try this. Download the file 'numberbatch-en-17.06.txt' from https://conceptnet.s3.amazonaws.com/downloads/2017/numberbatch/numberbatch-en-17.06.txt.gz and extract it. The function 'get_sentence_vector' uses a simple sum of word vectors. However it can be improved by using weighted sum where weights are proportional to Tf-Idf of each word.

import math
import numpy as np

std_embeddings_index = {}
with open('path/to/numberbatch-en-17.06.txt') as f:
    for line in f:
        values = line.split(' ')
        word = values[0]
        embedding = np.asarray(values[1:], dtype='float32')
        std_embeddings_index[word] = embedding

def cosineValue(v1,v2):
    "compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
    sumxx, sumxy, sumyy = 0, 0, 0
    for i in range(len(v1)):
        x = v1[i]; y = v2[i]
        sumxx += x*x
        sumyy += y*y
        sumxy += x*y
    return sumxy/math.sqrt(sumxx*sumyy)


def get_sentence_vector(sentence, std_embeddings_index = std_embeddings_index ):
    sent_vector = 0
    for word in sentence.lower().split():
        if word not in std_embeddings_index :
            word_vector = np.array(np.random.uniform(-1.0, 1.0, 300))
            std_embeddings_index[word] = word_vector
        else:
            word_vector = std_embeddings_index[word]
        sent_vector = sent_vector + word_vector

    return sent_vector

def cosine_sim(sent1, sent2):
    return cosineValue(get_sentence_vector(sent1), get_sentence_vector(sent2))

I did run for the given sentences and found the following results

s1 = "This is a foo bar sentence ."
s2 = "This sentence is similar to a foo bar sentence ."
s3 = "What is this string ? Totally not related to the other two lines ."

print cosine_sim(s1, s2) # Should give high cosine similarity
print cosine_sim(s1, s3) # Shouldn't give high cosine similarity value
print cosine_sim(s2, s3) # Shouldn't give high cosine similarity value

0.9851735249068168
0.6570885718962608
0.6589335425458225

How to remove jar file from local maven repository which was added with install:install-file?

  1. cd ~/.m2
  2. git init
  3. git commit -am "some comments"
  4. cd /path/to/your/project
  5. mvn install
  6. cd ~/.m2
  7. git reset --hard

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

I tried several solutions that you provided, but occasionally I still receive this error. I am positive that my process is not running, and when i try to delete the executable file with internet explorer it is removed from the file list, but then I press F5 and voila, the file is back. It has not been deleted at all.

But if i delete the file through the TotalCommander, the exe file is actually deleted and I can successfully build the project.

I am using windows 7 x64 and total commander 7.56a 32 bit.

How do I write to the console from a Laravel Controller?

If you want the fancy command IO from Laravel (like styling, asking and table) then I created this class below

Instructions

I have not fully verified everywhere that it is THE cleanest solution etc, but it works nice (but I only tested it from within a unit test case, under Laravel 5.5).

So most probably you can use it however you like:

$cmd = new ConsoleCommand;

$cmd->error("Aw snap!");
$cmd->table($headers, $rows);
$answer = $cmd->ask("Tell me, what do you need?");

//even Symfony's progress bar
$cmd->outputStyle->progressStart(5);  //set n = 100% (here 100% is 5 steps)
$cmd->outputStyle->progressAdvance(); //you can call it n times
$cmd->outputStyle->progressFinish();  //set to 100%

Or course you can also wrap in your own facade, or some static singleton etc, or anyway you wish.

The class itself

class ConsoleCommand extends \Illuminate\Console\Command
{
    protected $name = 'NONEXISTENT';
    protected $hidden = true;

    public $outputSymfony;
    public $outputStyle;

    public function __construct($argInput = null)
    {
        parent::__construct();

        $this->input = new \Symfony\Component\Console\Input\StringInput($argInput);

        $this->outputSymfony = new \Symfony\Component\Console\Output\ConsoleOutput();
        $this->outputStyle = new \Illuminate\Console\OutputStyle($this->input, $this->outputSymfony);

        $this->output = $this->outputStyle;
    }

}

Check free disk space for current partition in bash

df --output=avail -B 1 "$PWD" |tail -n 1

you get size in bytes this way.

Is it possible to CONTINUE a loop from an exception?

For this example you really should just use an outer join.

declare
begin
  FOR attr_rec IN ( 
    select attr 
    from USER_TABLE u 
    left outer join attribute_table a 
    on ( u.USERTYPE = 'X' and a.user_id = u.id ) 
  ) LOOP
    <process records> 
    <if primary key of attribute_table is null 
     then the attribute does not exist for this user.>
  END LOOP;
END;

jQuery check if <input> exists and has a value

I would do something like this: $('input[value]').something . This finds all inputs that have value and operates something onto them.

Having a UITextField in a UITableViewCell

For next/return events on multiple UITextfield inside UITableViewCell in this method I had taken UITextField in storyboard.

@interface MyViewController () {
    NSInteger currentTxtRow;
}
@end
@property (strong, nonatomic) NSIndexPath   *currentIndex;//Current Selected Row

@implementation MyViewController


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UITextField *txtDetails = (UITextField *)[cell.contentView viewWithTag:100];
        txtDetails.delegate = self;

        txtDetails.placeholder = self.arrReciversDetails[indexPath.row];
        return cell;
}


#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    CGPoint point = [textField convertPoint:CGPointZero toView:self.tableView];
    self.currentIndex = [self.tableView indexPathForRowAtPoint:point];//Get Current UITableView row
    currentTxtRow = self.currentIndex.row;
    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    currentTxtRow += 1;
    self.currentIndex = [NSIndexPath indexPathForRow:currentTxtRow inSection:0];

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.currentIndex];
    UITextField *currentTxtfield = (UITextField *)[cell.contentView viewWithTag:100];
    if (currentTxtRow < 3) {//Currently I have 3 Cells each cell have 1 UITextfield
        [currentTxtfield becomeFirstResponder];
    } else {
        [self.view endEditing:YES];
        [currentTxtfield resignFirstResponder];
    }

}  

To grab the text from textfield-

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
      switch (self.currentIndex.row) {

            case 0:
                NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
                break;

            case 1:
                 NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
                break;

            case 2:
                 NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
                break;

            default:
                break;
        }
}

Check if a key is down?

In addition to using keyup and keydown listeners to track when is key goes down and back up, there are actually some properties that tell you if certain keys are down.

window.onmousemove = function (e) {
  if (!e) e = window.event;
  if (e.shiftKey) {/*shift is down*/}
  if (e.altKey) {/*alt is down*/}
  if (e.ctrlKey) {/*ctrl is down*/}
  if (e.metaKey) {/*cmd is down*/}
}

This are available on all browser generated event objects, such as those from keydown, keyup, and keypress, so you don't have to use mousemove.

I tried generating my own event objects with document.createEvent('KeyboardEvent') and document.createEvent('KeyboardEvent') and looking for e.shiftKey and such, but I had no luck.

I'm using Chrome 17 on Mac

Disable / Check for Mock Location (prevent gps spoofing)

This scrip is working for all version of android and i find it after many search

LocationManager locMan;
    String[] mockProviders = {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER};

    try {
        locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        for (String p : mockProviders) {
            if (p.contentEquals(LocationManager.GPS_PROVIDER))
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_HIGH);
            else
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_LOW);

            locMan.setTestProviderEnabled(p, true);
            locMan.setTestProviderStatus(p, android.location.LocationProvider.AVAILABLE, Bundle.EMPTY,
                    java.lang.System.currentTimeMillis());
        }
    } catch (Exception ignored) {
        // here you should show dialog which is mean the mock location is not enable
    }

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

Iterating over a 2 dimensional python list

Ref: zip built-in function

zip() in conjunction with the * operator can be used to unzip a list

unzip_lst = zip(*mylist)
for i in unzip_lst:
    for j in i:
        print j

Remove duplicate rows in MySQL

MySQL has restrictions about referring to the table you are deleting from. You can work around that with a temporary table, like:

create temporary table tmpTable (id int);

insert  into tmpTable
        (id)
select  id
from    YourTable yt
where   exists
        (
        select  *
        from    YourTabe yt2
        where   yt2.title = yt.title
                and yt2.company = yt.company
                and yt2.site_id = yt.site_id
                and yt2.id > yt.id
        );

delete  
from    YourTable
where   ID in (select id from tmpTable);

From Kostanos' suggestion in the comments:
The only slow query above is DELETE, for cases where you have a very large database. This query could be faster:

DELETE FROM YourTable USING YourTable, tmpTable WHERE YourTable.id=tmpTable.id

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

How to fix corrupted git repository?

I wanted to add this as a comment under Zoey Hewil's awesome answer above, but I don't currently have enough rep to do so, so I have to add it here and give credit for her work :P

If you're using Poshgit and are feeling exceptionally lazy, you can use the following to automatically extract your URL from your git config and make an easy job even easier. Standard caveats apply about testing this on a copy/backing up your local repo first in case it blows up in your face.

$config = get-content .git\config
$url = $config -match " url = (?<content>.*)"
$url = $url.trim().Substring(6)
$url

move-item -v .git .git_old;
git init;
git remote add origin "$url";
git fetch;
git reset origin/master --mixed

How do I check particular attributes exist or not in XML?

You can actually index directly into the Attributes collection (if you are using C# not VB):

foreach (XmlNode xNode in nodeListName)
{
  XmlNode parent = xNode.ParentNode;
  if (parent.Attributes != null
     && parent.Attributes["split"] != null)
  {
     parentSplit = parent.Attributes["split"].Value;
  }
}

Maven Error: Could not find or load main class

TLDR : check if packaging element inside the pom.xml file is set to jar.

Like this - <packaging>jar</packaging>. If it set to pom your target folder will not be created even after you Clean and Build your project and Maven executable won't be able to find .class files (because they don't exist), after which you get Error: Could not find or load main class your.package.name.MainClass


After creating a Maven POM project in Netbeans 8.2, the content of the default pom.xml file are as follows -

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.mycompany</groupId>
   <artifactId>myproject</artifactId>
   <version>1.0-SNAPSHOT</version>
   <packaging>pom</packaging>
   <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
</project>

Here packaging element is set to pom. Hence the target directory is not created as we are not enabling maven to package our application as a jar file. Change it to jar then Clean and Build your project, you should see target directory created at root location. Now you should be able to run that java file with main method.

When no packaging is declared, Maven assumes the packaging as jar. Other core packaging values are pom, war, maven-plugin, ejb, ear, rar. These define the goals that execute on each corresponsding build life-cycle phase of that package. See more here

How to pass command-line arguments to a PowerShell ps1 file

This article helps. In particular, this section:

-File

Runs the specified script in the local scope ("dot-sourced"), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters. File must be the last parameter in the command, because all characters typed after the File parameter name are interpreted as the script file path followed by the script parameters.

i.e.

powershell.exe -File "C:\myfile.ps1" arg1 arg2 arg3

means run the file myfile.ps1 and arg1 arg2 & arg3 are the parameters for the PowerShell script.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

We solved the problem by stopping the FinalizerWatchdogDaemon.

public static void fix() {
    try {
        Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");

        Method method = clazz.getSuperclass().getDeclaredMethod("stop");
        method.setAccessible(true);

        Field field = clazz.getDeclaredField("INSTANCE");
        field.setAccessible(true);

        method.invoke(field.get(null));

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

You can call the method in Application's lifecycle, like attachBaseContext(). For the same reason, you also can specific the phone's manufacture to fix the problem, it's up to you.

How to select following sibling/xml tag using xpath

How would I accomplish the nextsibling and is there an easier way of doing this?

You may use:

tr/td[@class='name']/following-sibling::td

but I'd rather use directly:

tr[td[@class='name'] ='Brand']/td[@class='desc']

This assumes that:

  1. The context node, against which the XPath expression is evaluated is the parent of all tr elements -- not shown in your question.

  2. Each tr element has only one td with class attribute valued 'name' and only one td with class attribute valued 'desc'.

Java HTML Parsing

The main problem as stated by preceding coments is malformed HTML, so an html cleaner or HTML-XML converter is a must. Once you get the XML code (XHTML) there are plenty of tools to handle it. You could get it with a simple SAX handler that extracts only the data you need or any tree-based method (DOM, JDOM, etc.) that let you even modify original code.

Here is a sample code that uses HTML cleaner to get all DIVs that use a certain class and print out all Text content inside it.

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

/**
 * @author Fernando Miguélez Palomo <fernandoDOTmiguelezATgmailDOTcom>
 */
public class TestHtmlParse
{
    static final String className = "tags";
    static final String url = "http://www.stackoverflow.com";

    TagNode rootNode;

    public TestHtmlParse(URL htmlPage) throws IOException
    {
        HtmlCleaner cleaner = new HtmlCleaner();
        rootNode = cleaner.clean(htmlPage);
    }

    List getDivsByClass(String CSSClassname)
    {
        List divList = new ArrayList();

        TagNode divElements[] = rootNode.getElementsByName("div", true);
        for (int i = 0; divElements != null && i < divElements.length; i++)
        {
            String classType = divElements[i].getAttributeByName("class");
            if (classType != null && classType.equals(CSSClassname))
            {
                divList.add(divElements[i]);
            }
        }

        return divList;
    }

    public static void main(String[] args)
    {
        try
        {
            TestHtmlParse thp = new TestHtmlParse(new URL(url));

            List divs = thp.getDivsByClass(className);
            System.out.println("*** Text of DIVs with class '"+className+"' at '"+url+"' ***");
            for (Iterator iterator = divs.iterator(); iterator.hasNext();)
            {
                TagNode divElement = (TagNode) iterator.next();
                System.out.println("Text child nodes of DIV: " + divElement.getText().toString());
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Java: How to get input from System.console()

Scanner in = new Scanner(System.in);

int i = in.nextInt();
String s = in.next();

Testing pointers for validity (C/C++)

I have seen various libraries use some method to check for unreferenced memory and such. I believe they simply "override" the memory allocation and deallocation methods (malloc/free), which has some logic that keeps track of the pointers. I suppose this is overkill for your use case, but it would be one way to do it.

Get current URL path in PHP

it should be :

$_SERVER['REQUEST_URI'];

Take a look at : Get the full URL in PHP

Java Regex to Validate Full Name allow only Spaces and Letters

To support language like Hindi which can contain /p{Mark} as well in between language characters. My solution is ^[\p{L}\p{M}]+([\p{L}\p{Pd}\p{Zs}'.]*[\p{L}\p{M}])+$|^[\p{L}\p{M}]+$

You can find all the test cases for this here https://regex101.com/r/3XPOea/1/tests

How to generate a number of most distinctive colors in R?

You can use the Polychrome package for this purpose. It just requires the number of colors and a few seedcolors. For example:

# install.packages("Polychrome")
library(Polychrome)

# create your own color palette based on `seedcolors`
P36 = createPalette(36,  c("#ff0000", "#00ff00", "#0000ff"))
swatch(P36)

You can learn more about this package at https://www.jstatsoft.org/article/view/v090c01.

How to center form in bootstrap 3

A simple way is to add

.center_div{
    margin: 0 auto;
    width:80% /* value of your choice which suits your alignment */
}

to you class .container.Add width:xx % to it and you get perfectly centered div!

eg :

<div class="container center_div">

but i feel that by default container is centered in BS!

View the change history of a file using Git versioning

If you are using eclipse with the git plugin, it has an excellent comparison view with history. Right click the file and select "compare with"=> "history"

Slide right to left Android Animations

You can make your own animations. For example create xml file in res/anim like this

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:interpolator="@android:anim/linear_interpolator">
    <translate
            android:fromXDelta="100%p"
            android:toXDelta="0"
            android:startOffset="0"
            android:duration="500"
            /> </set>

Then override animations in selected activity:

   overridePendingTransition(R.anim.animationIN, R.anim.animationOUT);

Declaring a variable and setting its value from a SELECT query in Oracle

One Additional point:

When you are converting from tsql to plsql you have to worry about no_data_found exception

DECLARE
   v_var NUMBER;
BEGIN
   SELECT clmn INTO v_var FROM tbl;
Exception when no_data_found then v_var := null; --what ever handle the exception.
END;

In tsql if no data found then the variable will be null but no exception

How can I remove all text after a character in bash?

An example might have been useful, but if I understood you correctly, this would work:

echo "Hello: world" | cut -f1 -d":"

This will convert Hello: world into Hello.

Laravel Eloquent: How to get only certain columns from joined tables

Change your model to specify what columns you want selected:

public function user() {
  return $this->belongs_to('User')->select(array('id', 'username'));
}

And don't forget to include the column you're joining on.

Remove decimal values using SQL query

First of all, you tried to replace the entire 12.00 with '', which isn't going to give your desired results.

Second you are trying to do replace directly on a decimal. Replace must be performed on a string, so you have to CAST.

There are many ways to get your desired results, but this replace would have worked (assuming your column name is "height":

REPLACE(CAST(height as varchar(31)),'.00','')

EDIT:

This script works:

DECLARE @Height decimal(6,2);
SET @Height = 12.00;
SELECT @Height, REPLACE(CAST(@Height AS varchar(31)),'.00','');

How do I get the current timezone name in Postgres 9.3?

See this answer: Source

If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone. If TZ is not defined or is not any of the time zone names known to PostgreSQL, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime(). The default time zone is selected as the closest match among PostgreSQL's known time zones. (These rules are also used to choose the default value of log_timezone, if not specified.) source

This means that if you do not define a timezone, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime().

If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone.

It seems to have the System's timezone to be set is possible indeed.

Get the OS local time zone from the shell. In psql:

=> \! date +%Z

Run .php file in Windows Command Prompt (cmd)

If running Windows 10:

  1. Open the start menu
  2. Type path
  3. Click Edit the system environment variables (usually, it's the top search result) and continue on step 6 below.

If on older Windows:

  1. Show Desktop.

  2. Right Click My Computer shortcut in the desktop.

  3. Click Properties.

  4. You should see a section of control Panel - Control Panel\System and Security\System.

  5. Click Advanced System Settings on the Left menu.

  6. Click Enviornment Variables towards the bottom of the System Properties window.

  7. Select PATH in the user variables list.

  8. Append your PHP Path (C:\myfolder\php) to your PATH variable, separated from the already existing string by a semi colon.

  9. Click OK

  10. Open your "cmd"

  11. Type PATH, press enter

  12. Make sure that you see your PHP folder among the list.

That should work.

Note: Make sure that your PHP folder has the php.exe. It should have the file type CLI. If you do not have the php.exe, go ahead and check the installation guidelines at - http://www.php.net/manual/en/install.windows.manual.php - and download the installation file from there.

FtpWebRequest Download File

    private static DataTable ReadFTP_CSV()
    {
        String ftpserver = "ftp://servername/ImportData/xxxx.csv";
        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));

        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        Stream responseStream = response.GetResponseStream();

        // use the stream to read file from FTP 
        StreamReader sr = new StreamReader(responseStream);
        DataTable dt_csvFile = new DataTable();

        #region Code
        //Add Code Here To Loop txt or CSV file
        #endregion

        return dt_csvFile;

    }

I hope it can help you.

Do I need to compile the header files in a C program?

In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.

Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.

Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.

Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.

Detect if value is number in MySQL

use a UDF (user defined function).

CREATE FUNCTION isnumber(inputValue VARCHAR(50))
  RETURNS INT
  BEGIN
    IF (inputValue REGEXP ('^[0-9]+$'))
    THEN
      RETURN 1;
    ELSE
      RETURN 0;
    END IF;
  END;

Then when you query

select isnumber('383XXXX') 

--returns 0

select isnumber('38333434') 

--returns 1

select isnumber(mycol) mycol1, col2, colx from tablex; -- will return 1s and 0s for column mycol1

--you can enhance the function to take decimals, scientific notation , etc...

The advantage of using a UDF is that you can use it on the left or right side of your "where clause" comparison. this greatly simplifies your SQL before being sent to the database:

 SELECT * from tablex where isnumber(columnX) = isnumber('UnkownUserInput');

hope this helps.

C# DataTable.Select() - How do I format the filter criteria to include null?

Try this

myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )

Edit: Relevant sources:

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.

Find control by name from Windows Forms controls

Use Control.ControlCollection.Find.

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

EDIT for asker:

Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
    tbxs[0].Text = "Found!";
}

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

Convert XML to JSON (and back) using Javascript

Disclaimer: I've written fast-xml-parser

Fast XML Parser can help to convert XML to JSON and vice versa. Here is the example;

var options = {
    attributeNamePrefix : "@_",
    attrNodeName: "attr", //default is 'false'
    textNodeName : "#text",
    ignoreAttributes : true,
    ignoreNameSpace : false,
    allowBooleanAttributes : false,
    parseNodeValue : true,
    parseAttributeValue : false,
    trimValues: true,
    decodeHTMLchar: false,
    cdataTagName: "__cdata", //default is 'false'
    cdataPositionChar: "\\c",
};
if(parser.validate(xmlData)=== true){//optional
    var jsonObj = parser.parse(xmlData,options);
}

If you want to parse JSON or JS object into XML then

//default options need not to set
var defaultOptions = {
    attributeNamePrefix : "@_",
    attrNodeName: "@", //default is false
    textNodeName : "#text",
    ignoreAttributes : true,
    encodeHTMLchar: false,
    cdataTagName: "__cdata", //default is false
    cdataPositionChar: "\\c",
    format: false, 
    indentBy: "  ",
    supressEmptyNode: false
};
var parser = new parser.j2xParser(defaultOptions);
var xml = parser.parse(json_or_js_obj);

How to paste yanked text into the Vim command line

Yes. Hit Ctrl-R then ". If you have literal control characters in what you have yanked, use Ctrl-R, Ctrl-O, ".

Here is an explanation of what you can do with registers. What you can do with registers is extraordinary, and once you know how to use them you cannot live without them.

Registers are basically storage locations for strings. Vim has many registers that work in different ways:

  • 0 (yank register: when you use y in normal mode, without specifying a register, yanked text goes there and also to the default register),
  • 1 to 9 (shifting delete registers, when you use commands such as c or d, what has been deleted goes to register 1, what was in register 1 goes to register 2, etc.),
  • " (default register, also known as unnamed register. This is where the " comes in Ctrl-R, "),
  • a to z for your own use (capitalized A to Z are for appending to corresponding registers).
  • _ (acts like /dev/null (Unix) or NUL (Windows), you can write to it but it's discarded and when you read from it, it is always empty),
  • - (small delete register),
  • / (search pattern register, updated when you look for text with /, ?, * or # for instance; you can also write to it to dynamically change the search pattern),
  • : (stores last VimL typed command via Q or :, readonly),
  • + and * (system clipboard registers, you can write to them to set the clipboard and read the clipboard contents from them)

See :help registers for the full reference.

You can, at any moment, use :registers to display the contents of all registers. Synonyms and shorthands for this command are :display, :reg and :di.

In Insert or Command-line mode, Ctrl-R plus a register name, inserts the contents of this register. If you want to insert them literally (no auto-indenting, no conversion of control characters like 0x08 to backspace, etc), you can use Ctrl-R, Ctrl-O, register name. See :help i_CTRL-R and following paragraphs for more reference.

But you can also do the following (and I probably forgot many uses for registers).

  • In normal mode, hit ":p. The last command you used in vim is pasted into your buffer.
    Let's decompose: " is a Normal mode command that lets you select what register is to be used during the next yank, delete or paste operation. So ": selects the colon register (storing last command). Then p is a command you already know, it pastes the contents of the register.

    cf. :help ", :help quote_:

  • You're editing a VimL file (for instance your .vimrc) and would like to execute a couple of consecutive lines right now: yj:@"Enter.
    Here, yj yanks current and next line (this is because j is a linewise motion but this is out of scope of this answer) into the default register (also known as the unnamed register). Then the :@ Ex command plays Ex commands stored in the register given as argument, and " is how you refer to the unnamed register. Also see the top of this answer, which is related.

    Do not confuse " used here (which is a register name) with the " from the previous example, which was a Normal-mode command.

    cf. :help :@ and :help quote_quote

  • Insert the last search pattern into your file in Insert mode, or into the command line, with Ctrl-R, /.

    cf. :help quote_/, help i_CTRL-R

    Corollary: Keep your search pattern but add an alternative: / Ctrl-R, / \|alternative.

  • You've selected two words in the middle of a line in visual mode, yanked them with y, they are in the unnamed register. Now you want to open a new line just below where you are, with those two words: :pu. This is shorthand for :put ". The :put command, like many Ex commands, works only linewise.

    cf. :help :put

    You could also have done: :call setreg('"', @", 'V') then p. The setreg function sets the register of which the name is given as first argument (as a string), initializes it with the contents of the second argument (and you can use registers as variables with the name @x where x is the register name in VimL), and turns it into the mode specified in the third argument, V for linewise, nothing for characterwise and literal ^V for blockwise.

    cf. :help setreg(). The reverse functions are getreg() and getregtype().

  • If you have recorded a macro with qa...q, then :echo @a will tell you what you have typed, and @a will replay the macro (probably you knew that one, very useful in order to avoid repetitive tasks)

    cf. :help q, help @

    Corollary from the previous example: If you have 8go in the clipboard, then @+ will play the clipboard contents as a macro, and thus go to the 8th byte of your file. Actually this will work with almost every register. If your last inserted string was dd in Insert mode, then @. will (because the . register contains the last inserted string) delete a line. (Vim documentation is wrong in this regard, since it states that the registers #, %, : and . will only work with p, P, :put and Ctrl-R).

    cf. :help @

    Don't confuse :@ (command that plays Vim commands from a register) and @ (normal-mode command that plays normal-mode commands from a register).

    Notable exception is @:. The command register does not contain the initial colon neither does it contain the final carriage return. However in Normal mode, @: will do what you expect, interpreting the register as an Ex command, not trying to play it in Normal mode. So if your last command was :e, the register contains e but @: will reload the file, not go to end of word.

    cf. :help @:

  • Show what you will be doing in Normal mode before running it: @='dd' Enter. As soon as you hit the = key, Vim switches to expression evaluation: as you enter an expression and hit Enter, Vim computes it, and the result acts as a register content. Of course the register = is read-only, and one-shot. Each time you start using it, you will have to enter a new expression.

    cf. :help quote_=

    Corollary: If you are editing a command, and you realize that you should need to insert into your command line some line from your current buffer: don't press Esc! Use Ctrl-R =getline(58) Enter. After that you will be back to command line editing, but it has inserted the contents of the 58th line.

  • Define a search pattern manually: :let @/ = 'foo'

    cf. :help :let

    Note that doing that, you needn't to escape / in the pattern. However you need to double all single quotes of course.

  • Copy all lines beginning with foo, and afterwards all lines containing bar to clipboard, chain these commands: qaq (resets the a register storing an empty macro inside it), :g/^foo/y A, :g/bar/y A, :let @+ = @a.

    Using a capital register name makes the register work in append mode

    Better, if Q has not been remapped by mswin.vim, start Ex mode with Q, chain those “colon commands” which are actually better called “Ex commands”, and go back to Normal mode by typing visual.

    cf. :help :g, :help :y, :help Q

  • Double-space your file: :g/^/put _. This puts the contents of the black hole register (empty when reading, but writable, behaving like /dev/null) linewise, after each line (because every line has a beginning!).

  • Add a line containing foo before each line: :g/^/-put ='foo'. This is a clever use of the expression register. Here, - is a synonym for .-1 (cf. :help :range). Since :put puts the text after the line, you have to explicitly tell it to act on the previous one.

  • Copy the entire buffer to the system clipboard: :%y+.

    cf. :help :range (for the % part) and :help :y.

  • If you have misrecorded a macro, you can type :let @a=' Ctrl-R =replace(@a,"'","''",'g') Enter ' and edit it. This will modify the contents of the macro stored in register a, and it's shown here how you can use the expression register to do that.

  • If you did dddd, you might do uu in order to undo. With p you could get the last deleted line. But actually you can also recover up to 9 deletes with the registers @1 through @9.

    Even better, if you do "1P, then . in Normal mode will play "2P, and so on.

    cf. :help . and :help quote_number

  • If you want to insert the current date in Insert mode: Ctrl-R=strftime('%y%m%d')Enter.

    cf. :help strftime()

Once again, what can be confusing:

  • :@ is a command-line command that interprets the contents of a register as vimscript and sources it
  • @ in normal mode command that interprets the contents of a register as normal-mode keystrokes (except when you use : register, that contains last played command without the initial colon: in this case it replays the command as if you also re-typed the colon and the final return key).

  • " in normal mode command that helps you select a register for yank, paste, delete, correct, etc.

  • " is also a valid register name (the default, or unnamed, register) and therefore can be passed as an arguments for commands that expect register names

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

You can use these Extension Methods: (Save as PartialWithScript.cs)

namespace System.Web.Mvc.Html
{
    public static class PartialWithScript
    {
        public static void RenderPartialWithScript(this HtmlHelper htmlHelper, string partialViewName)
        {
            if (htmlHelper.ViewBag.ScriptPartials == null)
            {
                htmlHelper.ViewBag.ScriptPartials = new List<string>();
            }

            if (!htmlHelper.ViewBag.ScriptPartials.Contains(partialViewName))
            {
                htmlHelper.ViewBag.ScriptPartials.Add(partialViewName);
            }

            htmlHelper.ViewBag.ScriptPartialHtml = true;
            htmlHelper.RenderPartial(partialViewName);
        }

        public static void RenderPartialScripts(this HtmlHelper htmlHelper)
        {
            if (htmlHelper.ViewBag.ScriptPartials != null)
            {
                htmlHelper.ViewBag.ScriptPartialHtml = false;
                foreach (string partial in htmlHelper.ViewBag.ScriptPartials)
                {
                    htmlHelper.RenderPartial(partial);
                }
            }
        }
    }
}

Use like this:

Example partial: (_MyPartial.cshtml) Put the html in the if, and the js in the else.

@if (ViewBag.ScriptPartialHtml ?? true)
    <p>I has htmls</p>
}
else {
    <script type="text/javascript">
        alert('I has javascripts');
    </script>
}

In your _Layout.cshtml, or wherever you want the scripts from the partials on to be rendered, put the following (once): It will render only the javascript of all partials on the current page at this location.

@{ Html.RenderPartialScripts(); }

Then to use your partial, simply do this: It will render only the html at this location.

@{Html.RenderPartialWithScript("~/Views/MyController/_MyPartial.cshtml");}

Why does AngularJS include an empty option in select?

This works perfectly fine

<select ng-model="contact.Title" ng-options="co for co in['Mr.','Ms.','Mrs.','Dr.','Prof.']">
    <option style="display:none" value=""></option>
</select>

the way it works is, that this gives the first option to be displayed before selecting something and the display:none removes it form the dropdown so if you want you can do

<select ng-model="contact.Title" ng-options="co for co in['Mr.','Ms.','Mrs.','Dr.','Prof.']">
    <option style="display:none" value="">select an option...</option>
</select>

and this will give you the select and option before selecting but once selected it will disappear, and it will not show up in the dropdown.

C string append

I write a function support dynamic variable string append, like PHP str append: str + str + ... etc.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

int str_append(char **json, const char *format, ...)
{
    char *str = NULL;
    char *old_json = NULL, *new_json = NULL;

    va_list arg_ptr;
    va_start(arg_ptr, format);
    vasprintf(&str, format, arg_ptr);

    // save old json
    asprintf(&old_json, "%s", (*json == NULL ? "" : *json));

    // calloc new json memory
    new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char));

    strcat(new_json, old_json);
    strcat(new_json, str);

    if (*json) free(*json);
    *json = new_json;

    free(old_json);
    free(str);

    return 0;
}

int main(int argc, char *argv[])
{
    char *json = NULL;

    str_append(&json, "name: %d, %d, %d", 1, 2, 3);
    str_append(&json, "sex: %s", "male");
    str_append(&json, "end");
    str_append(&json, "");
    str_append(&json, "{\"ret\":true}");

    int i;
    for (i = 0; i < 10; i++) {
        str_append(&json, "id-%d", i);
    }

    printf("%s\n", json);

    if (json) free(json);

    return 0;
}

Python dictionary replace values

I think this may help you solve your issue.

Imagine you have a dictionary like this:

dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}

And you want to change values by this one:

dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}

You can use code bellow to change values of dic0 properly respected to dic0t01 without worrying yourself about indexes in dictionary:

for x, y in dic0.items():
    dic0[x] = dic0to1[y]

Now you have:

>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}

How can I implement prepend and append with regular JavaScript?

var insertedElement = parentElement.insertBefore(newElement, referenceElement);

If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.

insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.

Examples can be found here: Node.insertBefore

How to force page refreshes or reloads in jQuery?

Replace that line with:

$("#someElement").click(function() {
    window.location.href = window.location.href;
});

or:

$("#someElement").click(function() {
    window.location.reload();
});

How to sort List of objects by some property

public class ActiveAlarm implements Comparable<ActiveAlarm> {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;

    public int compareTo(ActiveAlarm a) {
        if ( this.timeStarted > a.timeStarted )
            return 1;
        else if ( this.timeStarted < a.timeStarted )
            return -1;
        else {
             if ( this.timeEnded > a.timeEnded )
                 return 1;
             else
                 return -1;
        }
 }

That should give you a rough idea. Once that's done, you can call Collections.sort() on the list.

How do I install Python libraries in wheel format?

For windows, there are automatic installer packages available at this site

It includes most of the python packages.

But the best way for it is of course using pip.

Convert to date format dd/mm/yyyy

<?php
$test1='2010-04-19 18:31:27';
echo date('d/m/Y',strtotime($test1));
?>

try this

How to explain callbacks in plain english? How are they different from calling one function from another function?

“In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.” - Wikipedia

Callback in C using Function Pointer

In C, callback is implemented using Function Pointer. Function Pointer - as the name suggests, is a pointer to a function.

For example, int (*ptrFunc) ();

Here, ptrFunc is a pointer to a function that takes no arguments and returns an integer. DO NOT forget to put in the parenthesis, otherwise the compiler will assume that ptrFunc is a normal function name, which takes nothing and returns a pointer to an integer.

Here is some code to demonstrate the function pointer.

#include<stdio.h>
int func(int, int);
int main(void)
{
    int result1,result2;
    /* declaring a pointer to a function which takes
       two int arguments and returns an integer as result */
    int (*ptrFunc)(int,int);

    /* assigning ptrFunc to func's address */                    
    ptrFunc=func;

    /* calling func() through explicit dereference */
    result1 = (*ptrFunc)(10,20);

    /* calling func() through implicit dereference */        
    result2 = ptrFunc(10,20);            
    printf("result1 = %d result2 = %d\n",result1,result2);
    return 0;
}

int func(int x, int y)
{
    return x+y;
}

Now let us try to understand the concept of Callback in C using function pointer.

The complete program has three files: callback.c, reg_callback.h and reg_callback.c.

/* callback.c */
#include<stdio.h>
#include"reg_callback.h"

/* callback function definition goes here */
void my_callback(void)
{
    printf("inside my_callback\n");
}

int main(void)
{
    /* initialize function pointer to
    my_callback */
    callback ptr_my_callback=my_callback;                        
    printf("This is a program demonstrating function callback\n");
    /* register our callback function */
    register_callback(ptr_my_callback);                          
    printf("back inside main program\n");
    return 0;
}

/* reg_callback.h */
typedef void (*callback)(void);
void register_callback(callback ptr_reg_callback);


/* reg_callback.c */
#include<stdio.h>
#include"reg_callback.h"

/* registration goes here */
void register_callback(callback ptr_reg_callback)
{
    printf("inside register_callback\n");
    /* calling our callback function my_callback */
    (*ptr_reg_callback)();                               
}

If we run this program, the output will be

This is a program demonstrating function callback inside register_callback inside my_callback back inside main program

The higher layer function calls a lower layer function as a normal call and the callback mechanism allows the lower layer function to call the higher layer function through a pointer to a callback function.

Callback in Java Using Interface

Java does not have the concept of function pointer It implements Callback mechanism through its Interface mechanism Here instead of a function pointer, we declare an Interface having a method which will be called when the callee finishes its task

Let me demonstrate it through an example:

The Callback Interface

public interface Callback
{
    public void notify(Result result);
}

The Caller or the Higher Level Class

public Class Caller implements Callback
{
Callee ce = new Callee(this); //pass self to the callee

//Other functionality
//Call the Asynctask
ce.doAsynctask();

public void notify(Result result){
//Got the result after the callee has finished the task
//Can do whatever i want with the result
}
}

The Callee or the lower layer function

public Class Callee {
Callback cb;
Callee(Callback cb){
this.cb = cb;
}

doAsynctask(){
//do the long running task
//get the result
cb.notify(result);//after the task is completed, notify the caller
}
}

Callback Using EventListener pattern

  • List item

This pattern is used to notify 0 to n numbers of Observers/Listeners that a particular task has finished

  • List item

The difference between Callback mechanism and EventListener/Observer mechanism is that in callback, the callee notifies the single caller, whereas in Eventlisener/Observer, the callee can notify anyone who is interested in that event (the notification may go to some other parts of the application which has not triggered the task)

Let me explain it through an example.

The Event Interface

public interface Events {

public void clickEvent();
public void longClickEvent();
}

Class Widget

package com.som_itsolutions.training.java.exampleeventlistener;

import java.util.ArrayList;
import java.util.Iterator;

public class Widget implements Events{

    ArrayList<OnClickEventListener> mClickEventListener = new ArrayList<OnClickEventListener>(); 
    ArrayList<OnLongClickEventListener> mLongClickEventListener = new ArrayList<OnLongClickEventListener>();

    @Override
    public void clickEvent() {
        // TODO Auto-generated method stub
        Iterator<OnClickEventListener> it = mClickEventListener.iterator();
                while(it.hasNext()){
                    OnClickEventListener li = it.next();
                    li.onClick(this);
                }   
    }
    @Override
    public void longClickEvent() {
        // TODO Auto-generated method stub
        Iterator<OnLongClickEventListener> it = mLongClickEventListener.iterator();
        while(it.hasNext()){
            OnLongClickEventListener li = it.next();
            li.onLongClick(this);
        }

    }

    public interface OnClickEventListener
    {
        public void onClick (Widget source);
    }

    public interface OnLongClickEventListener
    {
        public void onLongClick (Widget source);
    }

    public void setOnClickEventListner(OnClickEventListener li){
        mClickEventListener.add(li);
    }
    public void setOnLongClickEventListner(OnLongClickEventListener li){
        mLongClickEventListener.add(li);
    }
}

Class Button

public class Button extends Widget{
private String mButtonText;
public Button (){
} 
public String getButtonText() {
return mButtonText;
}
public void setButtonText(String buttonText) {
this.mButtonText = buttonText;
}
}

Class Checkbox

public class CheckBox extends Widget{
private boolean checked;
public CheckBox() {
checked = false;
}
public boolean isChecked(){
return (checked == true);
}
public void setCheck(boolean checked){
this.checked = checked;
}
}

Activity Class

package com.som_itsolutions.training.java.exampleeventlistener;

public class Activity implements Widget.OnClickEventListener
{
    public Button mButton;
    public CheckBox mCheckBox;
    private static Activity mActivityHandler;
    public static Activity getActivityHandle(){
        return mActivityHandler;
    }
    public Activity ()
    {
        mActivityHandler = this;
        mButton = new Button();
        mButton.setOnClickEventListner(this);
        mCheckBox = new CheckBox();
        mCheckBox.setOnClickEventListner(this);
        } 
    public void onClick (Widget source)
    {
        if(source == mButton){
            mButton.setButtonText("Thank you for clicking me...");
            System.out.println(((Button) mButton).getButtonText());
        }
        if(source == mCheckBox){
            if(mCheckBox.isChecked()==false){
                mCheckBox.setCheck(true);
                System.out.println("The checkbox is checked...");
            }
            else{
                mCheckBox.setCheck(false);
                System.out.println("The checkbox is not checked...");
            }       
        }
    }
    public void doSomeWork(Widget source){
        source.clickEvent();
    }   
}

Other Class

public class OtherClass implements Widget.OnClickEventListener{
Button mButton;
public OtherClass(){
mButton = Activity.getActivityHandle().mButton;
mButton.setOnClickEventListner(this);//interested in the click event                        //of the button
}
@Override
public void onClick(Widget source) {
if(source == mButton){
System.out.println("Other Class has also received the event notification...");
}
}

Main Class

public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Activity a = new Activity();
OtherClass o = new OtherClass();
a.doSomeWork(a.mButton);
a.doSomeWork(a.mCheckBox);
}
}

As you can see from the above code, that we have an interface called events which basically lists all the events that may happen for our application. The Widget class is the base class for all the UI components like Button, Checkbox. These UI components are the objects that actually receive the events from the framework code. Widget class implements the Events interface and also it has two nested interfaces namely OnClickEventListener & OnLongClickEventListener

These two interfaces are responsible for listening to events that may occur on the Widget derived UI components like Button or Checkbox. So if we compare this example with the earlier Callback example using Java Interface, these two interfaces work as the Callback interface. So the higher level code (Here Activity) implements these two interfaces. And whenever an event occurs to a widget, the higher level code (or the method of these interfaces implemented in the higher level code, which is here Activity) will be called.

Now let me discuss the basic difference between Callback and Eventlistener pattern. As we have mentioned that using Callback, the Callee can notify only a single Caller. But in the case of EventListener pattern, any other part or class of the Application can register for the events that may occur on the Button or Checkbox. The example of this kind of class is the OtherClass. If you see the code of the OtherClass, you will find that it has registered itself as a listener to the ClickEvent that may occur in the Button defined in the Activity. Interesting part is that, besides the Activity ( the Caller), this OtherClass will also be notified whenever the click event occurs on the Button.

How can I quickly sum all numbers in a file?

More succinct:

# Ruby
ruby -e 'puts open("random_numbers").map(&:to_i).reduce(:+)'

# Python
python -c 'print(sum(int(l) for l in open("random_numbers")))'

How to change a text with jQuery

Something like this should work

var text = $('#toptitle').text();
if (text == 'Profil'){
    $('#toptitle').text('New Word');
}

How to print number with commas as thousands separators?

This is what I do for floats. Although, honestly, I'm not sure which versions it works for - I'm using 2.7:

my_number = 4385893.382939491

my_string = '{:0,.2f}'.format(my_number)

Returns: 4,385,893.38

Update: I recently had an issue with this format (couldn't tell you the exact reason), but was able to fix it by dropping the 0:

my_string = '{:,.2f}'.format(my_number)

jQuery - setting the selected value of a select control via its text description

Here is very simple way. plz use it

$("#free").val("y").change();

Merge trunk to branch in Subversion

It is “old-fashioned” way to specify ranges of revisions you wish to merge. With 1.5+ you can use:

svn merge HEAD url/of/trunk path/to/branch/wc

Convert boolean result into number/integer

try

val*1

_x000D_
_x000D_
let t=true;_x000D_
let f=false;_x000D_
_x000D_
console.log(t*1);_x000D_
console.log(f*1)
_x000D_
_x000D_
_x000D_

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

How to create many labels and textboxes dynamically depending on the value of an integer variable?

You can try this:

int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e) 
{
     TextBox txt = new TextBox();
     this.Controls.Add(txt);
     txt.Top = cleft * 40;
     txt.Size = new Size(200, 16);
     txt.Left = 150;
     cleft = cleft + 1;
     Label lbl = new Label();
     this.Controls.Add(lbl);
     lbl.Top = aleft * 40;
     lbl.Size = new Size(100, 16);
     lbl.ForeColor = Color.Blue;
     lbl.Text = "BoxNo/CardNo";
     lbl.Left = 70;
     aleft = aleft + 1;
     return;
}
private void btd_Click(object sender, EventArgs e)
{ 
    //Here you Delete Text Box One By One(int ix for Text Box)
    for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
    //Here you Delete Lable One By One(int ix for Lable)
    for (int x = this.Controls.Count - 2; x >= 0; x--)
    {
        if (this.Controls[ix] is TextBox) 
        this.Controls[ix].Dispose();
        if (this.Controls[x] is Label) 
        this.Controls[x].Dispose();
        return;
    }
}

Solving "adb server version doesn't match this client" error

For me it was happening because I had android tools installed in two places: 1. The location where I manually downloaded it from google 2. Automatic download by Android studio

What I was able to do was completely delete the folder in #1 and point my bash profile and all other references to the location where Android studio installed it for me: /Users/my_user_name/Library/Android/sdk

This solved it.

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Update for latest SDK:

Now @zeuter's answer is correct for Facebook SDK v4.7+:

LoginManager.getInstance().logOut();

Original answer:

Please do not use SessionTracker. It is an internal (package private) class, and is not meant to be consumed as part of the public API. As such, its API may change at any time without any backwards compatibility guarantees. You should be able to get rid of all instances of SessionTracker in your code, and just use the active session instead.

To answer your question, if you don't want to keep any session data, simply call closeAndClearTokenInformation when your app closes.

Replace a string in shell script using a variable

Single quotes are very strong. Once inside, there's nothing you can do to invoke variable substitution, until you leave. Use double quotes instead:

echo $LINE | sed -e "s/12345678/$replace/g"

500.21 Bad module "ManagedPipelineHandler" in its module list

I got this error on my ASP.Net 4.5 app on Windows Server 2012 R2.

Go to start menu -> "Turn windows features on or off". A wizard popped up for me.

Click Next to Server Roles

I had to check these to get this to work, located under Web Server IIS->Web Server-> Application Development (these are based on Jeremy Cook's answer above):

enter image description here

Then click next to Features and make sure the following is checked:

enter image description here

Then click next and Install. At this point, the error went away for me. Good luck!

input() error - NameError: name '...' is not defined

For python 3 and above

s = raw_input()

it will solve the problem on pycharm IDE if you are solving on online site exactly hackerrank then use:

s = input()

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

Although there's CSS defines a text-wrap property, it's not supported by any major browser, but maybe vastly supported white-space property solves your problem.

How do I disable right click on my web page?

Try this code for disabling inspect element option

    jQuery(document).ready(function() {
    function disableSelection(e) {
        if (typeof e.onselectstart != "undefined") e.onselectstart = function() {
            return false
        };
        else if (typeof e.style.MozUserSelect != "undefined") e.style.MozUserSelect = "none";
        else e.onmousedown = function() {
            return false
        };
        e.style.cursor = "default"
    }
    window.onload = function() {
        disableSelection(document.body)
    };

    window.addEventListener("keydown", function(e) {
        if (e.ctrlKey && (e.which == 65 || e.which == 66 || e.which == 67 || e.which == 70 || e.which == 73 || e.which == 80 || e.which == 83 || e.which == 85 || e.which == 86)) {
            e.preventDefault()
        }
    });
    document.keypress = function(e) {
        if (e.ctrlKey && (e.which == 65 || e.which == 66 || e.which == 70 || e.which == 67 || e.which == 73 || e.which == 80 || e.which == 83 || e.which == 85 || e.which == 86)) {}
        return false
    };

    document.onkeydown = function(e) {
        e = e || window.event;
        if (e.keyCode == 123 || e.keyCode == 18) {
            return false
        }
    };

    document.oncontextmenu = function(e) {
        var t = e || window.event;
        var n = t.target || t.srcElement;
        if (n.nodeName != "A") return false
    };
    document.ondragstart = function() {
        return false
    };
});

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For people using boto3 (Python SDK) use the below code

from botocore.client import Config


s3 = boto3.resource(
    's3',
    aws_access_key_id='xxxxxx',
    aws_secret_access_key='xxxxxx',
    config=Config(signature_version='s3v4')
)

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

How to resolve compiler warning 'implicit declaration of function memset'

You need:

#include <string.h> /* memset */
#include <unistd.h> /* close */

in your code.

References: POSIX for close, the C standard for memset.

Posting raw image data as multipart/form-data in curl

As of PHP 5.6 @$filePath will not work in CURLOPT_POSTFIELDS without CURLOPT_SAFE_UPLOAD being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.

$fields = [
    'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);

How to add a JAR in NetBeans

Right click 'libraries' in the project list, then click add.

How can I count occurrences with groupBy?

If you're open to using a third-party library, you can use the Collectors2 class in Eclipse Collections to convert the List to a Bag using a Stream. A Bag is a data structure that is built for counting.

Bag<String> counted =
        list.stream().collect(Collectors2.countBy(each -> each));

Assert.assertEquals(1, counted.occurrencesOf("World"));
Assert.assertEquals(2, counted.occurrencesOf("Hello"));

System.out.println(counted.toStringOfItemToCount());

Output:

{World=1, Hello=2}

In this particular case, you can simply collect the List directly into a Bag.

Bag<String> counted = 
        list.stream().collect(Collectors2.toBag());

You can also create the Bag without using a Stream by adapting the List with the Eclipse Collections protocols.

Bag<String> counted = Lists.adapt(list).countBy(each -> each);

or in this particular case:

Bag<String> counted = Lists.adapt(list).toBag();

You could also just create the Bag directly.

Bag<String> counted = Bags.mutable.with("Hello", "Hello", "World");

A Bag<String> is like a Map<String, Integer> in that it internally keeps track of keys and their counts. But, if you ask a Map for a key it doesn't contain, it will return null. If you ask a Bag for a key it doesn't contain using occurrencesOf, it will return 0.

Note: I am a committer for Eclipse Collections.

How to concatenate multiple column values into a single column in Panda dataframe

Another solution using DataFrame.apply(), with slightly less typing and more scalable when you want to join more columns:

cols = ['foo', 'bar', 'new']
df['combined'] = df[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)

How to make a Div appear on top of everything else on the screen?

z-index is not that simple friend. It doesn't actually matter if you put z-index:999999999999..... But it matters WHEN you gave it that z-index. Different dom-elements take precedence over each other as well.

I did one solution where I used jQuery to modify the elements css, and gave it the z-index only when I needed the element to be on top. That way we can be sure that the z-index of this item has been given last and the index will be noted. This one requires some action to be handled though, but in your case it seems to be possible.

Not sure if this works, but you could try giving the !important parameter too:

#desired_element { z-index: 99 !important; }

Edit: Adding a quote from the link for quick clarification:

First of all, z-index only works on positioned elements. If you try to set a z-index on an element with no position specified, it will do nothing. Secondly, z-index values can create stacking contexts, and now suddenly what seemed simple just got a lot more complicated.

Adding the z-index for the element via jQuery, gives the element different stacking context, and thus it tends to work. I do not recommend this, but try to keep the html and css in a such order that all elements are predictable.

The provided link is a must read. Stacking order etc. of html elements was something I was not aware as a newbie coder and that article cleared it for me pretty good.

Reference philipwalton.com

C++ vector's insert & push_back difference

Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

  1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
  2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
  3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

For example, you could risk the following code:

auto pe = v.end();
for (auto& s: a)
    v.insert(pe, v);

This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

If you do it this way:

copy(a.begin(), a.end(), back_inserter(v);

it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

[EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

copy(a.begin(), a.end(), inserter(v, v.end());

So this code will also add all elements in the original order without any risk.

How do I enable/disable log levels in Android?

We can use class Log in our local component and define the methods as v/i/e/d. Based on the need of we can make call further.
example is shown below.

    public class Log{
        private static boolean TAG = false;
        public static void d(String enable_tag, String message,Object...args){
            if(TAG)
            android.util.Log.d(enable_tag, message+args);
        }
        public static void e(String enable_tag, String message,Object...args){
            if(TAG)
            android.util.Log.e(enable_tag, message+args);
        }
        public static void v(String enable_tag, String message,Object...args){
            if(TAG)
            android.util.Log.v(enable_tag, message+args);
        }
    }
    if we do not need any print(s), at-all make TAG as false for all else 
    remove the check for type of Log (say Log.d).
    as 
    public static void i(String enable_tag, String message,Object...args){
    //      if(TAG)
            android.util.Log.i(enable_tag, message+args);
    }

here message is for string and and args is the value you want to print.

How to Maximize a firefox browser window using Selenium WebDriver with node.js

As of 2020, the correct answer is :

driver.maximize_window()

ActiveRecord: size vs count

You should read that, it's still valid.

You'll adapt the function you use depending on your needs.

Basically:

  • if you already load all entries, say User.all, then you should use length to avoid another db query

  • if you haven't anything loaded, use count to make a count query on your db

  • if you don't want to bother with these considerations, use size which will adapt

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

You might be importing @Test from org.junit.Test, which is a JUnit 4 annotation. The Junit5 test runner will not discover it.

The Junit5 test runner will discover a test annotated with org.junit.jupiter.api.Test

Found the answer from Import org.junit.Test throws error as "No Test found with Test Runner "JUnit 5""

How to print out more than 20 items (documents) in MongoDB's shell?

In the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, the cursor is automatically iterated to access up to the first 20 documents that match the query. You can set the DBQuery.shellBatchSize variable to change the number of automatically iterated documents.

Reference - https://docs.mongodb.com/v3.2/reference/method/db.collection.find/

SQL is null and = null

In SQL, a comparison between a null value and any other value (including another null) using a comparison operator (eg =, !=, <, etc) will result in a null, which is considered as false for the purposes of a where clause (strictly speaking, it's "not true", rather than "false", but the effect is the same).

The reasoning is that a null means "unknown", so the result of any comparison to a null is also "unknown". So you'll get no hit on rows by coding where my_column = null.

SQL provides the special syntax for testing if a column is null, via is null and is not null, which is a special condition to test for a null (or not a null).

Here's some SQL showing a variety of conditions and and their effect as per above.

create table t (x int, y int);
insert into t values (null, null), (null, 1), (1, 1);

select 'x = null' as test , x, y from t where x = null
union all
select 'x != null', x, y from t where x != null
union all
select 'not (x = null)', x, y from t where not (x = null)
union all
select 'x = y', x, y from t where x = y
union all
select 'not (x = y)', x, y from t where not (x = y);

returns only 1 row (as expected):

TEST    X   Y
x = y   1   1

See this running on SQLFiddle

Is there a good JSP editor for Eclipse?

"Web Page Editor (optional)" package from the Eclipse Galileo/Helios update site has the following very minor quirks in a JSP editor:

  • Auto-commenting in Java code fragments does not work (Ctrl /); [fixed in Helios SR2]
  • [present in Galileo, fixed in Eclipse Helios SR1] If a Java code fragment has errors that are already fixed, the editor does not remove the error marks until you modify the erroneous place or close/reopen the file being edited;

This was valid at Dec 7, 2010.

How do I set hostname in docker-compose?

Based on docker documentation: https://docs.docker.com/compose/compose-file/#/command

I simply put hostname: <string> in my docker-compose file.

E.g.:

[...]

lb01:
  hostname: at-lb01
  image: at-client-base:v1

[...]

and container lb01 picks up at-lb01 as hostname.

Google Recaptcha v3 example demo

I process POST on PHP from an angular ajax call. I also like to see the SCORE from google.

This works well for me...

$postData = json_decode(file_get_contents('php://input'), true); //get data sent via post
$captcha = $postData['g-recaptcha-response'];

header('Content-Type: application/json');
if($captcha === ''){
    //Do something with error
    echo '{ "status" : "bad", "score" : "none"}';
} else {
    $secret   = 'your-secret-key';
    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
    );
    // use json_decode to extract json response
    $response = json_decode($response);

    if ($response->success === false) {
        //Do something with error
        echo '{ "status" : "bad", "score" : "none"}';
    }else if ($response->success==true && $response->score <= 0.5) {
        echo '{ "status" : "bad", "score" : "'.$response->score.'"}';
    }else {
        echo '{ "status" : "ok", "score" : "'.$response->score.'"}';
    }
}

On HTML

<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">

On js

$scope.grabCaptchaV3=function(){
    var params = {
                     method: 'POST',
                     url: 'api/recaptcha.php',
                     headers: {
                       'Content-Type': undefined
                     },
                     data:   {'g-recaptcha-response' : myCaptcha }
     }
     $http(params).then(function(result){ 
                console.log(result.data);
     }, function(response){
                console.log(response.statusText);
     }); 
}

no default constructor exists for class

Because you have this:

Blowfish(BlowfishAlgorithm algorithm);

It's not a default constructor. The default constructor is one which takes no parameters. i.e.

Blowfish();

Gmail: 530 5.5.1 Authentication Required. Learn more at

Get to your Gmail account's security settings and set permissions for "Less secure apps" to Enabled. Worked for me.

When does a cookie with expiration time 'At end of session' expire?

When you use setcookie, you can either set the expiration time to 0 or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).

Generate C# class from XML

To convert XML into a C# Class:

  • Navigate to the Microsoft Visual Studio Marketplace: -- https://marketplace.visualstudio.com
  • In the search bar enter text: -- xml to class code tool
  • Download, install, and use the app

Note: in the fullness of time, this app may be replaced, but chances are, there'll be another tool that does the same thing.

How to get the ActionBar height?

In javafx (using Gluon), the height is set at runtime or something like it. While being able to get the width just like normal...

double width = appBar.getWidth();

You have to create a listener:

GluonApplication application = this;

application.getAppBar().heightProperty().addListener(new ChangeListener(){
    @Override
    public void changed(ObservableValue observable, Object oldValue, Object newValue) {
        // Take most recent value given here
        application.getAppBar.heightProperty.get()
    }
});

...And take the most recent value it changed to. To get the height.

Remove file from SVN repository without deleting local copy

Rename your file, commit the changes including the "deleted" file, and don't include the new (renamed) file.

Rename your file back.

ImportError: No module named PyQt4

It is likely that you are running the python executable from /usr/bin (Apple version) instead of /usr/loca/bin (Brew version)

You can either

a) check your PATH variable

or

b) run brew doctor

or

c) run which python

to check if it is the case.

Converting cv::Mat to IplImage*

Personaly I think it's not the problem caused by type casting but a buffer overflow problem; it is this line

cvCopy(iplimagearray[i], xyz);   

that I think will cause segment fault, I suggest that you confirm the array iplimagearray[i] have enough size of buffer to receive copyed data

Database Diagram Support Objects cannot be Installed ... no valid owner

Select your database - Right Click - Select Properties

Select FILE in left side of page

In the OWNER box, select button which has three dots (…) in it

Now select user ‘sa and Click OK

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

Jackson how to transform JsonNode to ArrayNode without casting?

In Java 8 you can do it like this:

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

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

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

It is a problem with Java InputStream. When the stream is read once the file offset position counter is moved to the end of file. On the subsequent read by using the same stream you'll get this error. So you have to close and reopen the stream again or call inputStream.reset() to reset the offset counter to its initial position.

error C2065: 'cout' : undeclared identifier

I had same problem on Visual Studio C++ 2010. It's easy to fix. Above the main() function just replace the standard include lines with this below but with the pound symbol in front of the includes.

# include "stdafx.h"
# include <iostream>
using  namespace std;

What's the best way to share data between activities?

Using the hashmap of weak reference approach, described above, and in http://developer.android.com/guide/faq/framework.html seems problematic to me. How are entire entries reclaimed, not just the map value? What scope do you allocate it in? As the framework is in control of the Activity lifecycle, having one of the participating Activities own it risks runtime errors when the owner is destroyed in advance of its clients. If the Application owns it, some Activity must explicitly remove the entry to avoid the hashmap from holding on to entries with a valid key and a potentially garbaged collected weak reference. Furthermore, what should a client do when the value returned for a key is null?

It seems to me that a WeakHashMap owned by the Application or within a singleton is a better choice. An value in the map is accessed via a key object, and when no strong references to the key exist (i.e. all Activities are done with the key and what it maps to), GC can reclaim the map entry.

How can I show three columns per row?

Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:

_x000D_
_x000D_
.flex-row-container {_x000D_
    background: #aaa;_x000D_
    display: flex;_x000D_
    flex-wrap: wrap;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
    flex: 1 1 30%; /*grow | shrink | basis */_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
  background-color: #fff4e6;_x000D_
  border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
  <div class="flex-row-item">1</div>_x000D_
  <div class="flex-row-item">2</div>_x000D_
  <div class="flex-row-item">3</div>_x000D_
  <div class="flex-row-item">4</div>_x000D_
  <div class="flex-row-item">5</div>_x000D_
  <div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps someone else.

git pull error "The requested URL returned error: 503 while accessing"

This problem is not only created by no_proxy, because it created by git server down issue also.

So When happening this issue first you open and check gitlab in browser.

And check if It shows any error like "503 An internal server error occured". .

The gitlab shows "503" page, this issue create by gitlab server down not in your system.

So you wait some time until the server going up and continue your work.

How to use getJSON, sending data with post method?

if you have just two parameters you can do this:

$.getJSON('/url-you-are-posting-to',data,function(result){

    //do something useful with returned result//
    result.variable-in-result;
});

Difference between private, public, and protected inheritance

1) Public Inheritance:

a. Private members of Base class are not accessible in Derived class.

b. Protected members of Base class remain protected in Derived class.

c. Public members of Base class remain public in Derived class.

So, other classes can use public members of Base class through Derived class object.

2) Protected Inheritance:

a. Private members of Base class are not accessible in Derived class.

b. Protected members of Base class remain protected in Derived class.

c. Public members of Base class too become protected members of Derived class.

So, other classes can't use public members of Base class through Derived class object; but they are available to subclass of Derived.

3) Private Inheritance:

a. Private members of Base class are not accessible in Derived class.

b. Protected & public members of Base class become private members of Derived class.

So, no members of Base class can be accessed by other classes through Derived class object as they are private in Derived class. So, even subclass of Derived class can't access them.

How do I check that a Java String is not all whitespaces?

The trim method should work great for you.

http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/lang/String.html#trim()

Returns a copy of the string, with leading and trailing whitespace omitted. If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.

Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.

Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).

This method may be used to trim whitespace from the beginning and end of a string; in fact, it trims all ASCII control characters as well.

Returns: A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.leading or trailing white space.

You could trim and then compare to an empty string or possibly check the length for 0.

Oracle: how to set user password unexpire?

If you create a user using a profile like this:

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

then you can change the password lifetime like this:

ALTER PROFILE my_profile LIMIT
  PASSWORD_LIFE_TIME UNLIMITED;

I hope that helps.

Getter and Setter declaration in .NET

The first one is the "short" form - you use it, when you do not want to do something fancy with your getters and setters. It is not possible to execute a method or something like that in this form.

The second and third form are almost identical, albeit the second one is compressed to one line. This form is discouraged by stylecop because it looks somewhat weird and does not conform to C' Stylguides.

I would use the third form if I expectd to use my getters / setters for something special, e.g. use a lazy construct or so.

cast a List to a Collection

Not knowing your code, it's a bit hard to answer your question, but based on all the info here, I believe the issue is you're trying to use Collections.sort passing in an object defined as Collection, and sort doesn't support that.

First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?

If client was defined as a List, Map or Set, you wouldn't have this issue, as then you'd be able to directly use Collections.sort(client).

HTH

What characters are allowed in an email address?

The short answer is that there are 2 answers. There is one standard for what you should do. ie behaviour that is wise and will keep you out of trouble. There is another (much broader) standard for the behaviour you should accept without making trouble. This duality works for sending and accepting email but has broad application in life.

For a good guide to the addresses you create; see: http://www.remote.org/jochen/mail/info/chars.html

To filter valid emails, just pass on anything comprehensible enough to see a next step. Or start reading a bunch of RFCs, caution, here be dragons.

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You need to add an event, before call your handleFunction like this:

function SingInContainer() {
..
..
handleClose = () => {
}

return (
    <SnackBar
        open={open}
        handleClose={() => handleClose}
        variant={variant}
        message={message}
        />
    <SignInForm/>
)

}

How to sort ArrayList<Long> in decreasing order?

So, There is something I would like to bring up which I think is important and I think that you should consider. runtime and memory. Say you have a list and want to sort it, well you can, there is a built in sort or you could develop your own. Then you say, want to reverse the list. That is the answer which is listed above.

If you are creating that list though, it might be good to use a different datastructure to store it and then just dump it into an array.

Heaps do just this. You filter in data, and it will handle everything, then you can pop everything off of the object and it would be sorted.

Another option would be to understand how maps work. A lot of times, a Map or HashMap as something things are called, have an underlying concept behind it.

For example.... you feed in a bunch of key-value pairs where the key is the long, and when you add all the elements, you can do: .keys and it would return to you a sorted list automatically.

It depends on how you process the data prior as to how i think you should continue with your sorting and subsequent reverses

How to iterate through a table rows and get the cell values using jQuery

$(this) instead of $this

$("tr.item").each(function() {
        var quantity1 = $(this).find("input.name").val(),
            quantity2 = $(this).find("input.id").val();
});

Proof_1:

proof_2:

Android: install .apk programmatically

This question is very helpfully BUT Don't forget to mount SD Card in your emulator, if you don't do this its doesn't work.

I lose my time before discover this.

Get JavaScript object from array of objects by value of property

var result = jsObjects.filter(x=> x.b === 6);

will be better, using return in filter sometimes you can't get result (I dunno why)

argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

How can I obtain the element-wise logical NOT of a pandas Series?

You can also use numpy.invert:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: s = pd.Series([True, True, False, True])

In [4]: np.invert(s)
Out[4]: 
0    False
1    False
2     True
3    False

EDIT: The difference in performance appears on Ubuntu 12.04, Python 2.7, NumPy 1.7.0 - doesn't seem to exist using NumPy 1.6.2 though:

In [5]: %timeit (-s)
10000 loops, best of 3: 26.8 us per loop

In [6]: %timeit np.invert(s)
100000 loops, best of 3: 7.85 us per loop

In [7]: %timeit ~s
10000 loops, best of 3: 27.3 us per loop

How do you parse and process HTML/XML in PHP?

For HTML5, html5 lib has been abandoned for years now. The only HTML5 library I can find with a recent update and maintenance records is html5-php which was just brought to beta 1.0 a little over a week ago.

Checkout one file from Subversion

Do something like this:

mkdir <your directory>/repos/test

svn cat http://svn.red-bean.com/repos/test/readme.txt > <your directory>/repos/test/readme.txt

Basically the idea is create the directory where you want to grab the file from SVN. Use the svn cat command and redirect the output to the same named file. By default, the cat will dump information on stdio.

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

This solution works nice when using Latin American accents, such as 'ñ'.

I have solved this problem just by adding

df = pd.read_csv(fileName,encoding='latin1')

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Put this in C2 and copy down

=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")

Then if the value in A isn't in B the cell in column C will say "not in B".

How to convert number of minutes to hh:mm format in TSQL?

This seems to work for me:

SELECT FORMAT(@mins / 60 * 100 + @mins % 60, '#:0#')

How to remove specific value from array using jQuery

With jQuery, you can do a single-line operation like this:

Example: http://jsfiddle.net/HWKQY/

y.splice( $.inArray(removeItem, y), 1 );

Uses the native .splice() and jQuery's $.inArray().

How can I merge properties of two JavaScript objects dynamically?

Three ways you can do that:-

Approach 1:-

// using spread ...
    let obj1 = {
        ...obj2
    };

Approach2:-

// using  Object.assign() method
let obj1 = Object.assign({}, obj2);

Approach3:-

// using JSON
let obj1 = JSON.parse(JSON.stringify(obj2));

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

A trick if you want to keep the order of the list:

df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
countries_to_keep = ['Germany', 'US']


ind=[df.index[df['country']==i].tolist() for i in countries_to_keep]
flat_ind=[item for sublist in ind for item in sublist]

df.reindex(flat_ind)

   country
2  Germany
0       US

Gradle Build Android Project "Could not resolve all dependencies" error

As Peter says, they won't be in Maven Central

from the Android SDK Manager download the 'Android Support Repository' and a Maven repo of the support libraries will be downloaded to your Android SDK directory (see 'extras' folder)

to deploy the libraries to your local .m2 repository you can use maven-android-sdk-deployer

2017 edit:

you can now reference the Google online M2 repo

repositories {
google()
jcenter()
}

How to show full object in Chrome console?

this worked perfectly for me:

for(a in array)console.log(array[a])

you can extract any array created in console for find/replace cleanup and posterior usage of this data extracted

How to find substring inside a string (or how to grep a variable)?

You can use "index" if you only want to find a single character, e.g.:

LIST="server1 server2 server3 server4 server5"
SOURCE="3"
if expr index "$LIST" "$SOURCE"; then
    echo "match"
    exit -1
else
    echo "no match"
fi

Output is:

23
match

SHA512 vs. Blowfish and Bcrypt

Blowfish isn't better than MD5 or SHA512, as they serve different purposes. MD5 and SHA512 are hashing algorithms, Blowfish is an encryption algorithm. Two entirely different cryptographic functions.

JUnit test for System.out.println()

using ByteArrayOutputStream and System.setXXX is simple:

private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;

@Before
public void setUpStreams() {
    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));
}

@After
public void restoreStreams() {
    System.setOut(originalOut);
    System.setErr(originalErr);
}

sample test cases:

@Test
public void out() {
    System.out.print("hello");
    assertEquals("hello", outContent.toString());
}

@Test
public void err() {
    System.err.print("hello again");
    assertEquals("hello again", errContent.toString());
}

I used this code to test the command line option (asserting that -version outputs the version string, etc etc)

Edit: Prior versions of this answer called System.setOut(null) after the tests; This is the cause of NullPointerExceptions commenters refer to.

How to update Python?

  • Official Python .msi installers are designed to replace:

    • any previous micro release (in x.y.z, z is "micro") because they are guaranteed to be backward-compatible and binary-compatible
    • a "snapshot" (built from source) installation with any micro version
  • A snapshot installer is designed to replace any snapshot with a lower micro version.

(See responsible code for 2.x, for 3.x)

Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:

  • If you installed any modules from bdist_wininst packages (Windows .exes), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logic
  • modules installed with setuptools/pip that reside in Lib\site-packages can just be deleted afterwards
  • packages that you installed per-user, if any, reside in %APPDATA%/Python/PythonXY/site-packages and can likewise be deleted

How to get the number of columns from a JDBC ResultSet?

You can get columns number from ResultSetMetaData:

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();

int columnsNumber = rsmd.getColumnCount();

calculating the difference in months between two dates

Combing two of the answers above, another extension method is:

public static int ElapsedMonths(this DateTime date1, DateTime date2)
{
    DateTime earlierDate = (date1 > date2) ? date2 : date1;
    DateTime laterDate = (date1 > date2) ? date1 : date2;
    var eMonths = (laterDate.Month - earlierDate.Month) + 12 * (laterDate.Year - earlierDate.Year) - 
                                            ((earlierDate.Day > laterDate.Day) ? 1 : 0);
    return eMonths;
}

Thanks to @AdamRobinson and @MarkWhittaker

Should I put #! (shebang) in Python scripts, and what form should it take?

Absolute vs Logical Path:

This is really a question about whether the path to the Python interpreter should be absolute or Logical (/usr/bin/env) in respect to portability.

Encountering other answers on this and other Stack sites which talked about the issue in a general way without supporting proofs, I've performed some really, REALLY, granular testing & analysis on this very question on the unix.stackexchange.com. Rather than paste that answer here, I'll point those interested to the comparative analysis to that answer:

https://unix.stackexchange.com/a/566019/334294

Being a Linux Engineer, my goal is always to provide the most suitable, optimized hosts for my developer clients, so the issue of Python environments was something I really needed a solid answer to. My view after the testing was that the logical path in the she-bang was the better of the (2) options.

How do I block comment in Jupyter notebook?

After searching for a while I have found a solution to comment on an AZERTY mac. The shortcut is Ctrl +/= key

Jquery to change form action

To change action value of form dynamically, you can try below code:

below code is if you are opening some dailog box and inside that dailog box you have form and you want to change the action of it. I used Bootstrap dailog box and on opening of that dailog box I am assigning action value to the form.

$('#your-dailog-id').on('show.bs.modal', function (event) {
    var link = $(event.relatedTarget);// Link that triggered the modal
    var cURL= link.data('url');// Extract info from data-* attributes
    $("#delUserform").attr("action", cURL);
});

If you are trying to change the form action on regular page, use below code

$("#yourElementId").change(function() { 
  var action = <generate_action>;
  $("#formId").attr("action", action);
});

Download file through an ajax call php

A very simple solution using jQuery:

on the client side:

$('.act_download_statement').click(function(e){
    e.preventDefault();
    form = $('#my_form');
    form.submit();
});

and on the server side, make sure you send back the correct Content-Type header, so the browser will know its an attachment and the download will begin.

How do I login and authenticate to Postgresql after a fresh install?

by default you would need to use the postgres user:

sudo -u postgres psql postgres

How to prevent caching of my Javascript file?

You can append a queryString to your src and change it only when you will release an updated version:

<script src="test.js?v=1"></script>

In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)

Call a python function from jinja2

from jinja2 import Template

def custom_function(a):
    return a.replace('o', 'ay')

template = Template('Hey, my name is {{ custom_function(first_name) }} {{ func2(last_name) }}')
template.globals['custom_function'] = custom_function

You can also give the function in the fields as per Matroskin's answer

fields = {'first_name': 'Jo', 'last_name': 'Ko', 'func2': custom_function}
print template.render(**fields)

Will output:

Hey, my name is Jay Kay

Works with Jinja2 version 2.7.3

And if you want a decorator to ease defining functions on template.globals check out Bruno Bronosky's answer

How do you test your Request.QueryString[] variables?

Below is an extension method that will allow you to write code like this:

int id = request.QueryString.GetValue<int>("id");
DateTime date = request.QueryString.GetValue<DateTime>("date");

It makes use of TypeDescriptor to perform the conversion. Based on your needs, you could add an overload which takes a default value instead of throwing an exception:

public static T GetValue<T>(this NameValueCollection collection, string key)
{
    if(collection == null)
    {
        throw new ArgumentNullException("collection");
    }

    var value = collection[key];

    if(value == null)
    {
        throw new ArgumentOutOfRangeException("key");
    }

    var converter = TypeDescriptor.GetConverter(typeof(T));

    if(!converter.CanConvertFrom(typeof(string)))
    {
        throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T)));
    }

    return (T) converter.ConvertFrom(value);
}

Is it possible to have empty RequestParam values use the defaultValue?

You can also do something like this -

 @RequestParam(value= "i", defaultValue = "20") Optional<Integer> i

'namespace' but is used like a 'type'

I suspect you've got the same problem at least twice.

Here:

namespace TimeTest
{
    class TimeTest
    {
}

... you're declaring a type with the same name as the namespace it's in. Don't do that.

Now you apparently have the same problem with Time2. I suspect if you add:

using Time2;

to your list of using directives, your code will compile. But please, please, please fix the bigger problem: the problematic choice of names. (Follow the link above to find out more details of why it's a bad idea.)

(Additionally, unless you're really interested in writing time-based types, I'd advise you not to do so... and I say that as someone who does do exactly that. Use the built-in capabilities, or a third party library such as, um, mine. Working with dates and times correctly is surprisingly hairy. :)

URL encoding the space character: + or %20?

From Wikipedia (emphasis and link added):

When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.

So, the real percent encoding uses %20 while form data in URLs is in a modified form that uses +. So you're most likely to only see + in URLs in the query string after an ?.

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Go through C:\apache-tomcat-7.0.47\lib path (this path may be differ based on where you installed the Tomcat server) then past ojdbc14.jar if its not contain.

Then restart the server in eclipse then run your app on server

Best way to compare dates in Android

Your code could be reduced to

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}

or

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (System.currentTimeMillis() > strDate.getTime()) {
    catalog_outdated = 1;
}